freecs 3.17.0

A high-performance, archetype-based Entity Component System (ECS) written in Rust.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
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
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
//! Runtime-registered components over the same archetype kernel.
//!
//! The `ecs!` macro fixes the component set at compile time and generates a
//! typed accessor per name. This module is the other entry point: component
//! types register at runtime, storage is still one contiguous `Vec<T>` per
//! component per archetype, and dynamic dispatch is confined to the places
//! runtime registration makes unavoidable. Structural changes go through a
//! per-type table of plain function pointers, and typed access crosses one
//! safe `Any` downcast per column per table. Query inner loops run over
//! concrete slices, the same machine code the macro produces.
//!
//! Nothing here uses `unsafe`. Columns are erased as whole `Vec<T>` values
//! behind `Box<dyn Any + Send + Sync>`, never as raw bytes, so `Drop` and
//! thread-safety come from the vec itself, and a type must exist at the
//! registration call site.
//!
//! # Quick start
//!
//! ```rust
//! use freecs::dynamic::DynWorld;
//!
//! #[derive(Default, Clone, Debug, PartialEq)]
//! struct Position { x: f32, y: f32 }
//!
//! #[derive(Default, Clone, Debug)]
//! struct Velocity { x: f32, y: f32 }
//!
//! let mut world = DynWorld::new();
//!
//! // Types register lazily on first use; tuples spawn as bundles.
//! let entity = world.spawn((
//!     Position { x: 0.0, y: 0.0 },
//!     Velocity { x: 1.0, y: 2.0 },
//! ));
//!
//! world
//!     .query::<(&mut Position, &Velocity)>()
//!     .for_each(|_entity, (position, velocity)| {
//!         position.x += velocity.x;
//!         position.y += velocity.y;
//!     });
//!
//! assert_eq!(world.get::<Position>(entity), Some(&Position { x: 1.0, y: 2.0 }));
//! ```
//!
//! Query tuples take up to eight elements of `&T`, `&mut T`, `Option<&T>`,
//! or `Option<&mut T>`; optional elements yield `None` instead of narrowing
//! the match, and single-component queries can skip the tuple entirely
//! (`world.query::<&mut Position>()`). Both query forms filter by
//! `changed::<T>()` (mutated since the last step) and `added::<T>()` (gained
//! since the last step, surviving table migrations). On a shared borrow,
//! [`DynWorld::query_ref`] runs read-only tuples as a real [`Iterator`],
//! with `single()` and `iter_combinations()` on top:
//!
//! ```rust
//! # use freecs::dynamic::DynWorld;
//! # #[derive(Default, Clone, Debug, PartialEq)]
//! # struct Position { x: f32, y: f32 }
//! # #[derive(Default, Clone, Debug)]
//! # struct Velocity { x: f32, y: f32 }
//! # let mut world = DynWorld::new();
//! # world.spawn((Position { x: 1.0, y: 2.0 }, Velocity { x: 1.0, y: 2.0 }));
//! let total: f32 = world
//!     .query_ref::<(&Position, Option<&Velocity>)>()
//!     .iter()
//!     .map(|(_entity, (position, velocity))| {
//!         position.x + velocity.map_or(0.0, |velocity| velocity.x)
//!     })
//!     .sum();
//! # assert_eq!(total, 2.0);
//! ```
//!
//! Tags can be named by marker types (`world.add_tag_type::<Selected>(entity)`,
//! `.with_tag_type::<Selected>()`), registering lazily like components, or
//! held as [`TagKey`] values; both forms are the same sparse sets underneath.
//!
//! Events buffer for two frames, so per-frame handlers consume through a
//! cursor: `world.consume_events::<T>(&mut cursor)` yields each event exactly
//! once per consumer, while `read_events` re-reads the whole buffer.
//!
//! Registration is a schema: mask bits are assigned in registration order, so
//! anything serializing masks should register components deterministically,
//! or build one [`ComponentRegistry`] up front and construct worlds from it.

use std::any::{Any, TypeId};
use std::collections::HashMap;
use std::marker::PhantomData;
use std::sync::atomic::{AtomicU32, Ordering};

use crate::{
    ArchetypeEdges, ArchetypeRouting, Entity, EntityAllocator, EntityLocation, EntityLocations,
    EventChannel, STRUCTURAL_LOG_CAPACITY, SparseTagSet, StructuralChange, StructuralChangeKind,
    archetype_cached_tables, archetype_register_table, tick_is_newer,
};

static NEXT_REGISTRY_ID: AtomicU32 = AtomicU32::new(1);

type ErasedColumn = Box<dyn Any + Send + Sync>;

fn column_new<T: Send + Sync + Default + 'static>() -> ErasedColumn {
    Box::new(Vec::<T>::new())
}

fn column_vec<T: 'static>(column: &(dyn Any + Send + Sync)) -> &Vec<T> {
    column
        .downcast_ref::<Vec<T>>()
        .expect("column type does not match its registered component")
}

fn column_vec_mut<T: 'static>(column: &mut (dyn Any + Send + Sync)) -> &mut Vec<T> {
    column
        .downcast_mut::<Vec<T>>()
        .expect("column type does not match its registered component")
}

fn column_push_default<T: Send + Sync + Default + 'static>(
    column: &mut (dyn Any + Send + Sync),
    count: usize,
) {
    let column = column_vec_mut::<T>(column);
    column.reserve(count);
    for _ in 0..count {
        column.push(T::default());
    }
}

fn column_len_of<T: Send + Sync + Default + 'static>(column: &(dyn Any + Send + Sync)) -> usize {
    column_vec::<T>(column).len()
}

fn column_swap_remove<T: Send + Sync + Default + 'static>(
    column: &mut (dyn Any + Send + Sync),
    index: usize,
) {
    column_vec_mut::<T>(column).swap_remove(index);
}

fn column_move_row<T: Send + Sync + Default + 'static>(
    source: &mut (dyn Any + Send + Sync),
    index: usize,
    destination: &mut (dyn Any + Send + Sync),
) {
    let value = std::mem::take(&mut column_vec_mut::<T>(source)[index]);
    column_vec_mut::<T>(destination).push(value);
}

/// The per-type operations a column needs, as a plain record of function
/// pointers captured at registration. This is the vtable, visible as data.
#[derive(Clone, Copy)]
pub struct ComponentInfo {
    pub type_id: TypeId,
    pub type_name: &'static str,
    pub mask: u64,
    pub new_column: fn() -> ErasedColumn,
    pub push_default: fn(&mut (dyn Any + Send + Sync), usize),
    pub swap_remove: fn(&mut (dyn Any + Send + Sync), usize),
    pub move_row: fn(&mut (dyn Any + Send + Sync), usize, &mut (dyn Any + Send + Sync)),
    pub column_len: fn(&(dyn Any + Send + Sync)) -> usize,
}

/// A typed handle to a registered component: the component's index, its mask
/// bit, and the registry it belongs to. Copyable plain data; holding one
/// skips the `TypeId` lookup the lazy typed API pays per call.
pub struct ComponentKey<T> {
    pub component_index: u32,
    pub mask: u64,
    pub registry_id: u32,
    marker: PhantomData<fn() -> T>,
}

impl<T> Clone for ComponentKey<T> {
    fn clone(&self) -> Self {
        *self
    }
}

impl<T> std::fmt::Debug for ComponentKey<T> {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("ComponentKey")
            .field("component_index", &self.component_index)
            .field("mask", &self.mask)
            .field("registry_id", &self.registry_id)
            .finish()
    }
}

impl<T> Copy for ComponentKey<T> {}

/// A handle to a registered tag. Tag mask bits are assigned from the top of
/// the `u64` downward, so they never collide with component bits.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct TagKey {
    pub tag_index: u32,
    pub mask: u64,
    pub registry_id: u32,
}

/// The component and tag schema for dynamic worlds. Bits are assigned in
/// registration order, so a registry built once and shared across worlds
/// guarantees every world agrees on masks.
#[derive(Clone)]
pub struct ComponentRegistry {
    pub registry_id: u32,
    pub components: Vec<ComponentInfo>,
    pub components_by_type: HashMap<TypeId, u32>,
    pub tag_count: u32,
    pub tags_by_type: HashMap<TypeId, u32>,
    #[cfg(feature = "snapshot")]
    pub codecs: Vec<Option<ComponentCodec>>,
}

impl Default for ComponentRegistry {
    fn default() -> Self {
        Self::new()
    }
}

impl ComponentRegistry {
    pub fn new() -> Self {
        Self {
            registry_id: NEXT_REGISTRY_ID.fetch_add(1, Ordering::Relaxed),
            components: Vec::new(),
            components_by_type: HashMap::new(),
            tag_count: 0,
            tags_by_type: HashMap::new(),
            #[cfg(feature = "snapshot")]
            codecs: Vec::new(),
        }
    }

    /// Registers `T` if it is not already registered and returns its key.
    /// Idempotent per type. `Default` is required because archetype migration
    /// moves values with `mem::take`, and `Send + Sync` because columns are
    /// shared across threads by the parallel iteration paths.
    pub fn register<T: Send + Sync + Default + 'static>(&mut self) -> ComponentKey<T> {
        if let Some(&component_index) = self.components_by_type.get(&TypeId::of::<T>()) {
            return self.key_for(component_index);
        }

        let component_index = self.components.len() as u32;
        assert!(
            (self.components.len() + self.tag_count as usize) < 64,
            "components plus tags must fit in a u64 mask"
        );
        self.components.push(ComponentInfo {
            type_id: TypeId::of::<T>(),
            type_name: std::any::type_name::<T>(),
            mask: 1 << component_index,
            new_column: column_new::<T>,
            push_default: column_push_default::<T>,
            swap_remove: column_swap_remove::<T>,
            move_row: column_move_row::<T>,
            column_len: column_len_of::<T>,
        });
        self.components_by_type
            .insert(TypeId::of::<T>(), component_index);
        #[cfg(feature = "snapshot")]
        self.codecs.push(None);
        self.key_for(component_index)
    }

    /// Registers `T` with a snapshot codec, so worlds carrying it can be
    /// serialized. The codec encodes whole columns with postcard; register
    /// through [`register_codec`](Self::register_codec) instead to supply a
    /// custom byte format.
    #[cfg(feature = "snapshot")]
    pub fn register_serde<T>(&mut self) -> ComponentKey<T>
    where
        T: serde::Serialize + serde::de::DeserializeOwned + Send + Sync + Default + 'static,
    {
        self.register_codec::<T>(ComponentCodec {
            encode_column: encode_column_postcard::<T>,
            decode_column: decode_column_postcard::<T>,
            encode_value: encode_value_postcard::<T>,
            apply_value: apply_value_postcard::<T>,
        })
    }

    /// Registers `T` with an explicit snapshot codec.
    #[cfg(feature = "snapshot")]
    pub fn register_codec<T: Send + Sync + Default + 'static>(
        &mut self,
        codec: ComponentCodec,
    ) -> ComponentKey<T> {
        let key = self.register::<T>();
        self.codecs[key.component_index as usize] = Some(codec);
        key
    }

    pub fn register_tag(&mut self) -> TagKey {
        assert!(
            (self.components.len() + self.tag_count as usize) < 64,
            "components plus tags must fit in a u64 mask"
        );
        let tag_index = self.tag_count;
        self.tag_count += 1;
        self.tag_key_for(tag_index)
    }

    /// Registers a tag identified by the marker type `T` if it is not
    /// already registered and returns its key. Idempotent per type; the tag
    /// is an ordinary sparse-set tag underneath, `T` is only its name.
    pub fn register_tag_type<T: 'static>(&mut self) -> TagKey {
        if let Some(&tag_index) = self.tags_by_type.get(&TypeId::of::<T>()) {
            return self.tag_key_for(tag_index);
        }
        let key = self.register_tag();
        self.tags_by_type.insert(TypeId::of::<T>(), key.tag_index);
        key
    }

    /// Resolves the marker type `T`'s tag key without registering.
    pub fn lookup_tag_type<T: 'static>(&self) -> Option<TagKey> {
        let &tag_index = self.tags_by_type.get(&TypeId::of::<T>())?;
        Some(self.tag_key_for(tag_index))
    }

    /// Finds a component by its registered type name, the full path
    /// `std::any::type_name` reports at registration. Linear scan over the
    /// schema; resolve once and hold the record when calling per frame.
    pub fn component_by_name(&self, name: &str) -> Option<&ComponentInfo> {
        self.components.iter().find(|info| info.type_name == name)
    }

    fn tag_key_for(&self, tag_index: u32) -> TagKey {
        TagKey {
            tag_index,
            mask: 1 << (63 - tag_index),
            registry_id: self.registry_id,
        }
    }

    fn key_for<T>(&self, component_index: u32) -> ComponentKey<T> {
        ComponentKey {
            component_index,
            mask: 1 << component_index,
            registry_id: self.registry_id,
            marker: PhantomData,
        }
    }

    /// How many of the 64 mask bits are still free. Components and tags
    /// share the budget, components from bit 0 up and tags from bit 63 down,
    /// so this is the number of registrations of either kind left before
    /// `register` or `register_tag` panics.
    pub fn remaining_bits(&self) -> u32 {
        64 - self.components.len() as u32 - self.tag_count
    }

    pub fn all_components_mask(&self) -> u64 {
        if self.components.len() == 64 {
            u64::MAX
        } else {
            (1u64 << self.components.len()) - 1
        }
    }

    pub fn all_tags_mask(&self) -> u64 {
        let mut mask = 0;
        for tag_index in 0..self.tag_count {
            mask |= 1 << (63 - tag_index);
        }
        mask
    }
}

/// One erased column plus its tick columns. `data` always holds the `Vec<T>`
/// of the registered component; a hand-swapped wrong-type box panics on the
/// next typed access rather than misbehaving. `changed` restamps on every
/// mutable access; `added` stamps when the component arrives on the entity
/// and rides along through table migrations, which is what the `added`
/// query filters compare against.
pub struct ColumnSlot {
    pub component_index: u32,
    pub data: ErasedColumn,
    pub changed: Vec<u32>,
    pub peak_changed: u32,
    pub added: Vec<u32>,
    pub peak_added: u32,
}

/// An archetype table for dynamic worlds: entities plus one [`ColumnSlot`]
/// per component bit in `mask`, ordered by ascending bit.
pub struct DynComponentArrays {
    pub mask: u64,
    pub entity_indices: Vec<Entity>,
    pub columns: Vec<ColumnSlot>,
}

/// Index of `component_mask`'s column within a table of `table_mask`,
/// assuming columns are stored in ascending bit order.
#[inline]
pub fn column_position(table_mask: u64, component_mask: u64) -> usize {
    (table_mask & (component_mask - 1)).count_ones() as usize
}

impl DynComponentArrays {
    /// Typed view of one column. Costs a popcount and a downcast per call,
    /// so hoist it outside per-entity loops; inside a hot loop, resolve
    /// columns once per table via [`columns_pair`](Self::columns_pair) or the
    /// typed query tier instead.
    #[inline]
    pub fn column<T: 'static>(&self, key: ComponentKey<T>) -> &[T] {
        let position = column_position(self.mask, key.mask);
        column_vec::<T>(self.columns[position].data.as_ref())
    }

    /// Mutable raw column access. Does not stamp change ticks, and costs a
    /// popcount and a downcast per call, so hoist it outside per-entity
    /// loops. Use the typed query tier when change detection matters.
    #[inline]
    pub fn column_mut<T: 'static>(&mut self, key: ComponentKey<T>) -> &mut [T] {
        let position = column_position(self.mask, key.mask);
        column_vec_mut::<T>(self.columns[position].data.as_mut())
    }

    pub fn has_component(&self, mask: u64) -> bool {
        self.mask & mask != 0
    }

    /// Stamps every row of the masked columns as changed at `tick`, the
    /// bulk opt-in for whole-column raw writes: after filling a column
    /// through `column_mut` or `columns_pair` inside a table loop, one call
    /// here makes the pass visible to tick-diffing consumers at zero
    /// per-row cost during the write. Pass the world's `current_tick()`.
    pub fn mark_columns_changed(&mut self, mask: u64, tick: u32) {
        let mut remaining = self.mask & mask;
        while remaining != 0 {
            let component_mask = remaining & remaining.wrapping_neg();
            remaining &= remaining - 1;
            let position = column_position(self.mask, component_mask);
            let column = &mut self.columns[position];
            column.changed.fill(tick);
            column.peak_changed = tick;
        }
    }

    /// Disjoint mutable and shared column slices in one call, for hoisting
    /// column access out of per-entity loops. Panics if the two components
    /// are the same or either is absent from this table.
    #[inline]
    pub fn columns_pair<A: 'static, B: 'static>(
        &mut self,
        first: ComponentKey<A>,
        second: ComponentKey<B>,
    ) -> (&mut [A], &[B]) {
        let first_position = column_position(self.mask, first.mask);
        let second_position = column_position(self.mask, second.mask);
        let [first_slot, second_slot] = self
            .columns
            .get_disjoint_mut([first_position, second_position])
            .expect("columns_pair components must be distinct");
        (
            column_vec_mut::<A>(first_slot.data.as_mut()).as_mut_slice(),
            column_vec::<B>(second_slot.data.as_ref()).as_slice(),
        )
    }

    /// Two disjoint mutable column slices in one call, the mut-and-mut
    /// counterpart of [`columns_pair`](Self::columns_pair).
    #[inline]
    pub fn columns_pair_mut<A: 'static, B: 'static>(
        &mut self,
        first: ComponentKey<A>,
        second: ComponentKey<B>,
    ) -> (&mut [A], &mut [B]) {
        let first_position = column_position(self.mask, first.mask);
        let second_position = column_position(self.mask, second.mask);
        let [first_slot, second_slot] = self
            .columns
            .get_disjoint_mut([first_position, second_position])
            .expect("columns_pair_mut components must be distinct");
        (
            column_vec_mut::<A>(first_slot.data.as_mut()).as_mut_slice(),
            column_vec_mut::<B>(second_slot.data.as_mut()).as_mut_slice(),
        )
    }
}

enum DynCommand {
    SpawnEntities { mask: u64, count: usize },
    DespawnEntity(Entity),
    DespawnEntities(Vec<Entity>),
    AddComponents(Entity, u64),
    RemoveComponents(Entity, u64),
    AddTag(Entity, TagKey),
    RemoveTag(Entity, TagKey),
    Closure(Box<dyn FnOnce(&mut DynWorld) + Send + Sync>),
}

struct EventSlot {
    type_id: TypeId,
    data: ErasedColumn,
    update: fn(&mut (dyn Any + Send + Sync)),
}

fn event_update<T: Send + Sync + 'static>(data: &mut (dyn Any + Send + Sync)) {
    data.downcast_mut::<EventChannel<T>>()
        .expect("event channel type mismatch")
        .update();
}

/// The type-erased event channels one container owns. [`DynWorld`] and
/// [`DynEcs`] both embed one, so world-local and group-shared events run on
/// identical machinery: sequence-numbered channels, two-frame buffering
/// driven by [`update`](Self::update), and exactly-once consumption through
/// per-consumer cursors.
#[derive(Default)]
pub struct EventBus {
    slots: Vec<EventSlot>,
    by_type: HashMap<TypeId, usize>,
}

impl EventBus {
    fn slot_index<T: Send + Sync + 'static>(&mut self) -> usize {
        if let Some(&index) = self.by_type.get(&TypeId::of::<T>()) {
            return index;
        }
        let index = self.slots.len();
        self.slots.push(EventSlot {
            type_id: TypeId::of::<T>(),
            data: Box::new(EventChannel::<T>::new()),
            update: event_update::<T>,
        });
        self.by_type.insert(TypeId::of::<T>(), index);
        index
    }

    fn channel<T: Send + Sync + 'static>(&self) -> Option<&EventChannel<T>> {
        let index = *self.by_type.get(&TypeId::of::<T>())?;
        debug_assert_eq!(self.slots[index].type_id, TypeId::of::<T>());
        Some(
            self.slots[index]
                .data
                .downcast_ref::<EventChannel<T>>()
                .expect("event channel type mismatch"),
        )
    }

    fn channel_mut<T: Send + Sync + 'static>(&mut self) -> &mut EventChannel<T> {
        let index = self.slot_index::<T>();
        self.slots[index]
            .data
            .downcast_mut::<EventChannel<T>>()
            .expect("event channel type mismatch")
    }

    pub fn send<T: Send + Sync + 'static>(&mut self, event: T) {
        self.channel_mut::<T>().send(event);
    }

    pub fn read<T: Send + Sync + 'static>(&self) -> &[T] {
        self.channel::<T>()
            .map(|channel| channel.events.as_slice())
            .unwrap_or(&[])
    }

    pub fn read_since<T: Send + Sync + 'static>(&self, cursor: u64) -> &[T] {
        self.channel::<T>()
            .map(|channel| channel.events_since(cursor))
            .unwrap_or(&[])
    }

    pub fn consume<T: Send + Sync + 'static>(&self, cursor: &mut u64) -> &[T] {
        match self.channel::<T>() {
            Some(channel) => channel.consume(cursor),
            None => &[],
        }
    }

    pub fn sequence<T: Send + Sync + 'static>(&self) -> u64 {
        self.channel::<T>()
            .map(|channel| channel.sequence())
            .unwrap_or(0)
    }

    pub fn trim<T: Send + Sync + 'static>(&mut self, up_to_sequence: u64) {
        self.channel_mut::<T>().trim(up_to_sequence);
    }

    pub fn clear<T: Send + Sync + 'static>(&mut self) {
        self.channel_mut::<T>().clear();
    }

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

    /// Advances every channel one frame, expiring events past their
    /// two-frame window. The containers call this from their `step`.
    pub fn update(&mut self) {
        for slot in &mut self.slots {
            (slot.update)(slot.data.as_mut());
        }
    }
}

/// The type-keyed resource singletons one container owns. [`DynWorld`] and
/// [`DynEcs`] both embed one, so world-local and group-shared resources use
/// identical machinery; the containers add the expect and scope forms.
#[derive(Default)]
pub struct ResourceMap {
    pub entries: HashMap<TypeId, ErasedColumn>,
}

impl ResourceMap {
    pub fn insert<T: Send + Sync + 'static>(&mut self, value: T) {
        self.entries.insert(TypeId::of::<T>(), Box::new(value));
    }

    pub fn get<T: Send + Sync + 'static>(&self) -> Option<&T> {
        self.entries
            .get(&TypeId::of::<T>())
            .and_then(|value| value.downcast_ref::<T>())
    }

    pub fn get_mut<T: Send + Sync + 'static>(&mut self) -> Option<&mut T> {
        self.entries
            .get_mut(&TypeId::of::<T>())
            .and_then(|value| value.downcast_mut::<T>())
    }

    pub fn remove<T: Send + Sync + 'static>(&mut self) -> Option<T> {
        self.entries
            .remove(&TypeId::of::<T>())
            .and_then(|value| value.downcast::<T>().ok())
            .map(|value| *value)
    }
}

/// Access to a resource map for the free-function scope forms,
/// [`resource_scope()`] and [`resources_scope()`]. [`DynWorld`] and
/// [`DynEcs`] implement it over their own maps. A host that wraps either
/// in a larger state struct implements it by delegating to the wrapped
/// map, and the free scopes then lend the whole host to the closure,
/// which the inherent scope methods structurally cannot do.
pub trait ResourceHost {
    fn resource_map_mut(&mut self) -> &mut ResourceMap;
}

impl ResourceHost for DynWorld {
    fn resource_map_mut(&mut self) -> &mut ResourceMap {
        &mut self.resources
    }
}

impl ResourceHost for DynEcs {
    fn resource_map_mut(&mut self) -> &mut ResourceMap {
        &mut self.resources
    }
}

/// The host form of [`DynWorld::resource_scope`]: takes `R` out of the
/// host's resource map, runs the closure with the host and the resource as
/// independent borrows, then puts the resource back, even when the closure
/// panics. The host can be a world, a group, or any wrapper implementing
/// [`ResourceHost`], which is how an engine state struct holding a
/// [`DynWorld`] or [`DynEcs`] plus its own fields lends the whole wrapper
/// to systems. Panics if `R` is not present.
///
/// ```rust
/// use freecs::dynamic::{DynWorld, ResourceHost, ResourceMap};
///
/// struct Engine {
///     ecs: DynWorld,
///     frames: u32,
/// }
///
/// impl ResourceHost for Engine {
///     fn resource_map_mut(&mut self) -> &mut ResourceMap {
///         &mut self.ecs.resources
///     }
/// }
///
/// struct Score(u32);
///
/// let mut engine = Engine { ecs: DynWorld::new(), frames: 0 };
/// engine.ecs.insert_resource(Score(0));
///
/// freecs::dynamic::resource_scope(&mut engine, |engine, score: &mut Score| {
///     engine.frames += 1;
///     score.0 += 1;
/// });
///
/// assert_eq!(engine.frames, 1);
/// assert_eq!(engine.ecs.resource::<Score>().unwrap().0, 1);
/// ```
pub fn resource_scope<H: ResourceHost, R: Send + Sync + 'static, T>(
    host: &mut H,
    f: impl FnOnce(&mut H, &mut R) -> T,
) -> T {
    let mut resource = host.resource_map_mut().remove::<R>().unwrap_or_else(|| {
        panic!(
            "resource_scope requires {} to be present",
            std::any::type_name::<R>()
        )
    });
    let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| f(host, &mut resource)));
    host.resource_map_mut().insert(resource);
    match result {
        Ok(value) => value,
        Err(panic) => std::panic::resume_unwind(panic),
    }
}

/// The host form of [`DynWorld::resources_scope`]: the tuple variant of
/// [`resource_scope()`], with the same presence and distinctness checks
/// before anything is removed and the same reinsertion on panic.
pub fn resources_scope<H: ResourceHost, B: ResourceBundle, T>(
    host: &mut H,
    f: impl FnOnce(&mut H, &mut B) -> T,
) -> T {
    let mut bundle = B::take(host.resource_map_mut());
    let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| f(host, &mut bundle)));
    bundle.put(host.resource_map_mut());
    match result {
        Ok(value) => value,
        Err(panic) => std::panic::resume_unwind(panic),
    }
}

/// A world whose component set is a runtime value. Same archetype storage,
/// change detection, structural log, tags, events, and command deferral as
/// the macro-generated worlds, with dispatch confined to registration
/// boundaries. All fields are public plain data, matching the crate's
/// design philosophy; the invariants the methods maintain are documented on
/// [`ColumnSlot`] and [`ComponentRegistry`].
pub struct DynWorld {
    pub registry: ComponentRegistry,
    pub allocator: EntityAllocator,
    /// When true, a live handle this world has never stored gets a row
    /// inserted on `add_components`/`set`, gated by the retired-generation
    /// check. Grouped worlds under [`DynEcs`] need this; a standalone world
    /// leaves it false so unknown handles are refused outright.
    pub insert_missing_rows: bool,
    pub entity_locations: EntityLocations,
    pub tables: Vec<DynComponentArrays>,
    pub table_lookup: HashMap<u64, usize>,
    pub table_edges: Vec<ArchetypeEdges>,
    pub query_cache: HashMap<u64, Vec<usize>>,
    pub added_scratch: Vec<bool>,
    pub current_tick: u32,
    pub last_tick: u32,
    pub structural_log: Vec<StructuralChange>,
    pub structural_sequence: u64,
    pub tags: Vec<SparseTagSet>,
    command_buffer: Vec<DynCommand>,
    pub events: EventBus,
    pub resources: ResourceMap,
}

impl Default for DynWorld {
    fn default() -> Self {
        Self::new()
    }
}

fn get_location(locations: &EntityLocations, entity: Entity) -> Option<(usize, usize)> {
    let location = locations.get(entity.id)?;
    if !location.allocated || location.generation != entity.generation {
        return None;
    }
    Some((location.table_index as usize, location.array_index as usize))
}

fn insert_location(locations: &mut EntityLocations, entity: Entity, location: (usize, usize)) {
    locations.insert(
        entity.id,
        EntityLocation {
            generation: entity.generation,
            table_index: location.0 as u32,
            array_index: location.1 as u32,
            allocated: true,
        },
    );
}

impl DynWorld {
    pub fn new() -> Self {
        Self::from_registry(ComponentRegistry::new())
    }

    /// Builds a world over a prebuilt schema. Worlds built from clones of one
    /// registry agree on every mask bit.
    pub fn from_registry(registry: ComponentRegistry) -> Self {
        let tag_count = registry.tag_count as usize;
        let mut world = Self {
            registry,
            allocator: EntityAllocator::default(),
            insert_missing_rows: false,
            entity_locations: EntityLocations::default(),
            tables: Vec::new(),
            table_lookup: HashMap::new(),
            table_edges: Vec::new(),
            query_cache: HashMap::new(),
            added_scratch: Vec::new(),
            current_tick: 0,
            last_tick: 0,
            structural_log: Vec::new(),
            structural_sequence: 0,
            tags: Vec::new(),
            command_buffer: Vec::new(),
            events: EventBus::default(),
            resources: ResourceMap::default(),
        };
        while world.tags.len() < tag_count {
            world.tags.push(SparseTagSet::default());
        }
        world
    }

    /// Registers `T` on this world's registry and returns its key.
    pub fn register<T: Send + Sync + Default + 'static>(&mut self) -> ComponentKey<T> {
        self.registry.register::<T>()
    }

    pub fn register_tag(&mut self) -> TagKey {
        let key = self.registry.register_tag();
        while self.tags.len() < self.registry.tag_count as usize {
            self.tags.push(SparseTagSet::default());
        }
        key
    }

    /// The lazy typed tier for tags: resolves or registers the marker type
    /// `T`'s tag and returns its key.
    pub fn tag_key<T: 'static>(&mut self) -> TagKey {
        let key = self.registry.register_tag_type::<T>();
        while self.tags.len() < self.registry.tag_count as usize {
            self.tags.push(SparseTagSet::default());
        }
        key
    }

    /// Resolves the marker type `T`'s tag key without registering. Returns
    /// `None` for marker types this world has never seen.
    pub fn lookup_tag_key<T: 'static>(&self) -> Option<TagKey> {
        self.registry.lookup_tag_type::<T>()
    }

    /// How many of this world's 64 mask bits are still free for components
    /// and tags combined. Lazy registration spends them silently, so budget
    /// checks belong here rather than at the panic.
    pub fn remaining_bits(&self) -> u32 {
        self.registry.remaining_bits()
    }

    /// A point-in-time census of this world's storage and bookkeeping. See
    /// [`WorldStats`] for the fields.
    pub fn stats(&self) -> WorldStats {
        WorldStats {
            entity_count: self.entity_count(),
            table_count: self.tables.len(),
            empty_table_count: self
                .tables
                .iter()
                .filter(|table| table.entity_indices.is_empty())
                .count(),
            largest_table_rows: self
                .tables
                .iter()
                .map(|table| table.entity_indices.len())
                .max()
                .unwrap_or(0),
            table_rows: self
                .tables
                .iter()
                .map(|table| (table.mask, table.entity_indices.len()))
                .collect(),
            component_count: self.registry.components.len(),
            tag_count: self.registry.tag_count as usize,
            remaining_mask_bits: self.remaining_bits(),
            structural_log_entries: self.structural_log.len(),
            query_cache_entries: self.query_cache.len(),
            resource_count: self.resources.entries.len(),
            event_channels: self.events.channel_count(),
            pending_commands: self.command_count(),
        }
    }

    /// Drops empty archetype tables and rebuilds every structure that
    /// references table positions: entity locations remap in place with
    /// retired-generation stamps untouched, the mask lookup rebuilds, the
    /// archetype edge caches reset to refill lazily, and the query cache
    /// clears. Explicit and opt-in; call at loading screens or level
    /// boundaries, not per frame. Returns how many tables were dropped.
    pub fn compact(&mut self) -> usize {
        let mut remap: Vec<Option<usize>> = Vec::with_capacity(self.tables.len());
        let mut kept = 0usize;
        for table in &self.tables {
            if table.entity_indices.is_empty() {
                remap.push(None);
            } else {
                remap.push(Some(kept));
                kept += 1;
            }
        }
        let dropped = self.tables.len() - kept;
        if dropped == 0 {
            return 0;
        }

        self.tables.retain(|table| !table.entity_indices.is_empty());
        for location in &mut self.entity_locations.locations {
            if location.allocated
                && let Some(new_index) = remap[location.table_index as usize]
            {
                location.table_index = new_index as u32;
            }
        }
        self.table_lookup.clear();
        for (table_index, table) in self.tables.iter().enumerate() {
            self.table_lookup.insert(table.mask, table_index);
        }
        self.table_edges.clear();
        self.table_edges
            .resize_with(self.tables.len(), ArchetypeEdges::default);
        self.query_cache.clear();
        dropped
    }

    /// The components an entity currently carries, as registry records with
    /// their type names, masks, and vtables. Dead or rowless entities yield
    /// nothing. This is the inspection surface for editors and tooling; pair
    /// it with [`ComponentRegistry::component_by_name`] to go the other way.
    pub fn entity_components(&self, entity: Entity) -> impl Iterator<Item = &ComponentInfo> + '_ {
        let mask = self.component_mask(entity).unwrap_or(0);
        self.registry
            .components
            .iter()
            .filter(move |info| info.mask & mask != 0)
    }

    /// Delegates to [`ComponentRegistry::component_by_name`].
    pub fn component_by_name(&self, name: &str) -> Option<&ComponentInfo> {
        self.registry.component_by_name(name)
    }

    fn check_key(&self, registry_id: u32) {
        debug_assert_eq!(
            registry_id, self.registry.registry_id,
            "key was minted by a different registry than this world's"
        );
    }

    fn record_structural(&mut self, entity: Entity, kind: StructuralChangeKind, mask: u64) {
        if self.structural_log.len() >= STRUCTURAL_LOG_CAPACITY {
            self.structural_log.clear();
        }
        self.structural_sequence += 1;
        self.structural_log.push(StructuralChange {
            sequence: self.structural_sequence,
            entity,
            kind,
            mask,
        });
    }

    fn get_or_create_table(&mut self, mask: u64) -> usize {
        debug_assert_eq!(
            mask & !self.registry.all_components_mask(),
            0,
            "archetype masks must not contain tag bits or unregistered component bits"
        );
        if let Some(&index) = self.table_lookup.get(&mask) {
            return index;
        }

        let component_count = self.registry.components.len();
        for edges in &mut self.table_edges {
            if edges.add_edges.len() < component_count {
                edges.add_edges.resize(component_count, None);
                edges.remove_edges.resize(component_count, None);
            }
        }

        let table_index = self.tables.len();
        let mut columns = Vec::with_capacity(mask.count_ones() as usize);
        for info in &self.registry.components {
            if mask & info.mask != 0 {
                columns.push(ColumnSlot {
                    component_index: (info.mask.trailing_zeros()),
                    data: (info.new_column)(),
                    changed: Vec::new(),
                    peak_changed: self.current_tick,
                    added: Vec::new(),
                    peak_added: self.current_tick,
                });
            }
        }
        self.tables.push(DynComponentArrays {
            mask,
            entity_indices: Vec::new(),
            columns,
        });

        archetype_register_table(
            ArchetypeRouting {
                table_lookup: &mut self.table_lookup,
                table_edges: &mut self.table_edges,
                query_cache: &mut self.query_cache,
            },
            self.registry.components.len(),
            mask,
            table_index,
            self.tables.iter().map(|table| table.mask),
            self.registry
                .components
                .iter()
                .enumerate()
                .map(|(component_index, info)| (info.mask, component_index)),
        );

        table_index
    }

    pub fn spawn_entities(&mut self, mask: u64, count: usize) -> Vec<Entity> {
        let mut allocator = std::mem::take(&mut self.allocator);
        let entities = self.spawn_entities_in(&mut allocator, mask, count);
        self.allocator = allocator;
        entities
    }

    /// Spawns through an external allocator, the grouped-worlds form used by
    /// [`DynEcs`].
    pub fn spawn_entities_in(
        &mut self,
        allocator: &mut EntityAllocator,
        mask: u64,
        count: usize,
    ) -> Vec<Entity> {
        let table_index = self.get_or_create_table(mask);
        let current_tick = self.current_tick;

        let mut entities = Vec::new();
        allocator.allocate_batch(count, &mut entities);

        let start_index = self.tables[table_index].entity_indices.len();
        {
            let table = &mut self.tables[table_index];
            table.entity_indices.reserve(count);
            for column in &mut table.columns {
                let info = &self.registry.components[column.component_index as usize];
                (info.push_default)(column.data.as_mut(), count);
                column.changed.reserve(count);
                column.added.reserve(count);
                for _ in 0..count {
                    column.changed.push(current_tick);
                    column.added.push(current_tick);
                }
                column.peak_changed = current_tick;
                column.peak_added = current_tick;
            }
            for &entity in &entities {
                table.entity_indices.push(entity);
            }
        }

        for (offset, &entity) in entities.iter().enumerate() {
            insert_location(
                &mut self.entity_locations,
                entity,
                (table_index, start_index + offset),
            );
            self.record_structural(entity, StructuralChangeKind::Spawned, mask);
        }

        entities
    }

    pub fn spawn_batch<F>(&mut self, mask: u64, count: usize, mut init: F) -> Vec<Entity>
    where
        F: FnMut(&mut DynComponentArrays, usize),
    {
        let entities = self.spawn_entities(mask, count);
        if let Some(&first) = entities.first() {
            let (table_index, start_index) =
                get_location(&self.entity_locations, first).expect("just spawned");
            let table = &mut self.tables[table_index];
            for offset in 0..count {
                init(table, start_index + offset);
            }
        }
        entities
    }

    fn remove_row(&mut self, table_index: usize, array_index: usize) {
        let table = &mut self.tables[table_index];
        let last_index = table.entity_indices.len() - 1;
        let swapped = if array_index < last_index {
            Some(table.entity_indices[last_index])
        } else {
            None
        };

        for column in &mut table.columns {
            let info = &self.registry.components[column.component_index as usize];
            (info.swap_remove)(column.data.as_mut(), array_index);
            column.changed.swap_remove(array_index);
            column.added.swap_remove(array_index);
        }
        table.entity_indices.swap_remove(array_index);

        if let Some(swapped_entity) = swapped
            && let Some(location) = self.entity_locations.get_mut(swapped_entity.id)
            && location.allocated
        {
            location.array_index = array_index as u32;
        }
    }

    /// Removes the entity's row if present and retires this handle by
    /// recording the next generation. Must only be called with a handle the
    /// allocator confirmed live; `despawn_entities` guarantees that.
    pub fn retire_entity(&mut self, entity: Entity) -> bool {
        let mut removed = false;
        if let Some((table_index, array_index)) = get_location(&self.entity_locations, entity) {
            self.entity_locations.mark_deallocated(entity.id);
            let despawned_mask = self.tables[table_index].mask;
            self.record_structural(entity, StructuralChangeKind::Despawned, despawned_mask);
            self.remove_row(table_index, array_index);
            removed = true;
        }

        let next_generation = entity.generation.wrapping_add(1);
        let should_retire = match self.entity_locations.get(entity.id) {
            None => true,
            Some(location) => {
                !location.allocated && tick_is_newer(next_generation, location.generation)
            }
        };
        if should_retire {
            self.entity_locations
                .ensure_slot(entity.id, next_generation);
        }

        removed
    }

    pub fn despawn_entities(&mut self, entities: &[Entity]) -> Vec<Entity> {
        let mut allocator = std::mem::take(&mut self.allocator);
        let despawned = self.despawn_entities_in(&mut allocator, entities);
        self.allocator = allocator;
        despawned
    }

    /// Despawns every entity carrying at least one of the bundle's component
    /// types, so one call clears several kinds of entity at once:
    /// `world.despawn_with_any::<(Projectile, VisualEffect)>()`. Types
    /// register lazily; a type nothing carries despawns nothing. Returns the
    /// despawned entities.
    pub fn despawn_with_any<B: Bundle>(&mut self) -> Vec<Entity> {
        let mask = B::component_mask(self);
        let entities: Vec<Entity> = self
            .tables
            .iter()
            .filter(|table| table.mask & mask != 0)
            .flat_map(|table| table.entity_indices.iter().copied())
            .collect();
        self.despawn_entities(&entities)
    }

    /// Direct children of a parent: every entity whose [`ChildOf`] link
    /// points at it. A full scan of `ChildOf` carriers on each call, pull
    /// not push; cache user-side when it measures hot.
    pub fn children(&self, parent: Entity) -> Vec<Entity> {
        self.query_ref::<&ChildOf>()
            .iter()
            .filter(|(_entity, child_of)| child_of.0 == parent)
            .map(|(entity, _child_of)| entity)
            .collect()
    }

    /// Despawns an entity and every descendant reachable through
    /// [`ChildOf`] links, breadth-first over on-demand scans. Link cycles
    /// are tolerated, each entity despawns once. Returns the despawned
    /// entities. In a [`DynEcs`] group, despawn through
    /// [`DynEcs::despawn_recursive`] instead, so retirement broadcasts into
    /// every member world.
    pub fn despawn_recursive(&mut self, root: Entity) -> Vec<Entity> {
        let mut pending = vec![root];
        let mut to_despawn: Vec<Entity> = Vec::new();
        while let Some(parent) = pending.pop() {
            if to_despawn.contains(&parent) {
                continue;
            }
            to_despawn.push(parent);
            pending.extend(self.children(parent));
        }
        self.despawn_entities(&to_despawn)
    }

    /// Despawns through an external allocator, the grouped-worlds form used
    /// by [`DynEcs`].
    pub fn despawn_entities_in(
        &mut self,
        allocator: &mut EntityAllocator,
        entities: &[Entity],
    ) -> Vec<Entity> {
        let mut despawned = Vec::with_capacity(entities.len());
        for &entity in entities {
            if allocator.deallocate(entity) {
                self.retire_entity(entity);
                for tag_set in &mut self.tags {
                    tag_set.remove(entity);
                }
                despawned.push(entity);
            }
        }
        despawned
    }

    fn move_entity(
        &mut self,
        entity: Entity,
        from_table: usize,
        from_index: usize,
        to_table: usize,
    ) {
        let tick = self.current_tick;
        {
            let [source, destination] = self
                .tables
                .get_disjoint_mut([from_table, to_table])
                .expect("migration source and destination must differ");

            let shared = source.mask & destination.mask;
            let mut bits = shared;
            while bits != 0 {
                let component_mask = bits & bits.wrapping_neg();
                bits &= bits - 1;

                let source_position = column_position(source.mask, component_mask);
                let destination_position = column_position(destination.mask, component_mask);
                let info = &self.registry.components
                    [source.columns[source_position].component_index as usize];
                (info.move_row)(
                    source.columns[source_position].data.as_mut(),
                    from_index,
                    destination.columns[destination_position].data.as_mut(),
                );
                let carried_added = source.columns[source_position].added[from_index];
                let destination_column = &mut destination.columns[destination_position];
                destination_column.changed.push(tick);
                destination_column.peak_changed = tick;
                destination_column.added.push(carried_added);
                destination_column.peak_added = tick;
            }

            let mut gained = destination.mask & !source.mask;
            while gained != 0 {
                let component_mask = gained & gained.wrapping_neg();
                gained &= gained - 1;

                let destination_position = column_position(destination.mask, component_mask);
                let destination_column = &mut destination.columns[destination_position];
                let info = &self.registry.components[destination_column.component_index as usize];
                (info.push_default)(destination_column.data.as_mut(), 1);
                destination_column.changed.push(tick);
                destination_column.peak_changed = tick;
                destination_column.added.push(tick);
                destination_column.peak_added = tick;
            }

            destination.entity_indices.push(entity);
        }

        let new_index = self.tables[to_table].entity_indices.len() - 1;
        insert_location(&mut self.entity_locations, entity, (to_table, new_index));
        self.remove_row(from_table, from_index);
    }

    pub fn add_components(&mut self, entity: Entity, mask: u64) -> bool {
        debug_assert_eq!(
            mask & !self.registry.all_components_mask(),
            0,
            "component masks must not contain tag bits or unregistered component bits"
        );
        let Some((table_index, array_index)) = get_location(&self.entity_locations, entity) else {
            return self.insert_missing_rows && self.insert_row(entity, mask);
        };
        let current_mask = self.tables[table_index].mask;
        if current_mask & mask == mask {
            return true;
        }

        let target_table = if mask.count_ones() == 1 {
            self.table_edges[table_index]
                .add_edges
                .get(mask.trailing_zeros() as usize)
                .copied()
                .flatten()
        } else {
            self.table_edges[table_index]
                .multi_add_cache
                .get(&mask)
                .copied()
        };

        let new_table_index = target_table.unwrap_or_else(|| {
            let new_index = self.get_or_create_table(current_mask | mask);
            self.table_edges[table_index]
                .multi_add_cache
                .insert(mask, new_index);
            new_index
        });

        self.move_entity(entity, table_index, array_index, new_table_index);
        self.record_structural(
            entity,
            StructuralChangeKind::ComponentsAdded,
            mask & !current_mask,
        );
        true
    }

    /// Creates a row for a live handle this world has never stored. Refuses
    /// stale handles via the generation the despawn broadcast retired.
    fn insert_row(&mut self, entity: Entity, mask: u64) -> bool {
        if let Some(location) = self.entity_locations.get(entity.id)
            && (location.allocated || location.generation != entity.generation)
        {
            return false;
        }

        let table_index = self.get_or_create_table(mask);
        let current_tick = self.current_tick;
        let start_index = self.tables[table_index].entity_indices.len();
        {
            let table = &mut self.tables[table_index];
            for column in &mut table.columns {
                let info = &self.registry.components[column.component_index as usize];
                (info.push_default)(column.data.as_mut(), 1);
                column.changed.push(current_tick);
                column.peak_changed = current_tick;
                column.added.push(current_tick);
                column.peak_added = current_tick;
            }
            table.entity_indices.push(entity);
        }
        insert_location(
            &mut self.entity_locations,
            entity,
            (table_index, start_index),
        );
        self.record_structural(entity, StructuralChangeKind::Spawned, mask);
        true
    }

    pub fn remove_components(&mut self, entity: Entity, mask: u64) -> bool {
        debug_assert_eq!(
            mask & !self.registry.all_components_mask(),
            0,
            "component masks must not contain tag bits or unregistered component bits"
        );
        let Some((table_index, array_index)) = get_location(&self.entity_locations, entity) else {
            return false;
        };
        let current_mask = self.tables[table_index].mask;
        if current_mask & mask == 0 {
            return true;
        }

        let target_table = if mask.count_ones() == 1 {
            self.table_edges[table_index]
                .remove_edges
                .get(mask.trailing_zeros() as usize)
                .copied()
                .flatten()
        } else {
            self.table_edges[table_index]
                .multi_remove_cache
                .get(&mask)
                .copied()
        };

        let new_table_index = target_table.unwrap_or_else(|| {
            let new_index = self.get_or_create_table(current_mask & !mask);
            self.table_edges[table_index]
                .multi_remove_cache
                .insert(mask, new_index);
            new_index
        });

        self.move_entity(entity, table_index, array_index, new_table_index);
        self.record_structural(
            entity,
            StructuralChangeKind::ComponentsRemoved,
            current_mask & mask,
        );
        true
    }

    #[inline]
    pub fn get_keyed<T: 'static>(&self, key: ComponentKey<T>, entity: Entity) -> Option<&T> {
        self.check_key(key.registry_id);
        let (table_index, array_index) = get_location(&self.entity_locations, entity)?;
        let table = &self.tables[table_index];
        if table.mask & key.mask == 0 {
            return None;
        }
        let position = column_position(table.mask, key.mask);
        Some(&column_vec::<T>(table.columns[position].data.as_ref())[array_index])
    }

    #[inline]
    pub fn get_mut_keyed<T: 'static>(
        &mut self,
        key: ComponentKey<T>,
        entity: Entity,
    ) -> Option<&mut T> {
        self.check_key(key.registry_id);
        let (table_index, array_index) = get_location(&self.entity_locations, entity)?;
        let current_tick = self.current_tick;
        let table = &mut self.tables[table_index];
        if table.mask & key.mask == 0 {
            return None;
        }
        let position = column_position(table.mask, key.mask);
        let column = &mut table.columns[position];
        column.changed[array_index] = current_tick;
        column.peak_changed = current_tick;
        Some(&mut column_vec_mut::<T>(column.data.as_mut())[array_index])
    }

    /// Explicitly stamps change ticks for the masked components on one
    /// entity. This is the opt-in for raw-tier writes: table access through
    /// [`for_each_tables_mut`](Self::for_each_tables_mut), `column_mut`, and
    /// `columns_pair` does not stamp, so follow such writes with this call
    /// when downstream consumers diff by ticks. Returns false if the entity
    /// is missing or its table lacks every masked component.
    pub fn mark_changed(&mut self, entity: Entity, mask: u64) -> bool {
        let Some((table_index, array_index)) = get_location(&self.entity_locations, entity) else {
            return false;
        };
        let current_tick = self.current_tick;
        let table = &mut self.tables[table_index];
        let present = table.mask & mask & self.registry.all_components_mask();
        if present == 0 {
            return false;
        }
        let mut remaining = present;
        while remaining != 0 {
            let component_mask = remaining & remaining.wrapping_neg();
            remaining &= remaining - 1;
            let position = column_position(table.mask, component_mask);
            let column = &mut table.columns[position];
            column.changed[array_index] = current_tick;
            column.peak_changed = current_tick;
        }
        true
    }

    pub fn set_keyed<T: 'static>(&mut self, key: ComponentKey<T>, entity: Entity, value: T) {
        self.check_key(key.registry_id);
        let current_tick = self.current_tick;
        if let Some((table_index, array_index)) = get_location(&self.entity_locations, entity) {
            let table = &mut self.tables[table_index];
            if table.mask & key.mask != 0 {
                let position = column_position(table.mask, key.mask);
                let column = &mut table.columns[position];
                column_vec_mut::<T>(column.data.as_mut())[array_index] = value;
                column.changed[array_index] = current_tick;
                column.peak_changed = current_tick;
                return;
            }
        }
        if self.add_components(entity, key.mask)
            && let Some((table_index, array_index)) = get_location(&self.entity_locations, entity)
        {
            let table = &mut self.tables[table_index];
            let position = column_position(table.mask, key.mask);
            let column = &mut table.columns[position];
            column_vec_mut::<T>(column.data.as_mut())[array_index] = value;
            column.changed[array_index] = current_tick;
            column.peak_changed = current_tick;
        }
    }

    pub fn component_mask(&self, entity: Entity) -> Option<u64> {
        get_location(&self.entity_locations, entity)
            .map(|(table_index, _)| self.tables[table_index].mask)
    }

    pub fn entity_has_components(&self, entity: Entity, mask: u64) -> bool {
        self.component_mask(entity).unwrap_or(0) & mask == mask
    }

    pub fn contains_entity(&self, entity: Entity) -> bool {
        get_location(&self.entity_locations, entity).is_some()
    }

    pub fn is_alive(&self, entity: Entity) -> bool {
        self.allocator.is_alive(entity)
    }

    pub fn entity_count(&self) -> usize {
        self.tables
            .iter()
            .map(|table| table.entity_indices.len())
            .sum()
    }

    pub fn get_all_entities(&self) -> Vec<Entity> {
        let mut result = Vec::with_capacity(self.entity_count());
        for table in &self.tables {
            result.extend(table.entity_indices.iter().copied());
        }
        result
    }

    pub fn increment_tick(&mut self) {
        self.last_tick = self.current_tick;
        self.current_tick = self.current_tick.wrapping_add(1);
    }

    pub fn current_tick(&self) -> u32 {
        self.current_tick
    }

    pub fn last_tick(&self) -> u32 {
        self.last_tick
    }

    pub fn structural_sequence(&self) -> u64 {
        self.structural_sequence
    }

    pub fn structural_changes_since(&self, cursor: u64) -> &[StructuralChange] {
        let start = self
            .structural_log
            .partition_point(|change| change.sequence <= cursor);
        &self.structural_log[start..]
    }

    pub fn trim_structural_log(&mut self, up_to_sequence: u64) {
        let end = self
            .structural_log
            .partition_point(|change| change.sequence <= up_to_sequence);
        self.structural_log.drain(..end);
    }

    pub fn clear_structural_log(&mut self) {
        self.structural_log.clear();
    }

    pub fn add_tag(&mut self, key: TagKey, entity: Entity) {
        self.check_key(key.registry_id);
        if self.contains_entity(entity) && self.tags[key.tag_index as usize].insert(entity) {
            self.record_structural(entity, StructuralChangeKind::TagsAdded, key.mask);
        }
    }

    pub fn remove_tag(&mut self, key: TagKey, entity: Entity) -> bool {
        self.check_key(key.registry_id);
        let removed = self.tags[key.tag_index as usize].remove(entity);
        if removed {
            self.record_structural(entity, StructuralChangeKind::TagsRemoved, key.mask);
        }
        removed
    }

    pub fn has_tag(&self, key: TagKey, entity: Entity) -> bool {
        self.check_key(key.registry_id);
        self.tags[key.tag_index as usize].contains(entity)
    }

    pub fn query_tag(&self, key: TagKey) -> impl Iterator<Item = Entity> + '_ {
        self.check_key(key.registry_id);
        self.tags[key.tag_index as usize].iter()
    }

    /// Adds the marker type `T`'s tag to an entity, registering the tag on
    /// first use.
    pub fn add_tag_type<T: 'static>(&mut self, entity: Entity) {
        let key = self.tag_key::<T>();
        self.add_tag(key, entity);
    }

    /// Removes the marker type `T`'s tag from an entity. Unregistered marker
    /// types remove nothing.
    pub fn remove_tag_type<T: 'static>(&mut self, entity: Entity) -> bool {
        match self.lookup_tag_key::<T>() {
            Some(key) => self.remove_tag(key, entity),
            None => false,
        }
    }

    /// Whether an entity carries the marker type `T`'s tag. Unregistered
    /// marker types read as absent.
    pub fn has_tag_type<T: 'static>(&self, entity: Entity) -> bool {
        match self.lookup_tag_key::<T>() {
            Some(key) => self.has_tag(key, entity),
            None => false,
        }
    }

    /// Iterates entities carrying the marker type `T`'s tag. Unregistered
    /// marker types match nothing.
    pub fn query_tag_type<T: 'static>(&self) -> impl Iterator<Item = Entity> + '_ {
        self.lookup_tag_key::<T>()
            .into_iter()
            .flat_map(|key| self.tags[key.tag_index as usize].iter())
    }

    fn entity_matches_tags(&self, entity: Entity, tag_include: u64, tag_exclude: u64) -> bool {
        for (tag_index, tag_set) in self.tags.iter().enumerate() {
            let tag_mask = 1u64 << (63 - tag_index as u32);
            if tag_include & tag_mask != 0 && !tag_set.contains(entity) {
                return false;
            }
            if tag_exclude & tag_mask != 0 && tag_set.contains(entity) {
                return false;
            }
        }
        true
    }

    /// Returns None when an included tag has no members. Drops excluded tags
    /// whose sets are empty, so exclusion of an unused tag stays on the
    /// unfiltered path.
    fn reduce_tag_masks(&self, tag_include: u64, tag_exclude: u64) -> Option<(u64, u64)> {
        let mut reduced_exclude = tag_exclude;
        for (tag_index, tag_set) in self.tags.iter().enumerate() {
            let tag_mask = 1u64 << (63 - tag_index as u32);
            if tag_include & tag_mask != 0 && tag_set.is_empty() {
                return None;
            }
            if reduced_exclude & tag_mask != 0 && tag_set.is_empty() {
                reduced_exclude &= !tag_mask;
            }
        }
        Some((tag_include, reduced_exclude))
    }

    fn split_masks(&self, include: u64, exclude: u64) -> Option<(u64, u64, u64, u64)> {
        let all_tags = self.registry.all_tags_mask();
        let (tag_include, tag_exclude) =
            self.reduce_tag_masks(include & all_tags, exclude & all_tags)?;
        Some((
            include & !all_tags,
            exclude & !all_tags,
            tag_include,
            tag_exclude,
        ))
    }

    /// Table-granular iteration, the raw fast path: resolve columns once per
    /// table, then loop entities over concrete slices. Component masks only.
    /// Does not stamp change ticks.
    pub fn for_each_tables_mut<F>(&mut self, include: u64, exclude: u64, mut f: F)
    where
        F: FnMut(&mut DynComponentArrays),
    {
        debug_assert_eq!(
            include & !self.registry.all_components_mask(),
            0,
            "table-granular iteration takes component masks only"
        );
        let table_indices = archetype_cached_tables(
            &mut self.query_cache,
            self.tables.iter().map(|table| table.mask),
            include,
        );
        let tables = &mut self.tables;
        for &table_index in table_indices {
            let table = &mut tables[table_index];
            if table.mask & exclude != 0 || table.entity_indices.is_empty() {
                continue;
            }
            f(table);
        }
    }

    pub fn for_each_tables<F>(&self, include: u64, exclude: u64, mut f: F)
    where
        F: FnMut(&DynComponentArrays),
    {
        debug_assert_eq!(
            include & !self.registry.all_components_mask(),
            0,
            "table-granular iteration takes component masks only"
        );
        for table in &self.tables {
            if table.mask & include != include
                || table.mask & exclude != 0
                || table.entity_indices.is_empty()
            {
                continue;
            }
            f(table);
        }
    }

    pub fn for_each<F>(&self, include: u64, exclude: u64, mut f: F)
    where
        F: FnMut(Entity, &DynComponentArrays, usize),
    {
        let Some((component_include, component_exclude, tag_include, tag_exclude)) =
            self.split_masks(include, exclude)
        else {
            return;
        };

        for table in &self.tables {
            if table.mask & component_include != component_include
                || table.mask & component_exclude != 0
            {
                continue;
            }
            if tag_include == 0 && tag_exclude == 0 {
                for (index, &entity) in table.entity_indices.iter().enumerate() {
                    f(entity, table, index);
                }
            } else {
                for (index, &entity) in table.entity_indices.iter().enumerate() {
                    if self.entity_matches_tags(entity, tag_include, tag_exclude) {
                        f(entity, table, index);
                    }
                }
            }
        }
    }

    /// Entity-granular iteration with tag filtering, mirroring the static
    /// worlds' shape. Calling `column`/`column_mut` inside the closure pays a
    /// downcast per entity; prefer the typed query tier, or
    /// [`for_each_tables_mut`](Self::for_each_tables_mut) with columns
    /// hoisted, for hot loops.
    pub fn for_each_mut<F>(&mut self, include: u64, exclude: u64, mut f: F)
    where
        F: FnMut(Entity, &mut DynComponentArrays, usize),
    {
        let Some((component_include, component_exclude, tag_include, tag_exclude)) =
            self.split_masks(include, exclude)
        else {
            return;
        };

        let tags = &self.tags;
        let table_indices = archetype_cached_tables(
            &mut self.query_cache,
            self.tables.iter().map(|table| table.mask),
            component_include,
        );
        let tables = &mut self.tables;

        for &table_index in table_indices {
            let table = &mut tables[table_index];
            if table.mask & component_exclude != 0 {
                continue;
            }
            for index in 0..table.entity_indices.len() {
                let entity = table.entity_indices[index];
                if (tag_include != 0 || tag_exclude != 0)
                    && !tags_match(tags, entity, tag_include, tag_exclude)
                {
                    continue;
                }
                f(entity, table, index);
            }
        }
    }

    pub fn for_each_mut_changed<F>(&mut self, include: u64, exclude: u64, f: F)
    where
        F: FnMut(Entity, &mut DynComponentArrays, usize),
    {
        let since_tick = self.last_tick;
        self.for_each_mut_changed_since(include, exclude, since_tick, f);
    }

    pub fn for_each_mut_changed_since<F>(
        &mut self,
        include: u64,
        exclude: u64,
        since_tick: u32,
        mut f: F,
    ) where
        F: FnMut(Entity, &mut DynComponentArrays, usize),
    {
        let Some((component_include, component_exclude, tag_include, tag_exclude)) =
            self.split_masks(include, exclude)
        else {
            return;
        };

        let tags = &self.tags;
        let table_indices = archetype_cached_tables(
            &mut self.query_cache,
            self.tables.iter().map(|table| table.mask),
            component_include,
        );
        let tables = &mut self.tables;

        for &table_index in table_indices {
            let table = &mut tables[table_index];
            if table.mask & component_exclude != 0 {
                continue;
            }

            let mut table_changed = false;
            for column in &table.columns {
                let column_mask = 1u64 << column.component_index;
                if component_include & column_mask != 0
                    && tick_is_newer(column.peak_changed, since_tick)
                {
                    table_changed = true;
                }
            }
            if !table_changed {
                continue;
            }

            for index in 0..table.entity_indices.len() {
                let entity = table.entity_indices[index];
                if (tag_include != 0 || tag_exclude != 0)
                    && !tags_match(tags, entity, tag_include, tag_exclude)
                {
                    continue;
                }

                let mut changed = false;
                for column in &table.columns {
                    let column_mask = 1u64 << column.component_index;
                    if component_include & column_mask != 0
                        && tick_is_newer(column.changed[index], since_tick)
                    {
                        changed = true;
                    }
                }
                if changed {
                    f(entity, table, index);
                }
            }
        }
    }

    pub fn query_entities(&self, mask: u64) -> impl Iterator<Item = Entity> + '_ {
        debug_assert_eq!(
            mask & !self.registry.all_components_mask(),
            0,
            "query_entities takes component masks only"
        );
        self.tables
            .iter()
            .filter(move |table| table.mask & mask == mask)
            .flat_map(|table| table.entity_indices.iter().copied())
    }

    pub fn query_entities_changed(&self, mask: u64) -> impl Iterator<Item = Entity> + '_ {
        self.query_entities_changed_since(mask, self.last_tick)
    }

    pub fn query_entities_changed_since(
        &self,
        mask: u64,
        since_tick: u32,
    ) -> impl Iterator<Item = Entity> + '_ {
        debug_assert_eq!(
            mask & !self.registry.all_components_mask(),
            0,
            "changed queries take component masks only"
        );
        self.tables
            .iter()
            .filter(move |table| {
                table.mask & mask == mask
                    && table.columns.iter().any(|column| {
                        mask & (1u64 << column.component_index) != 0
                            && tick_is_newer(column.peak_changed, since_tick)
                    })
            })
            .flat_map(move |table| {
                table
                    .entity_indices
                    .iter()
                    .enumerate()
                    .filter(move |(index, _)| {
                        table.columns.iter().any(|column| {
                            mask & (1u64 << column.component_index) != 0
                                && tick_is_newer(column.changed[*index], since_tick)
                        })
                    })
                    .map(|(_, &entity)| entity)
            })
    }

    #[cfg(not(target_family = "wasm"))]
    pub fn par_for_each_mut<F>(&mut self, include: u64, exclude: u64, f: F)
    where
        F: Fn(Entity, &mut DynComponentArrays, usize) + Send + Sync,
    {
        use crate::rayon::prelude::*;

        let Some((component_include, component_exclude, tag_include, tag_exclude)) =
            self.split_masks(include, exclude)
        else {
            return;
        };

        let tags = &self.tags;
        self.tables
            .par_iter_mut()
            .filter(|table| {
                table.mask & component_include == component_include
                    && table.mask & component_exclude == 0
            })
            .for_each(|table| {
                for index in 0..table.entity_indices.len() {
                    let entity = table.entity_indices[index];
                    if (tag_include != 0 || tag_exclude != 0)
                        && !tags_match(tags, entity, tag_include, tag_exclude)
                    {
                        continue;
                    }
                    f(entity, table, index);
                }
            });
    }

    pub fn step(&mut self) {
        self.events.update();
        self.last_tick = self.current_tick;
        self.current_tick = self.current_tick.wrapping_add(1);
    }

    pub fn send<T: Send + Sync + 'static>(&mut self, event: T) {
        self.events.send(event);
    }

    /// Everything still buffered for `T`, oldest first. An unregistered event
    /// type reads as empty, which is indistinguishable from registered and
    /// empty.
    pub fn read_events<T: Send + Sync + 'static>(&self) -> &[T] {
        self.events.read::<T>()
    }

    pub fn read_events_since<T: Send + Sync + 'static>(&self, cursor: u64) -> &[T] {
        self.events.read_since::<T>(cursor)
    }

    /// The exactly-once read: yields events sent after the cursor and
    /// advances it past them, so a handler calling this every frame sees
    /// each event once. Events stay buffered for two frames, so
    /// [`read_events`](Self::read_events) re-delivers on the second frame;
    /// keep one `u64` cursor per consumer and reach for this by default.
    pub fn consume_events<T: Send + Sync + 'static>(&self, cursor: &mut u64) -> &[T] {
        self.events.consume::<T>(cursor)
    }

    pub fn event_sequence<T: Send + Sync + 'static>(&self) -> u64 {
        self.events.sequence::<T>()
    }

    pub fn trim_events<T: Send + Sync + 'static>(&mut self, up_to_sequence: u64) {
        self.events.trim::<T>(up_to_sequence);
    }

    pub fn clear_events<T: Send + Sync + 'static>(&mut self) {
        self.events.clear::<T>();
    }

    pub fn insert_resource<T: Send + Sync + 'static>(&mut self, value: T) {
        self.resources.insert(value);
    }

    pub fn resource<T: Send + Sync + 'static>(&self) -> Option<&T> {
        self.resources.get::<T>()
    }

    pub fn resource_mut<T: Send + Sync + 'static>(&mut self) -> Option<&mut T> {
        self.resources.get_mut::<T>()
    }

    /// [`resource`](Self::resource) for resources that must exist: panics
    /// with the type name instead of returning `Option`, so call sites for
    /// engine-style singletons stay free of `unwrap`.
    pub fn expect_resource<T: Send + Sync + 'static>(&self) -> &T {
        self.resource::<T>().unwrap_or_else(|| {
            panic!(
                "expect_resource requires {} to be present",
                std::any::type_name::<T>()
            )
        })
    }

    pub fn expect_resource_mut<T: Send + Sync + 'static>(&mut self) -> &mut T {
        self.resource_mut::<T>().unwrap_or_else(|| {
            panic!(
                "expect_resource_mut requires {} to be present",
                std::any::type_name::<T>()
            )
        })
    }

    pub fn remove_resource<T: Send + Sync + 'static>(&mut self) -> Option<T> {
        self.resources.remove::<T>()
    }

    /// Takes `R` out of the world, runs the closure with the world and the
    /// resource as independent borrows, then puts the resource back. This is
    /// the take/put pattern for systems that mutate both a resource and the
    /// world in one pass; the resource is absent from the world inside the
    /// closure and is reinserted even when the closure panics, before the
    /// panic resumes. Panics if `R` is not present. For several resources at
    /// once, use [`resources_scope`](Self::resources_scope).
    ///
    /// A host that wraps this world in a larger state struct cannot lend
    /// that wrapper through this method, because the closure receives only
    /// the `DynWorld`. Implement [`ResourceHost`] on the wrapper and use
    /// the free [`resource_scope()`] form, whose closure receives the host
    /// itself.
    pub fn resource_scope<R: Send + Sync + 'static, T>(
        &mut self,
        f: impl FnOnce(&mut DynWorld, &mut R) -> T,
    ) -> T {
        resource_scope(self, f)
    }

    /// The tuple form of [`resource_scope`](Self::resource_scope): takes
    /// every resource in the tuple out of the world, runs the closure with
    /// the world and the tuple as independent borrows, and puts them all
    /// back, even when the closure panics. Destructure the tuple in the
    /// closure parameter. Panics before touching anything if a resource is
    /// missing or a type repeats.
    ///
    /// ```rust
    /// # use freecs::dynamic::DynWorld;
    /// # #[derive(Default, Clone, Debug, PartialEq)]
    /// # struct Position { x: f32, y: f32 }
    /// struct DeltaTime(f32);
    /// struct Score(u32);
    ///
    /// let mut world = DynWorld::new();
    /// world.insert_resource(DeltaTime(0.5));
    /// world.insert_resource(Score(0));
    /// # world.spawn((Position { x: 1.0, y: 0.0 },));
    ///
    /// world.resources_scope(|world, (delta_time, score): &mut (DeltaTime, Score)| {
    ///     score.0 += world
    ///         .query_ref::<(&Position,)>()
    ///         .iter()
    ///         .filter(|(_entity, (position,))| position.x * delta_time.0 > 0.25)
    ///         .count() as u32;
    /// });
    ///
    /// assert_eq!(world.resource::<Score>().unwrap().0, 1);
    /// assert_eq!(world.resource::<DeltaTime>().unwrap().0, 0.5);
    /// ```
    pub fn resources_scope<B: ResourceBundle, T>(
        &mut self,
        f: impl FnOnce(&mut DynWorld, &mut B) -> T,
    ) -> T {
        resources_scope(self, f)
    }

    pub fn queue_spawn_entities(&mut self, mask: u64, count: usize) {
        self.command_buffer
            .push(DynCommand::SpawnEntities { mask, count });
    }

    pub fn queue_despawn_entity(&mut self, entity: Entity) {
        self.command_buffer.push(DynCommand::DespawnEntity(entity));
    }

    pub fn queue_despawn_entities(&mut self, entities: Vec<Entity>) {
        self.command_buffer
            .push(DynCommand::DespawnEntities(entities));
    }

    pub fn queue_add_components(&mut self, entity: Entity, mask: u64) {
        self.command_buffer
            .push(DynCommand::AddComponents(entity, mask));
    }

    pub fn queue_remove_components(&mut self, entity: Entity, mask: u64) {
        self.command_buffer
            .push(DynCommand::RemoveComponents(entity, mask));
    }

    pub fn queue_add_tag(&mut self, key: TagKey, entity: Entity) {
        self.command_buffer.push(DynCommand::AddTag(entity, key));
    }

    pub fn queue_remove_tag(&mut self, key: TagKey, entity: Entity) {
        self.command_buffer.push(DynCommand::RemoveTag(entity, key));
    }

    pub fn queue_add_tag_type<T: 'static>(&mut self, entity: Entity) {
        let key = self.tag_key::<T>();
        self.queue_add_tag(key, entity);
    }

    pub fn queue_remove_tag_type<T: 'static>(&mut self, entity: Entity) {
        let key = self.tag_key::<T>();
        self.queue_remove_tag(key, entity);
    }

    /// Queues a typed component write. The value is boxed with the command;
    /// registration happens at queue time so apply order cannot depend on it.
    pub fn queue_set<T: Send + Sync + Default + 'static>(&mut self, entity: Entity, value: T) {
        let key = self.component_key::<T>();
        self.command_buffer
            .push(DynCommand::Closure(Box::new(move |world| {
                world.set_keyed(key, entity, value);
            })));
    }

    /// Queues a bundle spawn and returns the entity handle immediately, so
    /// other queued commands and systems can reference it before it has
    /// rows. The handle is allocated now, alive with no components, and
    /// gains the bundle's components when
    /// [`apply_commands`](Self::apply_commands) runs.
    pub fn queue_spawn<B: Bundle + Send + Sync + 'static>(&mut self, bundle: B) -> Entity {
        let entity = self.allocator.allocate();
        self.queue(move |world| {
            if !world.is_alive(entity) {
                return;
            }
            let mask = B::component_mask(world);
            if !world.contains_entity(entity) {
                world.insert_row(entity, mask);
            }
            bundle.write(world, entity);
        });
        entity
    }

    /// Queues an arbitrary deferred mutation.
    pub fn queue(&mut self, command: impl FnOnce(&mut DynWorld) + Send + Sync + 'static) {
        self.command_buffer
            .push(DynCommand::Closure(Box::new(command)));
    }

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

    pub fn clear_commands(&mut self) {
        self.command_buffer.clear();
    }

    pub fn apply_commands(&mut self) {
        let commands = std::mem::take(&mut self.command_buffer);
        for command in commands {
            match command {
                DynCommand::SpawnEntities { mask, count } => {
                    self.spawn_entities(mask, count);
                }
                DynCommand::DespawnEntity(entity) => {
                    self.despawn_entities(&[entity]);
                }
                DynCommand::DespawnEntities(entities) => {
                    self.despawn_entities(&entities);
                }
                DynCommand::AddComponents(entity, mask) => {
                    self.add_components(entity, mask);
                }
                DynCommand::RemoveComponents(entity, mask) => {
                    self.remove_components(entity, mask);
                }
                DynCommand::AddTag(entity, key) => {
                    self.add_tag(key, entity);
                }
                DynCommand::RemoveTag(entity, key) => {
                    self.remove_tag(key, entity);
                }
                DynCommand::Closure(command) => {
                    command(self);
                }
            }
        }
    }

    /// The lazy typed tier: resolves or registers `T` and returns its key.
    pub fn component_key<T: Send + Sync + Default + 'static>(&mut self) -> ComponentKey<T> {
        self.registry.register::<T>()
    }

    /// Resolves `T`'s key without registering. Returns `None` for types this
    /// world has never seen.
    pub fn lookup_key<T: Send + Sync + Default + 'static>(&self) -> Option<ComponentKey<T>> {
        let &component_index = self.registry.components_by_type.get(&TypeId::of::<T>())?;
        Some(self.registry.key_for::<T>(component_index))
    }

    /// Typed read. Unregistered types read as absent.
    pub fn get<T: Send + Sync + Default + 'static>(&self, entity: Entity) -> Option<&T> {
        let key = self.lookup_key::<T>()?;
        self.get_keyed(key, entity)
    }

    pub fn get_mut<T: Send + Sync + Default + 'static>(
        &mut self,
        entity: Entity,
    ) -> Option<&mut T> {
        let key = self.component_key::<T>();
        self.get_mut_keyed(key, entity)
    }

    pub fn set<T: Send + Sync + Default + 'static>(&mut self, entity: Entity, value: T) {
        let key = self.component_key::<T>();
        self.set_keyed(key, entity, value);
    }

    pub fn remove<T: Send + Sync + Default + 'static>(&mut self, entity: Entity) -> bool {
        let key = self.component_key::<T>();
        self.remove_components(entity, key.mask)
    }

    pub fn has<T: Send + Sync + Default + 'static>(&self, entity: Entity) -> bool {
        self.get::<T>(entity).is_some()
    }

    /// Spawns one entity carrying the bundle's components, set to the given
    /// values. Bundle types register lazily.
    pub fn spawn<B: Bundle>(&mut self, bundle: B) -> Entity {
        let mask = B::component_mask(self);
        let entity = self.spawn_entities(mask, 1)[0];
        bundle.write(self, entity);
        entity
    }

    /// The typed bulk spawn: `count` entities each carrying a clone of the
    /// bundle. For per-entity initialization at batch speed, use the keyed
    /// [`spawn_batch`](Self::spawn_batch) instead.
    pub fn spawn_bundles<B: Bundle + Clone>(&mut self, bundle: B, count: usize) -> Vec<Entity> {
        let mask = B::component_mask(self);
        let entities = self.spawn_entities(mask, count);
        for &entity in &entities {
            bundle.clone().write(self, entity);
        }
        entities
    }

    /// Starts a typed query. Component types register lazily, borrow
    /// mutability comes from the tuple (`&T`, `&mut T`, and their `Option`
    /// forms), and mutable elements stamp change ticks per visited entity.
    /// Single-component queries can skip the tuple: `query::<&mut Position>()`.
    ///
    /// This method takes `&mut self` even for all-shared tuples, because
    /// lazy registration and the query cache mutate the world; when you only
    /// have `&world`, use [`query_ref`](Self::query_ref), which is also the
    /// form that returns a real iterator.
    pub fn query<Q: QueryTuple>(&mut self) -> DynQuery<'_, Q> {
        let include = Q::component_mask(self);
        DynQuery {
            world: self,
            include,
            exclude: 0,
            changed_mask: 0,
            added_mask: 0,
            element_masks: None,
            include_tag_sets: [None; 4],
            exclude_tag_sets: [None; 4],
            marker: PhantomData,
        }
    }

    /// Starts a read-only typed query on a shared world borrow. Tuples take
    /// `&T` and `Option<&T>` elements only, nothing registers, and a
    /// component type this world has never seen matches no entities. Unlike
    /// [`query`](Self::query), the result is a real [`Iterator`], so it
    /// composes with adapters and its items can be collected and outlive the
    /// iteration.
    pub fn query_ref<Q: ReadQueryTuple>(&self) -> DynQueryRef<'_, Q> {
        DynQueryRef {
            world: self,
            include: 0,
            exclude: 0,
            changed_mask: 0,
            added_mask: 0,
            resolved_masks: None,
            include_tag_sets: [None; 4],
            exclude_tag_sets: [None; 4],
            dead: false,
            marker: PhantomData,
        }
    }
}

/// A group of dynamic worlds over one shared entity allocator, the dynamic
/// counterpart of the macro's multi-world form. Each world carries its own
/// registry and full 64-bit mask space, so the group's component budget is
/// 64 per world rather than 64 total. One entity can hold rows in any
/// combination of worlds; despawning retires it everywhere and broadcasts
/// the bumped generation, so stale handles are refused in every world,
/// including worlds that never stored the entity.
///
/// Group tags live outside any world's mask space as plain sparse sets.
/// Filter per-world queries by them with
/// [`with_tag_set`](DynQuery::with_tag_set), or check membership directly.
///
/// The group keeps its own lifecycle log, the same two-log split as the
/// macro's multi-world form: this log records handle allocation (`Spawned`),
/// handle death anywhere (`Despawned`), and group tag flips, while each
/// member world's own structural log records that world's row history. Sync
/// world contents from the world logs and entity lifetime or group tags from
/// this one; a consumer merging both will see one entity spawn twice.
///
/// ```rust
/// use freecs::dynamic::{ComponentRegistry, DynEcs};
/// use freecs::StructuralChangeKind;
///
/// #[derive(Default, Clone, Debug)]
/// struct Position { x: f32 }
///
/// #[derive(Default, Clone, Debug)]
/// struct Sprite { id: u32 }
///
/// let mut ecs = DynEcs::new();
/// let core = ecs.add_world(ComponentRegistry::new());
/// let render = ecs.add_world(ComponentRegistry::new());
/// let selected = ecs.register_tag();
///
/// let entity = ecs.spawn();
/// ecs.worlds[core].set(entity, Position { x: 1.0 });
/// ecs.worlds[render].set(entity, Sprite { id: 7 });
/// ecs.add_tag(selected, entity);
///
/// assert_eq!(ecs.worlds[core].get::<Position>(entity).unwrap().x, 1.0);
/// assert!(ecs.despawn(entity));
/// assert!(ecs.worlds[render].get::<Sprite>(entity).is_none());
/// assert!(!ecs.has_tag(selected, entity));
///
/// // "Entity died anywhere" is one stream on the group, not a per-world
/// // question. Consumers keep a cursor and the owner trims consumed entries.
/// let mut cursor = 0;
/// let kinds: Vec<StructuralChangeKind> = ecs
///     .structural_changes_since(cursor)
///     .iter()
///     .map(|change| change.kind)
///     .collect();
/// assert_eq!(kinds, vec![
///     StructuralChangeKind::Spawned,
///     StructuralChangeKind::TagsAdded,
///     StructuralChangeKind::Despawned,
/// ]);
/// cursor = ecs.structural_sequence();
/// ecs.trim_structural_log(cursor);
/// assert!(ecs.structural_changes_since(0).is_empty());
/// ```
#[derive(Default)]
pub struct DynEcs {
    pub allocator: EntityAllocator,
    pub worlds: Vec<DynWorld>,
    pub tags: Vec<SparseTagSet>,
    pub structural_log: Vec<StructuralChange>,
    pub structural_sequence: u64,
    pub type_routes: HashMap<TypeId, usize>,
    pub tag_type_indices: HashMap<TypeId, usize>,
    pub tag_type_names: Vec<Option<String>>,
    pub resources: ResourceMap,
    pub events: EventBus,
}

impl DynEcs {
    pub fn new() -> Self {
        Self::default()
    }

    fn record_structural(&mut self, entity: Entity, kind: StructuralChangeKind, mask: u64) {
        if self.structural_log.len() >= STRUCTURAL_LOG_CAPACITY {
            self.structural_log.clear();
        }
        self.structural_sequence += 1;
        self.structural_log.push(StructuralChange {
            sequence: self.structural_sequence,
            entity,
            kind,
            mask,
        });
    }

    pub fn structural_sequence(&self) -> u64 {
        self.structural_sequence
    }

    /// The group-level lifecycle log: handle allocation (`Spawned` with mask
    /// 0), handle death anywhere (`Despawned` with mask 0), and group tag
    /// flips (`TagsAdded`/`TagsRemoved` carrying the tag index in the mask
    /// field, since group tags have no mask bits). Row-level history lives in
    /// each member world's own structural log, where an entity is `Spawned`
    /// with a component mask when its first components arrive there.
    pub fn structural_changes_since(&self, cursor: u64) -> &[StructuralChange] {
        let start = self
            .structural_log
            .partition_point(|change| change.sequence <= cursor);
        &self.structural_log[start..]
    }

    pub fn trim_structural_log(&mut self, up_to_sequence: u64) {
        let end = self
            .structural_log
            .partition_point(|change| change.sequence <= up_to_sequence);
        self.structural_log.drain(..end);
    }

    pub fn clear_structural_log(&mut self) {
        self.structural_log.clear();
    }

    /// Adds a world built from the given registry and returns its index.
    /// Grouped worlds insert rows for live handles they have never stored,
    /// which is what lets an entity gain components per world lazily.
    pub fn add_world(&mut self, registry: ComponentRegistry) -> usize {
        for info in &registry.components {
            for (index, world) in self.worlds.iter().enumerate() {
                assert!(
                    world.registry.component_by_name(info.type_name).is_none(),
                    "{} is already registered in member world {index};                      a component type must live in exactly one member world",
                    info.type_name
                );
            }
        }
        let mut world = DynWorld::from_registry(registry);
        world.insert_missing_rows = true;
        self.worlds.push(world);
        self.worlds.len() - 1
    }

    /// Allocates a handle with no rows anywhere. Give it components through
    /// any member world's `set`/`add_components`.
    pub fn spawn(&mut self) -> Entity {
        let entity = self.allocator.allocate();
        self.record_structural(entity, StructuralChangeKind::Spawned, 0);
        entity
    }

    /// Spawns one group entity carrying the bundle, with each component
    /// routed to the member world that registered its type, so a bundle can
    /// span worlds. Panics like [`set`](Self::set) if a component type is
    /// registered nowhere.
    pub fn spawn_with<B: Bundle>(&mut self, bundle: B) -> Entity {
        let entity = self.spawn();
        bundle.write_group(self, entity);
        entity
    }

    /// Which member world holds `T`, scanning members in index order and
    /// caching the answer in [`type_routes`](Self::type_routes). Returns
    /// `None` when no member world has registered `T`; group-typed access
    /// never registers lazily, because only a schema decides where a type
    /// lives.
    pub fn route<T: Send + Sync + Default + 'static>(&mut self) -> Option<usize> {
        if let Some(&index) = self.type_routes.get(&TypeId::of::<T>()) {
            return Some(index);
        }
        let index = route_world_scan(
            &self.worlds,
            |world| world.lookup_key::<T>().is_some(),
            std::any::type_name::<T>(),
        )?;
        self.type_routes.insert(TypeId::of::<T>(), index);
        Some(index)
    }

    fn route_ref<T: Send + Sync + Default + 'static>(&self) -> Option<usize> {
        if let Some(&index) = self.type_routes.get(&TypeId::of::<T>()) {
            return Some(index);
        }
        route_world_scan(
            &self.worlds,
            |world| world.lookup_key::<T>().is_some(),
            std::any::type_name::<T>(),
        )
    }

    /// Reads `T` from whichever member world holds it, no world index
    /// required.
    pub fn get<T: Send + Sync + Default + 'static>(&self, entity: Entity) -> Option<&T> {
        let index = self.route_ref::<T>()?;
        self.worlds[index].get::<T>(entity)
    }

    /// The mutable form of [`get`](Self::get); stamps change ticks exactly
    /// like the member world's accessor.
    pub fn get_mut<T: Send + Sync + Default + 'static>(
        &mut self,
        entity: Entity,
    ) -> Option<&mut T> {
        let index = self.route::<T>()?;
        self.worlds[index].get_mut::<T>(entity)
    }

    /// Writes `T` on the member world that registered it, adding the
    /// component if the entity lacks it. Panics if no member world has
    /// registered `T`: group-typed access never picks a world for a new
    /// type, that is a schema decision.
    pub fn set<T: Send + Sync + Default + 'static>(&mut self, entity: Entity, value: T) {
        let Some(index) = self.route::<T>() else {
            panic!(
                "{} is not registered in any member world; add it to a member schema first",
                std::any::type_name::<T>()
            );
        };
        self.worlds[index].set(entity, value);
    }

    /// Whether the entity carries `T` in whichever member world holds it.
    pub fn has<T: Send + Sync + Default + 'static>(&self, entity: Entity) -> bool {
        self.route_ref::<T>()
            .is_some_and(|index| self.worlds[index].has::<T>(entity))
    }

    /// Removes `T` from the member world that holds it. Returns false when
    /// the type is registered nowhere or the entity lacks it.
    pub fn remove<T: Send + Sync + Default + 'static>(&mut self, entity: Entity) -> bool {
        match self.route::<T>() {
            Some(index) => self.worlds[index].remove::<T>(entity),
            None => false,
        }
    }

    /// A typed query against the first member world where every required
    /// element of the tuple is registered; optional elements do not
    /// constrain the routing. Panics when no member world qualifies: a
    /// mutable query cannot pick a world to register types in, and a tuple
    /// spanning member worlds runs through
    /// [`query_join`](Self::query_join) instead.
    pub fn query<Q: QueryTuple>(&mut self) -> DynQuery<'_, Q> {
        let index = self
            .worlds
            .iter()
            .position(|world| Q::routing_match(world))
            .expect(
                "no member world registers every required component of the query tuple; \
                 tuples spanning member worlds run through query_join",
            );
        self.worlds[index].query::<Q>()
    }

    /// A typed query whose tuple may span member worlds, joined by entity.
    /// One world drives the iteration at full slice speed, the world
    /// holding every mutable element; the other worlds resolve their
    /// elements per entity at `get` speed, read-only, skipping entities
    /// that lack a required foreign component. Mutable elements in two
    /// different worlds panic at [`for_each`](DynJoin::for_each): mutate
    /// your own state, read theirs, or co-locate the types in one schema
    /// when a hot loop needs slice speed for everything. A tuple that
    /// resolves to a single world degenerates to a plain scan of it.
    pub fn query_join<Q: QueryTuple>(&mut self) -> DynJoin<'_, Q> {
        DynJoin {
            ecs: self,
            include_tag_types: [None; 4],
            exclude_tag_types: [None; 4],
            changed_lookups: [None; 4],
            added_lookups: [None; 4],
            marker: PhantomData,
        }
    }

    /// The read-only cross-world join, a real [`Iterator`] on `&self`:
    /// items borrow the group, the driver world walks its tables, and
    /// foreign elements resolve per entity, read-only like every join
    /// element. Unresolvable routing or filters degrade to an empty
    /// iterator, matching [`query_ref`](Self::query_ref).
    pub fn query_join_ref<Q: ReadQueryTuple>(&self) -> DynJoinRef<'_, Q> {
        DynJoinRef {
            ecs: self,
            include_tag_types: [None; 4],
            exclude_tag_types: [None; 4],
            changed_lookups: [None; 4],
            added_lookups: [None; 4],
            marker: PhantomData,
        }
    }

    /// The read-only routed query. When no member world registers every
    /// required element the query is empty rather than a panic, matching
    /// [`DynWorld::query_ref`]'s graceful degradation.
    pub fn query_ref<Q: ReadQueryTuple>(&self) -> DynQueryRef<'_, Q> {
        match self.worlds.iter().position(|world| Q::routing_match(world)) {
            Some(index) => self.worlds[index].query_ref::<Q>(),
            None => {
                let mut query = self.worlds[0].query_ref::<Q>();
                query.dead = true;
                query
            }
        }
    }

    /// Advances the group frame: expires group events past their two-frame
    /// window and steps every member world, so one call at frame end drives
    /// group-level and world-level event lifetimes and change windows
    /// together. This call replaces per-member stepping; call either this
    /// or the members' own `step`s each frame, never both, or change
    /// windows and event expiry advance twice per frame.
    pub fn step(&mut self) {
        self.events.update();
        for world in &mut self.worlds {
            world.step();
        }
    }

    /// Sends a group-level event, the shared channel for events that cross
    /// member-world (and plugin) boundaries; world-local events stay on
    /// [`DynWorld::send`]. Same two-frame buffer, expired by
    /// [`step`](Self::step).
    pub fn send<T: Send + Sync + 'static>(&mut self, event: T) {
        self.events.send(event);
    }

    /// Everything still buffered for `T` at the group level, oldest first.
    pub fn read_events<T: Send + Sync + 'static>(&self) -> &[T] {
        self.events.read::<T>()
    }

    pub fn read_events_since<T: Send + Sync + 'static>(&self, cursor: u64) -> &[T] {
        self.events.read_since::<T>(cursor)
    }

    /// The exactly-once group read: yields events sent after the cursor and
    /// advances it past them. Keep one `u64` cursor per consumer.
    pub fn consume_events<T: Send + Sync + 'static>(&self, cursor: &mut u64) -> &[T] {
        self.events.consume::<T>(cursor)
    }

    pub fn event_sequence<T: Send + Sync + 'static>(&self) -> u64 {
        self.events.sequence::<T>()
    }

    pub fn clear_events<T: Send + Sync + 'static>(&mut self) {
        self.events.clear::<T>();
    }

    /// Inserts a group-level resource, the home for state shared across
    /// member worlds and plugins; world-local resources stay on
    /// [`DynWorld::insert_resource`].
    pub fn insert_resource<T: Send + Sync + 'static>(&mut self, value: T) {
        self.resources.insert(value);
    }

    pub fn resource<T: Send + Sync + 'static>(&self) -> Option<&T> {
        self.resources.get::<T>()
    }

    pub fn resource_mut<T: Send + Sync + 'static>(&mut self) -> Option<&mut T> {
        self.resources.get_mut::<T>()
    }

    /// [`resource`](Self::resource) for resources that must exist: panics
    /// with the type name instead of returning `Option`.
    pub fn expect_resource<T: Send + Sync + 'static>(&self) -> &T {
        self.resource::<T>().unwrap_or_else(|| {
            panic!(
                "expect_resource requires {} to be present",
                std::any::type_name::<T>()
            )
        })
    }

    /// The mutable form of [`expect_resource`](Self::expect_resource).
    pub fn expect_resource_mut<T: Send + Sync + 'static>(&mut self) -> &mut T {
        match self.resource_mut::<T>() {
            Some(resource) => resource,
            None => panic!(
                "expect_resource_mut requires {} to be present",
                std::any::type_name::<T>()
            ),
        }
    }

    pub fn remove_resource<T: Send + Sync + 'static>(&mut self) -> Option<T> {
        self.resources.remove::<T>()
    }

    /// Takes a group resource out, runs the closure with the group and the
    /// resource as independent borrows, then puts it back, even when the
    /// closure panics. Panics if `R` is not present.
    ///
    /// The closure receives the bare `DynEcs`, so a host that wraps the
    /// group in its own state struct implements [`ResourceHost`] and uses
    /// the free [`resource_scope()`] form, whose closure receives the host
    /// itself.
    pub fn resource_scope<R: Send + Sync + 'static, T>(
        &mut self,
        f: impl FnOnce(&mut DynEcs, &mut R) -> T,
    ) -> T {
        resource_scope(self, f)
    }

    /// The tuple form of [`resource_scope`](Self::resource_scope), same
    /// semantics as [`DynWorld::resources_scope`].
    pub fn resources_scope<B: ResourceBundle, T>(
        &mut self,
        f: impl FnOnce(&mut DynEcs, &mut B) -> T,
    ) -> T {
        resources_scope(self, f)
    }

    /// [`add_world`](Self::add_world) with the index asserted against the
    /// constant a schema pairs with this member, replacing the hand-written
    /// add-then-assert dance. Panics when members register out of
    /// declaration order.
    pub fn add_world_at(&mut self, expected_index: usize, registry: ComponentRegistry) -> usize {
        let index = self.add_world(registry);
        assert_eq!(
            index, expected_index,
            "member world registered out of declaration order"
        );
        index
    }

    pub fn spawn_count(&mut self, count: usize) -> Vec<Entity> {
        let mut entities = Vec::new();
        self.allocator.allocate_batch(count, &mut entities);
        for &entity in &entities {
            self.record_structural(entity, StructuralChangeKind::Spawned, 0);
        }
        entities
    }

    /// Spawns entities with rows in one member world. The handles land in
    /// the group lifecycle log as `Spawned` with mask 0; the component mask
    /// lands in that world's own structural log.
    pub fn spawn_entities(&mut self, world_index: usize, mask: u64, count: usize) -> Vec<Entity> {
        let entities = self.worlds[world_index].spawn_entities_in(&mut self.allocator, mask, count);
        for &entity in &entities {
            self.record_structural(entity, StructuralChangeKind::Spawned, 0);
        }
        entities
    }

    pub fn is_alive(&self, entity: Entity) -> bool {
        self.allocator.is_alive(entity)
    }

    /// Despawns the entity across every world, dropping its group tags.
    /// Returns false for stale or already-despawned handles. Retirement
    /// broadcasts the bumped generation into every world's location table,
    /// 16 bytes per despawned id per world, which is what makes stale writes
    /// refusable everywhere.
    pub fn despawn(&mut self, entity: Entity) -> bool {
        if !self.allocator.deallocate(entity) {
            return false;
        }
        for world in &mut self.worlds {
            world.retire_entity(entity);
        }
        for tag_set in &mut self.tags {
            tag_set.remove(entity);
        }
        self.record_structural(entity, StructuralChangeKind::Despawned, 0);
        true
    }

    pub fn despawn_entities(&mut self, entities: &[Entity]) -> Vec<Entity> {
        let mut despawned = Vec::with_capacity(entities.len());
        for &entity in entities {
            if self.despawn(entity) {
                despawned.push(entity);
            }
        }
        despawned
    }

    /// Despawns an entity and every descendant reachable through [`ChildOf`]
    /// links in any member world, breadth-first over on-demand scans. This
    /// is the grouped form of [`DynWorld::despawn_recursive`]: each entity
    /// dies through the group, so retirement broadcasts into every member
    /// world, group tags drop, and the lifecycle log records each death.
    /// Link cycles are tolerated, each entity despawns once. Returns the
    /// despawned entities.
    pub fn despawn_recursive(&mut self, root: Entity) -> Vec<Entity> {
        let mut pending = vec![root];
        let mut to_despawn: Vec<Entity> = Vec::new();
        while let Some(parent) = pending.pop() {
            if to_despawn.contains(&parent) {
                continue;
            }
            to_despawn.push(parent);
            for world in &self.worlds {
                pending.extend(world.children(parent));
            }
        }
        self.despawn_entities(&to_despawn)
    }

    /// Registers a group-level tag and returns its index. Group tags have no
    /// mask bit; they filter queries by set reference.
    pub fn register_tag(&mut self) -> usize {
        self.tags.push(SparseTagSet::default());
        self.tag_type_names.push(None);
        self.tags.len() - 1
    }

    pub fn add_tag(&mut self, tag_index: usize, entity: Entity) {
        if self.allocator.is_alive(entity) && self.tags[tag_index].insert(entity) {
            self.record_structural(entity, StructuralChangeKind::TagsAdded, tag_index as u64);
        }
    }

    pub fn remove_tag(&mut self, tag_index: usize, entity: Entity) -> bool {
        let removed = self.tags[tag_index].remove(entity);
        if removed {
            self.record_structural(entity, StructuralChangeKind::TagsRemoved, tag_index as u64);
        }
        removed
    }

    pub fn has_tag(&self, tag_index: usize, entity: Entity) -> bool {
        self.tags[tag_index].contains(entity)
    }

    pub fn query_tag(&self, tag_index: usize) -> impl Iterator<Item = Entity> + '_ {
        self.tags[tag_index].iter()
    }

    /// The group-level census. See [`EcsStats`] for the fields.
    pub fn stats(&self) -> EcsStats {
        EcsStats {
            live_entities: self
                .allocator
                .slots
                .iter()
                .filter(|slot| slot.alive)
                .count(),
            free_ids: self.allocator.free_ids.len(),
            group_tag_count: self.tags.len(),
            group_structural_log_entries: self.structural_log.len(),
            group_resource_count: self.resources.entries.len(),
            group_event_channels: self.events.channel_count(),
            worlds: self.worlds.iter().map(|world| world.stats()).collect(),
        }
    }

    /// [`DynWorld::compact`] over every member world. Returns the total
    /// number of tables dropped.
    pub fn compact(&mut self) -> usize {
        self.worlds.iter_mut().map(|world| world.compact()).sum()
    }

    /// The group tag index for marker type `T`, registering the tag on
    /// first use. Group tags are the natural home for entity-scoped
    /// markers: they consume no member world's mask bits and need no world
    /// index to touch.
    pub fn tag_type_index<T: 'static>(&mut self) -> usize {
        if let Some(&index) = self.tag_type_indices.get(&TypeId::of::<T>()) {
            return index;
        }
        let name = std::any::type_name::<T>();
        let index = match self.scan_tag_type_names(name) {
            Some(index) => index,
            None => {
                let index = self.register_tag();
                self.tag_type_names[index] = Some(name.to_string());
                index
            }
        };
        self.tag_type_indices.insert(TypeId::of::<T>(), index);
        index
    }

    /// The group tag index for marker type `T` if it has been used, without
    /// registering it. Falls back to the persisted type names, so marker
    /// tags restored by [`DynEcs::from_snapshot`] resolve here before the
    /// `TypeId` map is rebuilt.
    pub fn lookup_tag_type<T: 'static>(&self) -> Option<usize> {
        if let Some(&index) = self.tag_type_indices.get(&TypeId::of::<T>()) {
            return Some(index);
        }
        self.scan_tag_type_names(std::any::type_name::<T>())
    }

    fn scan_tag_type_names(&self, name: &str) -> Option<usize> {
        self.tag_type_names
            .iter()
            .position(|stored| stored.as_deref() == Some(name))
    }

    /// Adds the marker type `T`'s group tag to an entity, registering the
    /// tag on first use.
    pub fn add_tag_type<T: 'static>(&mut self, entity: Entity) {
        let index = self.tag_type_index::<T>();
        self.add_tag(index, entity);
    }

    /// Removes the marker type `T`'s group tag from an entity. Unregistered
    /// marker types remove nothing.
    pub fn remove_tag_type<T: 'static>(&mut self, entity: Entity) -> bool {
        match self.lookup_tag_type::<T>() {
            Some(index) => self.remove_tag(index, entity),
            None => false,
        }
    }

    /// Whether an entity carries the marker type `T`'s group tag.
    /// Unregistered marker types read as absent.
    pub fn has_tag_type<T: 'static>(&self, entity: Entity) -> bool {
        match self.lookup_tag_type::<T>() {
            Some(index) => self.has_tag(index, entity),
            None => false,
        }
    }

    /// Iterates entities carrying the marker type `T`'s group tag.
    /// Unregistered marker types match nothing.
    pub fn query_tag_type<T: 'static>(&self) -> impl Iterator<Item = Entity> + '_ {
        self.lookup_tag_type::<T>()
            .into_iter()
            .flat_map(|index| self.tags[index].iter())
    }

    /// The marker type `T`'s group tag set, for composing into per-world
    /// typed queries with `with_tag_set`/`without_tag_set`. `None` until
    /// the tag's first use.
    pub fn tag_set_type<T: 'static>(&self) -> Option<&SparseTagSet> {
        self.lookup_tag_type::<T>().map(|index| &self.tags[index])
    }
}

#[cfg(feature = "snapshot")]
mod snapshot {
    use super::*;

    /// Column byte codec for one component type, plain function pointers
    /// like the rest of the registry's vtable. The built-in pair encodes the
    /// whole `Vec<T>` with postcard; any byte format works as long as encode
    /// and decode agree.
    /// Encodes one entity's component as codec bytes; `None` when absent.
    pub type EncodeValueFn = fn(&DynWorld, Entity) -> Option<Result<Vec<u8>, SnapshotError>>;

    #[derive(Clone, Copy)]
    pub struct ComponentCodec {
        pub encode_column: fn(&(dyn Any + Send + Sync)) -> Result<Vec<u8>, SnapshotError>,
        pub decode_column: fn(&[u8]) -> Result<ErasedColumn, SnapshotError>,
        pub encode_value: EncodeValueFn,
        pub apply_value: fn(&mut DynWorld, Entity, &[u8]) -> Result<(), SnapshotError>,
    }

    pub(super) fn encode_value_postcard<T>(
        world: &DynWorld,
        entity: Entity,
    ) -> Option<Result<Vec<u8>, SnapshotError>>
    where
        T: serde::Serialize + Send + Sync + Default + 'static,
    {
        world.get::<T>(entity).map(|value| {
            postcard::to_allocvec(value).map_err(|error| SnapshotError::Codec(error.to_string()))
        })
    }

    pub(super) fn apply_value_postcard<T>(
        world: &mut DynWorld,
        entity: Entity,
        bytes: &[u8],
    ) -> Result<(), SnapshotError>
    where
        T: serde::de::DeserializeOwned + Send + Sync + Default + 'static,
    {
        let value: T =
            postcard::from_bytes(bytes).map_err(|error| SnapshotError::Codec(error.to_string()))?;
        world.set(entity, value);
        Ok(())
    }

    pub(super) fn encode_column_postcard<T>(
        column: &(dyn Any + Send + Sync),
    ) -> Result<Vec<u8>, SnapshotError>
    where
        T: serde::Serialize + Send + Sync + Default + 'static,
    {
        postcard::to_allocvec(column_vec::<T>(column))
            .map_err(|error| SnapshotError::Codec(error.to_string()))
    }

    pub(super) fn decode_column_postcard<T>(bytes: &[u8]) -> Result<ErasedColumn, SnapshotError>
    where
        T: serde::de::DeserializeOwned + Send + Sync + Default + 'static,
    {
        let column: Vec<T> =
            postcard::from_bytes(bytes).map_err(|error| SnapshotError::Codec(error.to_string()))?;
        Ok(Box::new(column))
    }

    #[derive(Debug, Clone, PartialEq)]
    pub enum SnapshotError {
        /// A component present in a table has no registered codec.
        MissingCodec(&'static str),
        /// The registry's component names or order do not match the snapshot.
        SchemaMismatch { expected: String, found: String },
        /// A column failed to encode or decode.
        Codec(String),
        /// No registered component carries the requested type name.
        UnknownComponent(String),
        /// A value write named an entity that is not alive.
        DeadEntity,
    }

    impl std::fmt::Display for SnapshotError {
        fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            match self {
                SnapshotError::MissingCodec(type_name) => {
                    write!(formatter, "component {type_name} has no snapshot codec")
                }
                SnapshotError::SchemaMismatch { expected, found } => write!(
                    formatter,
                    "registry schema mismatch: snapshot has {expected}, registry has {found}"
                ),
                SnapshotError::Codec(message) => write!(formatter, "codec error: {message}"),
                SnapshotError::UnknownComponent(name) => {
                    write!(formatter, "no registered component is named {name}")
                }
                SnapshotError::DeadEntity => {
                    write!(formatter, "the entity is not alive")
                }
            }
        }
    }

    impl std::error::Error for SnapshotError {}

    /// One archetype table's serialized form: the mask, the entity handles,
    /// and one postcard-or-custom byte payload per column in ascending bit
    /// order.
    #[derive(serde::Serialize, serde::Deserialize)]
    pub struct DynTableSnapshot {
        pub mask: u64,
        pub entities: Vec<Entity>,
        pub columns: Vec<Vec<u8>>,
    }

    /// A serializable image of a [`DynWorld`]: schema names for validation,
    /// allocator state, tables, tag memberships, and tick counters. Events,
    /// pending commands, and the structural log are transient and not
    /// captured. Serialize this with any serde format.
    #[derive(serde::Serialize, serde::Deserialize)]
    pub struct DynWorldSnapshot {
        pub component_types: Vec<String>,
        pub allocator: EntityAllocator,
        pub tables: Vec<DynTableSnapshot>,
        pub tags: Vec<Vec<Entity>>,
        pub current_tick: u32,
        pub last_tick: u32,
    }

    /// A serializable image of a [`DynEcs`]: the shared allocator, one world
    /// snapshot per member, and group tag memberships.
    #[derive(serde::Serialize, serde::Deserialize)]
    pub struct DynEcsSnapshot {
        pub allocator: EntityAllocator,
        pub worlds: Vec<DynWorldSnapshot>,
        pub tags: Vec<Vec<Entity>>,
        pub tag_type_names: Vec<Option<String>>,
    }

    /// Rebuilds the retirement stamps a despawn broadcast would have left,
    /// from allocator liveness: dead ids stamp the next generation, live ids
    /// stamp their current one, so stale-handle refusal survives a restore
    /// even for entities that never had a row in this world.
    fn stamp_retirements(world: &mut DynWorld, slots: &[crate::EntitySlot]) {
        for (id, slot) in slots.iter().enumerate() {
            let id = id as u32;
            let expected_generation = if slot.alive {
                slot.generation
            } else {
                slot.generation.wrapping_add(1)
            };
            let needs_stamp = match world.entity_locations.get(id) {
                None => true,
                Some(location) => !location.allocated,
            };
            if needs_stamp {
                world.entity_locations.ensure_slot(id, expected_generation);
            }
        }
    }

    impl DynWorld {
        fn value_codec(&self, name: &str) -> Result<&ComponentCodec, SnapshotError> {
            let info = self
                .registry
                .component_by_name(name)
                .ok_or_else(|| SnapshotError::UnknownComponent(name.to_string()))?;
            self.registry.codecs[info.mask.trailing_zeros() as usize]
                .as_ref()
                .ok_or(SnapshotError::MissingCodec(info.type_name))
        }

        /// Sets one component on an entity from codec bytes, resolved by
        /// registered type name, adding the component when the entity lacks
        /// it and stamping change ticks like any `set`. The wire format is
        /// whatever the component's codec chose, postcard for
        /// `register_serde` components; together with
        /// [`Self::get_component_by_name`] this is the value-level door for
        /// editors and protocols, no per-component dispatch required.
        /// Standalone worlds reject dead entities with
        /// [`SnapshotError::DeadEntity`]; a grouped member world defers
        /// liveness to its group, so route grouped writes through
        /// [`DynEcs::set_component_by_name`], which checks it.
        pub fn set_component_by_name(
            &mut self,
            entity: Entity,
            name: &str,
            bytes: &[u8],
        ) -> Result<(), SnapshotError> {
            if !self.insert_missing_rows && !self.is_alive(entity) {
                return Err(SnapshotError::DeadEntity);
            }
            let apply = self.value_codec(name)?.apply_value;
            apply(self, entity, bytes)
        }

        /// One component's codec bytes for an entity, resolved by registered
        /// type name. `Ok(None)` when the entity does not carry it.
        pub fn get_component_by_name(
            &self,
            entity: Entity,
            name: &str,
        ) -> Result<Option<Vec<u8>>, SnapshotError> {
            let encode = self.value_codec(name)?.encode_value;
            encode(self, entity).transpose()
        }

        /// Captures the world. Fails with [`SnapshotError::MissingCodec`] if
        /// any component stored in a table was registered without a codec.
        pub fn snapshot(&self) -> Result<DynWorldSnapshot, SnapshotError> {
            let mut tables = Vec::with_capacity(self.tables.len());
            for table in &self.tables {
                let mut columns = Vec::with_capacity(table.columns.len());
                for column in &table.columns {
                    let info = &self.registry.components[column.component_index as usize];
                    let codec = self.registry.codecs[column.component_index as usize]
                        .as_ref()
                        .ok_or(SnapshotError::MissingCodec(info.type_name))?;
                    columns.push((codec.encode_column)(column.data.as_ref())?);
                }
                tables.push(DynTableSnapshot {
                    mask: table.mask,
                    entities: table.entity_indices.clone(),
                    columns,
                });
            }

            Ok(DynWorldSnapshot {
                component_types: self
                    .registry
                    .components
                    .iter()
                    .map(|info| info.type_name.to_string())
                    .collect(),
                allocator: EntityAllocator {
                    next_id: self.allocator.next_id,
                    free_ids: self.allocator.free_ids.clone(),
                    slots: self.allocator.slots.clone(),
                },
                tables,
                tags: self
                    .tags
                    .iter()
                    .map(|tag_set| tag_set.iter().collect())
                    .collect(),
                current_tick: self.current_tick,
                last_tick: self.last_tick,
            })
        }

        /// Rebuilds a world from a snapshot over a registry with the same
        /// registration order. The registry may have additional components
        /// appended after the snapshot's schema; masks stay stable because
        /// bits are assigned in registration order. Every restored slot is
        /// stamped with the restored `current_tick`, so change-detection
        /// consumers see the whole world as changed on load.
        pub fn from_snapshot(
            registry: ComponentRegistry,
            snapshot: &DynWorldSnapshot,
        ) -> Result<DynWorld, SnapshotError> {
            for (index, expected) in snapshot.component_types.iter().enumerate() {
                let found = registry
                    .components
                    .get(index)
                    .map(|info| info.type_name)
                    .unwrap_or("<unregistered>");
                if expected != found {
                    return Err(SnapshotError::SchemaMismatch {
                        expected: expected.clone(),
                        found: found.to_string(),
                    });
                }
            }

            let mut world = DynWorld::from_registry(registry);
            world.allocator = EntityAllocator {
                next_id: snapshot.allocator.next_id,
                free_ids: snapshot.allocator.free_ids.clone(),
                slots: snapshot.allocator.slots.clone(),
            };
            world.current_tick = snapshot.current_tick;
            world.last_tick = snapshot.last_tick;

            for table_snapshot in &snapshot.tables {
                let table_index = world.get_or_create_table(table_snapshot.mask);
                let table = &mut world.tables[table_index];
                table.entity_indices = table_snapshot.entities.clone();

                let mut column_payloads = table_snapshot.columns.iter();
                for column in &mut table.columns {
                    let info = &world.registry.components[column.component_index as usize];
                    let codec = world.registry.codecs[column.component_index as usize]
                        .as_ref()
                        .ok_or(SnapshotError::MissingCodec(info.type_name))?;
                    let payload = column_payloads.next().ok_or_else(|| {
                        SnapshotError::Codec("missing column payload".to_string())
                    })?;
                    column.data = (codec.decode_column)(payload)?;
                    let decoded_rows = (info.column_len)(column.data.as_ref());
                    if decoded_rows != table_snapshot.entities.len() {
                        return Err(SnapshotError::Codec(format!(
                            "column {} decoded {decoded_rows} rows for {} entities",
                            info.type_name,
                            table_snapshot.entities.len()
                        )));
                    }
                    column.changed = vec![snapshot.current_tick; table_snapshot.entities.len()];
                    column.peak_changed = snapshot.current_tick;
                    column.added = vec![snapshot.current_tick; table_snapshot.entities.len()];
                    column.peak_added = snapshot.current_tick;
                }

                for (array_index, &entity) in table_snapshot.entities.iter().enumerate() {
                    insert_location(
                        &mut world.entity_locations,
                        entity,
                        (table_index, array_index),
                    );
                }
            }

            stamp_retirements(&mut world, &snapshot.allocator.slots);

            for (tag_index, tag_entities) in snapshot.tags.iter().enumerate() {
                while world.tags.len() <= tag_index {
                    world.tags.push(SparseTagSet::default());
                }
                for &entity in tag_entities {
                    world.tags[tag_index].insert(entity);
                }
            }

            Ok(world)
        }
    }

    /// Where a delta stream stands: the structural sequence and change tick
    /// a capture starts from. Take the first cursor right after the full
    /// snapshot that seeds a replica, then chain each delta's `to` cursor
    /// into the next capture.
    #[derive(Clone, Copy, Debug, Default, serde::Serialize, serde::Deserialize)]
    pub struct DeltaCursor {
        pub sequence: u64,
        pub tick: u32,
    }

    /// A serialized change-set for one world since a [`DeltaCursor`]:
    /// the structural entries in order, then one codec payload per changed
    /// component value, reflecting end-of-window state. Apply with
    /// [`DynWorld::apply_delta`] to a replica seeded from a snapshot of the
    /// same lineage; deltas must apply in unbroken cursor order, the same
    /// trust boundary snapshots carry.
    #[derive(serde::Serialize, serde::Deserialize)]
    pub struct DynWorldDelta {
        pub since: DeltaCursor,
        pub to: DeltaCursor,
        pub structural: Vec<StructuralChange>,
        pub values: Vec<(Entity, u32, Vec<u8>)>,
    }

    /// The group form: the group's own structural window (handle lifecycle
    /// and group tags) plus one [`DynWorldDelta`] per member.
    #[derive(serde::Serialize, serde::Deserialize)]
    pub struct DynEcsDelta {
        pub group_since: u64,
        pub group_to: u64,
        pub group_structural: Vec<StructuralChange>,
        pub tag_type_names: Vec<Option<String>>,
        pub worlds: Vec<DynWorldDelta>,
    }

    /// The group cursor: the group sequence plus one world cursor per
    /// member.
    #[derive(Clone, Debug, Default, serde::Serialize, serde::Deserialize)]
    pub struct DynEcsDeltaCursor {
        pub group_sequence: u64,
        pub worlds: Vec<DeltaCursor>,
    }

    fn structural_window(
        log: &[StructuralChange],
        latest_sequence: u64,
        since_sequence: u64,
    ) -> Result<Vec<StructuralChange>, SnapshotError> {
        let start = log.partition_point(|change| change.sequence <= since_sequence);
        let window = &log[start..];
        match window.first() {
            Some(first) => {
                if first.sequence != since_sequence + 1 {
                    return Err(SnapshotError::Codec(format!(
                        "structural log gap: delta cursor at {since_sequence}, oldest retained \
                         entry is {}; reseed the replica from a full snapshot",
                        first.sequence
                    )));
                }
            }
            None => {
                if latest_sequence > since_sequence {
                    return Err(SnapshotError::Codec(format!(
                        "structural log gap: delta cursor at {since_sequence}, log trimmed \
                         through {latest_sequence}; reseed the replica from a full snapshot",
                    )));
                }
            }
        }
        Ok(window.to_vec())
    }

    impl DynWorld {
        /// The cursor a delta stream starts from, taken right after the
        /// full snapshot that seeds the replica. Fences the change window
        /// with [`increment_tick`](Self::increment_tick), so writes made
        /// after this call land in the first delta; without the fence,
        /// same-tick writes would silently miss it.
        pub fn delta_cursor(&mut self) -> DeltaCursor {
            let cursor = DeltaCursor {
                sequence: self.structural_sequence,
                tick: self.current_tick,
            };
            self.increment_tick();
            cursor
        }

        /// Captures everything that changed since the cursor as a
        /// serialized change-set, then fences the change window with
        /// [`increment_tick`](Self::increment_tick) so later writes land in
        /// the next delta. Fails with a gap error when the structural log
        /// was trimmed or overflowed past the cursor (reseed from a full
        /// snapshot), and with [`SnapshotError::MissingCodec`] when a
        /// component without a codec changed inside the window.
        pub fn delta_since(
            &mut self,
            cursor: &DeltaCursor,
        ) -> Result<DynWorldDelta, SnapshotError> {
            let structural = structural_window(
                &self.structural_log,
                self.structural_sequence,
                cursor.sequence,
            )?;

            let mut values = Vec::new();
            for (component_index, info) in self.registry.components.iter().enumerate() {
                let mut changed = self
                    .query_entities_changed_since(info.mask, cursor.tick)
                    .peekable();
                match &self.registry.codecs[component_index] {
                    Some(codec) => {
                        for entity in changed {
                            if let Some(bytes) = (codec.encode_value)(self, entity) {
                                values.push((entity, component_index as u32, bytes?));
                            }
                        }
                    }
                    None => {
                        if changed.peek().is_some() {
                            return Err(SnapshotError::MissingCodec(info.type_name));
                        }
                    }
                }
            }

            let to = DeltaCursor {
                sequence: self.structural_sequence,
                tick: self.current_tick,
            };
            self.increment_tick();
            Ok(DynWorldDelta {
                since: *cursor,
                to,
                structural,
                values,
            })
        }

        /// Replays a delta onto a replica: structural entries in order
        /// (spawns revive the exact handle, despawns retire it, component
        /// and tag changes reapply), then the changed component values
        /// through their codecs. The replica must be seeded from a snapshot
        /// of the same lineage and receive every delta in cursor order;
        /// like snapshots, delta payloads are a trust boundary.
        pub fn apply_delta(&mut self, delta: &DynWorldDelta) -> Result<(), SnapshotError> {
            for change in &delta.structural {
                match change.kind {
                    StructuralChangeKind::Spawned => {
                        self.allocator.revive(change.entity);
                        if change.mask != 0 {
                            self.insert_row(change.entity, change.mask);
                        }
                    }
                    StructuralChangeKind::Despawned => {
                        self.despawn_entities(&[change.entity]);
                    }
                    StructuralChangeKind::ComponentsAdded => {
                        self.add_components(change.entity, change.mask);
                    }
                    StructuralChangeKind::ComponentsRemoved => {
                        self.remove_components(change.entity, change.mask);
                    }
                    StructuralChangeKind::TagsAdded => {
                        let tag_index = change.mask.leading_zeros();
                        while self.tags.len() <= tag_index as usize {
                            self.tags.push(SparseTagSet::default());
                        }
                        let key = self.registry.tag_key_for(tag_index);
                        self.add_tag(key, change.entity);
                    }
                    StructuralChangeKind::TagsRemoved => {
                        let tag_index = change.mask.leading_zeros();
                        if (tag_index as usize) < self.tags.len() {
                            let key = self.registry.tag_key_for(tag_index);
                            self.remove_tag(key, change.entity);
                        }
                    }
                }
            }

            for (entity, component_index, bytes) in &delta.values {
                let info = self
                    .registry
                    .components
                    .get(*component_index as usize)
                    .ok_or_else(|| {
                        SnapshotError::UnknownComponent(format!(
                            "component index {component_index}"
                        ))
                    })?;
                let codec = self.registry.codecs[*component_index as usize]
                    .as_ref()
                    .ok_or(SnapshotError::MissingCodec(info.type_name))?;
                (codec.apply_value)(self, *entity, bytes)?;
            }
            Ok(())
        }
    }

    impl DynEcs {
        /// The group cursor a delta stream starts from, fencing every
        /// member's change window like [`DynWorld::delta_cursor`].
        pub fn delta_cursor(&mut self) -> DynEcsDeltaCursor {
            DynEcsDeltaCursor {
                group_sequence: self.structural_sequence,
                worlds: self.worlds.iter_mut().map(DynWorld::delta_cursor).collect(),
            }
        }

        /// [`DynWorld::delta_since`] across the whole group: the group's
        /// structural window (handle lifecycle and group tags) plus one
        /// world delta per member, each fenced.
        pub fn delta_since(
            &mut self,
            cursor: &DynEcsDeltaCursor,
        ) -> Result<DynEcsDelta, SnapshotError> {
            if cursor.worlds.len() != self.worlds.len() {
                return Err(SnapshotError::SchemaMismatch {
                    expected: format!("{} member cursors", self.worlds.len()),
                    found: format!("{} member cursors", cursor.worlds.len()),
                });
            }
            let group_structural = structural_window(
                &self.structural_log,
                self.structural_sequence,
                cursor.group_sequence,
            )?;
            let mut worlds = Vec::with_capacity(self.worlds.len());
            for (world, world_cursor) in self.worlds.iter_mut().zip(&cursor.worlds) {
                worlds.push(world.delta_since(world_cursor)?);
            }
            Ok(DynEcsDelta {
                group_since: cursor.group_sequence,
                group_to: self.structural_sequence,
                group_structural,
                tag_type_names: self.tag_type_names.clone(),
                worlds,
            })
        }

        /// Replays a group delta: group handle lifecycle and group tags in
        /// order, then each member's delta.
        pub fn apply_delta(&mut self, delta: &DynEcsDelta) -> Result<(), SnapshotError> {
            if delta.worlds.len() != self.worlds.len() {
                return Err(SnapshotError::SchemaMismatch {
                    expected: format!("{} member deltas", self.worlds.len()),
                    found: format!("{} member deltas", delta.worlds.len()),
                });
            }
            for (index, name) in delta.tag_type_names.iter().enumerate() {
                while self.tag_type_names.len() <= index {
                    self.tags.push(SparseTagSet::default());
                    self.tag_type_names.push(None);
                }
                if name.is_some() && self.tag_type_names[index].is_none() {
                    self.tag_type_names[index] = name.clone();
                }
            }
            for change in &delta.group_structural {
                match change.kind {
                    StructuralChangeKind::Spawned => {
                        self.allocator.revive(change.entity);
                    }
                    StructuralChangeKind::Despawned => {
                        self.despawn(change.entity);
                    }
                    StructuralChangeKind::TagsAdded => {
                        let tag_index = change.mask as usize;
                        while self.tags.len() <= tag_index {
                            self.tags.push(SparseTagSet::default());
                            self.tag_type_names.push(None);
                        }
                        self.tags[tag_index].insert(change.entity);
                    }
                    StructuralChangeKind::TagsRemoved => {
                        if (change.mask as usize) < self.tags.len() {
                            self.tags[change.mask as usize].remove(change.entity);
                        }
                    }
                    StructuralChangeKind::ComponentsAdded
                    | StructuralChangeKind::ComponentsRemoved => {}
                }
            }
            for (world, world_delta) in self.worlds.iter_mut().zip(&delta.worlds) {
                world.apply_delta(world_delta)?;
            }
            Ok(())
        }
    }

    impl DynEcs {
        /// [`DynWorld::set_component_by_name`] routed to the member world
        /// whose registry carries the name.
        pub fn set_component_by_name(
            &mut self,
            entity: Entity,
            name: &str,
            bytes: &[u8],
        ) -> Result<(), SnapshotError> {
            if !self.is_alive(entity) {
                return Err(SnapshotError::DeadEntity);
            }
            let index = self
                .worlds
                .iter()
                .position(|world| world.registry.component_by_name(name).is_some())
                .ok_or_else(|| SnapshotError::UnknownComponent(name.to_string()))?;
            self.worlds[index].set_component_by_name(entity, name, bytes)
        }

        /// [`DynWorld::get_component_by_name`] routed to the member world
        /// whose registry carries the name.
        pub fn get_component_by_name(
            &self,
            entity: Entity,
            name: &str,
        ) -> Result<Option<Vec<u8>>, SnapshotError> {
            let index = self
                .worlds
                .iter()
                .position(|world| world.registry.component_by_name(name).is_some())
                .ok_or_else(|| SnapshotError::UnknownComponent(name.to_string()))?;
            self.worlds[index].get_component_by_name(entity, name)
        }

        pub fn snapshot(&self) -> Result<DynEcsSnapshot, SnapshotError> {
            let mut worlds = Vec::with_capacity(self.worlds.len());
            for world in &self.worlds {
                worlds.push(world.snapshot()?);
            }
            Ok(DynEcsSnapshot {
                allocator: EntityAllocator {
                    next_id: self.allocator.next_id,
                    free_ids: self.allocator.free_ids.clone(),
                    slots: self.allocator.slots.clone(),
                },
                worlds,
                tags: self
                    .tags
                    .iter()
                    .map(|tag_set| tag_set.iter().collect())
                    .collect(),
                tag_type_names: self.tag_type_names.clone(),
            })
        }

        /// Rebuilds a group from a snapshot and one registry per member
        /// world, in the same order the worlds were added. Snapshots do not
        /// carry structural logs, so the restored group and its worlds start
        /// with empty logs; treat a load as a full-sync boundary and rely on
        /// the restored slots being stamped changed.
        pub fn from_snapshot(
            registries: Vec<ComponentRegistry>,
            snapshot: &DynEcsSnapshot,
        ) -> Result<DynEcs, SnapshotError> {
            if registries.len() != snapshot.worlds.len() {
                return Err(SnapshotError::SchemaMismatch {
                    expected: format!("{} worlds", snapshot.worlds.len()),
                    found: format!("{} registries", registries.len()),
                });
            }

            let mut ecs = DynEcs::new();
            ecs.allocator = EntityAllocator {
                next_id: snapshot.allocator.next_id,
                free_ids: snapshot.allocator.free_ids.clone(),
                slots: snapshot.allocator.slots.clone(),
            };
            for (registry, world_snapshot) in registries.into_iter().zip(&snapshot.worlds) {
                let mut world = DynWorld::from_snapshot(registry, world_snapshot)?;
                world.insert_missing_rows = true;
                stamp_retirements(&mut world, &snapshot.allocator.slots);
                ecs.worlds.push(world);
            }
            for tag_entities in &snapshot.tags {
                let tag_index = ecs.register_tag();
                if let Some(name) = snapshot.tag_type_names.get(tag_index) {
                    ecs.tag_type_names[tag_index] = name.clone();
                }
                for &entity in tag_entities {
                    ecs.tags[tag_index].insert(entity);
                }
            }
            Ok(ecs)
        }
    }
}

#[cfg(feature = "snapshot")]
pub use snapshot::{
    ComponentCodec, DeltaCursor, DynEcsDelta, DynEcsDeltaCursor, DynEcsSnapshot, DynTableSnapshot,
    DynWorldDelta, DynWorldSnapshot, EncodeValueFn, SnapshotError,
};

#[cfg(feature = "snapshot")]
use snapshot::{
    apply_value_postcard, decode_column_postcard, encode_column_postcard, encode_value_postcard,
};

mod sealed {
    pub trait SealedElement {}
    pub trait SealedQueryTuple {}
    pub trait SealedBundle {}
    pub trait SealedResourceBundle {}
}

/// One element of a typed query tuple: `&T`, `&mut T`, `Option<&T>`, or
/// `Option<&mut T>`. Optional elements do not constrain which entities the
/// query visits; they yield `None` on entities missing the component.
pub trait QueryElement: sealed::SealedElement {
    type Fetch<'table>;
    type Item<'item>;
    const REQUIRED: bool;
    const MUTABLE: bool;
    fn component_mask(world: &mut DynWorld) -> u64;
    fn route_registered(world: &DynWorld) -> bool;
    fn foreign_item<'world>(world: &'world DynWorld, entity: Entity) -> Option<Self::Item<'world>>;
    fn fetch<'table>(
        slot: Option<&'table mut ColumnSlot>,
        current_tick: u32,
    ) -> Self::Fetch<'table>;
    fn changed_newer(fetch: &Self::Fetch<'_>, index: usize, since_tick: u32) -> bool;
    fn item<'fetch>(fetch: &'fetch mut Self::Fetch<'_>, index: usize) -> Self::Item<'fetch>;
    fn stamp_peaks(fetch: &mut Self::Fetch<'_>);
}

impl<T: Send + Sync + Default + 'static> sealed::SealedElement for &T {}

impl<T: Send + Sync + Default + 'static> QueryElement for &T {
    type Fetch<'table> = (&'table [T], &'table [u32]);
    type Item<'item> = &'item T;
    const REQUIRED: bool = true;
    const MUTABLE: bool = false;

    fn component_mask(world: &mut DynWorld) -> u64 {
        world.component_key::<T>().mask
    }

    fn route_registered(world: &DynWorld) -> bool {
        world.lookup_key::<T>().is_some()
    }

    fn foreign_item<'world>(world: &'world DynWorld, entity: Entity) -> Option<Self::Item<'world>> {
        world.get::<T>(entity)
    }

    fn fetch<'table>(
        slot: Option<&'table mut ColumnSlot>,
        _current_tick: u32,
    ) -> Self::Fetch<'table> {
        let slot = slot.expect("required query element column missing");
        (
            column_vec::<T>(slot.data.as_ref()).as_slice(),
            slot.changed.as_slice(),
        )
    }

    fn changed_newer(fetch: &Self::Fetch<'_>, index: usize, since_tick: u32) -> bool {
        tick_is_newer(fetch.1[index], since_tick)
    }

    fn item<'fetch>(fetch: &'fetch mut Self::Fetch<'_>, index: usize) -> Self::Item<'fetch> {
        &fetch.0[index]
    }

    fn stamp_peaks(_fetch: &mut Self::Fetch<'_>) {}
}

impl<T: Send + Sync + Default + 'static> sealed::SealedElement for &mut T {}

impl<T: Send + Sync + Default + 'static> QueryElement for &mut T {
    type Fetch<'table> = (&'table mut [T], &'table mut [u32], u32, &'table mut u32);
    type Item<'item> = &'item mut T;
    const REQUIRED: bool = true;
    const MUTABLE: bool = true;

    fn component_mask(world: &mut DynWorld) -> u64 {
        world.component_key::<T>().mask
    }

    fn route_registered(world: &DynWorld) -> bool {
        world.lookup_key::<T>().is_some()
    }

    fn foreign_item<'world>(
        _world: &'world DynWorld,
        _entity: Entity,
    ) -> Option<Self::Item<'world>> {
        unreachable!("cross-world queries mutate only driver-world components")
    }

    fn fetch<'table>(
        slot: Option<&'table mut ColumnSlot>,
        current_tick: u32,
    ) -> Self::Fetch<'table> {
        let slot = slot.expect("required query element column missing");
        let ColumnSlot {
            data,
            changed,
            peak_changed,
            ..
        } = slot;
        (
            column_vec_mut::<T>(data.as_mut()).as_mut_slice(),
            changed.as_mut_slice(),
            current_tick,
            peak_changed,
        )
    }

    fn changed_newer(fetch: &Self::Fetch<'_>, index: usize, since_tick: u32) -> bool {
        tick_is_newer(fetch.1[index], since_tick)
    }

    fn item<'fetch>(fetch: &'fetch mut Self::Fetch<'_>, index: usize) -> Self::Item<'fetch> {
        fetch.1[index] = fetch.2;
        &mut fetch.0[index]
    }

    fn stamp_peaks(fetch: &mut Self::Fetch<'_>) {
        *fetch.3 = fetch.2;
    }
}

impl<T: Send + Sync + Default + 'static> sealed::SealedElement for Option<&T> {}

impl<T: Send + Sync + Default + 'static> QueryElement for Option<&T> {
    type Fetch<'table> = Option<(&'table [T], &'table [u32])>;
    type Item<'item> = Option<&'item T>;
    const REQUIRED: bool = false;
    const MUTABLE: bool = false;

    fn component_mask(world: &mut DynWorld) -> u64 {
        world.component_key::<T>().mask
    }

    fn route_registered(world: &DynWorld) -> bool {
        world.lookup_key::<T>().is_some()
    }

    fn foreign_item<'world>(world: &'world DynWorld, entity: Entity) -> Option<Self::Item<'world>> {
        Some(world.get::<T>(entity))
    }

    fn fetch<'table>(
        slot: Option<&'table mut ColumnSlot>,
        current_tick: u32,
    ) -> Self::Fetch<'table> {
        slot.map(|slot| <&T as QueryElement>::fetch(Some(slot), current_tick))
    }

    fn changed_newer(fetch: &Self::Fetch<'_>, index: usize, since_tick: u32) -> bool {
        fetch
            .as_ref()
            .is_some_and(|fetch| tick_is_newer(fetch.1[index], since_tick))
    }

    fn item<'fetch>(fetch: &'fetch mut Self::Fetch<'_>, index: usize) -> Self::Item<'fetch> {
        fetch.as_ref().map(|fetch| &fetch.0[index])
    }

    fn stamp_peaks(_fetch: &mut Self::Fetch<'_>) {}
}

impl<T: Send + Sync + Default + 'static> sealed::SealedElement for Option<&mut T> {}

impl<T: Send + Sync + Default + 'static> QueryElement for Option<&mut T> {
    type Fetch<'table> = Option<(&'table mut [T], &'table mut [u32], u32, &'table mut u32)>;
    type Item<'item> = Option<&'item mut T>;
    const REQUIRED: bool = false;
    const MUTABLE: bool = true;

    fn component_mask(world: &mut DynWorld) -> u64 {
        world.component_key::<T>().mask
    }

    fn route_registered(world: &DynWorld) -> bool {
        world.lookup_key::<T>().is_some()
    }

    fn foreign_item<'world>(
        _world: &'world DynWorld,
        _entity: Entity,
    ) -> Option<Self::Item<'world>> {
        unreachable!("cross-world queries mutate only driver-world components")
    }

    fn fetch<'table>(
        slot: Option<&'table mut ColumnSlot>,
        current_tick: u32,
    ) -> Self::Fetch<'table> {
        slot.map(|slot| <&mut T as QueryElement>::fetch(Some(slot), current_tick))
    }

    fn changed_newer(fetch: &Self::Fetch<'_>, index: usize, since_tick: u32) -> bool {
        fetch
            .as_ref()
            .is_some_and(|fetch| tick_is_newer(fetch.1[index], since_tick))
    }

    fn item<'fetch>(fetch: &'fetch mut Self::Fetch<'_>, index: usize) -> Self::Item<'fetch> {
        fetch.as_mut().map(|fetch| {
            fetch.1[index] = fetch.2;
            &mut fetch.0[index]
        })
    }

    fn stamp_peaks(fetch: &mut Self::Fetch<'_>) {
        if let Some(fetch) = fetch {
            *fetch.3 = fetch.2;
        }
    }
}

/// The read-only half of [`QueryElement`], `&T` or `Option<&T>` only. Shared
/// fetches are `Copy` and items borrow the world rather than the fetch, which
/// is what lets [`DynQueryRef::iter`] hand out a real `Iterator`.
pub trait ReadQueryElement: QueryElement {
    type ReadFetch<'table>: Copy;
    fn lookup_mask(world: &DynWorld) -> Option<u64>;
    fn read_fetch<'table>(slot: Option<&'table ColumnSlot>) -> Self::ReadFetch<'table>;
    fn placeholder_read_fetch<'table>() -> Self::ReadFetch<'table>;
    fn read_changed_newer(fetch: Self::ReadFetch<'_>, index: usize, since_tick: u32) -> bool;
    fn read_added_newer(fetch: Self::ReadFetch<'_>, index: usize, since_tick: u32) -> bool;
    fn read_item<'table>(fetch: Self::ReadFetch<'table>, index: usize) -> Self::Item<'table>;
}

impl<T: Send + Sync + Default + 'static> ReadQueryElement for &T {
    type ReadFetch<'table> = (&'table [T], &'table [u32], &'table [u32]);

    fn lookup_mask(world: &DynWorld) -> Option<u64> {
        world.lookup_key::<T>().map(|key| key.mask)
    }

    fn read_fetch<'table>(slot: Option<&'table ColumnSlot>) -> Self::ReadFetch<'table> {
        let slot = slot.expect("required query element column missing");
        (
            column_vec::<T>(slot.data.as_ref()).as_slice(),
            slot.changed.as_slice(),
            slot.added.as_slice(),
        )
    }

    fn placeholder_read_fetch<'table>() -> Self::ReadFetch<'table> {
        (&[], &[], &[])
    }

    fn read_changed_newer(fetch: Self::ReadFetch<'_>, index: usize, since_tick: u32) -> bool {
        tick_is_newer(fetch.1[index], since_tick)
    }

    fn read_added_newer(fetch: Self::ReadFetch<'_>, index: usize, since_tick: u32) -> bool {
        tick_is_newer(fetch.2[index], since_tick)
    }

    fn read_item<'table>(fetch: Self::ReadFetch<'table>, index: usize) -> Self::Item<'table> {
        &fetch.0[index]
    }
}

impl<T: Send + Sync + Default + 'static> ReadQueryElement for Option<&T> {
    type ReadFetch<'table> = Option<(&'table [T], &'table [u32], &'table [u32])>;

    fn lookup_mask(world: &DynWorld) -> Option<u64> {
        world.lookup_key::<T>().map(|key| key.mask)
    }

    fn read_fetch<'table>(slot: Option<&'table ColumnSlot>) -> Self::ReadFetch<'table> {
        slot.map(|slot| <&T as ReadQueryElement>::read_fetch(Some(slot)))
    }

    fn placeholder_read_fetch<'table>() -> Self::ReadFetch<'table> {
        None
    }

    fn read_changed_newer(fetch: Self::ReadFetch<'_>, index: usize, since_tick: u32) -> bool {
        fetch.is_some_and(|fetch| tick_is_newer(fetch.1[index], since_tick))
    }

    fn read_added_newer(fetch: Self::ReadFetch<'_>, index: usize, since_tick: u32) -> bool {
        fetch.is_some_and(|fetch| tick_is_newer(fetch.2[index], since_tick))
    }

    fn read_item<'table>(fetch: Self::ReadFetch<'table>, index: usize) -> Self::Item<'table> {
        fetch.map(|fetch| &fetch.0[index])
    }
}

/// A tuple of query elements. Implemented for tuples of `&T`, `&mut T`,
/// `Option<&T>`, and `Option<&mut T>` up to eight elements; all component
/// types in one tuple must be distinct. Only the non-optional elements
/// constrain which entities the query visits.
pub(crate) fn route_world_scan(
    worlds: &[DynWorld],
    registered: impl Fn(&DynWorld) -> bool,
    type_name: &str,
) -> Option<usize> {
    let mut found: Option<usize> = None;
    for (index, world) in worlds.iter().enumerate() {
        if registered(world) {
            match found {
                None => found = Some(index),
                Some(first) => panic!(
                    "{type_name} is registered in member worlds {first} and {index}; \
                     a component type must live in exactly one member world"
                ),
            }
        }
    }
    found
}

/// The row filters one cross-world join carries: group tag sets to
/// include and exclude, and driver-world changed/added mask lookups. The
/// lookups resolve inside the join, after the tuple's driver-local
/// elements have registered, so a lazily-registered tuple element is a
/// valid filter target.
pub struct JoinFilters<'sets> {
    pub include_sets: [Option<&'sets SparseTagSet>; 4],
    pub exclude_sets: [Option<&'sets SparseTagSet>; 4],
    pub changed_lookups: [Option<JoinMaskLookup>; 4],
    pub added_lookups: [Option<JoinMaskLookup>; 4],
}

/// One query-tuple element's routing facts for a cross-world join: which
/// member world holds its type, whether the element narrows the match, and
/// whether it writes (writers must share one world, the driver).
#[derive(Clone, Copy)]
pub struct JoinRoute {
    pub world: Option<usize>,
    pub required: bool,
    pub mutable: bool,
    pub type_name: &'static str,
}

pub trait QueryTuple: sealed::SealedQueryTuple {
    type Fetch<'table>;
    type Item<'item>;
    fn component_mask(world: &mut DynWorld) -> u64;
    fn element_masks(world: &mut DynWorld) -> [u64; 8];
    fn routing_match(world: &DynWorld) -> bool;
    fn join_routes(worlds: &[DynWorld]) -> [Option<JoinRoute>; 8];
    fn join_for_each<F: for<'item> FnMut(Entity, Self::Item<'item>)>(
        driver: &mut DynWorld,
        element_worlds: &[Option<&DynWorld>; 8],
        filters: &JoinFilters<'_>,
        f: F,
    );
    #[cfg(not(target_family = "wasm"))]
    fn join_par_for_each<F: for<'item> Fn(Entity, Self::Item<'item>) + Send + Sync>(
        driver: &mut DynWorld,
        element_worlds: &[Option<&DynWorld>; 8],
        filters: &JoinFilters<'_>,
        f: F,
    );
    fn fetch<'table>(
        table_mask: u64,
        columns: &'table mut [ColumnSlot],
        element_masks: &[u64; 8],
        current_tick: u32,
    ) -> Self::Fetch<'table>;
    fn changed_newer(
        fetch: &Self::Fetch<'_>,
        index: usize,
        element_masks: &[u64; 8],
        changed_mask: u64,
        since_tick: u32,
    ) -> bool;
    fn item<'fetch>(fetch: &'fetch mut Self::Fetch<'_>, index: usize) -> Self::Item<'fetch>;
    fn stamp_peaks(fetch: &mut Self::Fetch<'_>);
}

/// The read-only half of [`QueryTuple`], tuples of `&T` and `Option<&T>`
/// only. Resolves masks without registering, fetches through shared borrows,
/// and hands out items that borrow the world, so results can outlive the
/// iteration.
pub trait ReadQueryTuple: QueryTuple {
    type ReadFetch<'table>: Copy;
    fn lookup_masks(world: &DynWorld) -> Option<([u64; 8], u64)>;
    fn read_fetch<'table>(
        table_mask: u64,
        columns: &'table [ColumnSlot],
        element_masks: &[u64; 8],
    ) -> Self::ReadFetch<'table>;
    fn read_changed_newer(
        fetch: Self::ReadFetch<'_>,
        index: usize,
        element_masks: &[u64; 8],
        changed_mask: u64,
        since_tick: u32,
    ) -> bool;
    fn read_added_newer(
        fetch: Self::ReadFetch<'_>,
        index: usize,
        element_masks: &[u64; 8],
        added_mask: u64,
        since_tick: u32,
    ) -> bool;
    fn read_item<'table>(fetch: Self::ReadFetch<'table>, index: usize) -> Self::Item<'table>;
    fn join_lookup(
        driver: &DynWorld,
        element_worlds: &[Option<&DynWorld>; 8],
    ) -> Option<([u64; 8], u64)>;
    fn join_read_fetch<'table>(
        table_mask: u64,
        columns: &'table [ColumnSlot],
        element_masks: &[u64; 8],
        element_worlds: &[Option<&DynWorld>; 8],
    ) -> Self::ReadFetch<'table>;
    fn join_read_item<'world>(
        fetch: Self::ReadFetch<'world>,
        element_worlds: &[Option<&'world DynWorld>; 8],
        entity: Entity,
        index: usize,
    ) -> Option<Self::Item<'world>>;
}

fn required_mask(elements: &[(u64, bool)]) -> u64 {
    let mut seen = 0;
    let mut required = 0;
    for &(mask, is_required) in elements {
        assert_eq!(
            seen & mask,
            0,
            "query tuples must not repeat a component type"
        );
        seen |= mask;
        if is_required {
            required |= mask;
        }
    }
    required
}

fn lookup_masks_from(elements: &[(Option<u64>, bool)]) -> Option<([u64; 8], u64)> {
    let mut masks = [0u64; 8];
    let mut seen = 0;
    let mut required = 0;
    for (position, &(mask, is_required)) in elements.iter().enumerate() {
        match mask {
            Some(mask) => {
                assert_eq!(
                    seen & mask,
                    0,
                    "query tuples must not repeat a component type"
                );
                seen |= mask;
                if is_required {
                    required |= mask;
                }
                masks[position] = mask;
            }
            None => {
                if is_required {
                    return None;
                }
            }
        }
    }
    Some((masks, required))
}

fn distribute_slots<const COUNT: usize>(
    columns: &mut [ColumnSlot],
    positions: [Option<usize>; COUNT],
) -> [Option<&mut ColumnSlot>; COUNT] {
    let mut slots = [const { None }; COUNT];
    for (column_index, slot) in columns.iter_mut().enumerate() {
        if let Some(element_index) = positions
            .iter()
            .position(|position| *position == Some(column_index))
        {
            slots[element_index] = Some(slot);
        }
    }
    slots
}

macro_rules! impl_query_tuple {
    ($(($element:ident, $position:tt)),+) => {
        impl<$($element: QueryElement),+> sealed::SealedQueryTuple for ($($element,)+) {}

        impl<$($element: QueryElement),+> QueryTuple for ($($element,)+) {
            type Fetch<'table> = ($($element::Fetch<'table>,)+);
            type Item<'item> = ($($element::Item<'item>,)+);

            fn component_mask(world: &mut DynWorld) -> u64 {
                let elements = [$(($element::component_mask(world), $element::REQUIRED),)+];
                required_mask(&elements)
            }

            fn element_masks(world: &mut DynWorld) -> [u64; 8] {
                let mut masks = [0u64; 8];
                $(
                    masks[$position] = $element::component_mask(world);
                )+
                masks
            }

            fn routing_match(world: &DynWorld) -> bool {
                let mut matched = true;
                $(
                    if $element::REQUIRED && !$element::route_registered(world) {
                        matched = false;
                    }
                )+
                matched
            }

            fn join_routes(worlds: &[DynWorld]) -> [Option<JoinRoute>; 8] {
                let mut routes = [None; 8];
                $(
                    routes[$position] = Some(JoinRoute {
                        world: route_world_scan(
                            worlds,
                            |world| $element::route_registered(world),
                            std::any::type_name::<$element>(),
                        ),
                        required: $element::REQUIRED,
                        mutable: $element::MUTABLE,
                        type_name: std::any::type_name::<$element>(),
                    });
                )+
                routes
            }

            #[allow(non_snake_case)]
            fn join_for_each<FN: for<'item> FnMut(Entity, Self::Item<'item>)>(
                driver: &mut DynWorld,
                element_worlds: &[Option<&DynWorld>; 8],
                filters: &JoinFilters<'_>,
                mut f: FN,
            ) {
                let mut element_masks = [0u64; 8];
                let mut local_include = 0u64;
                $(
                    if element_worlds[$position].is_none() {
                        element_masks[$position] = $element::component_mask(driver);
                        if $element::REQUIRED {
                            local_include |= element_masks[$position];
                        }
                    }
                )+
                let mut changed_mask = 0u64;
                for lookup in filters.changed_lookups.iter().flatten() {
                    changed_mask |= lookup(driver)
                        .expect("changed filters on query_join must name driver-world components");
                }
                let mut added_mask = 0u64;
                for lookup in filters.added_lookups.iter().flatten() {
                    added_mask |= lookup(driver)
                        .expect("added filters on query_join must name driver-world components");
                }
                let local_tuple_mask = element_masks
                    .iter()
                    .fold(0, |mask, element| mask | element);
                assert_eq!(
                    (changed_mask | added_mask) & !local_tuple_mask,
                    0,
                    "changed and added filters must name components present in the query tuple"
                );
                let since_tick = driver.last_tick;
                let current_tick = driver.current_tick;
                let mut added_scratch = std::mem::take(&mut driver.added_scratch);
                let table_indices = archetype_cached_tables(
                    &mut driver.query_cache,
                    driver.tables.iter().map(|table| table.mask),
                    local_include,
                );
                let tables = &mut driver.tables;
                for &table_index in table_indices {
                    let table = &mut tables[table_index];
                    let table_mask = table.mask;
                    let DynComponentArrays {
                        entity_indices,
                        columns,
                        ..
                    } = table;
                    let positions = [$(
                        if element_worlds[$position].is_none()
                            && table_mask & element_masks[$position] != 0
                        {
                            Some(column_position(table_mask, element_masks[$position]))
                        } else {
                            None
                        },
                    )+];
                    if added_mask != 0 {
                        added_scratch.clear();
                        added_scratch.resize(entity_indices.len(), false);
                        for column in columns.iter() {
                            if added_mask & (1u64 << column.component_index) == 0 {
                                continue;
                            }
                            for (row, &added_tick) in column.added.iter().enumerate() {
                                if tick_is_newer(added_tick, since_tick) {
                                    added_scratch[row] = true;
                                }
                            }
                        }
                    }
                    let [$($element,)+] = distribute_slots(columns, positions);
                    $(
                        let mut $element = if element_worlds[$position].is_none() {
                            Some(<$element as QueryElement>::fetch($element, current_tick))
                        } else {
                            None
                        };
                    )+
                    let mut visited = false;
                    'rows: for (row_index, &entity) in entity_indices.iter().enumerate() {
                        if !tag_sets_match(&filters.include_sets, &filters.exclude_sets, entity) {
                            continue 'rows;
                        }
                        if added_mask != 0 && !added_scratch[row_index] {
                            continue 'rows;
                        }
                        if changed_mask != 0 {
                            let mut newer = false;
                            $(
                                if !newer
                                    && changed_mask & element_masks[$position] != 0
                                    && let Some(fetch) = &$element
                                    && <$element as QueryElement>::changed_newer(
                                        fetch, row_index, since_tick,
                                    )
                                {
                                    newer = true;
                                }
                            )+
                            if !newer {
                                continue 'rows;
                            }
                        }
                        $crate::paste::paste! {
                            $(
                                let [<foreign_ $position>] = match element_worlds[$position] {
                                    Some(world) => {
                                        match <$element as QueryElement>::foreign_item(
                                            world, entity,
                                        ) {
                                            Some(item) => Some(item),
                                            None => continue 'rows,
                                        }
                                    }
                                    None => None,
                                };
                            )+
                            $(
                                let [<item_ $position>] = match [<foreign_ $position>] {
                                    Some(item) => item,
                                    None => <$element as QueryElement>::item(
                                        $element.as_mut().expect("local positions carry a fetch"),
                                        row_index,
                                    ),
                                };
                            )+
                            visited = true;
                            f(entity, ($([<item_ $position>],)+));
                        }
                    }
                    if visited {
                        $(
                            if let Some(fetch) = &mut $element {
                                <$element as QueryElement>::stamp_peaks(fetch);
                            }
                        )+
                    }
                }
                driver.added_scratch = added_scratch;
            }

            #[cfg(not(target_family = "wasm"))]
            #[allow(non_snake_case)]
            fn join_par_for_each<FN: for<'item> Fn(Entity, Self::Item<'item>) + Send + Sync>(
                driver: &mut DynWorld,
                element_worlds: &[Option<&DynWorld>; 8],
                filters: &JoinFilters<'_>,
                f: FN,
            ) {
                use crate::rayon::prelude::*;

                let mut element_masks = [0u64; 8];
                let mut local_include = 0u64;
                $(
                    if element_worlds[$position].is_none() {
                        element_masks[$position] = $element::component_mask(driver);
                        if $element::REQUIRED {
                            local_include |= element_masks[$position];
                        }
                    }
                )+
                let mut changed_mask = 0u64;
                for lookup in filters.changed_lookups.iter().flatten() {
                    changed_mask |= lookup(driver)
                        .expect("changed filters on query_join must name driver-world components");
                }
                let mut added_mask = 0u64;
                for lookup in filters.added_lookups.iter().flatten() {
                    added_mask |= lookup(driver)
                        .expect("added filters on query_join must name driver-world components");
                }
                let local_tuple_mask = element_masks
                    .iter()
                    .fold(0, |mask, element| mask | element);
                assert_eq!(
                    (changed_mask | added_mask) & !local_tuple_mask,
                    0,
                    "changed and added filters must name components present in the query tuple"
                );
                let since_tick = driver.last_tick;
                let current_tick = driver.current_tick;
                driver
                    .tables
                    .par_iter_mut()
                    .filter(|table| {
                        table.mask & local_include == local_include
                            && !table.entity_indices.is_empty()
                    })
                    .for_each(|table| {
                        let table_mask = table.mask;
                        let DynComponentArrays {
                            entity_indices,
                            columns,
                            ..
                        } = table;
                        let added_scratch: Vec<bool> = if added_mask != 0 {
                            let mut scratch = vec![false; entity_indices.len()];
                            for column in columns.iter() {
                                if added_mask & (1u64 << column.component_index) == 0 {
                                    continue;
                                }
                                for (row, &added_tick) in column.added.iter().enumerate() {
                                    if tick_is_newer(added_tick, since_tick) {
                                        scratch[row] = true;
                                    }
                                }
                            }
                            scratch
                        } else {
                            Vec::new()
                        };
                        let positions = [$(
                            if element_worlds[$position].is_none()
                                && table_mask & element_masks[$position] != 0
                            {
                                Some(column_position(table_mask, element_masks[$position]))
                            } else {
                                None
                            },
                        )+];
                        let [$($element,)+] = distribute_slots(columns, positions);
                        $(
                            let mut $element = if element_worlds[$position].is_none() {
                                Some(<$element as QueryElement>::fetch($element, current_tick))
                            } else {
                                None
                            };
                        )+
                        let mut visited = false;
                        'rows: for (row_index, &entity) in entity_indices.iter().enumerate() {
                            if !tag_sets_match(
                                &filters.include_sets,
                                &filters.exclude_sets,
                                entity,
                            ) {
                                continue 'rows;
                            }
                            if added_mask != 0 && !added_scratch[row_index] {
                                continue 'rows;
                            }
                            if changed_mask != 0 {
                                let mut newer = false;
                                $(
                                    if !newer
                                        && changed_mask & element_masks[$position] != 0
                                        && let Some(fetch) = &$element
                                        && <$element as QueryElement>::changed_newer(
                                            fetch, row_index, since_tick,
                                        )
                                    {
                                        newer = true;
                                    }
                                )+
                                if !newer {
                                    continue 'rows;
                                }
                            }
                            $crate::paste::paste! {
                                $(
                                    let [<foreign_ $position>] = match element_worlds[$position] {
                                        Some(world) => {
                                            match <$element as QueryElement>::foreign_item(
                                                world, entity,
                                            ) {
                                                Some(item) => Some(item),
                                                None => continue 'rows,
                                            }
                                        }
                                        None => None,
                                    };
                                )+
                                $(
                                    let [<item_ $position>] = match [<foreign_ $position>] {
                                        Some(item) => item,
                                        None => <$element as QueryElement>::item(
                                            $element
                                                .as_mut()
                                                .expect("local positions carry a fetch"),
                                            row_index,
                                        ),
                                    };
                                )+
                                visited = true;
                                f(entity, ($([<item_ $position>],)+));
                            }
                        }
                        if visited {
                            $(
                                if let Some(fetch) = &mut $element {
                                    <$element as QueryElement>::stamp_peaks(fetch);
                                }
                            )+
                        }
                    });
            }

            #[allow(non_snake_case)]
            fn fetch<'table>(
                table_mask: u64,
                columns: &'table mut [ColumnSlot],
                element_masks: &[u64; 8],
                current_tick: u32,
            ) -> Self::Fetch<'table> {
                let positions = [$(
                    if table_mask & element_masks[$position] != 0 {
                        Some(column_position(table_mask, element_masks[$position]))
                    } else {
                        None
                    },
                )+];
                let [$($element,)+] = distribute_slots(columns, positions);
                ($($element::fetch($element, current_tick),)+)
            }

            fn changed_newer(
                fetch: &Self::Fetch<'_>,
                index: usize,
                element_masks: &[u64; 8],
                changed_mask: u64,
                since_tick: u32,
            ) -> bool {
                let mut newer = false;
                $(
                    if changed_mask & element_masks[$position] != 0
                        && $element::changed_newer(&fetch.$position, index, since_tick)
                    {
                        newer = true;
                    }
                )+
                newer
            }

            fn item<'fetch>(fetch: &'fetch mut Self::Fetch<'_>, index: usize) -> Self::Item<'fetch> {
                ($($element::item(&mut fetch.$position, index),)+)
            }

            fn stamp_peaks(fetch: &mut Self::Fetch<'_>) {
                $($element::stamp_peaks(&mut fetch.$position);)+
            }
        }
    };
}

impl_query_tuple!((A, 0));
impl_query_tuple!((A, 0), (B, 1));
impl_query_tuple!((A, 0), (B, 1), (C, 2));
impl_query_tuple!((A, 0), (B, 1), (C, 2), (D, 3));
impl_query_tuple!((A, 0), (B, 1), (C, 2), (D, 3), (E, 4));
impl_query_tuple!((A, 0), (B, 1), (C, 2), (D, 3), (E, 4), (F, 5));
impl_query_tuple!((A, 0), (B, 1), (C, 2), (D, 3), (E, 4), (F, 5), (G, 6));
impl_query_tuple!(
    (A, 0),
    (B, 1),
    (C, 2),
    (D, 3),
    (E, 4),
    (F, 5),
    (G, 6),
    (H, 7)
);

macro_rules! impl_bare_element_query {
    ($($element:ty),+) => {
        $(
            impl<'element, T: Send + Sync + Default + 'static> sealed::SealedQueryTuple
                for $element
            {
            }

            impl<'element, T: Send + Sync + Default + 'static> QueryTuple for $element {
                type Fetch<'table> = <$element as QueryElement>::Fetch<'table>;
                type Item<'item> = <$element as QueryElement>::Item<'item>;

                fn component_mask(world: &mut DynWorld) -> u64 {
                    let elements = [(
                        <$element as QueryElement>::component_mask(world),
                        <$element as QueryElement>::REQUIRED,
                    )];
                    required_mask(&elements)
                }

                fn element_masks(world: &mut DynWorld) -> [u64; 8] {
                    let mut masks = [0u64; 8];
                    masks[0] = <$element as QueryElement>::component_mask(world);
                    masks
                }

                fn routing_match(world: &DynWorld) -> bool {
                    !<$element as QueryElement>::REQUIRED
                        || <$element as QueryElement>::route_registered(world)
                }

                fn join_routes(worlds: &[DynWorld]) -> [Option<JoinRoute>; 8] {
                    let mut routes = [None; 8];
                    routes[0] = Some(JoinRoute {
                        world: route_world_scan(
                            worlds,
                            |world| <$element as QueryElement>::route_registered(world),
                            std::any::type_name::<$element>(),
                        ),
                        required: <$element as QueryElement>::REQUIRED,
                        mutable: <$element as QueryElement>::MUTABLE,
                        type_name: std::any::type_name::<$element>(),
                    });
                    routes
                }

                fn join_for_each<FN: for<'item> FnMut(Entity, Self::Item<'item>)>(
                    driver: &mut DynWorld,
                    element_worlds: &[Option<&DynWorld>; 8],
                    filters: &JoinFilters<'_>,
                    mut f: FN,
                ) {
                    debug_assert!(
                        element_worlds[0].is_none(),
                        "a single-element tuple always drives its own world"
                    );
                    let mut element_masks = [0u64; 8];
                    element_masks[0] = <$element as QueryElement>::component_mask(driver);
                    let local_include = if <$element as QueryElement>::REQUIRED {
                        element_masks[0]
                    } else {
                        0
                    };
                    let mut changed_mask = 0u64;
                    for lookup in filters.changed_lookups.iter().flatten() {
                        changed_mask |= lookup(driver).expect(
                            "changed filters on query_join must name driver-world components",
                        );
                    }
                    let mut added_mask = 0u64;
                    for lookup in filters.added_lookups.iter().flatten() {
                        added_mask |= lookup(driver).expect(
                            "added filters on query_join must name driver-world components",
                        );
                    }
                    assert_eq!(
                        (changed_mask | added_mask) & !element_masks[0],
                        0,
                        "changed and added filters must name components present in the query tuple"
                    );
                    let since_tick = driver.last_tick;
                    let current_tick = driver.current_tick;
                    let mut added_scratch = std::mem::take(&mut driver.added_scratch);
                    let table_indices = archetype_cached_tables(
                        &mut driver.query_cache,
                        driver.tables.iter().map(|table| table.mask),
                        local_include,
                    );
                    let tables = &mut driver.tables;
                    for &table_index in table_indices {
                        let table = &mut tables[table_index];
                        let table_mask = table.mask;
                        let DynComponentArrays {
                            entity_indices,
                            columns,
                            ..
                        } = table;
                        let positions = [if table_mask & element_masks[0] != 0 {
                            Some(column_position(table_mask, element_masks[0]))
                        } else {
                            None
                        }];
                        if added_mask != 0 {
                            added_scratch.clear();
                            added_scratch.resize(entity_indices.len(), false);
                            for column in columns.iter() {
                                if added_mask & (1u64 << column.component_index) == 0 {
                                    continue;
                                }
                                for (row, &added_tick) in column.added.iter().enumerate() {
                                    if tick_is_newer(added_tick, since_tick) {
                                        added_scratch[row] = true;
                                    }
                                }
                            }
                        }
                        let [slot] = distribute_slots(columns, positions);
                        let mut fetch = <$element as QueryElement>::fetch(slot, current_tick);
                        let mut visited = false;
                        'rows: for (row_index, &entity) in entity_indices.iter().enumerate() {
                            if !tag_sets_match(
                                &filters.include_sets,
                                &filters.exclude_sets,
                                entity,
                            ) {
                                continue 'rows;
                            }
                            if added_mask != 0 && !added_scratch[row_index] {
                                continue 'rows;
                            }
                            if changed_mask != 0
                                && !<$element as QueryElement>::changed_newer(
                                    &fetch, row_index, since_tick,
                                )
                            {
                                continue 'rows;
                            }
                            let item = <$element as QueryElement>::item(&mut fetch, row_index);
                            visited = true;
                            f(entity, item);
                        }
                        if visited {
                            <$element as QueryElement>::stamp_peaks(&mut fetch);
                        }
                    }
                    driver.added_scratch = added_scratch;
                }

                #[cfg(not(target_family = "wasm"))]
                fn join_par_for_each<
                    FN: for<'item> Fn(Entity, Self::Item<'item>) + Send + Sync,
                >(
                    driver: &mut DynWorld,
                    element_worlds: &[Option<&DynWorld>; 8],
                    filters: &JoinFilters<'_>,
                    f: FN,
                ) {
                    use crate::rayon::prelude::*;

                    debug_assert!(
                        element_worlds[0].is_none(),
                        "a single-element tuple always drives its own world"
                    );
                    let mut element_masks = [0u64; 8];
                    element_masks[0] = <$element as QueryElement>::component_mask(driver);
                    let local_include = if <$element as QueryElement>::REQUIRED {
                        element_masks[0]
                    } else {
                        0
                    };
                    let mut changed_mask = 0u64;
                    for lookup in filters.changed_lookups.iter().flatten() {
                        changed_mask |= lookup(driver).expect(
                            "changed filters on query_join must name driver-world components",
                        );
                    }
                    let mut added_mask = 0u64;
                    for lookup in filters.added_lookups.iter().flatten() {
                        added_mask |= lookup(driver).expect(
                            "added filters on query_join must name driver-world components",
                        );
                    }
                    assert_eq!(
                        (changed_mask | added_mask) & !element_masks[0],
                        0,
                        "changed and added filters must name components present in the query tuple"
                    );
                    let since_tick = driver.last_tick;
                    let current_tick = driver.current_tick;
                    driver
                        .tables
                        .par_iter_mut()
                        .filter(|table| {
                            table.mask & local_include == local_include
                                && !table.entity_indices.is_empty()
                        })
                        .for_each(|table| {
                            let table_mask = table.mask;
                            let DynComponentArrays {
                                entity_indices,
                                columns,
                                ..
                            } = table;
                            let added_scratch: Vec<bool> = if added_mask != 0 {
                                let mut scratch = vec![false; entity_indices.len()];
                                for column in columns.iter() {
                                    if added_mask & (1u64 << column.component_index) == 0 {
                                        continue;
                                    }
                                    for (row, &added_tick) in column.added.iter().enumerate() {
                                        if tick_is_newer(added_tick, since_tick) {
                                            scratch[row] = true;
                                        }
                                    }
                                }
                                scratch
                            } else {
                                Vec::new()
                            };
                            let positions = [if table_mask & element_masks[0] != 0 {
                                Some(column_position(table_mask, element_masks[0]))
                            } else {
                                None
                            }];
                            let [slot] = distribute_slots(columns, positions);
                            let mut fetch =
                                <$element as QueryElement>::fetch(slot, current_tick);
                            let mut visited = false;
                            'rows: for (row_index, &entity) in
                                entity_indices.iter().enumerate()
                            {
                                if !tag_sets_match(
                                    &filters.include_sets,
                                    &filters.exclude_sets,
                                    entity,
                                ) {
                                    continue 'rows;
                                }
                                if added_mask != 0 && !added_scratch[row_index] {
                                    continue 'rows;
                                }
                                if changed_mask != 0
                                    && !<$element as QueryElement>::changed_newer(
                                        &fetch, row_index, since_tick,
                                    )
                                {
                                    continue 'rows;
                                }
                                let item =
                                    <$element as QueryElement>::item(&mut fetch, row_index);
                                visited = true;
                                f(entity, item);
                            }
                            if visited {
                                <$element as QueryElement>::stamp_peaks(&mut fetch);
                            }
                        });
                }

                fn fetch<'table>(
                    table_mask: u64,
                    columns: &'table mut [ColumnSlot],
                    element_masks: &[u64; 8],
                    current_tick: u32,
                ) -> Self::Fetch<'table> {
                    let position = if table_mask & element_masks[0] != 0 {
                        Some(column_position(table_mask, element_masks[0]))
                    } else {
                        None
                    };
                    let [slot] = distribute_slots(columns, [position]);
                    <$element as QueryElement>::fetch(slot, current_tick)
                }

                fn changed_newer(
                    fetch: &Self::Fetch<'_>,
                    index: usize,
                    element_masks: &[u64; 8],
                    changed_mask: u64,
                    since_tick: u32,
                ) -> bool {
                    changed_mask & element_masks[0] != 0
                        && <$element as QueryElement>::changed_newer(fetch, index, since_tick)
                }

                fn item<'fetch>(
                    fetch: &'fetch mut Self::Fetch<'_>,
                    index: usize,
                ) -> Self::Item<'fetch> {
                    <$element as QueryElement>::item(fetch, index)
                }

                fn stamp_peaks(fetch: &mut Self::Fetch<'_>) {
                    <$element as QueryElement>::stamp_peaks(fetch);
                }
            }
        )+
    };
}

impl_bare_element_query!(
    &'element T,
    &'element mut T,
    Option<&'element T>,
    Option<&'element mut T>
);

macro_rules! impl_bare_element_read_query {
    ($($element:ty),+) => {
        $(
            impl<'element, T: Send + Sync + Default + 'static> ReadQueryTuple for $element {
                type ReadFetch<'table> = <$element as ReadQueryElement>::ReadFetch<'table>;

                fn lookup_masks(world: &DynWorld) -> Option<([u64; 8], u64)> {
                    let elements = [(
                        <$element as ReadQueryElement>::lookup_mask(world),
                        <$element as QueryElement>::REQUIRED,
                    )];
                    lookup_masks_from(&elements)
                }

                fn read_fetch<'table>(
                    table_mask: u64,
                    columns: &'table [ColumnSlot],
                    element_masks: &[u64; 8],
                ) -> Self::ReadFetch<'table> {
                    <$element as ReadQueryElement>::read_fetch(
                        if table_mask & element_masks[0] != 0 {
                            Some(&columns[column_position(table_mask, element_masks[0])])
                        } else {
                            None
                        },
                    )
                }

                fn read_changed_newer(
                    fetch: Self::ReadFetch<'_>,
                    index: usize,
                    element_masks: &[u64; 8],
                    changed_mask: u64,
                    since_tick: u32,
                ) -> bool {
                    changed_mask & element_masks[0] != 0
                        && <$element as ReadQueryElement>::read_changed_newer(
                            fetch, index, since_tick,
                        )
                }

                fn read_added_newer(
                    fetch: Self::ReadFetch<'_>,
                    index: usize,
                    element_masks: &[u64; 8],
                    added_mask: u64,
                    since_tick: u32,
                ) -> bool {
                    added_mask & element_masks[0] != 0
                        && <$element as ReadQueryElement>::read_added_newer(
                            fetch, index, since_tick,
                        )
                }

                fn read_item<'table>(
                    fetch: Self::ReadFetch<'table>,
                    index: usize,
                ) -> Self::Item<'table> {
                    <$element as ReadQueryElement>::read_item(fetch, index)
                }

                fn join_lookup(
                    driver: &DynWorld,
                    element_worlds: &[Option<&DynWorld>; 8],
                ) -> Option<([u64; 8], u64)> {
                    let mut masks = [0u64; 8];
                    let mut required = 0u64;
                    if element_worlds[0].is_none() {
                        match <$element as ReadQueryElement>::lookup_mask(driver) {
                            Some(mask) => {
                                masks[0] = mask;
                                if <$element as QueryElement>::REQUIRED {
                                    required |= mask;
                                }
                            }
                            None => {
                                if <$element as QueryElement>::REQUIRED {
                                    return None;
                                }
                            }
                        }
                    }
                    Some((masks, required))
                }

                fn join_read_fetch<'table>(
                    table_mask: u64,
                    columns: &'table [ColumnSlot],
                    element_masks: &[u64; 8],
                    element_worlds: &[Option<&DynWorld>; 8],
                ) -> Self::ReadFetch<'table> {
                    if element_worlds[0].is_none() {
                        <$element as ReadQueryElement>::read_fetch(
                            if element_masks[0] != 0 && table_mask & element_masks[0] != 0 {
                                Some(&columns[column_position(table_mask, element_masks[0])])
                            } else {
                                None
                            },
                        )
                    } else {
                        <$element as ReadQueryElement>::placeholder_read_fetch()
                    }
                }

                fn join_read_item<'world>(
                    fetch: Self::ReadFetch<'world>,
                    element_worlds: &[Option<&'world DynWorld>; 8],
                    entity: Entity,
                    index: usize,
                ) -> Option<Self::Item<'world>> {
                    match element_worlds[0] {
                        Some(world) => <$element as QueryElement>::foreign_item(world, entity),
                        None => Some(<$element as ReadQueryElement>::read_item(fetch, index)),
                    }
                }
            }
        )+
    };
}

impl_bare_element_read_query!(&'element T, Option<&'element T>);

macro_rules! impl_read_query_tuple {
    ($(($element:ident, $position:tt)),+) => {
        impl<$($element: ReadQueryElement),+> ReadQueryTuple for ($($element,)+) {
            type ReadFetch<'table> = ($($element::ReadFetch<'table>,)+);

            fn lookup_masks(world: &DynWorld) -> Option<([u64; 8], u64)> {
                let elements = [$(($element::lookup_mask(world), $element::REQUIRED),)+];
                lookup_masks_from(&elements)
            }

            fn read_fetch<'table>(
                table_mask: u64,
                columns: &'table [ColumnSlot],
                element_masks: &[u64; 8],
            ) -> Self::ReadFetch<'table> {
                ($(
                    $element::read_fetch(
                        if table_mask & element_masks[$position] != 0 {
                            Some(&columns[column_position(table_mask, element_masks[$position])])
                        } else {
                            None
                        },
                    ),
                )+)
            }

            fn read_changed_newer(
                fetch: Self::ReadFetch<'_>,
                index: usize,
                element_masks: &[u64; 8],
                changed_mask: u64,
                since_tick: u32,
            ) -> bool {
                let mut newer = false;
                $(
                    if changed_mask & element_masks[$position] != 0
                        && $element::read_changed_newer(fetch.$position, index, since_tick)
                    {
                        newer = true;
                    }
                )+
                newer
            }

            fn read_added_newer(
                fetch: Self::ReadFetch<'_>,
                index: usize,
                element_masks: &[u64; 8],
                added_mask: u64,
                since_tick: u32,
            ) -> bool {
                let mut newer = false;
                $(
                    if added_mask & element_masks[$position] != 0
                        && $element::read_added_newer(fetch.$position, index, since_tick)
                    {
                        newer = true;
                    }
                )+
                newer
            }

            fn read_item<'table>(
                fetch: Self::ReadFetch<'table>,
                index: usize,
            ) -> Self::Item<'table> {
                ($($element::read_item(fetch.$position, index),)+)
            }

            fn join_lookup(
                driver: &DynWorld,
                element_worlds: &[Option<&DynWorld>; 8],
            ) -> Option<([u64; 8], u64)> {
                let mut masks = [0u64; 8];
                let mut required = 0u64;
                $(
                    if element_worlds[$position].is_none() {
                        match $element::lookup_mask(driver) {
                            Some(mask) => {
                                masks[$position] = mask;
                                if $element::REQUIRED {
                                    required |= mask;
                                }
                            }
                            None => {
                                if $element::REQUIRED {
                                    return None;
                                }
                            }
                        }
                    }
                )+
                Some((masks, required))
            }

            fn join_read_fetch<'table>(
                table_mask: u64,
                columns: &'table [ColumnSlot],
                element_masks: &[u64; 8],
                element_worlds: &[Option<&DynWorld>; 8],
            ) -> Self::ReadFetch<'table> {
                ($(
                    if element_worlds[$position].is_none() {
                        $element::read_fetch(
                            if element_masks[$position] != 0
                                && table_mask & element_masks[$position] != 0
                            {
                                Some(&columns
                                    [column_position(table_mask, element_masks[$position])])
                            } else {
                                None
                            },
                        )
                    } else {
                        $element::placeholder_read_fetch()
                    },
                )+)
            }

            #[allow(non_snake_case)]
            fn join_read_item<'world>(
                fetch: Self::ReadFetch<'world>,
                element_worlds: &[Option<&'world DynWorld>; 8],
                entity: Entity,
                index: usize,
            ) -> Option<Self::Item<'world>> {
                $crate::paste::paste! {
                    $(
                        let [<item_ $position>] = match element_worlds[$position] {
                            Some(world) => {
                                match <$element as QueryElement>::foreign_item(world, entity) {
                                    Some(item) => item,
                                    None => return None,
                                }
                            }
                            None => $element::read_item(fetch.$position, index),
                        };
                    )+
                    Some(($([<item_ $position>],)+))
                }
            }
        }
    };
}

impl_read_query_tuple!((A, 0));
impl_read_query_tuple!((A, 0), (B, 1));
impl_read_query_tuple!((A, 0), (B, 1), (C, 2));
impl_read_query_tuple!((A, 0), (B, 1), (C, 2), (D, 3));
impl_read_query_tuple!((A, 0), (B, 1), (C, 2), (D, 3), (E, 4));
impl_read_query_tuple!((A, 0), (B, 1), (C, 2), (D, 3), (E, 4), (F, 5));
impl_read_query_tuple!((A, 0), (B, 1), (C, 2), (D, 3), (E, 4), (F, 5), (G, 6));
impl_read_query_tuple!(
    (A, 0),
    (B, 1),
    (C, 2),
    (D, 3),
    (E, 4),
    (F, 5),
    (G, 6),
    (H, 7)
);

/// A typed query in progress. Filters compose before `for_each` runs it.
/// Like everything else in the crate, the fields are plain data: the filter
/// methods are conveniences over them, and writing them directly is fine.
/// [`DynWorld::query`] seeds `include` with the tuple's required components;
/// a hand-built query whose `include` misses one panics at fetch rather than
/// misbehaving.
pub struct DynQuery<'world, Q: QueryTuple> {
    pub world: &'world mut DynWorld,
    pub include: u64,
    pub exclude: u64,
    pub changed_mask: u64,
    pub added_mask: u64,
    pub include_tag_sets: [Option<&'world SparseTagSet>; 4],
    pub exclude_tag_sets: [Option<&'world SparseTagSet>; 4],
    pub element_masks: Option<[u64; 8]>,
    pub marker: PhantomData<Q>,
}

fn push_tag_set<'world>(
    slots: &mut [Option<&'world SparseTagSet>; 4],
    tag_set: &'world SparseTagSet,
) {
    for slot in slots.iter_mut() {
        if slot.is_none() {
            *slot = Some(tag_set);
            return;
        }
    }
    panic!("a query supports at most four tag-set filters per side");
}

fn tag_sets_match(
    include: &[Option<&SparseTagSet>; 4],
    exclude: &[Option<&SparseTagSet>; 4],
    entity: Entity,
) -> bool {
    for tag_set in include.iter().flatten() {
        if !tag_set.contains(entity) {
            return false;
        }
    }
    for tag_set in exclude.iter().flatten() {
        if tag_set.contains(entity) {
            return false;
        }
    }
    true
}

impl<'world, Q: QueryTuple> DynQuery<'world, Q> {
    pub fn with<T: Send + Sync + Default + 'static>(mut self) -> Self {
        self.include |= self.world.component_key::<T>().mask;
        self
    }

    pub fn without<T: Send + Sync + Default + 'static>(mut self) -> Self {
        self.exclude |= self.world.component_key::<T>().mask;
        self
    }

    pub fn with_mask(mut self, mask: u64) -> Self {
        self.include |= mask;
        self
    }

    pub fn without_mask(mut self, mask: u64) -> Self {
        self.exclude |= mask;
        self
    }

    pub fn with_tag(mut self, key: TagKey) -> Self {
        self.include |= key.mask;
        self
    }

    pub fn without_tag(mut self, key: TagKey) -> Self {
        self.exclude |= key.mask;
        self
    }

    /// Filter by the marker type `T`'s tag, registering it on first use.
    /// Registration permanently consumes one of the world's 64 mask bits,
    /// even when nothing carries the tag yet; on a shared borrow,
    /// [`DynQueryRef::with_tag_type`] looks up without registering.
    pub fn with_tag_type<T: 'static>(mut self) -> Self {
        self.include |= self.world.tag_key::<T>().mask;
        self
    }

    pub fn without_tag_type<T: 'static>(mut self) -> Self {
        self.exclude |= self.world.tag_key::<T>().mask;
        self
    }

    /// Filter by membership in an external tag set, the grouped-worlds form:
    /// [`DynEcs`] tags live outside any single world's mask space, so they
    /// filter by set reference instead of by mask bit.
    pub fn with_tag_set(mut self, tag_set: &'world SparseTagSet) -> Self {
        push_tag_set(&mut self.include_tag_sets, tag_set);
        self
    }

    pub fn without_tag_set(mut self, tag_set: &'world SparseTagSet) -> Self {
        push_tag_set(&mut self.exclude_tag_sets, tag_set);
        self
    }

    /// Only visit entities whose `T` changed since the last step. `T` must be
    /// one of the tuple's components.
    pub fn changed<T: Send + Sync + Default + 'static>(mut self) -> Self {
        let mask = self.world.component_key::<T>().mask;
        self.changed_mask |= mask;
        self
    }

    /// Only visit entities that gained `T` since the last step, whether by
    /// spawn or by a component add; mutating `T` does not retrigger this, and
    /// the added stamp rides along through table migrations. `T` must be one
    /// of the tuple's components.
    pub fn added<T: Send + Sync + Default + 'static>(mut self) -> Self {
        let mask = self.world.component_key::<T>().mask;
        self.added_mask |= mask;
        self
    }

    /// Freezes this query's resolved masks into a reusable
    /// [`PreparedQuery`], registering the tuple's types now. Tag-set
    /// references cannot be captured (they borrow the world); apply those
    /// at run time on the rehydrated query.
    pub fn prepare(self) -> PreparedQuery<Q> {
        assert!(
            self.include_tag_sets.iter().all(Option::is_none)
                && self.exclude_tag_sets.iter().all(Option::is_none),
            "prepared queries cannot capture tag-set references; \
             apply with_tag_set/without_tag_set on the rehydrated query"
        );
        PreparedQuery {
            element_masks: match self.element_masks {
                Some(masks) => masks,
                None => Q::element_masks(self.world),
            },
            include: self.include,
            exclude: self.exclude,
            changed_mask: self.changed_mask,
            added_mask: self.added_mask,
            marker: PhantomData,
        }
    }

    pub fn for_each(self, mut f: impl for<'item> FnMut(Entity, Q::Item<'item>)) {
        let element_masks = match self.element_masks {
            Some(masks) => masks,
            None => Q::element_masks(self.world),
        };
        let tuple_mask = element_masks.iter().fold(0, |mask, element| mask | element);
        assert_eq!(
            (self.changed_mask | self.added_mask) & !tuple_mask,
            0,
            "changed filters must name components present in the query tuple"
        );

        let Some((component_include, component_exclude, tag_include, tag_exclude)) =
            self.world.split_masks(self.include, self.exclude)
        else {
            return;
        };

        let since_tick = self.world.last_tick;
        let current_tick = self.world.current_tick;
        let changed_mask = self.changed_mask;
        let added_mask = self.added_mask;

        let has_row_filters = tag_include != 0
            || tag_exclude != 0
            || changed_mask != 0
            || added_mask != 0
            || self.include_tag_sets.iter().any(Option::is_some)
            || self.exclude_tag_sets.iter().any(Option::is_some);

        let tags = &self.world.tags;
        let table_indices = archetype_cached_tables(
            &mut self.world.query_cache,
            self.world.tables.iter().map(|table| table.mask),
            component_include,
        );
        let added_scratch = &mut self.world.added_scratch;
        let tables = &mut self.world.tables;

        for &table_index in table_indices {
            let table = &mut tables[table_index];
            if table.mask & component_exclude != 0 {
                continue;
            }

            if added_mask != 0 {
                added_scratch.clear();
                added_scratch.resize(table.entity_indices.len(), false);
                for column in &table.columns {
                    if added_mask & (1u64 << column.component_index) == 0 {
                        continue;
                    }
                    for (row, &added_tick) in column.added.iter().enumerate() {
                        if tick_is_newer(added_tick, since_tick) {
                            added_scratch[row] = true;
                        }
                    }
                }
            }

            let table_mask = table.mask;
            let entity_indices = &table.entity_indices;
            let mut fetch = Q::fetch(table_mask, &mut table.columns, &element_masks, current_tick);

            if has_row_filters {
                let mut visited = false;
                for (index, &entity) in entity_indices.iter().enumerate() {
                    if (tag_include != 0 || tag_exclude != 0)
                        && !tags_match(tags, entity, tag_include, tag_exclude)
                    {
                        continue;
                    }
                    if !tag_sets_match(&self.include_tag_sets, &self.exclude_tag_sets, entity) {
                        continue;
                    }
                    if changed_mask != 0
                        && !Q::changed_newer(
                            &fetch,
                            index,
                            &element_masks,
                            changed_mask,
                            since_tick,
                        )
                    {
                        continue;
                    }
                    if added_mask != 0 && !added_scratch[index] {
                        continue;
                    }
                    visited = true;
                    f(entity, Q::item(&mut fetch, index));
                }
                if visited {
                    Q::stamp_peaks(&mut fetch);
                }
            } else {
                for (index, &entity) in entity_indices.iter().enumerate() {
                    f(entity, Q::item(&mut fetch, index));
                }
                if !entity_indices.is_empty() {
                    Q::stamp_peaks(&mut fetch);
                }
            }
        }
    }

    /// The parallel form of [`for_each`](Self::for_each): matching tables
    /// run concurrently while rows within a table stay sequential, so
    /// parallelism is table-granular like [`DynWorld::par_for_each_mut`].
    /// Same filter set and stamping semantics; the closure is `Fn` because
    /// tables run on worker threads, and the `added` filter builds one
    /// scratch buffer per table task.
    #[cfg(not(target_family = "wasm"))]
    pub fn par_for_each<F>(self, f: F)
    where
        F: for<'item> Fn(Entity, Q::Item<'item>) + Send + Sync,
    {
        use crate::rayon::prelude::*;

        let element_masks = match self.element_masks {
            Some(masks) => masks,
            None => Q::element_masks(self.world),
        };
        let tuple_mask = element_masks.iter().fold(0, |mask, element| mask | element);
        assert_eq!(
            (self.changed_mask | self.added_mask) & !tuple_mask,
            0,
            "changed and added filters must name components present in the query tuple"
        );

        let Some((component_include, component_exclude, tag_include, tag_exclude)) =
            self.world.split_masks(self.include, self.exclude)
        else {
            return;
        };

        let since_tick = self.world.last_tick;
        let current_tick = self.world.current_tick;
        let changed_mask = self.changed_mask;
        let added_mask = self.added_mask;
        let include_tag_sets = self.include_tag_sets;
        let exclude_tag_sets = self.exclude_tag_sets;

        let has_row_filters = tag_include != 0
            || tag_exclude != 0
            || changed_mask != 0
            || added_mask != 0
            || include_tag_sets.iter().any(Option::is_some)
            || exclude_tag_sets.iter().any(Option::is_some);

        let tags = &self.world.tags;
        self.world
            .tables
            .par_iter_mut()
            .filter(|table| {
                table.mask & component_include == component_include
                    && table.mask & component_exclude == 0
                    && !table.entity_indices.is_empty()
            })
            .for_each(|table| {
                let added_scratch: Vec<bool> = if added_mask != 0 {
                    let mut scratch = vec![false; table.entity_indices.len()];
                    for column in &table.columns {
                        if added_mask & (1u64 << column.component_index) == 0 {
                            continue;
                        }
                        for (row, &added_tick) in column.added.iter().enumerate() {
                            if tick_is_newer(added_tick, since_tick) {
                                scratch[row] = true;
                            }
                        }
                    }
                    scratch
                } else {
                    Vec::new()
                };

                let table_mask = table.mask;
                let DynComponentArrays {
                    entity_indices,
                    columns,
                    ..
                } = table;
                let mut fetch = Q::fetch(table_mask, columns, &element_masks, current_tick);

                if has_row_filters {
                    let mut visited = false;
                    for (index, &entity) in entity_indices.iter().enumerate() {
                        if (tag_include != 0 || tag_exclude != 0)
                            && !tags_match(tags, entity, tag_include, tag_exclude)
                        {
                            continue;
                        }
                        if !tag_sets_match(&include_tag_sets, &exclude_tag_sets, entity) {
                            continue;
                        }
                        if changed_mask != 0
                            && !Q::changed_newer(
                                &fetch,
                                index,
                                &element_masks,
                                changed_mask,
                                since_tick,
                            )
                        {
                            continue;
                        }
                        if added_mask != 0 && !added_scratch[index] {
                            continue;
                        }
                        visited = true;
                        f(entity, Q::item(&mut fetch, index));
                    }
                    if visited {
                        Q::stamp_peaks(&mut fetch);
                    }
                } else {
                    for (index, &entity) in entity_indices.iter().enumerate() {
                        f(entity, Q::item(&mut fetch, index));
                    }
                    if !entity_indices.is_empty() {
                        Q::stamp_peaks(&mut fetch);
                    }
                }
            });
    }
}

/// A read-only typed query in progress, from [`DynWorld::query_ref`].
/// Filters compose before [`iter`](Self::iter) runs it. The fields are the
/// plain query description and writing them directly is fine; `iter`
/// resolves the tuple's masks itself, so `include` only carries extra
/// filters.
pub struct DynQueryRef<'world, Q: ReadQueryTuple> {
    pub world: &'world DynWorld,
    pub include: u64,
    pub exclude: u64,
    pub changed_mask: u64,
    pub added_mask: u64,
    pub include_tag_sets: [Option<&'world SparseTagSet>; 4],
    pub exclude_tag_sets: [Option<&'world SparseTagSet>; 4],
    pub resolved_masks: Option<([u64; 8], u64)>,
    pub dead: bool,
    pub marker: PhantomData<Q>,
}

impl<'world, Q: ReadQueryTuple> DynQueryRef<'world, Q> {
    pub fn with<T: Send + Sync + Default + 'static>(mut self) -> Self {
        match self.world.lookup_key::<T>() {
            Some(key) => self.include |= key.mask,
            None => self.dead = true,
        }
        self
    }

    pub fn without<T: Send + Sync + Default + 'static>(mut self) -> Self {
        if let Some(key) = self.world.lookup_key::<T>() {
            self.exclude |= key.mask;
        }
        self
    }

    pub fn with_mask(mut self, mask: u64) -> Self {
        self.include |= mask;
        self
    }

    pub fn without_mask(mut self, mask: u64) -> Self {
        self.exclude |= mask;
        self
    }

    pub fn with_tag(mut self, key: TagKey) -> Self {
        self.include |= key.mask;
        self
    }

    pub fn without_tag(mut self, key: TagKey) -> Self {
        self.exclude |= key.mask;
        self
    }

    /// Filter by the marker type `T`'s tag. Unregistered marker types match
    /// no entities.
    pub fn with_tag_type<T: 'static>(mut self) -> Self {
        match self.world.lookup_tag_key::<T>() {
            Some(key) => self.include |= key.mask,
            None => self.dead = true,
        }
        self
    }

    pub fn without_tag_type<T: 'static>(mut self) -> Self {
        if let Some(key) = self.world.lookup_tag_key::<T>() {
            self.exclude |= key.mask;
        }
        self
    }

    pub fn with_tag_set(mut self, tag_set: &'world SparseTagSet) -> Self {
        push_tag_set(&mut self.include_tag_sets, tag_set);
        self
    }

    pub fn without_tag_set(mut self, tag_set: &'world SparseTagSet) -> Self {
        push_tag_set(&mut self.exclude_tag_sets, tag_set);
        self
    }

    /// Only visit entities whose `T` changed since the last step. `T` must be
    /// one of the tuple's components.
    pub fn changed<T: Send + Sync + Default + 'static>(mut self) -> Self {
        match self.world.lookup_key::<T>() {
            Some(key) => self.changed_mask |= key.mask,
            None => self.dead = true,
        }
        self
    }

    /// Only visit entities that gained `T` since the last step, whether by
    /// spawn or by a component add; mutating `T` does not retrigger this.
    /// `T` must be one of the tuple's components.
    pub fn added<T: Send + Sync + Default + 'static>(mut self) -> Self {
        match self.world.lookup_key::<T>() {
            Some(key) => self.added_mask |= key.mask,
            None => self.dead = true,
        }
        self
    }

    /// Freezes this query's resolved masks into a reusable
    /// [`PreparedQueryRef`]. Tag-set references cannot be captured; apply
    /// those at run time on the rehydrated query.
    pub fn prepare(self) -> PreparedQueryRef<Q> {
        assert!(
            self.include_tag_sets.iter().all(Option::is_none)
                && self.exclude_tag_sets.iter().all(Option::is_none),
            "prepared queries cannot capture tag-set references; \
             apply with_tag_set/without_tag_set on the rehydrated query"
        );
        PreparedQueryRef {
            resolved_masks: if self.dead {
                None
            } else {
                match self.resolved_masks {
                    Some(resolved) => Some(resolved),
                    None => Q::lookup_masks(self.world),
                }
            },
            include: self.include,
            exclude: self.exclude,
            changed_mask: self.changed_mask,
            added_mask: self.added_mask,
            marker: PhantomData,
        }
    }

    /// Runs the query as an iterator of `(Entity, items)`. Items borrow the
    /// world, not the iterator, so they survive collection.
    pub fn iter(self) -> DynQueryRefIter<'world, Q> {
        let mut done = self.dead;
        let mut element_masks = [0u64; 8];
        let mut include = self.include;
        let resolved = match self.resolved_masks {
            Some(resolved) => Some(resolved),
            None => Q::lookup_masks(self.world),
        };
        match resolved {
            Some((masks, required)) => {
                element_masks = masks;
                include |= required;
            }
            None => done = true,
        }

        if !done {
            let tuple_mask = element_masks.iter().fold(0, |mask, element| mask | element);
            assert_eq!(
                (self.changed_mask | self.added_mask) & !tuple_mask,
                0,
                "changed and added filters must name components present in the query tuple"
            );
        }

        let mut component_include = 0;
        let mut component_exclude = 0;
        let mut tag_include = 0;
        let mut tag_exclude = 0;
        match self.world.split_masks(include, self.exclude) {
            Some((components_in, components_out, tags_in, tags_out)) => {
                component_include = components_in;
                component_exclude = components_out;
                tag_include = tags_in;
                tag_exclude = tags_out;
            }
            None => done = true,
        }

        let cached_tables = self
            .world
            .query_cache
            .get(&component_include)
            .map(|indices| indices.as_slice());

        DynQueryRefIter {
            world: self.world,
            element_masks,
            include: component_include,
            exclude: component_exclude,
            tag_include,
            tag_exclude,
            include_tag_sets: self.include_tag_sets,
            exclude_tag_sets: self.exclude_tag_sets,
            changed_mask: self.changed_mask,
            added_mask: self.added_mask,
            since_tick: self.world.last_tick,
            cached_tables,
            table_index: 0,
            row_index: 0,
            current: None,
            done,
        }
    }

    /// The exactly-one match: `Some` when precisely one entity matches,
    /// `None` for zero or several. The get-the-player call; take the entity
    /// and go back through `get_mut` when you need to write.
    pub fn single(self) -> Option<(Entity, Q::Item<'world>)> {
        let mut matches = self.iter();
        let first = matches.next()?;
        if matches.next().is_some() {
            return None;
        }
        Some(first)
    }

    /// Every unordered pair of distinct matches, for pairwise logic like
    /// collision tests. Items are shared borrows of the world, so pairs are
    /// `Copy` and this is a real [`Iterator`]. Matches are collected once up
    /// front, one `(Entity, item)` per match.
    pub fn iter_combinations(self) -> DynQueryCombinations<'world, Q>
    where
        Q::Item<'world>: Copy,
    {
        DynQueryCombinations {
            items: self.iter().collect(),
            first: 0,
            second: 1,
        }
    }
}

/// The iterator behind [`DynQueryRef::iter_combinations`]: yields each
/// unordered pair of distinct matches exactly once, in match order.
pub struct DynQueryCombinations<'world, Q: ReadQueryTuple> {
    pub items: Vec<(Entity, Q::Item<'world>)>,
    pub first: usize,
    pub second: usize,
}

impl<'world, Q: ReadQueryTuple> Iterator for DynQueryCombinations<'world, Q>
where
    Q::Item<'world>: Copy,
{
    type Item = ((Entity, Q::Item<'world>), (Entity, Q::Item<'world>));

    fn next(&mut self) -> Option<Self::Item> {
        while self.second >= self.items.len() {
            if self.first + 2 >= self.items.len() {
                return None;
            }
            self.first += 1;
            self.second = self.first + 1;
        }
        let pair = (self.items[self.first], self.items[self.second]);
        self.second += 1;
        Some(pair)
    }
}

/// The iterator behind [`DynQueryRef::iter`]. Walks matching tables in
/// order, resolving columns once per table. When a `&mut` query path has
/// already cached this include mask's table list, the iterator reuses it
/// instead of scanning every table; the cache stays valid because table
/// registration appends to matching entries.
pub struct DynQueryRefIter<'world, Q: ReadQueryTuple> {
    pub world: &'world DynWorld,
    pub element_masks: [u64; 8],
    pub include: u64,
    pub exclude: u64,
    pub tag_include: u64,
    pub tag_exclude: u64,
    pub include_tag_sets: [Option<&'world SparseTagSet>; 4],
    pub exclude_tag_sets: [Option<&'world SparseTagSet>; 4],
    pub changed_mask: u64,
    pub added_mask: u64,
    pub since_tick: u32,
    pub cached_tables: Option<&'world [usize]>,
    pub table_index: usize,
    pub row_index: usize,
    pub current: Option<(&'world [Entity], Q::ReadFetch<'world>)>,
    pub done: bool,
}

impl<'world, Q: ReadQueryTuple> Iterator for DynQueryRefIter<'world, Q> {
    type Item = (Entity, Q::Item<'world>);

    fn next(&mut self) -> Option<Self::Item> {
        if self.done {
            return None;
        }
        loop {
            if let Some((entities, fetch)) = self.current {
                while self.row_index < entities.len() {
                    let index = self.row_index;
                    self.row_index += 1;
                    let entity = entities[index];
                    if (self.tag_include != 0 || self.tag_exclude != 0)
                        && !tags_match(&self.world.tags, entity, self.tag_include, self.tag_exclude)
                    {
                        continue;
                    }
                    if !tag_sets_match(&self.include_tag_sets, &self.exclude_tag_sets, entity) {
                        continue;
                    }
                    if self.changed_mask != 0
                        && !Q::read_changed_newer(
                            fetch,
                            index,
                            &self.element_masks,
                            self.changed_mask,
                            self.since_tick,
                        )
                    {
                        continue;
                    }
                    if self.added_mask != 0
                        && !Q::read_added_newer(
                            fetch,
                            index,
                            &self.element_masks,
                            self.added_mask,
                            self.since_tick,
                        )
                    {
                        continue;
                    }
                    return Some((entity, Q::read_item(fetch, index)));
                }
                self.current = None;
            }

            loop {
                let table = if let Some(indices) = self.cached_tables {
                    let Some(&cached_index) = indices.get(self.table_index) else {
                        self.done = true;
                        return None;
                    };
                    self.table_index += 1;
                    &self.world.tables[cached_index]
                } else {
                    let Some(table) = self.world.tables.get(self.table_index) else {
                        self.done = true;
                        return None;
                    };
                    self.table_index += 1;
                    if table.mask & self.include != self.include {
                        continue;
                    }
                    table
                };
                if table.mask & self.exclude == 0 && !table.entity_indices.is_empty() {
                    self.row_index = 0;
                    self.current = Some((
                        table.entity_indices.as_slice(),
                        Q::read_fetch(table.mask, &table.columns, &self.element_masks),
                    ));
                    break;
                }
            }
        }
    }
}

fn tags_match(tags: &[SparseTagSet], entity: Entity, tag_include: u64, tag_exclude: u64) -> bool {
    for (tag_index, tag_set) in tags.iter().enumerate() {
        let tag_mask = 1u64 << (63 - tag_index as u32);
        if tag_include & tag_mask != 0 && !tag_set.contains(entity) {
            return false;
        }
        if tag_exclude & tag_mask != 0 && tag_set.contains(entity) {
            return false;
        }
    }
    true
}

/// A set of components spawned together. Implemented for tuples of
/// registered component types up to eight elements.
pub trait Bundle: sealed::SealedBundle {
    fn component_mask(world: &mut DynWorld) -> u64;
    fn write(self, world: &mut DynWorld, entity: Entity);
    fn write_group(self, ecs: &mut DynEcs, entity: Entity);
}

macro_rules! impl_bundle {
    ($($element:ident),+) => {
        impl<$($element: Send + Sync + Default + 'static),+> sealed::SealedBundle for ($($element,)+) {}

        impl<$($element: Send + Sync + Default + 'static),+> Bundle for ($($element,)+) {
            fn component_mask(world: &mut DynWorld) -> u64 {
                let mut mask = 0;
                $(
                    let element_mask = world.component_key::<$element>().mask;
                    assert_eq!(
                        mask & element_mask,
                        0,
                        "bundles must not repeat a component type"
                    );
                    mask |= element_mask;
                )+
                mask
            }

            #[allow(non_snake_case)]
            fn write(self, world: &mut DynWorld, entity: Entity) {
                let ($($element,)+) = self;
                $(world.set(entity, $element);)+
            }

            #[allow(non_snake_case)]
            fn write_group(self, ecs: &mut DynEcs, entity: Entity) {
                let ($($element,)+) = self;
                $(ecs.set(entity, $element);)+
            }
        }
    };
}

impl_bundle!(A);
impl_bundle!(A, B);
impl_bundle!(A, B, C);
impl_bundle!(A, B, C, D);
impl_bundle!(A, B, C, D, E);
impl_bundle!(A, B, C, D, E, F);
impl_bundle!(A, B, C, D, E, F, G);
impl_bundle!(A, B, C, D, E, F, G, H);

/// A cross-world typed query in progress, from [`DynEcs::query_join`].
/// The fields are plain data like every query builder in this crate. Tag
/// filters name group marker tags; `changed`/`added` filters name
/// driver-world components and panic when the type routes elsewhere, since
/// only the driver's ticks are walked in place.
/// Resolves one filter type's mask against the join's driver world.
pub type JoinMaskLookup = fn(&DynWorld) -> Option<u64>;

pub struct DynJoin<'ecs, Q: QueryTuple> {
    pub ecs: &'ecs mut DynEcs,
    pub include_tag_types: [Option<TypeId>; 4],
    pub exclude_tag_types: [Option<TypeId>; 4],
    pub changed_lookups: [Option<JoinMaskLookup>; 4],
    pub added_lookups: [Option<JoinMaskLookup>; 4],
    pub marker: PhantomData<Q>,
}

fn push_join_slot<T: Copy>(slots: &mut [Option<T>; 4], value: T) {
    for slot in slots.iter_mut() {
        if slot.is_none() {
            *slot = Some(value);
            return;
        }
    }
    panic!("a join filter family holds at most four entries");
}

fn join_mask_of<T: Send + Sync + Default + 'static>(world: &DynWorld) -> Option<u64> {
    world.lookup_key::<T>().map(|key| key.mask)
}

impl<Q: QueryTuple> DynJoin<'_, Q> {
    /// Only visit entities carrying the marker type `T`'s group tag. A tag
    /// nothing has used yet matches nothing.
    pub fn with_tag_type<T: 'static>(mut self) -> Self {
        push_join_slot(&mut self.include_tag_types, TypeId::of::<T>());
        self
    }

    /// Skip entities carrying the marker type `T`'s group tag.
    pub fn without_tag_type<T: 'static>(mut self) -> Self {
        push_join_slot(&mut self.exclude_tag_types, TypeId::of::<T>());
        self
    }

    /// Only visit entities whose `T` changed since the driver world's last
    /// step. `T` must be one of the tuple's driver-world components.
    pub fn changed<T: Send + Sync + Default + 'static>(mut self) -> Self {
        push_join_slot(&mut self.changed_lookups, join_mask_of::<T>);
        self
    }

    /// Only visit entities that gained `T` since the driver world's last
    /// step. `T` must be one of the tuple's driver-world components.
    pub fn added<T: Send + Sync + Default + 'static>(mut self) -> Self {
        push_join_slot(&mut self.added_lookups, join_mask_of::<T>);
        self
    }

    /// Runs the join. Routing, the driver rule, and the borrow split are
    /// documented on [`DynEcs::query_join`].
    pub fn for_each(self, f: impl for<'item> FnMut(Entity, Q::Item<'item>)) {
        let routes = Q::join_routes(&self.ecs.worlds);

        let mut driver: Option<usize> = None;
        for route in routes.iter().flatten() {
            if route.required && route.world.is_none() {
                panic!(
                    "{} is not registered in any member world; add it to a member schema first",
                    route.type_name
                );
            }
            if route.mutable
                && let Some(world) = route.world
            {
                match driver {
                    None => driver = Some(world),
                    Some(existing) => assert_eq!(
                        existing, world,
                        "cross-world queries mutate only one world's components; \
                         {} lives in member world {world}, but another mutable element \
                         already fixed the driver to member world {existing}",
                        route.type_name
                    ),
                }
            }
        }
        let driver = driver.unwrap_or_else(|| {
            let mut counts = vec![0usize; self.ecs.worlds.len()];
            for route in routes.iter().flatten() {
                if let Some(world) = route.world {
                    counts[world] += 1;
                }
            }
            counts
                .iter()
                .copied()
                .enumerate()
                .max_by_key(|&(index, count)| (count, usize::MAX - index))
                .map(|(index, _)| index)
                .expect("query_join requires at least one member world")
        });

        let mut include_sets: [Option<&SparseTagSet>; 4] = [None; 4];
        let mut exclude_sets: [Option<&SparseTagSet>; 4] = [None; 4];
        for (slot, type_id) in include_sets.iter_mut().zip(self.include_tag_types.iter()) {
            if let Some(type_id) = type_id {
                match self.ecs.tag_type_indices.get(type_id) {
                    Some(&index) => *slot = Some(&self.ecs.tags[index]),
                    None => return,
                }
            }
        }
        for (slot, type_id) in exclude_sets.iter_mut().zip(self.exclude_tag_types.iter()) {
            if let Some(type_id) = type_id
                && let Some(&index) = self.ecs.tag_type_indices.get(type_id)
            {
                *slot = Some(&self.ecs.tags[index]);
            }
        }

        let (left, rest) = self.ecs.worlds.split_at_mut(driver);
        let (driver_world, right) = rest
            .split_first_mut()
            .expect("the driver index is within the member list");
        let left: &[DynWorld] = left;
        let right: &[DynWorld] = right;

        let mut element_worlds: [Option<&DynWorld>; 8] = [None; 8];
        for (position, route) in routes.iter().enumerate() {
            if let Some(route) = route
                && let Some(world) = route.world
                && world != driver
            {
                element_worlds[position] = Some(if world < driver {
                    &left[world]
                } else {
                    &right[world - driver - 1]
                });
            }
        }

        let filters = JoinFilters {
            include_sets,
            exclude_sets,
            changed_lookups: self.changed_lookups,
            added_lookups: self.added_lookups,
        };
        Q::join_for_each(driver_world, &element_worlds, &filters, f);
    }

    /// The parallel form of [`for_each`](Self::for_each): driver tables run
    /// concurrently, rows within a table sequentially, foreign worlds are
    /// shared across threads read-only, and the `added` filter builds one
    /// scratch buffer per table task. Same routing rules and stamping.
    #[cfg(not(target_family = "wasm"))]
    pub fn par_for_each<F>(self, f: F)
    where
        F: for<'item> Fn(Entity, Q::Item<'item>) + Send + Sync,
    {
        let routes = Q::join_routes(&self.ecs.worlds);

        let mut driver: Option<usize> = None;
        for route in routes.iter().flatten() {
            if route.required && route.world.is_none() {
                panic!(
                    "{} is not registered in any member world; add it to a member schema first",
                    route.type_name
                );
            }
            if route.mutable
                && let Some(world) = route.world
            {
                match driver {
                    None => driver = Some(world),
                    Some(existing) => assert_eq!(
                        existing, world,
                        "cross-world queries mutate only one world's components; \
                         {} lives in member world {world}, but another mutable element \
                         already fixed the driver to member world {existing}",
                        route.type_name
                    ),
                }
            }
        }
        let driver = driver.unwrap_or_else(|| {
            let mut counts = vec![0usize; self.ecs.worlds.len()];
            for route in routes.iter().flatten() {
                if let Some(world) = route.world {
                    counts[world] += 1;
                }
            }
            counts
                .iter()
                .copied()
                .enumerate()
                .max_by_key(|&(index, count)| (count, usize::MAX - index))
                .map(|(index, _)| index)
                .expect("query_join requires at least one member world")
        });

        let mut include_sets: [Option<&SparseTagSet>; 4] = [None; 4];
        let mut exclude_sets: [Option<&SparseTagSet>; 4] = [None; 4];
        for (slot, type_id) in include_sets.iter_mut().zip(self.include_tag_types.iter()) {
            if let Some(type_id) = type_id {
                match self.ecs.tag_type_indices.get(type_id) {
                    Some(&index) => *slot = Some(&self.ecs.tags[index]),
                    None => return,
                }
            }
        }
        for (slot, type_id) in exclude_sets.iter_mut().zip(self.exclude_tag_types.iter()) {
            if let Some(type_id) = type_id
                && let Some(&index) = self.ecs.tag_type_indices.get(type_id)
            {
                *slot = Some(&self.ecs.tags[index]);
            }
        }

        let (left, rest) = self.ecs.worlds.split_at_mut(driver);
        let (driver_world, right) = rest
            .split_first_mut()
            .expect("the driver index is within the member list");
        let left: &[DynWorld] = left;
        let right: &[DynWorld] = right;

        let mut element_worlds: [Option<&DynWorld>; 8] = [None; 8];
        for (position, route) in routes.iter().enumerate() {
            if let Some(route) = route
                && let Some(world) = route.world
                && world != driver
            {
                element_worlds[position] = Some(if world < driver {
                    &left[world]
                } else {
                    &right[world - driver - 1]
                });
            }
        }

        let filters = JoinFilters {
            include_sets,
            exclude_sets,
            changed_lookups: self.changed_lookups,
            added_lookups: self.added_lookups,
        };
        Q::join_par_for_each(driver_world, &element_worlds, &filters, f);
    }
}

/// The read-only cross-world join builder, from
/// [`DynEcs::query_join_ref`]. Filter semantics mirror [`DynJoin`]'s,
/// except failures degrade to empty instead of panicking where the
/// read-only single-world path also degrades.
pub struct DynJoinRef<'ecs, Q: ReadQueryTuple> {
    pub ecs: &'ecs DynEcs,
    pub include_tag_types: [Option<TypeId>; 4],
    pub exclude_tag_types: [Option<TypeId>; 4],
    pub changed_lookups: [Option<JoinMaskLookup>; 4],
    pub added_lookups: [Option<JoinMaskLookup>; 4],
    pub marker: PhantomData<Q>,
}

impl<'ecs, Q: ReadQueryTuple> DynJoinRef<'ecs, Q> {
    /// Only visit entities carrying the marker type `T`'s group tag.
    pub fn with_tag_type<T: 'static>(mut self) -> Self {
        push_join_slot(&mut self.include_tag_types, TypeId::of::<T>());
        self
    }

    /// Skip entities carrying the marker type `T`'s group tag.
    pub fn without_tag_type<T: 'static>(mut self) -> Self {
        push_join_slot(&mut self.exclude_tag_types, TypeId::of::<T>());
        self
    }

    /// Only visit entities whose `T` changed since the driver world's last
    /// step. `T` must be one of the tuple's driver-world components; an
    /// unregistered `T` reads as an empty iterator.
    pub fn changed<T: Send + Sync + Default + 'static>(mut self) -> Self {
        push_join_slot(&mut self.changed_lookups, join_mask_of::<T>);
        self
    }

    /// Only visit entities that gained `T` since the driver world's last
    /// step, with the same rules as [`changed`](Self::changed).
    pub fn added<T: Send + Sync + Default + 'static>(mut self) -> Self {
        push_join_slot(&mut self.added_lookups, join_mask_of::<T>);
        self
    }

    /// Runs the join as an iterator of `(Entity, items)` borrowing the
    /// group.
    pub fn iter(self) -> DynJoinRefIter<'ecs, Q> {
        let dead_iterator = |ecs: &'ecs DynEcs| DynJoinRefIter {
            driver: &ecs.worlds[0],
            element_worlds: [None; 8],
            element_masks: [0u64; 8],
            include: 0,
            include_sets: [None; 4],
            exclude_sets: [None; 4],
            changed_mask: 0,
            added_mask: 0,
            since_tick: 0,
            added_scratch: Vec::new(),
            table_index: 0,
            row_index: 0,
            current: None,
            done: true,
            marker: PhantomData,
        };

        if self.ecs.worlds.is_empty() {
            panic!("query_join requires at least one member world");
        }

        let routes = Q::join_routes(&self.ecs.worlds);
        for route in routes.iter().flatten() {
            if route.required && route.world.is_none() {
                return dead_iterator(self.ecs);
            }
        }
        let mut counts = vec![0usize; self.ecs.worlds.len()];
        for route in routes.iter().flatten() {
            if let Some(world) = route.world {
                counts[world] += 1;
            }
        }
        let driver_index = counts
            .iter()
            .copied()
            .enumerate()
            .max_by_key(|&(index, count)| (count, usize::MAX - index))
            .map(|(index, _)| index)
            .expect("query_join requires at least one member world");

        let mut include_sets: [Option<&SparseTagSet>; 4] = [None; 4];
        let mut exclude_sets: [Option<&SparseTagSet>; 4] = [None; 4];
        for (slot, type_id) in include_sets.iter_mut().zip(self.include_tag_types.iter()) {
            if let Some(type_id) = type_id {
                match self.ecs.tag_type_indices.get(type_id) {
                    Some(&index) => *slot = Some(&self.ecs.tags[index]),
                    None => return dead_iterator(self.ecs),
                }
            }
        }
        for (slot, type_id) in exclude_sets.iter_mut().zip(self.exclude_tag_types.iter()) {
            if let Some(type_id) = type_id
                && let Some(&index) = self.ecs.tag_type_indices.get(type_id)
            {
                *slot = Some(&self.ecs.tags[index]);
            }
        }

        let driver = &self.ecs.worlds[driver_index];
        let mut element_worlds: [Option<&'ecs DynWorld>; 8] = [None; 8];
        for (position, route) in routes.iter().enumerate() {
            if let Some(route) = route
                && let Some(world) = route.world
                && world != driver_index
            {
                element_worlds[position] = Some(&self.ecs.worlds[world]);
            }
        }

        let Some((element_masks, include)) = Q::join_lookup(driver, &element_worlds) else {
            return dead_iterator(self.ecs);
        };

        let mut changed_mask = 0u64;
        for lookup in self.changed_lookups.iter().flatten() {
            match lookup(driver) {
                Some(mask) => changed_mask |= mask,
                None => return dead_iterator(self.ecs),
            }
        }
        let mut added_mask = 0u64;
        for lookup in self.added_lookups.iter().flatten() {
            match lookup(driver) {
                Some(mask) => added_mask |= mask,
                None => return dead_iterator(self.ecs),
            }
        }
        let local_tuple_mask = element_masks.iter().fold(0, |mask, element| mask | element);
        assert_eq!(
            (changed_mask | added_mask) & !local_tuple_mask,
            0,
            "changed and added filters must name components present in the query tuple"
        );

        DynJoinRefIter {
            driver,
            element_worlds,
            element_masks,
            include,
            include_sets,
            exclude_sets,
            changed_mask,
            added_mask,
            since_tick: driver.last_tick,
            added_scratch: Vec::new(),
            table_index: 0,
            row_index: 0,
            current: None,
            done: false,
            marker: PhantomData,
        }
    }
}

/// The iterator behind [`DynJoinRef::iter`]: walks the driver world's
/// matching tables in order, resolving foreign elements per entity. The
/// `added` filter recomputes its scratch per table into an iterator-owned
/// buffer.
pub struct DynJoinRefIter<'ecs, Q: ReadQueryTuple> {
    pub driver: &'ecs DynWorld,
    pub element_worlds: [Option<&'ecs DynWorld>; 8],
    pub element_masks: [u64; 8],
    pub include: u64,
    pub include_sets: [Option<&'ecs SparseTagSet>; 4],
    pub exclude_sets: [Option<&'ecs SparseTagSet>; 4],
    pub changed_mask: u64,
    pub added_mask: u64,
    pub since_tick: u32,
    pub added_scratch: Vec<bool>,
    pub table_index: usize,
    pub row_index: usize,
    pub current: Option<(&'ecs [Entity], Q::ReadFetch<'ecs>)>,
    pub done: bool,
    pub marker: PhantomData<Q>,
}

impl<'ecs, Q: ReadQueryTuple> Iterator for DynJoinRefIter<'ecs, Q> {
    type Item = (Entity, Q::Item<'ecs>);

    fn next(&mut self) -> Option<Self::Item> {
        if self.done {
            return None;
        }
        loop {
            if let Some((entities, fetch)) = self.current {
                while self.row_index < entities.len() {
                    let index = self.row_index;
                    self.row_index += 1;
                    let entity = entities[index];
                    if !tag_sets_match(&self.include_sets, &self.exclude_sets, entity) {
                        continue;
                    }
                    if self.added_mask != 0 && !self.added_scratch[index] {
                        continue;
                    }
                    if self.changed_mask != 0
                        && !Q::read_changed_newer(
                            fetch,
                            index,
                            &self.element_masks,
                            self.changed_mask,
                            self.since_tick,
                        )
                    {
                        continue;
                    }
                    match Q::join_read_item(fetch, &self.element_worlds, entity, index) {
                        Some(item) => return Some((entity, item)),
                        None => continue,
                    }
                }
                self.current = None;
            }

            let table = loop {
                let Some(table) = self.driver.tables.get(self.table_index) else {
                    self.done = true;
                    return None;
                };
                self.table_index += 1;
                if table.mask & self.include == self.include && !table.entity_indices.is_empty() {
                    break table;
                }
            };

            if self.added_mask != 0 {
                self.added_scratch.clear();
                self.added_scratch.resize(table.entity_indices.len(), false);
                for column in &table.columns {
                    if self.added_mask & (1u64 << column.component_index) == 0 {
                        continue;
                    }
                    for (row, &added_tick) in column.added.iter().enumerate() {
                        if tick_is_newer(added_tick, self.since_tick) {
                            self.added_scratch[row] = true;
                        }
                    }
                }
            }
            let fetch = Q::join_read_fetch(
                table.mask,
                &table.columns,
                &self.element_masks,
                &self.element_worlds,
            );
            self.current = Some((table.entity_indices.as_slice(), fetch));
            self.row_index = 0;
        }
    }
}

/// A mutable typed query resolved once and reused: element masks and
/// filter masks cached as plain copyable data, so hot systems skip the
/// per-call `TypeId` resolution. Build one by configuring a
/// [`DynQuery`] and calling [`prepare`](DynQuery::prepare); run it with
/// [`query`](Self::query). Prepared against one world's schema; running it
/// against a world with different mask assignments is a logic error that
/// the column machinery surfaces as a panic rather than wrong data.
#[derive(Clone, Copy)]
pub struct PreparedQuery<Q: QueryTuple> {
    pub element_masks: [u64; 8],
    pub include: u64,
    pub exclude: u64,
    pub changed_mask: u64,
    pub added_mask: u64,
    pub marker: PhantomData<Q>,
}

impl<Q: QueryTuple> PreparedQuery<Q> {
    /// Rehydrates the prepared masks into a runnable [`DynQuery`].
    /// Tag-set filters compose here at run time
    /// (`prepared.query(world).with_tag_set(...)`).
    pub fn query<'world>(&self, world: &'world mut DynWorld) -> DynQuery<'world, Q> {
        DynQuery {
            world,
            include: self.include,
            exclude: self.exclude,
            changed_mask: self.changed_mask,
            added_mask: self.added_mask,
            include_tag_sets: [None; 4],
            exclude_tag_sets: [None; 4],
            element_masks: Some(self.element_masks),
            marker: PhantomData,
        }
    }
}

/// The read-only prepared form, from [`DynQueryRef::prepare`]. A tuple
/// whose required elements were unregistered at prepare time stays dead,
/// matching `query_ref`'s graceful degradation.
#[derive(Clone, Copy)]
pub struct PreparedQueryRef<Q: ReadQueryTuple> {
    pub resolved_masks: Option<([u64; 8], u64)>,
    pub include: u64,
    pub exclude: u64,
    pub changed_mask: u64,
    pub added_mask: u64,
    pub marker: PhantomData<Q>,
}

impl<Q: ReadQueryTuple> PreparedQueryRef<Q> {
    /// Rehydrates the prepared masks into a runnable [`DynQueryRef`].
    pub fn query<'world>(&self, world: &'world DynWorld) -> DynQueryRef<'world, Q> {
        DynQueryRef {
            world,
            include: self.include,
            exclude: self.exclude,
            changed_mask: self.changed_mask,
            added_mask: self.added_mask,
            include_tag_sets: [None; 4],
            exclude_tag_sets: [None; 4],
            resolved_masks: self.resolved_masks,
            dead: self.resolved_masks.is_none(),
            marker: PhantomData,
        }
    }
}

/// A point-in-time census of one world's storage and bookkeeping, from
/// [`DynWorld::stats`]: table occupancy, schema budget, and the lengths of
/// every log and cache an editor overlay or a perf investigation reaches
/// for. Plain data, cheap to build, allocation proportional to the table
/// count.
#[derive(Clone, Debug, Default)]
pub struct WorldStats {
    pub entity_count: usize,
    pub table_count: usize,
    pub empty_table_count: usize,
    pub largest_table_rows: usize,
    pub table_rows: Vec<(u64, usize)>,
    pub component_count: usize,
    pub tag_count: usize,
    pub remaining_mask_bits: u32,
    pub structural_log_entries: usize,
    pub query_cache_entries: usize,
    pub resource_count: usize,
    pub event_channels: usize,
    pub pending_commands: usize,
}

/// The group-level census, from [`DynEcs::stats`]: allocator liveness,
/// group tags, logs, resources, and events, plus one [`WorldStats`] per
/// member world.
#[derive(Clone, Debug, Default)]
pub struct EcsStats {
    pub live_entities: usize,
    pub free_ids: usize,
    pub group_tag_count: usize,
    pub group_structural_log_entries: usize,
    pub group_resource_count: usize,
    pub group_event_channels: usize,
    pub worlds: Vec<WorldStats>,
}

/// A parent link for entity hierarchies: plain data, pull-maintained, no
/// hooks. Attach with `world.set(child, ChildOf(parent))`;
/// [`DynWorld::children`] and [`DynWorld::despawn_recursive`] scan it on
/// demand, [`HierarchyIndex`] answers from a synced map, and a link to a
/// despawned parent is just a link nothing resolves.
#[derive(Default, Clone, Copy, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct ChildOf(pub Entity);

/// A maintained child index over [`ChildOf`] links, for hierarchy-heavy
/// consumers: [`DynWorld::children`] scans every link carrier on demand,
/// while this answers from maps kept current by [`sync`](Self::sync).
///
/// Plain data owned by the consumer, no hooks: `sync` consumes the world's
/// structural log and change ticks, so every link write that stamps ticks
/// is picked up — spawns, `set`, migrations, and raw-tier writes followed
/// by [`DynWorld::mark_changed`] — and each sync costs proportional to what
/// changed since the last one. Reads reflect the last sync. In a
/// [`DynEcs`] group, sync against the member world holding the links and
/// despawn through the group using [`descendants`](Self::descendants).
pub struct HierarchyIndex {
    pub children: HashMap<Entity, Vec<Entity>>,
    pub parent_of: HashMap<Entity, Entity>,
    pub structural_cursor: u64,
    pub tick_cursor: u32,
}

impl Default for HierarchyIndex {
    fn default() -> Self {
        Self {
            children: HashMap::new(),
            parent_of: HashMap::new(),
            structural_cursor: 0,
            tick_cursor: u32::MAX,
        }
    }
}

impl HierarchyIndex {
    pub fn new() -> Self {
        Self::default()
    }

    /// Brings the index up to date with the world, then fences the change
    /// window with [`DynWorld::increment_tick`] so writes made after this
    /// call land in the next sync. Despawns and `ChildOf` removals unlink
    /// through the structural log; new and rewritten links relink from the
    /// component's current value.
    pub fn sync(&mut self, world: &mut DynWorld) {
        let child_mask = world
            .lookup_key::<ChildOf>()
            .map(|key| key.mask)
            .unwrap_or(0);

        let unlinks: Vec<Entity> = world
            .structural_changes_since(self.structural_cursor)
            .iter()
            .filter(|change| match change.kind {
                StructuralChangeKind::Despawned => true,
                StructuralChangeKind::ComponentsRemoved => change.mask & child_mask != 0,
                _ => false,
            })
            .map(|change| change.entity)
            .collect();
        for entity in unlinks {
            self.unlink(entity);
        }

        if child_mask != 0 {
            let relinks: Vec<Entity> = world
                .query_entities_changed_since(child_mask, self.tick_cursor)
                .collect();
            for entity in relinks {
                if let Some(child_of) = world.get::<ChildOf>(entity) {
                    self.relink(entity, child_of.0);
                }
            }
        }

        self.structural_cursor = world.structural_sequence();
        self.tick_cursor = world.current_tick();
        world.increment_tick();
    }

    fn unlink(&mut self, entity: Entity) {
        if let Some(parent) = self.parent_of.remove(&entity)
            && let Some(siblings) = self.children.get_mut(&parent)
        {
            siblings.retain(|&child| child != entity);
            if siblings.is_empty() {
                self.children.remove(&parent);
            }
        }
    }

    fn relink(&mut self, entity: Entity, parent: Entity) {
        if self.parent_of.get(&entity) == Some(&parent) {
            return;
        }
        self.unlink(entity);
        self.parent_of.insert(entity, parent);
        self.children.entry(parent).or_default().push(entity);
    }

    /// Children of a parent as of the last sync.
    pub fn children(&self, parent: Entity) -> &[Entity] {
        self.children.get(&parent).map(Vec::as_slice).unwrap_or(&[])
    }

    /// Every entity reachable from the root through child edges as of the
    /// last sync, breadth-first, root excluded. Link cycles are tolerated.
    pub fn descendants(&self, root: Entity) -> Vec<Entity> {
        let mut pending = vec![root];
        let mut visited: Vec<Entity> = Vec::new();
        while let Some(parent) = pending.pop() {
            for &child in self.children(parent) {
                if child != root && !visited.contains(&child) {
                    visited.push(child);
                    pending.push(child);
                }
            }
        }
        visited
    }

    /// Despawns the root and its indexed descendants in one pass, eagerly
    /// unlinking them so the index is consistent before the next sync.
    /// Answers from the index, not a scan, so sync first if links changed
    /// since the last one. Returns the despawned entities.
    pub fn despawn_recursive(&mut self, world: &mut DynWorld, root: Entity) -> Vec<Entity> {
        let mut targets = self.descendants(root);
        targets.insert(0, root);
        for &entity in &targets {
            self.unlink(entity);
            self.children.remove(&entity);
        }
        world.despawn_entities(&targets)
    }
}

/// A tuple of resource types taken out of a [`ResourceMap`] together by
/// [`DynWorld::resources_scope`] and [`DynEcs::resources_scope`].
/// Implemented for tuples of up to eight distinct resource types; presence
/// and distinctness are checked before anything is removed, so a failed
/// take leaves the map untouched.
pub trait ResourceBundle: sealed::SealedResourceBundle + Sized {
    fn take(resources: &mut ResourceMap) -> Self;
    fn put(self, resources: &mut ResourceMap);
}

macro_rules! impl_resource_bundle {
    ($($element:ident),+) => {
        impl<$($element: Send + Sync + 'static),+> sealed::SealedResourceBundle for ($($element,)+) {}

        impl<$($element: Send + Sync + 'static),+> ResourceBundle for ($($element,)+) {
            fn take(resources: &mut ResourceMap) -> Self {
                let elements = [$((TypeId::of::<$element>(), std::any::type_name::<$element>()),)+];
                for (index, (type_id, name)) in elements.iter().enumerate() {
                    assert!(
                        !elements[..index].iter().any(|(seen, _)| seen == type_id),
                        "resource scopes must not repeat a resource type: {name}"
                    );
                    assert!(
                        resources.entries.contains_key(type_id),
                        "resources_scope requires {name} to be present"
                    );
                }
                ($(
                    resources
                        .remove::<$element>()
                        .expect("presence was checked before any removal"),
                )+)
            }

            #[allow(non_snake_case)]
            fn put(self, resources: &mut ResourceMap) {
                let ($($element,)+) = self;
                $(resources.insert($element);)+
            }
        }
    };
}

impl_resource_bundle!(A);
impl_resource_bundle!(A, B);
impl_resource_bundle!(A, B, C);
impl_resource_bundle!(A, B, C, D);
impl_resource_bundle!(A, B, C, D, E);
impl_resource_bundle!(A, B, C, D, E, F);
impl_resource_bundle!(A, B, C, D, E, F, G);
impl_resource_bundle!(A, B, C, D, E, F, G, H);

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

    #[derive(Default, Clone, Debug, PartialEq)]
    #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
    pub struct Position {
        pub x: f32,
        pub y: f32,
    }

    #[derive(Default, Clone, Debug, PartialEq)]
    #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
    pub struct Velocity {
        pub x: f32,
        pub y: f32,
    }

    #[derive(Default, Clone, Debug, PartialEq)]
    #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
    pub struct Health {
        pub value: f32,
    }

    #[derive(Default, Debug, Clone, PartialEq)]
    #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
    pub struct PingEvent {
        pub value: u32,
    }

    struct Lcg(u64);

    impl Lcg {
        fn next(&mut self) -> u64 {
            self.0 = self
                .0
                .wrapping_mul(6364136223846793005)
                .wrapping_add(1442695040888963407);
            self.0 >> 16
        }
    }

    #[test]
    fn test_register_is_idempotent_and_orders_bits() {
        let mut world = DynWorld::new();
        let position = world.register::<Position>();
        let velocity = world.register::<Velocity>();
        let position_again = world.register::<Position>();

        assert_eq!(position.mask, 1);
        assert_eq!(velocity.mask, 2);
        assert_eq!(position.mask, position_again.mask);
        assert_eq!(world.registry.all_components_mask(), 0b11);
    }

    #[test]
    fn test_spawn_get_set_keyed() {
        let mut world = DynWorld::new();
        let position = world.register::<Position>();
        let velocity = world.register::<Velocity>();

        let entity = world.spawn_entities(position.mask | velocity.mask, 1)[0];
        assert_eq!(
            world.get_keyed(position, entity),
            Some(&Position { x: 0.0, y: 0.0 })
        );

        world.set_keyed(position, entity, Position { x: 1.0, y: 2.0 });
        assert_eq!(world.get_keyed(position, entity).unwrap().x, 1.0);

        world.get_mut_keyed(velocity, entity).unwrap().x = 5.0;
        assert_eq!(world.get_keyed(velocity, entity).unwrap().x, 5.0);
    }

    #[test]
    fn test_set_adds_missing_component_by_migration() {
        let mut world = DynWorld::new();
        let position = world.register::<Position>();
        let health = world.register::<Health>();

        let entity = world.spawn_entities(position.mask, 1)[0];
        world.set_keyed(position, entity, Position { x: 3.0, y: 0.0 });
        world.set_keyed(health, entity, Health { value: 10.0 });

        assert_eq!(
            world.component_mask(entity),
            Some(position.mask | health.mask)
        );
        assert_eq!(
            world.get_keyed(position, entity).unwrap().x,
            3.0,
            "migration must preserve existing component values"
        );
        assert_eq!(world.get_keyed(health, entity).unwrap().value, 10.0);
    }

    #[test]
    fn test_despawn_refuses_stale_and_double() {
        let mut world = DynWorld::new();
        let position = world.register::<Position>();

        let entity = world.spawn_entities(position.mask, 1)[0];
        assert_eq!(world.despawn_entities(&[entity]).len(), 1);
        assert!(world.despawn_entities(&[entity]).is_empty());

        let reused = world.spawn_entities(position.mask, 1)[0];
        assert_eq!(reused.id, entity.id);
        assert_eq!(reused.generation, entity.generation + 1);
        assert!(world.get_keyed(position, entity).is_none());
        assert!(!world.add_components(entity, position.mask));
        assert!(world.is_alive(reused));
        assert!(!world.is_alive(entity));
    }

    #[test]
    fn test_tags_and_structural_log() {
        let mut world = DynWorld::new();
        let position = world.register::<Position>();
        let boss = world.register_tag();

        let entity = world.spawn_entities(position.mask, 1)[0];
        world.add_tag(boss, entity);
        assert!(world.has_tag(boss, entity));
        assert_eq!(world.query_tag(boss).count(), 1);

        let kinds: Vec<StructuralChangeKind> = world
            .structural_changes_since(0)
            .iter()
            .map(|change| change.kind)
            .collect();
        assert_eq!(
            kinds,
            vec![
                StructuralChangeKind::Spawned,
                StructuralChangeKind::TagsAdded
            ]
        );

        world.despawn_entities(&[entity]);
        assert!(!world.has_tag(boss, entity));
    }

    #[test]
    fn test_typed_tier_and_bundles() {
        let mut world = DynWorld::new();

        let entity = world.spawn((Position { x: 1.0, y: 2.0 }, Velocity { x: 3.0, y: 4.0 }));

        assert_eq!(world.get::<Position>(entity).unwrap().x, 1.0);
        assert_eq!(world.get::<Velocity>(entity).unwrap().y, 4.0);
        assert!(world.get::<Health>(entity).is_none());
        assert!(world.has::<Position>(entity));

        world.set(entity, Health { value: 50.0 });
        assert_eq!(world.get::<Health>(entity).unwrap().value, 50.0);

        assert!(world.remove::<Health>(entity));
        assert!(world.get::<Health>(entity).is_none());
    }

    #[test]
    fn test_typed_query_iterates_and_stamps() {
        let mut world = DynWorld::new();
        let moving = world.spawn((Position::default(), Velocity { x: 2.0, y: 0.0 }));
        let still = world.spawn((Position { x: 9.0, y: 9.0 },));

        world.step();

        let mut visited = Vec::new();
        world
            .query::<(&mut Position, &Velocity)>()
            .for_each(|entity, (position, velocity)| {
                position.x += velocity.x;
                visited.push(entity);
            });

        assert_eq!(visited, vec![moving]);
        assert_eq!(world.get::<Position>(moving).unwrap().x, 2.0);
        assert_eq!(world.get::<Position>(still).unwrap().x, 9.0);

        let position_mask = world.component_key::<Position>().mask;
        let changed: Vec<Entity> = world.query_entities_changed(position_mask).collect();
        assert_eq!(
            changed,
            vec![moving],
            "mutable query elements must stamp change ticks"
        );
    }

    #[test]
    fn test_typed_query_filters() {
        let mut world = DynWorld::new();
        let selected = world.register_tag();

        let plain = world.spawn((Position::default(),));
        let tagged = world.spawn((Position::default(),));
        let armored = world.spawn((Position::default(), Health { value: 1.0 }));
        world.add_tag(selected, tagged);

        let mut with_tag = Vec::new();
        world
            .query::<(&Position,)>()
            .with_tag(selected)
            .for_each(|entity, _| with_tag.push(entity));
        assert_eq!(with_tag, vec![tagged]);

        let mut without_health = Vec::new();
        world
            .query::<(&Position,)>()
            .without::<Health>()
            .for_each(|entity, _| without_health.push(entity));
        assert_eq!(without_health.len(), 2);
        assert!(!without_health.contains(&armored));
        assert!(without_health.contains(&plain));
    }

    #[test]
    fn test_typed_query_changed_filter() {
        let mut world = DynWorld::new();
        let first = world.spawn((Position::default(), Velocity::default()));
        let second = world.spawn((Position::default(), Velocity::default()));

        world.step();
        world.get_mut::<Position>(first).unwrap().x = 1.0;

        let mut visited = Vec::new();
        world
            .query::<(&Position, &Velocity)>()
            .changed::<Position>()
            .for_each(|entity, _| visited.push(entity));

        assert_eq!(visited, vec![first]);
        let _ = second;
    }

    #[test]
    #[should_panic(expected = "must not repeat a component type")]
    fn test_typed_query_rejects_repeated_component() {
        let mut world = DynWorld::new();
        world.spawn((Position::default(),));
        world
            .query::<(&mut Position, &Position)>()
            .for_each(|_, _| {});
    }

    #[test]
    #[should_panic(expected = "must not repeat a component type")]
    fn test_typed_query_rejects_optional_repeat_of_component() {
        let mut world = DynWorld::new();
        world.spawn((Position::default(),));
        world
            .query::<(&mut Position, Option<&Position>)>()
            .for_each(|_, _| {});
    }

    #[test]
    fn test_optional_element_yields_none_on_missing_component() {
        let mut world = DynWorld::new();
        let plain = world.spawn((Position { x: 1.0, y: 0.0 },));
        let moving = world.spawn((Position { x: 2.0, y: 0.0 }, Velocity { x: 5.0, y: 0.0 }));

        let mut visited = Vec::new();
        world
            .query::<(&Position, Option<&Velocity>)>()
            .for_each(|entity, (position, velocity)| {
                visited.push((entity, position.x, velocity.map(|velocity| velocity.x)));
            });

        visited.sort_by(|left, right| left.1.total_cmp(&right.1));
        assert_eq!(visited, vec![(plain, 1.0, None), (moving, 2.0, Some(5.0))]);
    }

    #[test]
    fn test_optional_mut_element_stamps_only_present_rows() {
        let mut world = DynWorld::new();
        let velocity_key = world.register::<Velocity>();
        let plain = world.spawn((Position::default(),));
        let moving = world.spawn((Position::default(), Velocity::default()));

        world.step();
        world
            .query::<(&Position, Option<&mut Velocity>)>()
            .for_each(|_entity, (_position, velocity)| {
                if let Some(velocity) = velocity {
                    velocity.x += 1.0;
                }
            });

        assert_eq!(world.get::<Velocity>(moving).unwrap().x, 1.0);
        let changed: Vec<Entity> = world.query_entities_changed(velocity_key.mask).collect();
        assert_eq!(changed, vec![moving]);
        let _ = plain;
    }

    #[test]
    fn test_optional_only_tuple_visits_every_entity() {
        let mut world = DynWorld::new();
        world.spawn((Position::default(),));
        world.spawn((Velocity::default(),));
        world.spawn((Health::default(),));

        let mut count = 0;
        world
            .query::<(Option<&Position>, Option<&Velocity>)>()
            .for_each(|_entity, _items| count += 1);
        assert_eq!(count, 3);
    }

    #[test]
    fn test_changed_filter_on_optional_element() {
        let mut world = DynWorld::new();
        let still = world.spawn((Position::default(), Velocity::default()));
        let moving = world.spawn((Position::default(), Velocity::default()));
        let bare = world.spawn((Position::default(),));

        world.step();
        world.get_mut::<Velocity>(moving).unwrap().x = 3.0;

        let mut visited = Vec::new();
        world
            .query::<(&Position, Option<&Velocity>)>()
            .changed::<Velocity>()
            .for_each(|entity, _| visited.push(entity));

        assert_eq!(visited, vec![moving]);
        let _ = (still, bare);
    }

    #[test]
    fn test_query_tuple_arity_eight() {
        #[derive(Default, Clone, Debug, PartialEq)]
        struct C1(f32);
        #[derive(Default, Clone, Debug, PartialEq)]
        struct C2(f32);
        #[derive(Default, Clone, Debug, PartialEq)]
        struct C3(f32);
        #[derive(Default, Clone, Debug, PartialEq)]
        struct C4(f32);
        #[derive(Default, Clone, Debug, PartialEq)]
        struct C5(f32);
        #[derive(Default, Clone, Debug, PartialEq)]
        struct C6(f32);
        #[derive(Default, Clone, Debug, PartialEq)]
        struct C7(f32);
        #[derive(Default, Clone, Debug, PartialEq)]
        struct C8(f32);

        let mut world = DynWorld::new();
        let entity = world.spawn((
            C1(1.0),
            C2(2.0),
            C3(3.0),
            C4(4.0),
            C5(5.0),
            C6(6.0),
            C7(7.0),
            C8(8.0),
        ));

        let mut total = 0.0;
        world
            .query::<(&C1, &C2, &C3, &mut C4, &C5, &C6, &C7, &mut C8)>()
            .for_each(|seen, (c1, c2, c3, c4, c5, c6, c7, c8)| {
                assert_eq!(seen, entity);
                c4.0 += 10.0;
                c8.0 += 10.0;
                total = c1.0 + c2.0 + c3.0 + c4.0 + c5.0 + c6.0 + c7.0 + c8.0;
            });

        assert_eq!(total, 56.0);
        assert_eq!(world.get::<C4>(entity).unwrap().0, 14.0);
        assert_eq!(world.get::<C8>(entity).unwrap().0, 18.0);
    }

    #[test]
    fn test_query_ref_iterates_and_collects_borrows() {
        let mut world = DynWorld::new();
        let plain = world.spawn((Position { x: 1.0, y: 0.0 },));
        let moving = world.spawn((Position { x: 2.0, y: 0.0 }, Velocity { x: 5.0, y: 0.0 }));

        let mut collected: Vec<(Entity, &Position, Option<&Velocity>)> = world
            .query_ref::<(&Position, Option<&Velocity>)>()
            .iter()
            .map(|(entity, (position, velocity))| (entity, position, velocity))
            .collect();
        collected.sort_by(|left, right| left.1.x.total_cmp(&right.1.x));

        assert_eq!(collected.len(), 2);
        assert_eq!(collected[0], (plain, &Position { x: 1.0, y: 0.0 }, None));
        assert_eq!(
            collected[1],
            (
                moving,
                &Position { x: 2.0, y: 0.0 },
                Some(&Velocity { x: 5.0, y: 0.0 })
            )
        );

        let total: f32 = world
            .query_ref::<(&Position,)>()
            .iter()
            .map(|(_entity, (position,))| position.x)
            .sum();
        assert_eq!(total, 3.0);
    }

    #[test]
    fn test_query_ref_filters_match_for_each() {
        let mut world = DynWorld::new();
        let boss = world.register_tag();
        let tagged = world.spawn((Position { x: 1.0, y: 0.0 }, Velocity::default()));
        let untagged = world.spawn((Position { x: 2.0, y: 0.0 }, Velocity::default()));
        let frozen = world.spawn((Position { x: 3.0, y: 0.0 },));
        world.add_tag(boss, tagged);

        let with_velocity: Vec<Entity> = world
            .query_ref::<(&Position,)>()
            .with::<Velocity>()
            .iter()
            .map(|(entity, _)| entity)
            .collect();
        assert_eq!(with_velocity, vec![tagged, untagged]);

        let without_velocity: Vec<Entity> = world
            .query_ref::<(&Position,)>()
            .without::<Velocity>()
            .iter()
            .map(|(entity, _)| entity)
            .collect();
        assert_eq!(without_velocity, vec![frozen]);

        let tagged_only: Vec<Entity> = world
            .query_ref::<(&Position,)>()
            .with_tag(boss)
            .iter()
            .map(|(entity, _)| entity)
            .collect();
        assert_eq!(tagged_only, vec![tagged]);

        world.step();
        world.get_mut::<Position>(untagged).unwrap().x = 9.0;
        let changed: Vec<Entity> = world
            .query_ref::<(&Position,)>()
            .changed::<Position>()
            .iter()
            .map(|(entity, _)| entity)
            .collect();
        assert_eq!(changed, vec![untagged]);
    }

    #[test]
    fn test_query_ref_unregistered_types_match_nothing_and_do_not_register() {
        #[derive(Default, Clone, Debug)]
        struct Unseen;

        let mut world = DynWorld::new();
        world.spawn((Position::default(),));
        let registered = world.registry.components.len();

        assert_eq!(world.query_ref::<(&Unseen,)>().iter().count(), 0);
        assert_eq!(
            world
                .query_ref::<(&Position, Option<&Unseen>)>()
                .iter()
                .map(|(_entity, (_position, unseen))| {
                    assert!(unseen.is_none());
                })
                .count(),
            1
        );
        assert_eq!(
            world
                .query_ref::<(&Position,)>()
                .with::<Unseen>()
                .iter()
                .count(),
            0
        );
        assert_eq!(world.registry.components.len(), registered);
    }

    #[test]
    fn test_marker_tags_register_lazily_and_share_index_space() {
        struct Boss;
        struct Frozen;

        let mut world = DynWorld::new();
        let keyed = world.register_tag();
        let boss = world.tag_key::<Boss>();
        let boss_again = world.tag_key::<Boss>();

        assert_eq!(boss.tag_index, keyed.tag_index + 1);
        assert_eq!(boss, boss_again);
        assert!(world.lookup_tag_key::<Frozen>().is_none());

        let entity = world.spawn((Position::default(),));
        world.add_tag_type::<Boss>(entity);
        assert!(world.has_tag_type::<Boss>(entity));
        assert!(world.has_tag(boss, entity));
        assert!(!world.has_tag_type::<Frozen>(entity));

        assert_eq!(
            world.query_tag_type::<Boss>().collect::<Vec<_>>(),
            vec![entity]
        );
        assert_eq!(world.query_tag_type::<Frozen>().count(), 0);

        assert!(world.remove_tag_type::<Boss>(entity));
        assert!(!world.has_tag_type::<Boss>(entity));
        assert!(!world.remove_tag_type::<Frozen>(entity));
    }

    #[test]
    fn test_marker_tag_query_filters() {
        struct Boss;

        let mut world = DynWorld::new();
        let tagged = world.spawn((Position { x: 1.0, y: 0.0 },));
        let untagged = world.spawn((Position { x: 2.0, y: 0.0 },));
        world.add_tag_type::<Boss>(tagged);

        let mut with_tag = Vec::new();
        world
            .query::<(&Position,)>()
            .with_tag_type::<Boss>()
            .for_each(|entity, _| with_tag.push(entity));
        assert_eq!(with_tag, vec![tagged]);

        let mut without_tag = Vec::new();
        world
            .query::<(&Position,)>()
            .without_tag_type::<Boss>()
            .for_each(|entity, _| without_tag.push(entity));
        assert_eq!(without_tag, vec![untagged]);

        let with_tag_ref: Vec<Entity> = world
            .query_ref::<(&Position,)>()
            .with_tag_type::<Boss>()
            .iter()
            .map(|(entity, _)| entity)
            .collect();
        assert_eq!(with_tag_ref, vec![tagged]);
    }

    #[test]
    fn test_marker_tag_filters_on_unregistered_types() {
        struct Never;

        let mut world = DynWorld::new();
        world.spawn((Position::default(),));

        assert_eq!(
            world
                .query_ref::<(&Position,)>()
                .with_tag_type::<Never>()
                .iter()
                .count(),
            0
        );
        assert_eq!(
            world
                .query_ref::<(&Position,)>()
                .without_tag_type::<Never>()
                .iter()
                .count(),
            1
        );
        assert!(world.lookup_tag_key::<Never>().is_none());
    }

    #[test]
    fn test_marker_tag_commands() {
        struct Boss;

        let mut world = DynWorld::new();
        let entity = world.spawn((Position::default(),));

        world.queue_add_tag_type::<Boss>(entity);
        world.apply_commands();
        assert!(world.has_tag_type::<Boss>(entity));

        world.queue_remove_tag_type::<Boss>(entity);
        world.apply_commands();
        assert!(!world.has_tag_type::<Boss>(entity));
    }

    #[test]
    fn test_mark_changed_stamps_raw_writes() {
        let mut world = DynWorld::new();
        let position = world.register::<Position>();
        let entities = world.spawn_entities(position.mask, 3);

        world.step();
        world.for_each_tables_mut(position.mask, 0, |table| {
            table.column_mut(position)[1].x = 5.0;
        });
        assert_eq!(world.query_entities_changed(position.mask).count(), 0);

        assert!(world.mark_changed(entities[1], position.mask));
        let changed: Vec<Entity> = world.query_entities_changed(position.mask).collect();
        assert_eq!(changed, vec![entities[1]]);
    }

    #[test]
    fn test_mark_changed_rejects_missing_rows() {
        let mut world = DynWorld::new();
        let position = world.register::<Position>();
        let velocity = world.register::<Velocity>();
        let entity = world.spawn_entities(position.mask, 1)[0];
        let dead = world.spawn_entities(position.mask, 1)[0];
        world.despawn_entities(&[dead]);

        assert!(!world.mark_changed(entity, velocity.mask));
        assert!(!world.mark_changed(dead, position.mask));

        let boss = world.register_tag();
        assert!(!world.mark_changed(entity, boss.mask));
        assert!(world.mark_changed(entity, position.mask | boss.mask));
    }

    #[test]
    fn test_mark_columns_changed_bulk_stamps_one_table() {
        let mut world = DynWorld::new();
        let position = world.register::<Position>();
        let velocity = world.register::<Velocity>();
        let plain = world.spawn_entities(position.mask, 2);
        let moving = world.spawn_entities(position.mask | velocity.mask, 2);

        world.step();
        let current_tick = world.current_tick();
        world.for_each_tables_mut(position.mask | velocity.mask, 0, |table| {
            for value in table.column_mut(position) {
                value.x += 1.0;
            }
            table.mark_columns_changed(position.mask, current_tick);
        });

        let changed: Vec<Entity> = world.query_entities_changed(position.mask).collect();
        assert_eq!(changed, moving);
        assert_eq!(world.query_entities_changed(velocity.mask).count(), 0);
        let _ = plain;
    }

    #[test]
    fn test_despawn_with_any_clears_matching_kinds() {
        let mut world = DynWorld::new();
        let plain = world.spawn((Position::default(),));
        let moving = world.spawn((Position::default(), Velocity::default()));
        let hurt = world.spawn((Health::default(),));

        let despawned = world.despawn_with_any::<(Velocity, Health)>();

        assert_eq!(despawned.len(), 2);
        assert!(despawned.contains(&moving));
        assert!(despawned.contains(&hurt));
        assert!(world.is_alive(plain));
        assert!(!world.is_alive(moving));
        assert!(!world.is_alive(hurt));

        #[derive(Default, Clone)]
        struct NeverSpawned;
        assert!(world.despawn_with_any::<(NeverSpawned,)>().is_empty());
        assert!(world.is_alive(plain));
    }

    #[test]
    fn test_mutable_query_stamps_peak_only_when_rows_are_visited() {
        let mut world = DynWorld::new();
        let position = world.register::<Position>();
        let boss = world.register_tag();
        world.spawn_entities(position.mask, 2);

        world.step();
        world
            .query::<(&mut Position,)>()
            .with_tag(boss)
            .for_each(|_entity, _items| {});

        for table in &world.tables {
            if table.mask == position.mask {
                assert!(
                    !tick_is_newer(table.columns[0].peak_changed, world.last_tick),
                    "a query that visits no rows must not stamp the table peak"
                );
            }
        }

        world
            .query::<(&mut Position,)>()
            .for_each(|_entity, _items| {});
        for table in &world.tables {
            if table.mask == position.mask {
                assert!(tick_is_newer(
                    table.columns[0].peak_changed,
                    world.last_tick
                ));
            }
        }
    }

    #[test]
    fn test_filtered_mutable_query_keeps_changed_sets_exact() {
        let mut world = DynWorld::new();
        let position = world.register::<Position>();
        let boss = world.register_tag();
        let entities = world.spawn_entities(position.mask, 4);
        world.add_tag(boss, entities[1]);
        world.add_tag(boss, entities[3]);

        world.step();
        world
            .query::<(&mut Position,)>()
            .with_tag(boss)
            .for_each(|_entity, (value,)| value.x += 1.0);

        let changed: Vec<Entity> = world.query_entities_changed(position.mask).collect();
        assert_eq!(changed, vec![entities[1], entities[3]]);

        world.step();
        assert_eq!(world.query_entities_changed(position.mask).count(), 0);
    }

    #[test]
    fn test_query_ref_reuses_cached_table_lists() {
        let mut world = DynWorld::new();
        let position = world.register::<Position>();
        world.spawn_entities(position.mask, 2);
        let velocity = world.register::<Velocity>();
        world.spawn_entities(position.mask | velocity.mask, 3);

        world.for_each_mut(position.mask, 0, |_entity, _table, _index| {});
        assert!(world.query_cache.contains_key(&position.mask));

        assert_eq!(world.query_ref::<(&Position,)>().iter().count(), 5);

        world.spawn_entities(position.mask, 1);
        assert_eq!(
            world.query_ref::<(&Position,)>().iter().count(),
            6,
            "cache entries must stay current as tables grow"
        );
    }

    #[test]
    #[should_panic(expected = "bundles must not repeat a component type")]
    fn test_bundle_rejects_repeated_component() {
        let mut world = DynWorld::new();
        world.spawn((Position::default(), Position { x: 1.0, y: 0.0 }));
    }

    #[test]
    fn test_resource_scope_preserves_resource_on_panic() {
        struct Score {
            value: u32,
        }

        let mut world = DynWorld::new();
        world.insert_resource(Score { value: 7 });

        let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            world.resource_scope(|_world, _score: &mut Score| panic!("boom"));
        }));

        assert!(result.is_err());
        assert_eq!(world.resource::<Score>().unwrap().value, 7);
    }

    #[test]
    fn test_consume_events_delivers_exactly_once_per_cursor() {
        let mut world = DynWorld::new();
        world.send(PingEvent { value: 1 });
        world.send(PingEvent { value: 2 });

        let mut first_cursor = 0;
        let mut second_cursor = 0;

        let values: Vec<u32> = world
            .consume_events::<PingEvent>(&mut first_cursor)
            .iter()
            .map(|event| event.value)
            .collect();
        assert_eq!(values, vec![1, 2]);
        assert!(
            world
                .consume_events::<PingEvent>(&mut first_cursor)
                .is_empty()
        );

        world.step();
        world.send(PingEvent { value: 3 });

        let next: Vec<u32> = world
            .consume_events::<PingEvent>(&mut first_cursor)
            .iter()
            .map(|event| event.value)
            .collect();
        assert_eq!(next, vec![3], "the two-frame buffer must not re-deliver");

        let all: Vec<u32> = world
            .consume_events::<PingEvent>(&mut second_cursor)
            .iter()
            .map(|event| event.value)
            .collect();
        assert_eq!(
            all,
            vec![1, 2, 3],
            "independent consumers own their cursors"
        );

        struct NeverSent;
        let mut untouched = 0;
        assert!(world.consume_events::<NeverSent>(&mut untouched).is_empty());
        assert_eq!(untouched, 0);
    }

    #[test]
    fn test_expect_resource_returns_and_panics_with_type_name() {
        struct Score(u32);

        let mut world = DynWorld::new();
        world.insert_resource(Score(5));

        assert_eq!(world.expect_resource::<Score>().0, 5);
        world.expect_resource_mut::<Score>().0 += 1;
        assert_eq!(world.expect_resource::<Score>().0, 6);
    }

    #[test]
    #[should_panic(expected = "expect_resource requires")]
    fn test_expect_resource_panics_on_missing_resource() {
        struct Missing;

        let world = DynWorld::new();
        world.expect_resource::<Missing>();
    }

    #[test]
    fn test_spawn_bundles_clones_per_entity() {
        let mut world = DynWorld::new();
        let entities = world.spawn_bundles(
            (Position { x: 4.0, y: 0.0 }, Velocity { x: 1.0, y: 0.0 }),
            3,
        );

        assert_eq!(entities.len(), 3);
        for &entity in &entities {
            assert_eq!(world.get::<Position>(entity).unwrap().x, 4.0);
            assert_eq!(world.get::<Velocity>(entity).unwrap().x, 1.0);
        }
    }

    #[test]
    fn test_bare_element_queries_match_single_tuples() {
        let mut world = DynWorld::new();
        let plain = world.spawn((Position { x: 1.0, y: 0.0 },));
        let moving = world.spawn((Position { x: 2.0, y: 0.0 }, Velocity { x: 5.0, y: 0.0 }));

        world
            .query::<&mut Position>()
            .for_each(|_entity, position| position.x += 10.0);
        assert_eq!(world.get::<Position>(plain).unwrap().x, 11.0);
        assert_eq!(world.get::<Position>(moving).unwrap().x, 12.0);

        let mut velocities = Vec::new();
        world
            .query::<Option<&Velocity>>()
            .for_each(|entity, velocity| {
                velocities.push((entity, velocity.map(|velocity| velocity.x)));
            });
        velocities.sort_by_key(|(entity, _)| entity.id);
        assert_eq!(velocities, vec![(plain, None), (moving, Some(5.0))]);

        let total: f32 = world
            .query_ref::<&Position>()
            .iter()
            .map(|(_entity, position)| position.x)
            .sum();
        assert_eq!(total, 23.0);

        let with_velocity: Vec<Entity> = world
            .query_ref::<Option<&Velocity>>()
            .iter()
            .filter(|(_entity, velocity)| velocity.is_some())
            .map(|(entity, _)| entity)
            .collect();
        assert_eq!(with_velocity, vec![moving]);

        world.step();
        world.get_mut::<Position>(plain).unwrap().x = 0.0;
        let mut changed = Vec::new();
        world
            .query::<&Position>()
            .changed::<Position>()
            .for_each(|entity, _position| changed.push(entity));
        assert_eq!(changed, vec![plain]);
    }

    #[test]
    fn test_remaining_bits_counts_components_and_tags() {
        let mut world = DynWorld::new();
        assert_eq!(world.remaining_bits(), 64);
        world.register::<Position>();
        world.register::<Velocity>();
        world.register_tag();
        world.tag_key::<Health>();
        assert_eq!(world.remaining_bits(), 60);
    }

    #[test]
    fn test_added_filter_matches_spawns_and_component_adds_only() {
        let mut world = DynWorld::new();
        let velocity = world.register::<Velocity>();
        let veteran = world.spawn((Position::default(),));

        world.step();
        let fresh = world.spawn((Position::default(),));
        world.add_components(veteran, velocity.mask);
        let mut added_positions = Vec::new();
        world
            .query::<&Position>()
            .added::<Position>()
            .for_each(|entity, _position| added_positions.push(entity));
        assert_eq!(
            added_positions,
            vec![fresh],
            "a migration must carry the original added tick"
        );

        let mut added_velocities = Vec::new();
        world
            .query::<&Velocity>()
            .added::<Velocity>()
            .for_each(|entity, _velocity| added_velocities.push(entity));
        assert_eq!(added_velocities, vec![veteran]);

        world.step();
        world.get_mut::<Position>(fresh).unwrap().x = 5.0;
        let added_now: Vec<Entity> = world
            .query_ref::<&Position>()
            .added::<Position>()
            .iter()
            .map(|(entity, _position)| entity)
            .collect();
        assert!(
            added_now.is_empty(),
            "mutation must not retrigger the added filter"
        );
        let changed_now: Vec<Entity> = world
            .query_ref::<&Position>()
            .changed::<Position>()
            .iter()
            .map(|(entity, _position)| entity)
            .collect();
        assert_eq!(changed_now, vec![fresh]);
    }

    #[test]
    #[should_panic(expected = "added filters must name components")]
    fn test_added_filter_rejects_types_outside_tuple() {
        let mut world = DynWorld::new();
        world.register::<Velocity>();
        world.spawn((Position::default(),));
        world
            .query_ref::<&Position>()
            .added::<Velocity>()
            .iter()
            .count();
    }

    #[test]
    fn test_queue_spawn_returns_live_handle_before_apply() {
        let mut world = DynWorld::new();

        let entity = world.queue_spawn((Position { x: 3.0, y: 0.0 }, Velocity::default()));
        assert!(world.is_alive(entity));
        assert!(world.get::<Position>(entity).is_none());

        world.queue_set(entity, Health { value: 50.0 });
        world.apply_commands();

        assert_eq!(world.get::<Position>(entity).unwrap().x, 3.0);
        assert_eq!(world.get::<Health>(entity).unwrap().value, 50.0);
    }

    #[test]
    fn test_entity_components_and_component_by_name() {
        let mut world = DynWorld::new();
        let entity = world.spawn((Position::default(), Velocity::default()));
        world.register::<Health>();

        let mut names: Vec<&str> = world
            .entity_components(entity)
            .map(|info| info.type_name)
            .collect();
        names.sort_unstable();
        assert_eq!(names.len(), 2);
        assert!(names[0].ends_with("Position"));
        assert!(names[1].ends_with("Velocity"));

        let position_name = std::any::type_name::<Position>();
        let info = world.component_by_name(position_name).unwrap();
        assert_eq!(info.mask, world.lookup_key::<Position>().unwrap().mask);
        assert!(world.component_by_name("no::such::Component").is_none());

        let dead = world.spawn((Position::default(),));
        world.despawn_entities(&[dead]);
        assert_eq!(world.entity_components(dead).count(), 0);
    }

    #[test]
    fn test_iter_combinations_yields_each_pair_once() {
        let mut world = DynWorld::new();
        let first = world.spawn((Position { x: 1.0, y: 0.0 },));
        let second = world.spawn((Position { x: 2.0, y: 0.0 },));
        let third = world.spawn((Position { x: 3.0, y: 0.0 },));

        let pairs: Vec<(Entity, Entity)> = world
            .query_ref::<&Position>()
            .iter_combinations()
            .map(|((entity_a, _), (entity_b, _))| (entity_a, entity_b))
            .collect();
        assert_eq!(
            pairs,
            vec![(first, second), (first, third), (second, third)]
        );

        let total: f32 = world
            .query_ref::<&Position>()
            .iter_combinations()
            .map(|((_, a), (_, b))| a.x + b.x)
            .sum();
        assert_eq!(total, 12.0);

        world.despawn_entities(&[second, third]);
        assert_eq!(
            world.query_ref::<&Position>().iter_combinations().count(),
            0
        );
    }

    #[test]
    fn test_single_matches_exactly_one() {
        struct Player;

        let mut world = DynWorld::new();
        assert!(world.query_ref::<&Position>().single().is_none());

        let player = world.spawn((Position { x: 7.0, y: 0.0 },));
        world.add_tag_type::<Player>(player);
        let (entity, position) = world.query_ref::<&Position>().single().unwrap();
        assert_eq!(entity, player);
        assert_eq!(position.x, 7.0);

        world.spawn((Position::default(),));
        assert!(world.query_ref::<&Position>().single().is_none());
        assert!(
            world
                .query_ref::<&Position>()
                .with_tag_type::<Player>()
                .single()
                .is_some()
        );
    }

    #[cfg(not(target_family = "wasm"))]
    #[test]
    fn test_typed_par_for_each_matches_sequential() {
        let mut world = DynWorld::new();
        let boss = world.register_tag();
        let position = world.register::<Position>();
        let velocity = world.register::<Velocity>();
        let entities = world.spawn_entities(position.mask, 100);
        world.spawn_entities(velocity.mask | position.mask, 50);
        for &entity in entities.iter().take(10) {
            world.add_tag(boss, entity);
        }

        world.step();
        world
            .query::<(&mut Position, Option<&Velocity>)>()
            .par_for_each(|_entity, (position_value, velocity)| {
                position_value.x += 1.0 + velocity.map_or(0.0, |velocity| velocity.x);
            });

        let mut total = 0.0;
        world
            .query_ref::<&Position>()
            .iter()
            .for_each(|(_entity, position_value)| total += position_value.x);
        assert_eq!(total, 150.0);

        assert_eq!(
            world.query_entities_changed(position.mask).count(),
            150,
            "parallel mutable elements stamp change ticks"
        );

        world.step();
        let counted = std::sync::atomic::AtomicUsize::new(0);
        world
            .query::<&Position>()
            .with_tag(boss)
            .par_for_each(|_entity, _position| {
                counted.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
            });
        assert_eq!(counted.load(std::sync::atomic::Ordering::Relaxed), 10);
    }

    #[cfg(not(target_family = "wasm"))]
    #[test]
    fn test_typed_par_for_each_added_filter() {
        let mut world = DynWorld::new();
        world.spawn((Position::default(),));
        world.step();
        let fresh = world.spawn((Position::default(),));

        let seen = std::sync::Mutex::new(Vec::new());
        world
            .query::<&Position>()
            .added::<Position>()
            .par_for_each(|entity, _position| {
                seen.lock().unwrap().push(entity);
            });
        assert_eq!(*seen.lock().unwrap(), vec![fresh]);
    }

    #[test]
    fn test_hierarchy_index_links_relinks_and_unlinks() {
        let mut world = DynWorld::new();
        let mut index = HierarchyIndex::new();

        let parent_a = world.spawn((Position::default(),));
        let parent_b = world.spawn((Position::default(),));
        let child = world.spawn((Position::default(), ChildOf(parent_a)));

        index.sync(&mut world);
        assert_eq!(index.children(parent_a), &[child]);
        assert_eq!(index.parent_of.get(&child), Some(&parent_a));

        world.set(child, ChildOf(parent_b));
        index.sync(&mut world);
        assert!(index.children(parent_a).is_empty());
        assert_eq!(index.children(parent_b), &[child]);

        world.remove::<ChildOf>(child);
        index.sync(&mut world);
        assert!(index.children(parent_b).is_empty());
        assert!(index.parent_of.is_empty());

        world.set(child, ChildOf(parent_b));
        index.sync(&mut world);
        world.despawn_entities(&[child]);
        index.sync(&mut world);
        assert!(index.children(parent_b).is_empty());

        index.sync(&mut world);
        assert!(index.parent_of.is_empty(), "an idle sync changes nothing");
    }

    #[test]
    fn test_hierarchy_index_matches_scan_oracle() {
        for seed in [11u64, 1111, 111111] {
            let mut rng = Lcg(seed);
            let mut world = DynWorld::new();
            let mut index = HierarchyIndex::new();
            let mut handles: Vec<Entity> = Vec::new();

            for _ in 0..1200 {
                match rng.next() % 10 {
                    0..=2 => {
                        handles.push(world.spawn((Position::default(),)));
                    }
                    3..=4 => {
                        if handles.len() >= 2 {
                            let child = handles[rng.next() as usize % handles.len()];
                            let parent = handles[rng.next() as usize % handles.len()];
                            if child != parent {
                                world.set(child, ChildOf(parent));
                            }
                        }
                    }
                    5 => {
                        if !handles.is_empty() {
                            let entity = handles[rng.next() as usize % handles.len()];
                            world.remove::<ChildOf>(entity);
                        }
                    }
                    6 => {
                        if !handles.is_empty() {
                            let victim = handles.remove(rng.next() as usize % handles.len());
                            world.despawn_entities(&[victim]);
                        }
                    }
                    _ => {
                        index.sync(&mut world);
                    }
                }
            }

            index.sync(&mut world);
            for &parent in &handles {
                let mut indexed: Vec<Entity> = index.children(parent).to_vec();
                let mut scanned = world.children(parent);
                indexed.sort_unstable_by_key(|entity| entity.id);
                scanned.sort_unstable_by_key(|entity| entity.id);
                assert_eq!(
                    indexed, scanned,
                    "index diverged from scan with seed {seed}"
                );
            }
            for (&child, &parent) in &index.parent_of {
                assert_eq!(
                    world.get::<ChildOf>(child).map(|link| link.0),
                    Some(parent),
                    "stale upward link with seed {seed}"
                );
            }
        }
    }

    #[test]
    fn test_hierarchy_index_raw_writes_need_mark_changed() {
        let mut world = DynWorld::new();
        let mut index = HierarchyIndex::new();

        let parent_a = world.spawn((Position::default(),));
        let parent_b = world.spawn((Position::default(),));
        let child = world.spawn((ChildOf(parent_a),));
        index.sync(&mut world);

        let child_of = world.register::<ChildOf>();
        world.for_each_tables_mut(child_of.mask, 0, |table| {
            for link in table.column_mut(child_of) {
                link.0 = parent_b;
            }
        });
        index.sync(&mut world);
        assert_eq!(
            index.children(parent_a),
            &[child],
            "an unstamped raw write is invisible by covenant"
        );

        world.mark_changed(child, child_of.mask);
        index.sync(&mut world);
        assert_eq!(index.children(parent_b), &[child]);
    }

    #[test]
    fn test_hierarchy_index_despawn_recursive() {
        let mut world = DynWorld::new();
        let mut index = HierarchyIndex::new();

        let root = world.spawn((Position::default(),));
        let child = world.spawn((ChildOf(root),));
        let grandchild = world.spawn((ChildOf(child),));
        let bystander = world.spawn((Position::default(),));
        index.sync(&mut world);

        assert_eq!(index.descendants(root), vec![child, grandchild]);
        let despawned = index.despawn_recursive(&mut world, root);
        assert_eq!(despawned.len(), 3);
        assert!(index.children(root).is_empty());
        assert!(index.parent_of.is_empty());
        assert!(world.is_alive(bystander));

        index.sync(&mut world);
        assert!(index.parent_of.is_empty());
    }

    #[test]
    fn test_despawn_recursive_follows_child_links() {
        let mut world = DynWorld::new();
        let root = world.spawn((Position::default(),));
        let child = world.spawn((Position::default(), ChildOf(root)));
        let grandchild = world.spawn((Position::default(), ChildOf(child)));
        let bystander = world.spawn((Position::default(),));

        assert_eq!(world.children(root), vec![child]);
        assert_eq!(world.children(child), vec![grandchild]);

        let despawned = world.despawn_recursive(root);
        assert_eq!(despawned.len(), 3);
        assert!(!world.is_alive(root));
        assert!(!world.is_alive(child));
        assert!(!world.is_alive(grandchild));
        assert!(world.is_alive(bystander));

        let cycle_a = world.spawn((ChildOf(bystander),));
        let cycle_b = world.spawn((ChildOf(cycle_a),));
        world.set(cycle_a, ChildOf(cycle_b));
        let despawned = world.despawn_recursive(cycle_a);
        assert_eq!(despawned.len(), 2, "link cycles must terminate");
        assert!(world.is_alive(bystander));
    }

    #[test]
    fn test_resource_scope_takes_and_restores() {
        struct Score {
            value: u32,
        }

        let mut world = DynWorld::new();
        world.insert_resource(Score { value: 1 });

        let spawned = world.resource_scope(|world, score: &mut Score| {
            assert!(world.resource::<Score>().is_none());
            score.value += 1;
            world.spawn((Position { x: 7.0, y: 0.0 },))
        });

        assert_eq!(world.resource::<Score>().unwrap().value, 2);
        assert_eq!(world.get::<Position>(spawned).unwrap().x, 7.0);
    }

    #[test]
    fn test_resources_scope_takes_tuple_and_restores() {
        struct DeltaTime(f32);
        struct Score(u32);

        let mut world = DynWorld::new();
        world.insert_resource(DeltaTime(0.25));
        world.insert_resource(Score(10));

        let spawned =
            world.resources_scope(|world, (delta_time, score): &mut (DeltaTime, Score)| {
                assert!(world.resource::<DeltaTime>().is_none());
                assert!(world.resource::<Score>().is_none());
                delta_time.0 *= 2.0;
                score.0 += 1;
                world.spawn((Position { x: 3.0, y: 0.0 },))
            });

        assert_eq!(world.resource::<DeltaTime>().unwrap().0, 0.5);
        assert_eq!(world.resource::<Score>().unwrap().0, 11);
        assert_eq!(world.get::<Position>(spawned).unwrap().x, 3.0);
    }

    #[test]
    fn test_resources_scope_preserves_tuple_on_panic() {
        struct DeltaTime(f32);
        struct Score(u32);

        let mut world = DynWorld::new();
        world.insert_resource(DeltaTime(0.25));
        world.insert_resource(Score(10));

        let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            world.resources_scope(|_world, (_delta_time, _score): &mut (DeltaTime, Score)| {
                panic!("boom")
            });
        }));

        assert!(result.is_err());
        assert_eq!(world.resource::<DeltaTime>().unwrap().0, 0.25);
        assert_eq!(world.resource::<Score>().unwrap().0, 10);
    }

    #[test]
    #[should_panic(expected = "resources_scope requires")]
    fn test_resources_scope_missing_resource_leaves_world_untouched() {
        struct Present;
        struct Missing;

        let mut world = DynWorld::new();
        world.insert_resource(Present);

        world.resources_scope(|_world, (_present, _missing): &mut (Present, Missing)| {});
    }

    #[test]
    fn test_resources_scope_failed_take_removes_nothing() {
        struct Present(u32);
        struct Missing;

        let mut world = DynWorld::new();
        world.insert_resource(Present(1));

        let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            world.resources_scope(|_world, (_missing, _present): &mut (Missing, Present)| {});
        }));

        assert!(result.is_err());
        assert_eq!(world.resource::<Present>().unwrap().0, 1);
    }

    #[test]
    #[should_panic(expected = "must not repeat a resource type")]
    fn test_resources_scope_rejects_repeated_type() {
        struct Score;

        let mut world = DynWorld::new();
        world.insert_resource(Score);

        world.resources_scope(|_world, (_first, _second): &mut (Score, Score)| {});
    }

    #[test]
    #[should_panic(expected = "resource_scope requires")]
    fn test_resource_scope_panics_on_missing_resource() {
        struct Missing;

        let mut world = DynWorld::new();
        world.resource_scope(|_world, _missing: &mut Missing| {});
    }

    #[test]
    fn test_events_cursor_and_step() {
        let mut world = DynWorld::new();

        world.send(PingEvent { value: 1 });
        world.send(PingEvent { value: 2 });

        assert_eq!(world.read_events::<PingEvent>().len(), 2);
        let mut cursor = 0;
        assert_eq!(world.read_events_since::<PingEvent>(cursor).len(), 2);
        cursor = world.event_sequence::<PingEvent>();
        assert!(world.read_events_since::<PingEvent>(cursor).is_empty());

        world.step();
        assert_eq!(world.read_events::<PingEvent>().len(), 2);
        world.step();
        assert!(world.read_events::<PingEvent>().is_empty());
        assert_eq!(world.event_sequence::<PingEvent>(), 2);
    }

    #[test]
    fn test_resources() {
        let mut world = DynWorld::new();
        world.insert_resource(0.016f32);
        assert_eq!(world.resource::<f32>(), Some(&0.016));
        *world.resource_mut::<f32>().unwrap() = 0.033;
        assert_eq!(world.remove_resource::<f32>(), Some(0.033));
        assert!(world.resource::<f32>().is_none());
    }

    #[test]
    fn test_commands() {
        let mut world = DynWorld::new();
        let position = world.register::<Position>();

        let entity = world.spawn_entities(position.mask, 1)[0];
        world.queue_set(entity, Position { x: 7.0, y: 0.0 });
        world.queue_spawn_entities(position.mask, 2);
        world.queue_despawn_entity(entity);

        assert_eq!(world.command_count(), 3);
        assert_eq!(world.get_keyed(position, entity).unwrap().x, 0.0);

        world.apply_commands();

        assert!(world.get_keyed(position, entity).is_none());
        assert_eq!(world.entity_count(), 2);
    }

    #[test]
    fn test_mask_iteration_with_tags() {
        let mut world = DynWorld::new();
        let position = world.register::<Position>();
        let enemy = world.register_tag();

        let entities = world.spawn_entities(position.mask, 3);
        world.add_tag(enemy, entities[0]);
        world.add_tag(enemy, entities[2]);

        let mut count = 0;
        world.for_each(position.mask | enemy.mask, 0, |_entity, _table, _index| {
            count += 1;
        });
        assert_eq!(count, 2);

        count = 0;
        world.for_each_mut(position.mask, enemy.mask, |_entity, table, index| {
            table.column_mut(position)[index].x = 4.0;
            count += 1;
        });
        assert_eq!(count, 1);
        assert_eq!(world.get_keyed(position, entities[1]).unwrap().x, 4.0);
    }

    #[cfg(not(target_family = "wasm"))]
    #[test]
    fn test_par_for_each_mut() {
        let mut world = DynWorld::new();
        let position = world.register::<Position>();
        let entities = world.spawn_entities(position.mask, 100);

        world.par_for_each_mut(position.mask, 0, |_entity, table, index| {
            table.column_mut(position)[index].x = 1.0;
        });

        for &entity in &entities {
            assert_eq!(world.get_keyed(position, entity).unwrap().x, 1.0);
        }
    }

    #[derive(Default, Clone)]
    struct ModelEntity {
        mask: u64,
        position: Option<f32>,
        position_changed: bool,
        boss: bool,
    }

    #[test]
    fn test_property_dyn_world_matches_model() {
        for seed in [11u64, 71, 3131] {
            let mut rng = Lcg(seed);
            let mut world = DynWorld::new();
            let position = world.register::<Position>();
            let velocity = world.register::<Velocity>();
            let health = world.register::<Health>();
            let boss = world.register_tag();
            let component_masks = [position.mask, velocity.mask, health.mask];

            let mut model: HashMap<Entity, ModelEntity> = HashMap::new();
            let mut handles: Vec<Entity> = Vec::new();
            let mut pending_pings: Vec<u32> = Vec::new();
            let mut total_pings: u64 = 0;

            world.step();

            let random_mask = |rng: &mut Lcg| {
                let mut mask = 0;
                for &component in &component_masks {
                    if rng.next().is_multiple_of(2) {
                        mask |= component;
                    }
                }
                mask
            };
            let pick = |rng: &mut Lcg, handles: &[Entity]| {
                if handles.is_empty() {
                    None
                } else {
                    Some(handles[rng.next() as usize % handles.len()])
                }
            };

            for _ in 0..3000 {
                match rng.next() % 12 {
                    0 | 1 => {
                        let mask = random_mask(&mut rng);
                        let entity = world.spawn_entities(mask, 1)[0];
                        model.insert(
                            entity,
                            ModelEntity {
                                mask,
                                position: (mask & position.mask != 0).then_some(0.0),
                                position_changed: mask & position.mask != 0,
                                ..Default::default()
                            },
                        );
                        handles.push(entity);
                    }
                    2 => {
                        if let Some(entity) = pick(&mut rng, &handles) {
                            let despawned = world.despawn_entities(&[entity]);
                            let was_live = model.remove(&entity).is_some();
                            assert_eq!(despawned.len() == 1, was_live);
                        }
                    }
                    3 => {
                        if let Some(entity) = pick(&mut rng, &handles) {
                            let mask = random_mask(&mut rng);
                            let accepted = world.add_components(entity, mask);
                            match model.get_mut(&entity) {
                                Some(model_entity) => {
                                    assert!(accepted);
                                    let migrated = mask & !model_entity.mask != 0;
                                    if mask & position.mask != 0
                                        && model_entity.mask & position.mask == 0
                                    {
                                        model_entity.position = Some(0.0);
                                    }
                                    model_entity.mask |= mask;
                                    if migrated && model_entity.mask & position.mask != 0 {
                                        model_entity.position_changed = true;
                                    }
                                }
                                None => assert!(!accepted),
                            }
                        }
                    }
                    4 => {
                        if let Some(entity) = pick(&mut rng, &handles) {
                            let mask = random_mask(&mut rng);
                            let accepted = world.remove_components(entity, mask);
                            match model.get_mut(&entity) {
                                Some(model_entity) => {
                                    assert!(accepted);
                                    let migrated = mask & model_entity.mask != 0;
                                    if mask & position.mask != 0 {
                                        model_entity.position = None;
                                    }
                                    model_entity.mask &= !mask;
                                    if migrated && model_entity.mask & position.mask != 0 {
                                        model_entity.position_changed = true;
                                    }
                                }
                                None => assert!(!accepted),
                            }
                        }
                    }
                    5 => {
                        if let Some(entity) = pick(&mut rng, &handles) {
                            let value = (rng.next() % 1000) as f32;
                            world.set_keyed(position, entity, Position { x: value, y: 0.0 });
                            match model.get_mut(&entity) {
                                Some(model_entity) => {
                                    model_entity.mask |= position.mask;
                                    model_entity.position = Some(value);
                                    model_entity.position_changed = true;
                                }
                                None => assert!(world.get_keyed(position, entity).is_none()),
                            }
                        }
                    }
                    6 => {
                        if let Some(entity) = pick(&mut rng, &handles) {
                            world.add_tag(boss, entity);
                            if let Some(model_entity) = model.get_mut(&entity) {
                                model_entity.boss = true;
                            }
                            assert_eq!(
                                world.has_tag(boss, entity),
                                model.get(&entity).map(|m| m.boss).unwrap_or(false)
                            );
                        }
                    }
                    7 => {
                        if let Some(entity) = pick(&mut rng, &handles) {
                            let removed = world.remove_tag(boss, entity);
                            let expected = match model.get_mut(&entity) {
                                Some(model_entity) => {
                                    let had = model_entity.boss;
                                    model_entity.boss = false;
                                    had
                                }
                                None => false,
                            };
                            assert_eq!(removed, expected);
                        }
                    }
                    8 => {
                        if let Some(entity) = pick(&mut rng, &handles) {
                            world.queue_set(entity, Health { value: 1.0 });
                            let live = model.contains_key(&entity);
                            world.apply_commands();
                            if live {
                                let model_entity = model.get_mut(&entity).unwrap();
                                let migrated = model_entity.mask & health.mask == 0;
                                model_entity.mask |= health.mask;
                                if migrated && model_entity.mask & position.mask != 0 {
                                    model_entity.position_changed = true;
                                }
                            }
                        }
                    }
                    9 => {
                        let value = rng.next() as u32;
                        world.send(PingEvent { value });
                        pending_pings.push(value);
                        total_pings += 1;
                    }
                    _ => {
                        let changed: std::collections::HashSet<Entity> =
                            world.query_entities_changed(position.mask).collect();
                        let expected: std::collections::HashSet<Entity> = model
                            .iter()
                            .filter(|(_, model_entity)| {
                                model_entity.mask & position.mask != 0
                                    && model_entity.position_changed
                            })
                            .map(|(&entity, _)| entity)
                            .collect();
                        assert_eq!(
                            changed, expected,
                            "changed-query set diverged with seed {seed}"
                        );

                        world.step();
                        for model_entity in model.values_mut() {
                            model_entity.position_changed = false;
                        }

                        let buffered: Vec<u32> = world
                            .read_events::<PingEvent>()
                            .iter()
                            .map(|ping| ping.value)
                            .collect();
                        assert_eq!(buffered, pending_pings);
                        assert_eq!(world.event_sequence::<PingEvent>(), total_pings);
                        pending_pings.clear();
                    }
                }
            }

            assert_eq!(world.entity_count(), model.len());
            for (&entity, model_entity) in &model {
                assert_eq!(world.component_mask(entity), Some(model_entity.mask));
                assert_eq!(
                    world.get_keyed(position, entity).map(|p| p.x),
                    model_entity.position
                );
                assert_eq!(world.has_tag(boss, entity), model_entity.boss);
                assert!(world.is_alive(entity));
            }
            for &handle in &handles {
                if !model.contains_key(&handle) {
                    assert_eq!(world.component_mask(handle), None);
                    assert!(!world.is_alive(handle));
                    assert!(!world.has_tag(boss, handle));
                }
            }
            for mask in component_masks {
                let expected = model
                    .values()
                    .filter(|model_entity| model_entity.mask & mask == mask)
                    .count();
                assert_eq!(world.query_entities(mask).count(), expected);
            }
        }
    }

    #[test]
    fn test_spawn_batch_initializes_rows() {
        let mut world = DynWorld::new();
        let position = world.register::<Position>();
        let velocity = world.register::<Velocity>();

        let entities = world.spawn_batch(position.mask | velocity.mask, 100, |table, index| {
            table.column_mut(position)[index] = Position {
                x: index as f32,
                y: 0.0,
            };
        });

        assert_eq!(entities.len(), 100);
        for (offset, &entity) in entities.iter().enumerate() {
            assert_eq!(world.get_keyed(position, entity).unwrap().x, offset as f32);
            assert_eq!(world.get_keyed(velocity, entity).unwrap().x, 0.0);
        }
    }

    #[test]
    fn test_for_each_mut_changed_visits_only_stamped_slots() {
        let mut world = DynWorld::new();
        let position = world.register::<Position>();
        let entities = world.spawn_entities(position.mask, 3);

        world.step();
        world.get_mut_keyed(position, entities[1]).unwrap().x = 5.0;

        let mut visited = Vec::new();
        world.for_each_mut_changed(position.mask, 0, |entity, _table, _index| {
            visited.push(entity);
        });
        assert_eq!(visited, vec![entities[1]]);

        world.step();
        visited.clear();
        world.for_each_mut_changed(position.mask, 0, |entity, _table, _index| {
            visited.push(entity);
        });
        assert!(visited.is_empty(), "a step must expire the changed window");
    }

    #[test]
    fn test_for_each_mut_changed_since_cursor() {
        let mut world = DynWorld::new();
        let position = world.register::<Position>();
        let entity = world.spawn_entities(position.mask, 1)[0];

        world.step();
        let cursor = world.last_tick();
        world.set_keyed(position, entity, Position { x: 1.0, y: 0.0 });
        world.step();
        world.step();

        let mut visited = Vec::new();
        world.for_each_mut_changed_since(position.mask, 0, cursor, |seen, _table, _index| {
            visited.push(seen);
        });
        assert_eq!(visited, vec![entity]);

        let cursor = world.current_tick();
        visited.clear();
        world.for_each_mut_changed_since(position.mask, 0, cursor, |seen, _table, _index| {
            visited.push(seen);
        });
        assert!(visited.is_empty());
    }

    #[test]
    fn test_changed_skips_untouched_tables() {
        let mut world = DynWorld::new();
        let position = world.register::<Position>();
        let velocity = world.register::<Velocity>();

        world.spawn_entities(position.mask, 3);
        let moving = world.spawn_entities(position.mask | velocity.mask, 1)[0];

        world.step();
        world.get_mut_keyed(position, moving).unwrap().x = 1.0;

        let changed: Vec<Entity> = world.query_entities_changed(position.mask).collect();
        assert_eq!(changed, vec![moving]);

        for table in &world.tables {
            let column = &table.columns[0];
            if table.mask == position.mask {
                assert!(!tick_is_newer(column.peak_changed, world.last_tick));
            }
        }
    }

    #[test]
    fn test_structural_log_capacity_backstop() {
        let mut world = DynWorld::new();
        let position = world.register::<Position>();
        let entity = world.spawn_entities(position.mask, 1)[0];

        for _ in 0..STRUCTURAL_LOG_CAPACITY {
            world.record_structural(entity, StructuralChangeKind::ComponentsAdded, position.mask);
        }

        assert_eq!(world.structural_log.len(), 1);
        assert_eq!(
            world.structural_sequence(),
            STRUCTURAL_LOG_CAPACITY as u64 + 1
        );
        let tail = world.structural_changes_since(0);
        assert_eq!(tail.len(), 1);
        assert_eq!(tail[0].sequence, world.structural_sequence());
    }

    #[test]
    fn test_structural_log_trim_and_clear() {
        let mut world = DynWorld::new();
        let position = world.register::<Position>();
        let entity = world.spawn_entities(position.mask, 1)[0];
        world.add_components(entity, position.mask);
        world.remove_components(entity, position.mask);

        let cursor = world.structural_changes_since(0)[0].sequence;
        world.trim_structural_log(cursor);
        assert_eq!(world.structural_changes_since(0).len(), 1);

        world.clear_structural_log();
        assert!(world.structural_changes_since(0).is_empty());
        assert_eq!(world.structural_sequence(), 2);
    }

    #[test]
    fn test_commands_full_surface() {
        let mut world = DynWorld::new();
        let position = world.register::<Position>();
        let velocity = world.register::<Velocity>();
        let boss = world.register_tag();

        let entity = world.spawn_entities(position.mask, 1)[0];

        world.queue_spawn_entities(velocity.mask, 3);
        world.queue_add_components(entity, velocity.mask);
        world.queue_add_tag(boss, entity);
        world.queue(move |world| {
            world.set_keyed(position, entity, Position { x: 9.0, y: 0.0 });
        });
        assert_eq!(world.command_count(), 4);

        world.apply_commands();

        assert_eq!(world.entity_count(), 4);
        assert!(world.get_keyed(velocity, entity).is_some());
        assert!(world.has_tag(boss, entity));
        assert_eq!(world.get_keyed(position, entity).unwrap().x, 9.0);

        world.queue_remove_components(entity, velocity.mask);
        world.queue_remove_tag(boss, entity);
        world.apply_commands();
        assert!(world.get_keyed(velocity, entity).is_none());
        assert!(!world.has_tag(boss, entity));

        world.queue_despawn_entity(entity);
        world.clear_commands();
        assert_eq!(world.command_count(), 0);
        assert!(world.is_alive(entity), "cleared commands must not apply");
    }

    #[test]
    fn test_events_trim_and_clear() {
        let mut world = DynWorld::new();
        for value in 0..6u32 {
            world.send(PingEvent { value });
        }

        world.trim_events::<PingEvent>(2);
        assert_eq!(world.read_events::<PingEvent>().len(), 4);
        assert_eq!(world.read_events::<PingEvent>()[0].value, 2);
        assert_eq!(world.event_sequence::<PingEvent>(), 6);

        world.clear_events::<PingEvent>();
        assert!(world.read_events::<PingEvent>().is_empty());
        assert_eq!(world.event_sequence::<PingEvent>(), 6);
    }

    #[test]
    fn test_query_mask_filters_and_empty_tag_fast_path() {
        let mut world = DynWorld::new();
        let velocity_key = world.register::<Velocity>();
        let boss = world.register_tag();

        let plain = world.spawn((Position { x: 1.0, y: 0.0 },));
        let fast = world.spawn((Position { x: 2.0, y: 0.0 }, Velocity::default()));

        let mut with_mask = Vec::new();
        world
            .query::<(&Position,)>()
            .with_mask(velocity_key.mask)
            .for_each(|entity, _| with_mask.push(entity));
        assert_eq!(with_mask, vec![fast]);

        let mut without_mask = Vec::new();
        world
            .query::<(&Position,)>()
            .without_mask(velocity_key.mask)
            .for_each(|entity, _| without_mask.push(entity));
        assert_eq!(without_mask, vec![plain]);

        let mut excluding_empty_tag = Vec::new();
        world
            .query::<(&Position,)>()
            .without_tag(boss)
            .for_each(|entity, _| excluding_empty_tag.push(entity));
        assert_eq!(
            excluding_empty_tag.len(),
            2,
            "excluding a tag nobody has excludes nothing"
        );

        let mut including_empty_tag = Vec::new();
        world
            .query::<(&Position,)>()
            .with_tag(boss)
            .for_each(|entity, _| including_empty_tag.push(entity));
        assert!(
            including_empty_tag.is_empty(),
            "including a tag nobody has matches nothing"
        );
    }

    #[cfg(not(target_family = "wasm"))]
    #[test]
    fn test_par_for_each_mut_with_tag_masks() {
        let mut world = DynWorld::new();
        let position = world.register::<Position>();
        let boss = world.register_tag();

        let entities = world.spawn_entities(position.mask, 10);
        for &entity in &entities[..5] {
            world.add_tag(boss, entity);
        }

        world.par_for_each_mut(position.mask | boss.mask, 0, |_entity, table, index| {
            table.column_mut(position)[index].x = 7.0;
        });

        for (offset, &entity) in entities.iter().enumerate() {
            let expected = if offset < 5 { 7.0 } else { 0.0 };
            assert_eq!(world.get_keyed(position, entity).unwrap().x, expected);
        }
    }

    #[cfg(feature = "snapshot")]
    #[test]
    fn test_component_values_by_name() {
        let mut registry = ComponentRegistry::new();
        registry.register_serde::<Position>();
        registry.register::<Velocity>();
        let mut world = DynWorld::from_registry(registry);

        let entity = world.spawn((Position { x: 1.0, y: 2.0 },));
        let name = std::any::type_name::<Position>();

        let bytes = world.get_component_by_name(entity, name).unwrap().unwrap();
        let decoded: Position = postcard::from_bytes(&bytes).unwrap();
        assert_eq!(decoded, Position { x: 1.0, y: 2.0 });

        world.step();
        let replacement = postcard::to_allocvec(&Position { x: 7.0, y: 8.0 }).unwrap();
        world
            .set_component_by_name(entity, name, &replacement)
            .unwrap();
        assert_eq!(world.get::<Position>(entity).unwrap().x, 7.0);
        assert_eq!(
            world
                .query_entities_changed(world.lookup_key::<Position>().unwrap().mask)
                .count(),
            1,
            "value writes stamp change ticks like any set"
        );

        let bare = world.spawn((Velocity::default(),));
        world
            .set_component_by_name(bare, name, &replacement)
            .unwrap();
        assert_eq!(
            world.get::<Position>(bare).unwrap().x,
            7.0,
            "value writes add the component when absent"
        );

        assert!(matches!(
            world.get_component_by_name(entity, "no::such::Type"),
            Err(SnapshotError::UnknownComponent(_))
        ));
        assert!(matches!(
            world.set_component_by_name(entity, std::any::type_name::<Velocity>(), &[]),
            Err(SnapshotError::MissingCodec(_))
        ));
        let rowless = world.spawn((Velocity::default(),));
        assert_eq!(
            world.get_component_by_name(rowless, name).unwrap(),
            None,
            "an entity without the component reads as None"
        );

        let mut game_registry = ComponentRegistry::new();
        game_registry.register_serde::<Health>();
        let mut ecs = DynEcs::new();
        let mut core_registry = ComponentRegistry::new();
        core_registry.register_serde::<Position>();
        ecs.add_world_at(0, core_registry);
        ecs.add_world_at(1, game_registry);
        let grouped = ecs.spawn_with((Position::default(), Health { value: 3.0 }));
        let health_name = std::any::type_name::<Health>();
        let health_bytes = postcard::to_allocvec(&Health { value: 42.0 }).unwrap();
        ecs.set_component_by_name(grouped, health_name, &health_bytes)
            .unwrap();
        assert_eq!(ecs.get::<Health>(grouped).unwrap().value, 42.0);
        assert!(
            ecs.get_component_by_name(grouped, health_name)
                .unwrap()
                .is_some(),
            "group value reads route by name"
        );
    }

    #[cfg(feature = "snapshot")]
    #[test]
    fn test_dyn_ecs_marker_tags_survive_snapshots() {
        struct Selected;

        let mut registry = ComponentRegistry::new();
        registry.register_serde::<Position>();
        let mut ecs = DynEcs::new();
        ecs.add_world_at(0, registry);

        let first = ecs.spawn_with((Position::default(),));
        let second = ecs.spawn_with((Position::default(),));
        ecs.add_tag_type::<Selected>(first);
        let anonymous = ecs.register_tag();
        ecs.add_tag(anonymous, second);

        let snapshot = ecs.snapshot().unwrap();
        let mut registry = ComponentRegistry::new();
        registry.register_serde::<Position>();
        let mut restored = DynEcs::from_snapshot(vec![registry], &snapshot).unwrap();

        assert!(
            restored.has_tag_type::<Selected>(first),
            "marker membership resolves after a restore"
        );
        assert_eq!(
            restored.query_tag_type::<Selected>().collect::<Vec<_>>(),
            vec![first]
        );
        assert!(restored.tag_set_type::<Selected>().is_some());

        let set_count = restored.tags.len();
        restored.add_tag_type::<Selected>(second);
        assert_eq!(
            restored.tags.len(),
            set_count,
            "adding after a restore reuses the persisted set instead of splitting membership"
        );
        let mut members: Vec<Entity> = restored.query_tag_type::<Selected>().collect();
        members.sort_unstable_by_key(|entity| entity.id);
        assert_eq!(members, vec![first, second]);
        assert!(restored.has_tag(anonymous, second));
    }

    #[test]
    #[should_panic(expected = "must live in exactly one member world")]
    fn test_dyn_ecs_add_world_rejects_duplicate_types() {
        let mut first = ComponentRegistry::new();
        first.register::<Position>();
        let mut second = ComponentRegistry::new();
        second.register::<Position>();

        let mut ecs = DynEcs::new();
        ecs.add_world(first);
        ecs.add_world(second);
    }

    #[test]
    #[should_panic(expected = "must live in exactly one member world")]
    fn test_dyn_ecs_route_detects_post_add_duplicates() {
        let mut ecs = DynEcs::new();
        ecs.add_world(ComponentRegistry::new());
        ecs.add_world(ComponentRegistry::new());
        ecs.worlds[0].register::<Position>();
        ecs.worlds[1].register::<Position>();

        let entity = ecs.spawn();
        let _ = ecs.get::<Position>(entity);
    }

    #[test]
    #[should_panic(expected = "must name components present in the query tuple")]
    fn test_query_join_filters_must_name_tuple_components() {
        let mut core_registry = ComponentRegistry::new();
        core_registry.register::<Position>();
        core_registry.register::<Velocity>();
        let mut game_registry = ComponentRegistry::new();
        game_registry.register::<Health>();

        let mut ecs = DynEcs::new();
        ecs.add_world_at(0, core_registry);
        ecs.add_world_at(1, game_registry);
        ecs.spawn_with((Position::default(), Health::default()));

        ecs.query_join::<(&mut Position, &Health)>()
            .changed::<Velocity>()
            .for_each(|_entity, (_position, _health)| {});
    }

    #[test]
    fn test_query_join_changed_accepts_lazily_registered_elements() {
        let mut core_registry = ComponentRegistry::new();
        core_registry.register::<Position>();

        let mut ecs = DynEcs::new();
        ecs.add_world_at(0, core_registry);
        ecs.spawn_with((Position::default(),));

        let mut visited = 0;
        ecs.query_join::<(&mut Position, Option<&mut Velocity>)>()
            .changed::<Velocity>()
            .for_each(|_entity, (_position, _velocity)| visited += 1);
        assert_eq!(
            visited, 0,
            "a lazily-registered tuple element is a valid filter target and never panics"
        );
    }

    #[cfg(feature = "snapshot")]
    #[test]
    fn test_set_component_by_name_rejects_dead_entities() {
        let mut registry = ComponentRegistry::new();
        registry.register_serde::<Position>();
        let mut world = DynWorld::from_registry(registry);
        let entity = world.spawn((Position::default(),));
        world.despawn_entities(&[entity]);

        let name = std::any::type_name::<Position>();
        let bytes = postcard::to_allocvec(&Position::default()).unwrap();
        assert!(matches!(
            world.set_component_by_name(entity, name, &bytes),
            Err(SnapshotError::DeadEntity)
        ));

        let mut registry = ComponentRegistry::new();
        registry.register_serde::<Position>();
        let mut ecs = DynEcs::new();
        ecs.add_world_at(0, registry);
        let grouped = ecs.spawn_with((Position::default(),));
        ecs.despawn(grouped);
        assert!(matches!(
            ecs.set_component_by_name(grouped, name, &bytes),
            Err(SnapshotError::DeadEntity)
        ));

        let live = ecs.spawn_with((Position::default(),));
        assert!(
            ecs.set_component_by_name(live, name, &bytes).is_ok(),
            "grouped members still accept writes for live group handles"
        );
    }

    #[cfg(feature = "snapshot")]
    #[test]
    fn test_from_snapshot_rejects_length_mismatched_columns() {
        let mut registry = ComponentRegistry::new();
        registry.register_serde::<Position>();
        let mut world = DynWorld::from_registry(registry);
        world.spawn((Position::default(),));
        world.spawn((Position::default(),));

        let mut snapshot = world.snapshot().unwrap();
        let truncated: Vec<Position> = vec![Position::default()];
        snapshot.tables[0].columns[0] = postcard::to_allocvec(&truncated).unwrap();

        let mut registry = ComponentRegistry::new();
        registry.register_serde::<Position>();
        let result = DynWorld::from_snapshot(registry, &snapshot);
        assert!(
            matches!(result, Err(SnapshotError::Codec(message)) if message.contains("decoded 1 rows for 2 entities"))
        );
    }

    #[test]
    fn test_dyn_ecs_group_marker_tags() {
        struct Selected;
        struct Locked;

        let mut core_registry = ComponentRegistry::new();
        core_registry.register::<Position>();
        let mut ecs = DynEcs::new();
        ecs.add_world_at(0, core_registry);

        let first = ecs.spawn_with((Position { x: 1.0, y: 0.0 },));
        let second = ecs.spawn_with((Position { x: 2.0, y: 0.0 },));

        assert!(!ecs.has_tag_type::<Selected>(first));
        assert_eq!(ecs.query_tag_type::<Selected>().count(), 0);
        assert!(!ecs.remove_tag_type::<Selected>(first));

        ecs.clear_structural_log();
        ecs.add_tag_type::<Selected>(first);
        ecs.add_tag_type::<Locked>(second);
        assert!(ecs.has_tag_type::<Selected>(first));
        assert!(!ecs.has_tag_type::<Selected>(second));
        assert_eq!(
            ecs.query_tag_type::<Selected>().collect::<Vec<_>>(),
            vec![first]
        );
        assert_eq!(
            ecs.structural_changes_since(0)
                .iter()
                .filter(|change| change.kind == StructuralChangeKind::TagsAdded)
                .count(),
            2,
            "marker tags land in the group structural log"
        );

        let selected_positions: Vec<Entity> = ecs.worlds[0]
            .query_ref::<&Position>()
            .with_tag_set(ecs.tag_set_type::<Selected>().unwrap())
            .iter()
            .map(|(entity, _position)| entity)
            .collect();
        assert_eq!(
            selected_positions,
            vec![first],
            "group marker sets compose into per-world typed queries"
        );

        assert!(ecs.remove_tag_type::<Selected>(first));
        assert!(!ecs.has_tag_type::<Selected>(first));

        ecs.add_tag_type::<Selected>(second);
        ecs.despawn(second);
        assert!(
            !ecs.has_tag_type::<Selected>(second),
            "despawn drops group marker tags"
        );

        assert!(
            ecs.worlds[0].remaining_bits() == 63,
            "group marker tags spend no member-world mask bits"
        );
    }

    #[cfg(feature = "snapshot")]
    fn assert_worlds_equivalent(left: &DynWorld, right: &DynWorld, context: &str) {
        let mut left_entities: Vec<Entity> = left
            .tables
            .iter()
            .flat_map(|table| table.entity_indices.iter().copied())
            .collect();
        let mut right_entities: Vec<Entity> = right
            .tables
            .iter()
            .flat_map(|table| table.entity_indices.iter().copied())
            .collect();
        left_entities.sort_unstable_by_key(|entity| entity.id);
        right_entities.sort_unstable_by_key(|entity| entity.id);
        assert_eq!(
            left_entities, right_entities,
            "entity sets diverge: {context}"
        );

        for &entity in &left_entities {
            assert_eq!(
                left.component_mask(entity),
                right.component_mask(entity),
                "masks diverge for {entity}: {context}"
            );
            for info in &left.registry.components {
                let name = info.type_name;
                let left_bytes = left.get_component_by_name(entity, name).unwrap();
                let right_bytes = right.get_component_by_name(entity, name).unwrap();
                assert_eq!(
                    left_bytes, right_bytes,
                    "{name} diverges for {entity}: {context}"
                );
            }
        }
        for (index, (left_set, right_set)) in left.tags.iter().zip(&right.tags).enumerate() {
            let mut left_members: Vec<Entity> = left_set.iter().collect();
            let mut right_members: Vec<Entity> = right_set.iter().collect();
            left_members.sort_unstable_by_key(|entity| entity.id);
            right_members.sort_unstable_by_key(|entity| entity.id);
            assert_eq!(
                left_members, right_members,
                "tag {index} diverges: {context}"
            );
        }
    }

    #[cfg(feature = "snapshot")]
    #[test]
    fn test_world_deltas_replicate_op_stream() {
        let mut registry = ComponentRegistry::new();
        registry.register_serde::<Position>();
        registry.register_serde::<Velocity>();
        registry.register_serde::<Health>();
        let mut source = DynWorld::from_registry(registry.clone());

        let seed_a = source.spawn((Position { x: 1.0, y: 0.0 }, Health { value: 5.0 }));
        source.spawn((Velocity { x: 2.0, y: 0.0 },));

        let snapshot = source.snapshot().unwrap();
        let mut replica = DynWorld::from_snapshot(registry, &snapshot).unwrap();
        let mut cursor = source.delta_cursor();

        let mut rng = Lcg(2024);
        let mut handles = vec![seed_a];
        for round in 0..6 {
            for _ in 0..40 {
                match rng.next() % 8 {
                    0 | 1 => handles.push(source.spawn((Position {
                        x: rng.next() as f32 % 10.0,
                        y: 0.0,
                    },))),
                    2 => {
                        if let Some(&entity) = handles.last() {
                            source.set(
                                entity,
                                Health {
                                    value: (rng.next() % 100) as f32,
                                },
                            );
                        }
                    }
                    3 => {
                        if !handles.is_empty() {
                            let entity = handles[rng.next() as usize % handles.len()];
                            if let Some(position) = source.get_mut::<Position>(entity) {
                                position.x += 1.0;
                            }
                        }
                    }
                    4 => {
                        if !handles.is_empty() {
                            let entity = handles[rng.next() as usize % handles.len()];
                            source.remove::<Health>(entity);
                        }
                    }
                    5 => {
                        if !handles.is_empty() {
                            let entity = handles[rng.next() as usize % handles.len()];
                            source.add_tag_type::<u8>(entity);
                        }
                    }
                    6 => {
                        if !handles.is_empty() {
                            let entity = handles[rng.next() as usize % handles.len()];
                            source.remove_tag_type::<u8>(entity);
                        }
                    }
                    _ => {
                        if handles.len() > 2 {
                            let victim = handles.remove(rng.next() as usize % handles.len());
                            source.despawn_entities(&[victim]);
                        }
                    }
                }
            }
            let delta = source.delta_since(&cursor).unwrap();
            cursor = delta.to;
            let bytes = postcard::to_allocvec(&delta).unwrap();
            let decoded: DynWorldDelta = postcard::from_bytes(&bytes).unwrap();
            replica.apply_delta(&decoded).unwrap();
            assert_worlds_equivalent(&source, &replica, &format!("round {round}"));
        }

        let stale = handles[0];
        source.despawn_entities(&[stale]);
        let delta = source.delta_since(&cursor).unwrap();
        replica.apply_delta(&delta).unwrap();
        assert!(!replica.is_alive(stale) || replica.get::<Position>(stale).is_none());
    }

    #[cfg(feature = "snapshot")]
    #[test]
    fn test_world_delta_detects_log_gaps() {
        let mut registry = ComponentRegistry::new();
        registry.register_serde::<Position>();
        let mut world = DynWorld::from_registry(registry);
        let cursor = world.delta_cursor();
        world.spawn((Position::default(),));
        world.trim_structural_log(world.structural_sequence);
        world.spawn((Position::default(),));
        world.trim_structural_log(world.structural_sequence);
        let result = world.delta_since(&cursor);
        assert!(
            matches!(result, Err(SnapshotError::Codec(message)) if message.contains("gap")),
            "a trimmed log past the cursor must be a loud gap"
        );
    }

    #[cfg(feature = "snapshot")]
    #[test]
    fn test_group_deltas_replicate_across_members() {
        struct Marked;

        let mut core_registry = ComponentRegistry::new();
        core_registry.register_serde::<Position>();
        let mut game_registry = ComponentRegistry::new();
        game_registry.register_serde::<Health>();

        let mut source = DynEcs::new();
        source.add_world_at(0, core_registry.clone());
        source.add_world_at(1, game_registry.clone());
        let anchor = source.spawn_with((Position { x: 1.0, y: 0.0 }, Health { value: 9.0 }));

        let snapshot = source.snapshot().unwrap();
        let mut replica =
            DynEcs::from_snapshot(vec![core_registry, game_registry], &snapshot).unwrap();
        let mut cursor = source.delta_cursor();

        let newcomer = source.spawn_with((Position { x: 5.0, y: 0.0 }, Health { value: 1.0 }));
        source.add_tag_type::<Marked>(newcomer);
        source.get_mut::<Health>(anchor).unwrap().value = 77.0;
        let doomed = source.spawn_with((Position::default(),));
        source.despawn(doomed);

        let delta = source.delta_since(&cursor).unwrap();
        cursor = DynEcsDeltaCursor {
            group_sequence: delta.group_to,
            worlds: delta.worlds.iter().map(|world| world.to).collect(),
        };
        replica.apply_delta(&delta).unwrap();

        assert!(replica.is_alive(newcomer));
        assert!(!replica.is_alive(doomed));
        assert_eq!(replica.get::<Health>(anchor).unwrap().value, 77.0);
        assert_eq!(replica.get::<Position>(newcomer).unwrap().x, 5.0);
        assert!(replica.has_tag_type::<Marked>(newcomer));
        assert_worlds_equivalent(&source.worlds[0], &replica.worlds[0], "core");
        assert_worlds_equivalent(&source.worlds[1], &replica.worlds[1], "game");

        source.remove_tag_type::<Marked>(newcomer);
        source.get_mut::<Position>(newcomer).unwrap().x = 6.0;
        let second = source.delta_since(&cursor).unwrap();
        replica.apply_delta(&second).unwrap();
        assert!(!replica.has_tag_type::<Marked>(newcomer));
        assert_eq!(replica.get::<Position>(newcomer).unwrap().x, 6.0);
    }

    #[test]
    fn test_prepared_queries_match_direct_queries() {
        let mut world = DynWorld::new();
        let moving = world.spawn((Position { x: 1.0, y: 0.0 }, Velocity { x: 1.0, y: 0.0 }));
        world.spawn((Position { x: 2.0, y: 0.0 },));

        let prepared = world
            .query::<(&mut Position, &Velocity)>()
            .changed::<Position>()
            .prepare();
        let prepared_read = world.query_ref::<&Position>().prepare();

        world.step();
        world.get_mut::<Position>(moving).unwrap().x = 5.0;

        let mut visited = Vec::new();
        prepared
            .query(&mut world)
            .for_each(|entity, (position, velocity)| {
                position.x += velocity.x;
                visited.push(entity);
            });
        assert_eq!(visited, vec![moving]);
        assert_eq!(world.get::<Position>(moving).unwrap().x, 6.0);

        let total = prepared_read.query(&world).iter().count();
        assert_eq!(total, 2);

        let again = prepared_read.query(&world).iter().count();
        assert_eq!(again, 2, "prepared queries rerun without re-resolving");
    }

    #[test]
    fn test_query_join_ref_iterates_across_worlds() {
        struct Chosen;

        let mut core_registry = ComponentRegistry::new();
        core_registry.register::<Position>();
        let mut game_registry = ComponentRegistry::new();
        game_registry.register::<Health>();

        let mut ecs = DynEcs::new();
        ecs.add_world_at(0, core_registry);
        ecs.add_world_at(1, game_registry);

        let both = ecs.spawn_with((Position { x: 1.0, y: 0.0 }, Health { value: 10.0 }));
        ecs.spawn_with((Position { x: 2.0, y: 0.0 },));
        let tagged = ecs.spawn_with((Position { x: 3.0, y: 0.0 }, Health { value: 30.0 }));
        ecs.add_tag_type::<Chosen>(tagged);

        let pairs: Vec<(Entity, f32)> = ecs
            .query_join_ref::<(&Position, &Health)>()
            .iter()
            .map(|(entity, (position, health))| (entity, position.x + health.value))
            .collect();
        assert_eq!(pairs, vec![(both, 11.0), (tagged, 33.0)]);

        let chosen: Vec<Entity> = ecs
            .query_join_ref::<(&Position, &Health)>()
            .with_tag_type::<Chosen>()
            .iter()
            .map(|(entity, _items)| entity)
            .collect();
        assert_eq!(chosen, vec![tagged]);

        assert_eq!(
            ecs.query_join_ref::<(&Position, &Velocity)>()
                .iter()
                .count(),
            0,
            "an unregistered required element degrades to empty"
        );
    }

    struct HostWorld {
        world: DynWorld,
        frames: u32,
    }

    impl ResourceHost for HostWorld {
        fn resource_map_mut(&mut self) -> &mut ResourceMap {
            &mut self.world.resources
        }
    }

    struct ScopePoints(u32);
    struct ScopeLabel(&'static str);

    #[test]
    fn test_host_resource_scope_lends_the_wrapper() {
        let mut host = HostWorld {
            world: DynWorld::new(),
            frames: 0,
        };
        host.world.insert_resource(ScopePoints(0));
        let entity = host.world.spawn((Position::default(),));

        let seen = resource_scope(&mut host, |host, points: &mut ScopePoints| {
            host.frames += 1;
            host.world.get_mut::<Position>(entity).unwrap().x = 2.0;
            points.0 += 5;
            points.0
        });

        assert_eq!(seen, 5);
        assert_eq!(host.frames, 1);
        assert_eq!(host.world.get::<Position>(entity).unwrap().x, 2.0);
        assert_eq!(host.world.resource::<ScopePoints>().unwrap().0, 5);
    }

    #[test]
    fn test_host_resource_scope_reinserts_on_panic() {
        let mut host = HostWorld {
            world: DynWorld::new(),
            frames: 0,
        };
        host.world.insert_resource(ScopePoints(3));

        let outcome = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            resource_scope(&mut host, |_host, points: &mut ScopePoints| {
                points.0 += 1;
                panic!("scope body panics");
            });
        }));

        assert!(outcome.is_err());
        assert_eq!(host.world.resource::<ScopePoints>().unwrap().0, 4);
    }

    #[test]
    fn test_host_resources_scope_takes_the_tuple() {
        let mut host = HostWorld {
            world: DynWorld::new(),
            frames: 0,
        };
        host.world.insert_resource(ScopePoints(1));
        host.world.insert_resource(ScopeLabel("group"));

        resources_scope(
            &mut host,
            |host, (points, label): &mut (ScopePoints, ScopeLabel)| {
                host.frames += 1;
                points.0 += 1;
                assert_eq!(label.0, "group");
            },
        );

        assert_eq!(host.frames, 1);
        assert_eq!(host.world.resource::<ScopePoints>().unwrap().0, 2);
        assert!(host.world.resource::<ScopeLabel>().is_some());
    }

    #[test]
    fn test_query_join_ref_filters_and_windows() {
        let mut core_registry = ComponentRegistry::new();
        core_registry.register::<Position>();
        let mut game_registry = ComponentRegistry::new();
        game_registry.register::<Health>();

        let mut ecs = DynEcs::new();
        ecs.add_world_at(0, core_registry);
        ecs.add_world_at(1, game_registry);
        let still = ecs.spawn_with((Position { x: 1.0, y: 0.0 }, Health { value: 1.0 }));
        let moved = ecs.spawn_with((Position { x: 2.0, y: 0.0 }, Health { value: 2.0 }));

        ecs.worlds[0].step();
        ecs.get_mut::<Position>(moved).unwrap().x = 9.0;
        let changed: Vec<Entity> = ecs
            .query_join_ref::<(&Position, &Health)>()
            .changed::<Position>()
            .iter()
            .map(|(entity, _items)| entity)
            .collect();
        assert_eq!(changed, vec![moved]);

        ecs.worlds[0].step();
        let fresh = ecs.spawn_with((Position { x: 3.0, y: 0.0 }, Health { value: 3.0 }));
        let appeared: Vec<Entity> = ecs
            .query_join_ref::<(&Position, &Health)>()
            .added::<Position>()
            .iter()
            .map(|(entity, _items)| entity)
            .collect();
        assert_eq!(appeared, vec![fresh]);

        assert_eq!(
            ecs.query_join_ref::<(&Position, &Health)>()
                .changed::<Velocity>()
                .iter()
                .count(),
            0,
            "an unregistered filter type degrades the read join to empty"
        );
        let _ = still;
    }

    #[cfg(not(target_family = "wasm"))]
    #[test]
    fn test_prepared_query_runs_parallel() {
        let mut world = DynWorld::new();
        world.spawn_bundles((Position::default(), Velocity { x: 1.0, y: 0.0 }), 64);
        let prepared = world.query::<(&mut Position, &Velocity)>().prepare();

        prepared
            .query(&mut world)
            .par_for_each(|_entity, (position, velocity)| {
                position.x += velocity.x;
            });
        let total: f32 = world
            .query_ref::<&Position>()
            .iter()
            .map(|(_entity, position)| position.x)
            .sum();
        assert_eq!(total, 64.0);
    }

    #[cfg(feature = "snapshot")]
    #[test]
    fn test_group_delta_serializes_and_group_compact_runs() {
        let mut core_registry = ComponentRegistry::new();
        core_registry.register_serde::<Position>();
        core_registry.register_serde::<Velocity>();
        let mut source = DynEcs::new();
        source.add_world_at(0, core_registry.clone());
        let seed = source.spawn_with((Position::default(),));

        let snapshot = source.snapshot().unwrap();
        let mut replica = DynEcs::from_snapshot(vec![core_registry], &snapshot).unwrap();
        let cursor = source.delta_cursor();

        source.get_mut::<Position>(seed).unwrap().x = 4.0;
        let doomed = source.spawn_with((Position { x: 9.0, y: 0.0 }, Velocity::default()));
        source.despawn(doomed);

        let delta = source.delta_since(&cursor).unwrap();
        let bytes = postcard::to_allocvec(&delta).unwrap();
        let decoded: DynEcsDelta = postcard::from_bytes(&bytes).unwrap();
        replica.apply_delta(&decoded).unwrap();
        assert_eq!(replica.get::<Position>(seed).unwrap().x, 4.0);
        assert!(!replica.is_alive(doomed));

        assert!(
            source.worlds[0].stats().empty_table_count >= 1,
            "the despawned spawn's table sits empty"
        );
        let dropped = source.compact();
        assert!(dropped >= 1);
        assert_eq!(source.get::<Position>(seed).unwrap().x, 4.0);
        assert_eq!(source.stats().free_ids, 1);
    }

    #[cfg(not(target_family = "wasm"))]
    #[test]
    fn test_query_join_par_for_each_matches_sequential() {
        let mut core_registry = ComponentRegistry::new();
        core_registry.register::<Position>();
        let mut game_registry = ComponentRegistry::new();
        game_registry.register::<Health>();

        let mut ecs = DynEcs::new();
        ecs.add_world_at(0, core_registry);
        ecs.add_world_at(1, game_registry);
        for index in 0..50 {
            let entity = ecs.spawn_with((Position {
                x: index as f32,
                y: 0.0,
            },));
            if index % 2 == 0 {
                ecs.set(entity, Health { value: 1.0 });
            }
        }

        ecs.worlds[0].step();
        ecs.query_join::<(&mut Position, &Health)>()
            .par_for_each(|_entity, (position, health)| {
                position.y += health.value;
            });

        let mut lifted = 0;
        ecs.query_join::<(&Position, &Health)>()
            .for_each(|_entity, (position, _health)| {
                if position.y == 1.0 {
                    lifted += 1;
                }
            });
        assert_eq!(lifted, 25);
        assert_eq!(
            ecs.worlds[0]
                .query_entities_changed(ecs.worlds[0].lookup_key::<Position>().unwrap().mask)
                .count(),
            25,
            "parallel join mutation stamps driver ticks"
        );
    }

    #[test]
    fn test_stats_and_compact() {
        let mut world = DynWorld::new();
        let mover = world.spawn((Position::default(), Velocity::default()));
        world.spawn((Position::default(),));
        world.insert_resource(7u32);
        world.send(3u8);

        let stats = world.stats();
        assert_eq!(stats.entity_count, 2);
        assert_eq!(stats.table_count, 2);
        assert_eq!(stats.empty_table_count, 0);
        assert_eq!(stats.component_count, 2);
        assert_eq!(stats.resource_count, 1);
        assert_eq!(stats.event_channels, 1);

        world.remove::<Velocity>(mover);
        assert_eq!(world.stats().empty_table_count, 1);

        let dropped = world.compact();
        assert_eq!(dropped, 1);
        assert_eq!(world.stats().table_count, 1);
        assert_eq!(world.get::<Position>(mover).unwrap().x, 0.0);
        world.set(mover, Velocity { x: 4.0, y: 0.0 });
        assert_eq!(world.get::<Velocity>(mover).unwrap().x, 4.0);
        assert_eq!(world.compact(), 0);

        let mut ecs = DynEcs::new();
        ecs.add_world(ComponentRegistry::new());
        let entity = ecs.spawn();
        ecs.add_tag_type::<u16>(entity);
        let group_stats = ecs.stats();
        assert_eq!(group_stats.live_entities, 1);
        assert_eq!(group_stats.group_tag_count, 1);
        assert_eq!(group_stats.worlds.len(), 1);
    }

    #[test]
    fn test_query_join_filters() {
        struct Cursed;

        let mut core_registry = ComponentRegistry::new();
        core_registry.register::<Position>();
        let mut game_registry = ComponentRegistry::new();
        game_registry.register::<Health>();

        let mut ecs = DynEcs::new();
        ecs.add_world_at(0, core_registry);
        ecs.add_world_at(1, game_registry);

        let cursed = ecs.spawn_with((Position { x: 1.0, y: 0.0 }, Health { value: 1.0 }));
        let plain = ecs.spawn_with((Position { x: 2.0, y: 0.0 }, Health { value: 2.0 }));
        ecs.add_tag_type::<Cursed>(cursed);

        let mut tagged = Vec::new();
        ecs.query_join::<(&Position, &Health)>()
            .with_tag_type::<Cursed>()
            .for_each(|entity, (_position, _health)| tagged.push(entity));
        assert_eq!(tagged, vec![cursed]);

        let mut untagged = Vec::new();
        ecs.query_join::<(&Position, &Health)>()
            .without_tag_type::<Cursed>()
            .for_each(|entity, (_position, _health)| untagged.push(entity));
        assert_eq!(untagged, vec![plain]);

        struct NeverUsed;
        let mut none = Vec::new();
        ecs.query_join::<(&Position, &Health)>()
            .with_tag_type::<NeverUsed>()
            .for_each(|entity, (_position, _health)| none.push(entity));
        assert!(none.is_empty(), "an unused include tag matches nothing");

        ecs.worlds[0].step();
        ecs.get_mut::<Position>(plain).unwrap().x = 9.0;
        let mut changed = Vec::new();
        ecs.query_join::<(&mut Position, &Health)>()
            .changed::<Position>()
            .for_each(|entity, (_position, _health)| changed.push(entity));
        assert_eq!(changed, vec![plain]);

        ecs.worlds[0].step();
        let fresh = ecs.spawn_with((Position { x: 5.0, y: 0.0 }, Health { value: 5.0 }));
        let mut appeared = Vec::new();
        ecs.query_join::<(&Position, &Health)>()
            .added::<Position>()
            .for_each(|entity, (_position, _health)| appeared.push(entity));
        assert_eq!(appeared, vec![fresh]);
    }

    #[test]
    #[should_panic(expected = "must name driver-world components")]
    fn test_query_join_changed_rejects_foreign_types() {
        let mut core_registry = ComponentRegistry::new();
        core_registry.register::<Position>();
        let mut game_registry = ComponentRegistry::new();
        game_registry.register::<Health>();

        let mut ecs = DynEcs::new();
        ecs.add_world_at(0, core_registry);
        ecs.add_world_at(1, game_registry);

        ecs.query_join::<(&mut Position, &Health)>()
            .changed::<Health>()
            .for_each(|_entity, (_position, _health)| {});
    }

    #[test]
    fn test_query_join_spans_member_worlds() {
        let mut core_registry = ComponentRegistry::new();
        core_registry.register::<Position>();
        let mut game_registry = ComponentRegistry::new();
        game_registry.register::<Health>();
        game_registry.register::<Velocity>();

        let mut ecs = DynEcs::new();
        ecs.add_world_at(0, core_registry);
        ecs.add_world_at(1, game_registry);

        let both = ecs.spawn_with((Position { x: 1.0, y: 0.0 }, Health { value: 10.0 }));
        let position_only = ecs.spawn_with((Position { x: 2.0, y: 0.0 },));
        let all_three = ecs.spawn_with((
            Position { x: 3.0, y: 0.0 },
            Health { value: 30.0 },
            Velocity { x: 9.0, y: 0.0 },
        ));
        ecs.spawn_with((Health { value: 99.0 },));

        ecs.worlds[0].step();
        let mut visited = Vec::new();
        ecs.query_join::<(&mut Position, &Health, Option<&Velocity>)>()
            .for_each(|entity, (position, health, velocity)| {
                position.x += health.value + velocity.map_or(0.0, |velocity| velocity.x);
                visited.push(entity);
            });
        assert_eq!(visited, vec![both, all_three]);
        assert_eq!(ecs.get::<Position>(both).unwrap().x, 11.0);
        assert_eq!(ecs.get::<Position>(all_three).unwrap().x, 42.0);
        assert_eq!(ecs.get::<Position>(position_only).unwrap().x, 2.0);
        assert_eq!(
            ecs.worlds[0]
                .query_entities_changed(ecs.worlds[0].lookup_key::<Position>().unwrap().mask)
                .count(),
            2,
            "join mutation stamps driver-world ticks per visited row"
        );

        let manual: Vec<(Entity, f32)> = {
            let mut pairs = Vec::new();
            for (entity, position) in ecs.worlds[0].query_ref::<&Position>().iter() {
                if let Some(health) = ecs.worlds[1].get::<Health>(entity) {
                    pairs.push((entity, position.x + health.value));
                }
            }
            pairs
        };
        let mut joined: Vec<(Entity, f32)> = Vec::new();
        ecs.query_join::<(&Position, &Health)>()
            .for_each(|entity, (position, health)| {
                joined.push((entity, position.x + health.value));
            });
        assert_eq!(
            joined, manual,
            "the join matches the hand-rolled routing loop"
        );

        let mut shared_only = Vec::new();
        ecs.query_join::<(&Health, &Position)>()
            .for_each(|entity, (_health, _position)| shared_only.push(entity));
        assert_eq!(
            shared_only.len(),
            2,
            "all-shared joins pick a driver themselves"
        );

        let mut degenerate = Vec::new();
        ecs.query_join::<(&Health, &Velocity)>()
            .for_each(|entity, (_health, _velocity)| degenerate.push(entity));
        assert_eq!(
            degenerate,
            vec![all_three],
            "a single-world tuple degenerates to a plain scan"
        );
    }

    #[test]
    #[should_panic(expected = "mutate only one world's components")]
    fn test_query_join_rejects_mutable_elements_in_two_worlds() {
        let mut core_registry = ComponentRegistry::new();
        core_registry.register::<Position>();
        let mut game_registry = ComponentRegistry::new();
        game_registry.register::<Health>();

        let mut ecs = DynEcs::new();
        ecs.add_world_at(0, core_registry);
        ecs.add_world_at(1, game_registry);

        ecs.query_join::<(&mut Position, &mut Health)>()
            .for_each(|_entity, (_position, _health)| {});
    }

    #[test]
    #[should_panic(expected = "not registered in any member world")]
    fn test_query_join_rejects_unregistered_required_types() {
        let mut ecs = DynEcs::new();
        ecs.add_world(ComponentRegistry::new());
        ecs.query_join::<(&Position,)>()
            .for_each(|_entity, (_position,)| {});
    }

    #[test]
    fn test_dyn_ecs_group_events_are_exactly_once_with_two_frame_expiry() {
        let mut ecs = DynEcs::new();
        ecs.add_world(ComponentRegistry::new());
        ecs.add_world(ComponentRegistry::new());

        ecs.send(42u32);
        let mut cursor = 0;
        assert_eq!(ecs.consume_events::<u32>(&mut cursor), &[42]);
        assert!(ecs.consume_events::<u32>(&mut cursor).is_empty());
        assert_eq!(
            ecs.read_events::<u32>(),
            &[42],
            "read_events re-reads inside the buffer window"
        );

        let core_tick = ecs.worlds[0].current_tick;
        ecs.step();
        assert_eq!(
            ecs.worlds[0].current_tick,
            core_tick.wrapping_add(1),
            "group step drives member ticks"
        );
        assert_eq!(ecs.read_events::<u32>(), &[42]);
        ecs.step();
        assert!(
            ecs.read_events::<u32>().is_empty(),
            "group events expire after two frames"
        );

        ecs.worlds[0].send(7u32);
        assert!(
            ecs.read_events::<u32>().is_empty(),
            "world-local channels stay separate from the group channel"
        );
    }

    #[test]
    fn test_dyn_ecs_group_resources_and_scopes() {
        struct Shared(u32);
        struct Delta(f32);

        let mut ecs = DynEcs::new();
        ecs.add_world(ComponentRegistry::new());

        assert!(ecs.resource::<Shared>().is_none());
        ecs.insert_resource(Shared(1));
        ecs.insert_resource(Delta(0.5));
        ecs.expect_resource_mut::<Shared>().0 += 1;
        assert_eq!(ecs.expect_resource::<Shared>().0, 2);

        let entity = ecs.spawn();
        ecs.resource_scope(|ecs, shared: &mut Shared| {
            shared.0 += u32::from(ecs.is_alive(entity));
        });
        assert_eq!(ecs.resource::<Shared>().unwrap().0, 3);

        ecs.resources_scope(|ecs, (shared, delta): &mut (Shared, Delta)| {
            shared.0 += u32::from(ecs.is_alive(entity)) + delta.0 as u32;
        });
        assert_eq!(ecs.resource::<Shared>().unwrap().0, 4);
        assert!(ecs.remove_resource::<Delta>().is_some());

        let panic = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            ecs.resource_scope(|_ecs, _shared: &mut Shared| panic!("boom"));
        }));
        assert!(panic.is_err());
        assert_eq!(
            ecs.resource::<Shared>().unwrap().0,
            4,
            "the resource is restored even when the closure panics"
        );
    }

    #[test]
    fn test_dyn_ecs_routes_typed_access_to_owning_world() {
        let mut core_registry = ComponentRegistry::new();
        core_registry.register::<Position>();
        let mut game_registry = ComponentRegistry::new();
        game_registry.register::<Health>();

        let mut ecs = DynEcs::new();
        let core = ecs.add_world_at(0, core_registry);
        let game = ecs.add_world_at(1, game_registry);

        let entity = ecs.spawn_with((Position { x: 1.0, y: 0.0 }, Health { value: 10.0 }));
        assert_eq!(ecs.worlds[core].get::<Position>(entity).unwrap().x, 1.0);
        assert_eq!(ecs.worlds[game].get::<Health>(entity).unwrap().value, 10.0);
        assert!(ecs.worlds[core].get::<Health>(entity).is_none());

        assert_eq!(ecs.get::<Health>(entity).unwrap().value, 10.0);
        ecs.worlds[core].step();
        ecs.get_mut::<Position>(entity).unwrap().x = 2.0;
        ecs.set(entity, Health { value: 5.0 });
        assert!(ecs.has::<Position>(entity));
        assert_eq!(ecs.type_routes.len(), 2);

        assert_eq!(
            ecs.worlds[core].query_entities_changed(1).count(),
            1,
            "routed mutation stamps ticks in the owning world"
        );

        assert!(ecs.remove::<Health>(entity));
        assert!(!ecs.has::<Health>(entity));

        let visited: Vec<Entity> = ecs
            .query_ref::<&Position>()
            .iter()
            .map(|(entity, _position)| entity)
            .collect();
        assert_eq!(visited, vec![entity]);
        ecs.query::<&mut Position>()
            .for_each(|_entity, position| position.y = 7.0);
        assert_eq!(ecs.get::<Position>(entity).unwrap().y, 7.0);

        assert!(ecs.get::<Velocity>(entity).is_none());
        assert!(!ecs.remove::<Velocity>(entity));
        assert_eq!(
            ecs.query_ref::<&Velocity>().iter().count(),
            0,
            "unrouteable read queries are empty, not a panic"
        );
    }

    #[test]
    #[should_panic(expected = "not registered in any member world")]
    fn test_dyn_ecs_set_rejects_unregistered_types() {
        let mut ecs = DynEcs::new();
        ecs.add_world(ComponentRegistry::new());
        let entity = ecs.spawn();
        ecs.set(entity, Position::default());
    }

    #[test]
    #[should_panic(expected = "member world registered out of declaration order")]
    fn test_dyn_ecs_add_world_at_asserts_index() {
        let mut ecs = DynEcs::new();
        ecs.add_world_at(1, ComponentRegistry::new());
    }

    #[test]
    fn test_dyn_ecs_despawn_recursive_cascades_across_worlds() {
        let mut ecs = DynEcs::new();
        let core = ecs.add_world(ComponentRegistry::new());
        let render = ecs.add_world(ComponentRegistry::new());

        let root = ecs.spawn();
        ecs.worlds[core].set(root, Position::default());

        let child = ecs.spawn();
        ecs.worlds[core].set(child, ChildOf(root));

        let grandchild = ecs.spawn();
        ecs.worlds[render].set(grandchild, ChildOf(child));

        let bystander = ecs.spawn();
        ecs.worlds[core].set(bystander, Position::default());

        ecs.clear_structural_log();
        let despawned = ecs.despawn_recursive(root);

        assert_eq!(despawned.len(), 3);
        assert!(!ecs.is_alive(root));
        assert!(!ecs.is_alive(child));
        assert!(!ecs.is_alive(grandchild));
        assert!(ecs.is_alive(bystander));
        assert!(ecs.worlds[core].get::<Position>(root).is_none());
        assert!(ecs.worlds[render].get::<ChildOf>(grandchild).is_none());

        let deaths = ecs
            .structural_changes_since(0)
            .iter()
            .filter(|change| change.kind == StructuralChangeKind::Despawned)
            .count();
        assert_eq!(deaths, 3, "every cascade death lands in the lifecycle log");
    }

    #[test]
    fn test_dyn_ecs_lifecycle_log_records_handles_and_group_tags() {
        let mut ecs = DynEcs::new();
        let core = ecs.add_world(ComponentRegistry::new());
        let position = ecs.worlds[core].register::<Position>();
        let marked = ecs.register_tag();

        let solo = ecs.spawn();
        let pair = ecs.spawn_count(2);
        let rowed = ecs.spawn_entities(core, position.mask, 1)[0];

        ecs.add_tag(marked, solo);
        ecs.add_tag(marked, solo);
        assert!(ecs.remove_tag(marked, solo));
        assert!(!ecs.remove_tag(marked, solo));

        assert!(ecs.despawn(pair[0]));
        assert!(!ecs.despawn(pair[0]));

        let entries: Vec<(Entity, StructuralChangeKind, u64)> = ecs
            .structural_changes_since(0)
            .iter()
            .map(|change| (change.entity, change.kind, change.mask))
            .collect();
        assert_eq!(
            entries,
            vec![
                (solo, StructuralChangeKind::Spawned, 0),
                (pair[0], StructuralChangeKind::Spawned, 0),
                (pair[1], StructuralChangeKind::Spawned, 0),
                (rowed, StructuralChangeKind::Spawned, 0),
                (solo, StructuralChangeKind::TagsAdded, marked as u64),
                (solo, StructuralChangeKind::TagsRemoved, marked as u64),
                (pair[0], StructuralChangeKind::Despawned, 0),
            ]
        );

        let sequences: Vec<u64> = ecs
            .structural_changes_since(0)
            .iter()
            .map(|change| change.sequence)
            .collect();
        assert_eq!(sequences, (1..=7).collect::<Vec<u64>>());

        let cursor = sequences[3];
        assert_eq!(ecs.structural_changes_since(cursor).len(), 3);
        ecs.trim_structural_log(cursor);
        assert_eq!(ecs.structural_changes_since(0).len(), 3);
        assert_eq!(ecs.structural_sequence(), 7);

        ecs.clear_structural_log();
        assert!(ecs.structural_changes_since(0).is_empty());
        assert_eq!(ecs.structural_sequence(), 7);
    }

    #[test]
    fn test_dyn_ecs_lifecycle_log_capacity_backstop() {
        let mut ecs = DynEcs::new();
        let entity = ecs.spawn();
        let marked = ecs.register_tag();

        for _ in 0..(STRUCTURAL_LOG_CAPACITY / 2) {
            ecs.add_tag(marked, entity);
            ecs.remove_tag(marked, entity);
        }

        assert!(ecs.structural_log.len() < STRUCTURAL_LOG_CAPACITY);
        assert_eq!(
            ecs.structural_sequence(),
            STRUCTURAL_LOG_CAPACITY as u64 + 1
        );
        let tail = ecs.structural_changes_since(0);
        assert_eq!(tail.last().unwrap().sequence, ecs.structural_sequence());
    }

    #[test]
    fn test_dyn_ecs_group_shares_entities_across_worlds() {
        let mut ecs = DynEcs::new();
        let core = ecs.add_world(ComponentRegistry::new());
        let render = ecs.add_world(ComponentRegistry::new());

        let entity = ecs.spawn();
        ecs.worlds[core].set(entity, Position { x: 1.0, y: 2.0 });
        ecs.worlds[render].set(entity, Health { value: 9.0 });

        assert_eq!(ecs.worlds[core].get::<Position>(entity).unwrap().x, 1.0);
        assert_eq!(ecs.worlds[render].get::<Health>(entity).unwrap().value, 9.0);
        assert!(ecs.worlds[core].get::<Health>(entity).is_none());

        let core_position = ecs.worlds[core].register::<Position>();
        let render_health = ecs.worlds[render].register::<Health>();
        assert_eq!(
            core_position.mask, render_health.mask,
            "each grouped world owns an independent 64-bit mask space"
        );
    }

    #[test]
    fn test_dyn_ecs_despawn_broadcasts_and_refuses_stale() {
        let mut ecs = DynEcs::new();
        let core = ecs.add_world(ComponentRegistry::new());
        let render = ecs.add_world(ComponentRegistry::new());

        let old = ecs.spawn();
        ecs.worlds[core].set(old, Position { x: 1.0, y: 0.0 });

        assert!(ecs.despawn(old));
        assert!(!ecs.despawn(old), "double despawn must be refused");

        assert!(
            !ecs.worlds[core].add_components(old, 1),
            "stale add must be refused in a world that stored the entity"
        );
        ecs.worlds[render].set(old, Health { value: 3.0 });
        assert!(
            ecs.worlds[render].get::<Health>(old).is_none(),
            "stale set must be refused in a world that never stored the entity"
        );

        let reused = ecs.spawn();
        assert_eq!(reused.id, old.id);
        assert_eq!(reused.generation, old.generation + 1);
        ecs.worlds[render].set(reused, Health { value: 5.0 });
        assert_eq!(ecs.worlds[render].get::<Health>(reused).unwrap().value, 5.0);
        assert!(ecs.worlds[render].get::<Health>(old).is_none());
    }

    #[test]
    fn test_dyn_ecs_group_tags_filter_queries() {
        let mut ecs = DynEcs::new();
        let core = ecs.add_world(ComponentRegistry::new());
        let selected = ecs.register_tag();

        let first = ecs.spawn();
        let second = ecs.spawn();
        ecs.worlds[core].set(first, Position { x: 1.0, y: 0.0 });
        ecs.worlds[core].set(second, Position { x: 2.0, y: 0.0 });
        ecs.add_tag(selected, first);

        let DynEcs { worlds, tags, .. } = &mut ecs;
        let mut visited = Vec::new();
        worlds[core]
            .query::<(&Position,)>()
            .with_tag_set(&tags[selected])
            .for_each(|entity, _| visited.push(entity));
        assert_eq!(visited, vec![first]);

        let mut excluded = Vec::new();
        worlds[core]
            .query::<(&Position,)>()
            .without_tag_set(&tags[selected])
            .for_each(|entity, _| excluded.push(entity));
        assert_eq!(excluded, vec![second]);

        assert!(ecs.despawn(first));
        assert!(!ecs.has_tag(selected, first), "despawn drops group tags");
    }

    #[test]
    fn test_dyn_ecs_spawn_entities_in_member_world() {
        let mut ecs = DynEcs::new();
        let core = ecs.add_world(ComponentRegistry::new());
        let position = ecs.worlds[core].register::<Position>();

        let entities = ecs.spawn_entities(core, position.mask, 3);
        assert_eq!(entities.len(), 3);
        for &entity in &entities {
            assert!(ecs.is_alive(entity));
            assert!(ecs.worlds[core].get_keyed(position, entity).is_some());
        }

        let next = ecs.spawn();
        assert_eq!(next.id, 3, "member spawns draw from the shared allocator");
    }

    #[cfg(feature = "snapshot")]
    mod snapshots {
        use super::*;

        fn build_registry() -> ComponentRegistry {
            let mut registry = ComponentRegistry::new();
            registry.register_serde::<Position>();
            registry.register_serde::<Velocity>();
            registry.register_serde::<Health>();
            registry.register_tag();
            registry
        }

        fn populated_world() -> (DynWorld, Vec<Entity>) {
            let mut world = DynWorld::from_registry(build_registry());
            let position = world.component_key::<Position>();
            let health = world.component_key::<Health>();
            let boss = TagKey {
                tag_index: 0,
                mask: 1 << 63,
                registry_id: world.registry.registry_id,
            };

            let mut entities = Vec::new();
            for index in 0..10 {
                let entity = world.spawn((
                    Position {
                        x: index as f32,
                        y: index as f32 * 2.0,
                    },
                    Velocity { x: 1.0, y: 0.0 },
                ));
                entities.push(entity);
            }
            world.set_keyed(health, entities[3], Health { value: 42.0 });
            world.despawn_entities(&[entities[5]]);
            world.add_tag(boss, entities[7]);
            world.step();
            let _ = position;
            (world, entities)
        }

        #[test]
        fn test_snapshot_round_trip_preserves_state() {
            let (world, entities) = populated_world();

            let snapshot = world.snapshot().unwrap();
            let bytes = postcard::to_allocvec(&snapshot).unwrap();
            let decoded: DynWorldSnapshot = postcard::from_bytes(&bytes).unwrap();
            let restored = DynWorld::from_snapshot(build_registry(), &decoded).unwrap();

            assert_eq!(restored.entity_count(), world.entity_count());
            for &entity in &entities {
                assert_eq!(restored.is_alive(entity), world.is_alive(entity));
                assert_eq!(
                    restored.component_mask(entity),
                    world.component_mask(entity)
                );
                assert_eq!(
                    restored.get::<Position>(entity).map(|p| (p.x, p.y)),
                    world.get::<Position>(entity).map(|p| (p.x, p.y))
                );
                assert_eq!(
                    restored.get::<Health>(entity).map(|h| h.value),
                    world.get::<Health>(entity).map(|h| h.value)
                );
            }
            assert_eq!(restored.tags[0].len(), 1);
            assert!(restored.tags[0].contains(entities[7]));

            let respawned = {
                let mut restored = restored;
                restored.spawn((Position::default(),))
            };
            assert_eq!(
                respawned.id, entities[5].id,
                "the restored allocator must recycle the despawned id"
            );
            assert_eq!(respawned.generation, entities[5].generation + 1);
        }

        #[test]
        fn test_snapshot_restored_world_stays_in_lockstep() {
            let (mut original, _) = populated_world();
            let snapshot = original.snapshot().unwrap();
            let mut restored = DynWorld::from_snapshot(build_registry(), &snapshot).unwrap();

            let mut rng = Lcg(99);
            let mut handles: Vec<Entity> = original.get_all_entities();
            for _ in 0..500 {
                match rng.next() % 5 {
                    0 => {
                        let first = original.spawn((Position { x: 1.0, y: 1.0 },));
                        let second = restored.spawn((Position { x: 1.0, y: 1.0 },));
                        assert_eq!(first, second);
                        handles.push(first);
                    }
                    1 => {
                        if !handles.is_empty() {
                            let entity = handles[rng.next() as usize % handles.len()];
                            assert_eq!(
                                original.despawn_entities(&[entity]),
                                restored.despawn_entities(&[entity])
                            );
                        }
                    }
                    2 => {
                        if !handles.is_empty() {
                            let entity = handles[rng.next() as usize % handles.len()];
                            let value = (rng.next() % 100) as f32;
                            original.set(entity, Health { value });
                            restored.set(entity, Health { value });
                        }
                    }
                    3 => {
                        if !handles.is_empty() {
                            let entity = handles[rng.next() as usize % handles.len()];
                            let velocity_mask = original.component_key::<Velocity>().mask;
                            assert_eq!(
                                original.remove_components(entity, velocity_mask),
                                restored.remove_components(entity, velocity_mask)
                            );
                        }
                    }
                    _ => {
                        original.step();
                        restored.step();
                    }
                }
            }

            assert_eq!(original.entity_count(), restored.entity_count());
            for &entity in &handles {
                assert_eq!(
                    original.component_mask(entity),
                    restored.component_mask(entity)
                );
                assert_eq!(
                    original.get::<Health>(entity).map(|h| h.value),
                    restored.get::<Health>(entity).map(|h| h.value)
                );
            }
        }

        #[test]
        fn test_snapshot_schema_mismatch_is_refused() {
            let (world, _) = populated_world();
            let snapshot = world.snapshot().unwrap();

            let mut wrong_order = ComponentRegistry::new();
            wrong_order.register_serde::<Velocity>();
            wrong_order.register_serde::<Position>();
            wrong_order.register_serde::<Health>();

            match DynWorld::from_snapshot(wrong_order, &snapshot) {
                Err(SnapshotError::SchemaMismatch { .. }) => {}
                Err(other) => panic!("expected schema mismatch, got {other:?}"),
                Ok(_) => panic!("expected schema mismatch, got a restored world"),
            }
        }

        #[test]
        fn test_snapshot_registry_may_extend_the_schema() {
            let (world, entities) = populated_world();
            let snapshot = world.snapshot().unwrap();

            let mut extended = build_registry();
            extended.register_serde::<PingEvent>();

            let restored = DynWorld::from_snapshot(extended, &snapshot).unwrap();
            assert_eq!(
                restored.get::<Position>(entities[0]).unwrap().x,
                0.0,
                "components appended after the snapshot schema must not shift masks"
            );
        }

        #[test]
        fn test_snapshot_missing_codec_is_refused() {
            let mut world = DynWorld::new();
            world.spawn((Position::default(),));

            match world.snapshot() {
                Err(SnapshotError::MissingCodec(_)) => {}
                other => panic!(
                    "expected missing codec for a plain-registered component, got {:?}",
                    other.map(|_| ())
                ),
            }
        }

        #[test]
        fn test_snapshot_restores_change_detection_as_all_changed() {
            let (world, _) = populated_world();
            let snapshot = world.snapshot().unwrap();
            let restored = DynWorld::from_snapshot(build_registry(), &snapshot).unwrap();

            let position_mask = 1u64;
            let changed = restored.query_entities_changed(position_mask).count();
            assert_eq!(
                changed,
                restored.entity_count(),
                "restored slots must read as changed so consumers resync"
            );
        }

        #[test]
        fn test_dyn_ecs_snapshot_round_trip() {
            let mut ecs = DynEcs::new();
            let core = ecs.add_world({
                let mut registry = ComponentRegistry::new();
                registry.register_serde::<Position>();
                registry
            });
            let render = ecs.add_world({
                let mut registry = ComponentRegistry::new();
                registry.register_serde::<Health>();
                registry
            });
            let selected = ecs.register_tag();

            let entity = ecs.spawn();
            ecs.worlds[core].set(entity, Position { x: 3.0, y: 4.0 });
            ecs.worlds[render].set(entity, Health { value: 7.0 });
            ecs.add_tag(selected, entity);
            let dead = ecs.spawn();
            ecs.despawn(dead);

            let snapshot = ecs.snapshot().unwrap();
            let bytes = postcard::to_allocvec(&snapshot).unwrap();
            let decoded: DynEcsSnapshot = postcard::from_bytes(&bytes).unwrap();

            let restored = DynEcs::from_snapshot(
                vec![
                    {
                        let mut registry = ComponentRegistry::new();
                        registry.register_serde::<Position>();
                        registry
                    },
                    {
                        let mut registry = ComponentRegistry::new();
                        registry.register_serde::<Health>();
                        registry
                    },
                ],
                &decoded,
            )
            .unwrap();

            assert!(restored.is_alive(entity));
            assert!(!restored.is_alive(dead));
            assert_eq!(
                restored.worlds[core].get::<Position>(entity).unwrap().x,
                3.0
            );
            assert_eq!(
                restored.worlds[render].get::<Health>(entity).unwrap().value,
                7.0
            );
            assert!(restored.has_tag(selected, entity));

            let mut restored = restored;
            assert!(
                !restored.worlds[core].add_components(dead, 1),
                "stale refusal must survive the round trip"
            );
        }
    }

    mod differential {
        use super::*;

        crate::ecs! {
            StaticWorld {
                position: Position => DIFF_POSITION,
                velocity: Velocity => DIFF_VELOCITY,
                health: Health => DIFF_HEALTH,
            }
            Tags {
                boss => DIFF_BOSS,
            }
            DiffResources {
                _unused: f32,
            }
        }

        mod group_differential {
            use super::*;

            crate::ecs! {
                StaticEcs {
                    StaticCore {
                        core_position: Position => GROUP_POSITION,
                        core_velocity: Velocity => GROUP_VELOCITY,
                    }
                    StaticRender {
                        render_health: Health => GROUP_HEALTH,
                    }
                }
                Tags {
                    marked => GROUP_MARKED,
                }
                GroupResources {
                    _unused: f32,
                }
            }

            /// Drives the macro multi-world and a DynEcs group with one seeded op
            /// stream and requires identical observable state, the grouped
            /// counterpart of the single-world differential below.
            #[test]
            fn test_differential_dyn_ecs_matches_static_multi_world() {
                for seed in [21u64, 2121, 212121] {
                    let mut rng = Lcg(seed);

                    let mut static_ecs = StaticEcs::default();
                    let mut dyn_ecs = DynEcs::new();
                    let core = dyn_ecs.add_world(ComponentRegistry::new());
                    let render = dyn_ecs.add_world(ComponentRegistry::new());
                    let position = dyn_ecs.worlds[core].register::<Position>();
                    let velocity = dyn_ecs.worlds[core].register::<Velocity>();
                    let health = dyn_ecs.worlds[render].register::<Health>();
                    let marked = dyn_ecs.register_tag();

                    assert_eq!(position.mask, GROUP_POSITION);
                    assert_eq!(velocity.mask, GROUP_VELOCITY);
                    assert_eq!(health.mask, GROUP_HEALTH);

                    let mut handles: Vec<Entity> = Vec::new();
                    let pick = |rng: &mut Lcg, handles: &[Entity]| {
                        if handles.is_empty() {
                            None
                        } else {
                            Some(handles[rng.next() as usize % handles.len()])
                        }
                    };

                    static_ecs.step();
                    dyn_ecs.step();

                    for _ in 0..2500 {
                        match rng.next() % 9 {
                            0 | 1 => {
                                let static_entity = static_ecs.spawn();
                                let dyn_entity = dyn_ecs.spawn();
                                assert_eq!(static_entity, dyn_entity);
                                handles.push(static_entity);
                            }
                            2 => {
                                if let Some(entity) = pick(&mut rng, &handles) {
                                    assert_eq!(static_ecs.despawn(entity), dyn_ecs.despawn(entity));
                                }
                            }
                            3 => {
                                if let Some(entity) = pick(&mut rng, &handles) {
                                    let value = (rng.next() % 1000) as f32;
                                    static_ecs
                                        .static_core
                                        .set_core_position(entity, Position { x: value, y: 0.0 });
                                    dyn_ecs.worlds[core].set_keyed(
                                        position,
                                        entity,
                                        Position { x: value, y: 0.0 },
                                    );
                                }
                            }
                            4 => {
                                if let Some(entity) = pick(&mut rng, &handles) {
                                    let value = (rng.next() % 1000) as f32;
                                    static_ecs
                                        .static_render
                                        .set_render_health(entity, Health { value });
                                    dyn_ecs.worlds[render].set_keyed(
                                        health,
                                        entity,
                                        Health { value },
                                    );
                                }
                            }
                            5 => {
                                if let Some(entity) = pick(&mut rng, &handles) {
                                    assert_eq!(
                                        static_ecs
                                            .static_core
                                            .remove_components(entity, GROUP_POSITION),
                                        dyn_ecs.worlds[core]
                                            .remove_components(entity, position.mask)
                                    );
                                }
                            }
                            6 => {
                                if let Some(entity) = pick(&mut rng, &handles) {
                                    static_ecs.add_marked(entity);
                                    dyn_ecs.add_tag(marked, entity);
                                    assert_eq!(
                                        static_ecs.has_marked(entity),
                                        dyn_ecs.has_tag(marked, entity)
                                    );
                                }
                            }
                            7 => {
                                if let Some(entity) = pick(&mut rng, &handles) {
                                    assert_eq!(
                                        static_ecs.remove_marked(entity),
                                        dyn_ecs.remove_tag(marked, entity)
                                    );
                                }
                            }
                            _ => {
                                let static_changed: std::collections::HashSet<Entity> = static_ecs
                                    .static_core
                                    .query_entities_changed(GROUP_POSITION)
                                    .collect();
                                let dyn_changed: std::collections::HashSet<Entity> = dyn_ecs.worlds
                                    [core]
                                    .query_entities_changed(position.mask)
                                    .collect();
                                assert_eq!(
                                    static_changed, dyn_changed,
                                    "core changed sets diverged with seed {seed}"
                                );

                                static_ecs.step();
                                dyn_ecs.step();
                            }
                        }
                    }

                    assert_eq!(
                        static_ecs.static_core.entity_count(),
                        dyn_ecs.worlds[core].entity_count()
                    );
                    assert_eq!(
                        static_ecs.static_render.entity_count(),
                        dyn_ecs.worlds[render].entity_count()
                    );
                    for &handle in &handles {
                        assert_eq!(static_ecs.is_alive(handle), dyn_ecs.is_alive(handle));
                        assert_eq!(
                            static_ecs.static_core.component_mask(handle),
                            dyn_ecs.worlds[core].component_mask(handle)
                        );
                        assert_eq!(
                            static_ecs.static_render.component_mask(handle),
                            dyn_ecs.worlds[render].component_mask(handle)
                        );
                        assert_eq!(
                            static_ecs.static_core.get_core_position(handle),
                            dyn_ecs.worlds[core].get_keyed(position, handle)
                        );
                        assert_eq!(
                            static_ecs
                                .static_render
                                .get_render_health(handle)
                                .map(|h| h.value),
                            dyn_ecs.worlds[render]
                                .get_keyed(health, handle)
                                .map(|h| h.value)
                        );
                        assert_eq!(
                            static_ecs.has_marked(handle),
                            dyn_ecs.has_tag(marked, handle)
                        );
                    }
                    let expected_marked = static_ecs.query_marked().count();
                    assert_eq!(dyn_ecs.query_tag(marked).count(), expected_marked);

                    let static_lifecycle: Vec<(u64, Entity, StructuralChangeKind)> = static_ecs
                        .structural_changes_since(0)
                        .iter()
                        .map(|change| (change.sequence, change.entity, change.kind))
                        .collect();
                    let dyn_lifecycle: Vec<(u64, Entity, StructuralChangeKind)> = dyn_ecs
                        .structural_changes_since(0)
                        .iter()
                        .map(|change| (change.sequence, change.entity, change.kind))
                        .collect();
                    assert_eq!(
                        static_lifecycle, dyn_lifecycle,
                        "group lifecycle logs diverged with seed {seed}"
                    );
                    assert_eq!(
                        static_ecs.structural_sequence(),
                        dyn_ecs.structural_sequence()
                    );
                }
            }
        }

        /// Drives the macro-generated world and the dynamic world with one
        /// seeded op stream and requires identical observable state. The
        /// static world, hardened by its own property suite, acts as the
        /// executable specification for the dynamic one. Allocators evolve
        /// identically, so handles are comparable directly.
        #[test]
        fn test_differential_dyn_world_matches_static_world() {
            for seed in [5u64, 555, 314159] {
                let mut rng = Lcg(seed);

                let mut static_world = StaticWorld::default();
                let mut dyn_world = DynWorld::new();
                let position = dyn_world.register::<Position>();
                let velocity = dyn_world.register::<Velocity>();
                let health = dyn_world.register::<Health>();
                let boss = dyn_world.register_tag();

                assert_eq!(position.mask, DIFF_POSITION);
                assert_eq!(velocity.mask, DIFF_VELOCITY);
                assert_eq!(health.mask, DIFF_HEALTH);

                let mut handles: Vec<Entity> = Vec::new();

                let random_mask = |rng: &mut Lcg| {
                    let mut mask = 0;
                    for component in [DIFF_POSITION, DIFF_VELOCITY, DIFF_HEALTH] {
                        if rng.next().is_multiple_of(2) {
                            mask |= component;
                        }
                    }
                    mask
                };
                let pick = |rng: &mut Lcg, handles: &[Entity]| {
                    if handles.is_empty() {
                        None
                    } else {
                        Some(handles[rng.next() as usize % handles.len()])
                    }
                };

                static_world.step();
                dyn_world.step();

                for _ in 0..3000 {
                    match rng.next() % 10 {
                        0 | 1 => {
                            let mask = random_mask(&mut rng);
                            let static_entity = static_world.spawn_entities(mask, 1)[0];
                            let dyn_entity = dyn_world.spawn_entities(mask, 1)[0];
                            assert_eq!(
                                static_entity, dyn_entity,
                                "allocators must evolve identically"
                            );
                            handles.push(static_entity);
                        }
                        2 => {
                            if let Some(entity) = pick(&mut rng, &handles) {
                                let static_despawned = static_world.despawn_entities(&[entity]);
                                let dyn_despawned = dyn_world.despawn_entities(&[entity]);
                                assert_eq!(static_despawned, dyn_despawned);
                            }
                        }
                        3 => {
                            if let Some(entity) = pick(&mut rng, &handles) {
                                let mask = random_mask(&mut rng);
                                assert_eq!(
                                    static_world.add_components(entity, mask),
                                    dyn_world.add_components(entity, mask)
                                );
                            }
                        }
                        4 => {
                            if let Some(entity) = pick(&mut rng, &handles) {
                                let mask = random_mask(&mut rng);
                                assert_eq!(
                                    static_world.remove_components(entity, mask),
                                    dyn_world.remove_components(entity, mask)
                                );
                            }
                        }
                        5 => {
                            if let Some(entity) = pick(&mut rng, &handles) {
                                let value = (rng.next() % 1000) as f32;
                                static_world.set_position(entity, Position { x: value, y: 0.0 });
                                dyn_world.set_keyed(
                                    position,
                                    entity,
                                    Position { x: value, y: 0.0 },
                                );
                            }
                        }
                        6 => {
                            if let Some(entity) = pick(&mut rng, &handles) {
                                static_world.add_boss(entity);
                                dyn_world.add_tag(boss, entity);
                            }
                        }
                        7 => {
                            if let Some(entity) = pick(&mut rng, &handles) {
                                assert_eq!(
                                    static_world.remove_boss(entity),
                                    dyn_world.remove_tag(boss, entity)
                                );
                            }
                        }
                        8 => {
                            if let Some(entity) = pick(&mut rng, &handles) {
                                let value = (rng.next() % 1000) as f32;
                                static_world
                                    .queue_set_position(entity, Position { x: value, y: 0.0 });
                                dyn_world.queue_set(entity, Position { x: value, y: 0.0 });
                                static_world.apply_commands();
                                dyn_world.apply_commands();
                            }
                        }
                        _ => {
                            let static_changed: std::collections::HashSet<Entity> =
                                static_world.query_entities_changed(DIFF_POSITION).collect();
                            let dyn_changed: std::collections::HashSet<Entity> =
                                dyn_world.query_entities_changed(DIFF_POSITION).collect();
                            assert_eq!(
                                static_changed, dyn_changed,
                                "changed sets diverged with seed {seed}"
                            );

                            static_world.step();
                            dyn_world.step();
                        }
                    }
                }

                assert_eq!(static_world.entity_count(), dyn_world.entity_count());
                for &handle in &handles {
                    assert_eq!(
                        static_world.component_mask(handle),
                        dyn_world.component_mask(handle),
                        "masks diverged for {handle:?} with seed {seed}"
                    );
                    assert_eq!(
                        static_world.get_position(handle),
                        dyn_world.get_keyed(position, handle),
                        "position diverged for {handle:?} with seed {seed}"
                    );
                    assert_eq!(
                        static_world.has_boss(handle),
                        dyn_world.has_tag(boss, handle)
                    );
                    assert_eq!(static_world.is_alive(handle), dyn_world.is_alive(handle));
                }
                for mask in [
                    DIFF_POSITION,
                    DIFF_VELOCITY,
                    DIFF_HEALTH,
                    DIFF_POSITION | DIFF_VELOCITY,
                ] {
                    assert_eq!(
                        static_world.query_entities(mask).count(),
                        dyn_world.query_entities(mask).count()
                    );
                }
            }
        }
    }
}