rustial-engine 0.0.1

Framework-agnostic 2.5D map engine for rustial
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
// ---------------------------------------------------------------------------
//! # Tile manager -- fetch, cache, and fallback orchestration
//!
//! [`TileManager`] is the framework-agnostic tile pipeline.  It sits
//! between the abstract [`TileSource`] (which knows how to fetch tile
//! bytes) and the renderer (which needs GPU-ready pixel data).  Every
//! frame the owning [`TileLayer`] calls [`TileManager::update`],
#![allow(clippy::too_many_lines)]
//! which performs five steps:
//!
//! 1. **Poll** the source for tiles that have completed since the
//!    previous frame.
//! 2. **Compute** the desired tile set from `viewport_bounds` and
//!    `zoom`, optionally refining flat perspective views with the
//!    shared footprint-aware selection path.
//! 3. **Cancel** pending requests that have scrolled out of the desired set.
//! 4. **Build** the [`VisibleTileSet`] with parent-tile fallbacks for
//!    tiles that are still loading or failed.
//! 5. **Request** missing tiles in a deterministic priority order.
//!
//! ## Payload validation
//!
//! All completed tile payloads are validated before entering the cache.
//! Malformed raster data (for example, invalid RGBA8 buffer length) is
//! downgraded to a decode failure and recorded as a failed cache entry
//! instead of poisoning the renderer with corrupt image metadata.
//!
//! Late responses that arrive after their pending cache entries were
//! evicted are still accepted for successfully decoded tiles, but failed
//! responses for already-evicted entries are ignored.
//!
//! ## Parent-tile fallback
//!
//! When a tile is not yet loaded, the manager walks up the zoom
//! pyramid via [`TileId::parent`](rustial_math::TileId::parent) to
//! find the nearest ancestor whose data is cached.  The renderer can
//! then display that coarser tile until the full-resolution tile arrives.
//!
//! ## Data cloning
//!
//! [`TileData`] contains an `Arc<Vec<u8>>` of decoded RGBA8 pixels.
//! The [`VisibleTileSet`] returned by `update()` clones tile data so that
//! the caller owns it independently of the cache.  Because pixel buffers
//! are wrapped in `Arc`, cloning is cheap.
//!
//! ## Request prioritisation
//!
//! Missing tiles are requested in a deterministic order:
//!
//! 1. **Coarser zooms first**
//! 2. **Nearer tiles first**
//!
//! ## Active-use retention
//!
//! Tiles that are currently visible -- including loaded ancestors used
//! as fallbacks -- are explicitly marked as recently used in the LRU
//! cache.
// ---------------------------------------------------------------------------

use crate::tile_cache::{TileCache, TileCacheStats};
use crate::tile_lifecycle::{TileLifecycleDiagnostics, TileLifecycleTracker};
use crate::tile_source::{TileData, TileSource, TileSourceDiagnostics};
use rustial_math::{
    geo_to_tile, tile_bounds_world, FlatTileSelectionConfig, FlatTileView, GeoCoord, TileId,
    WebMercator, WorldBounds,
};
use std::cmp::Ordering;
use std::collections::HashSet;
use std::time::SystemTime;

/// Default visible-tile budget used by [`TileSelectionConfig`].
const DEFAULT_VISIBLE_TILE_BUDGET: usize = 512;

/// Maximum number of zoom levels to walk upward when searching for a
/// loaded ancestor or bootstrapping parent-chain requests.  Matches
/// MapLibre's practical parent-fallback depth.
const MAX_ANCESTOR_DEPTH: u8 = 8;

// ---------------------------------------------------------------------------
// Tile selection policy
// ---------------------------------------------------------------------------

/// Engine-side policy controlling visible tile selection.
#[derive(Debug, Clone, PartialEq)]
pub struct TileSelectionConfig {
    /// Maximum number of visible tiles the selector should emit.
    pub visible_tile_budget: usize,
    /// Footprint-aware flat-view tile selection policy.
    pub flat_view: FlatTileSelectionConfig,
    /// Minimum zoom level supported by the tile source.
    ///
    /// Tiles at zoom levels below this are never requested.  When the
    /// camera zoom is below `source_min_zoom`, the manager does not
    /// emit any visible tiles.  Defaults to 0.
    pub source_min_zoom: u8,
    /// Maximum zoom level supported by the tile source.
    ///
    /// When the camera zoom exceeds this value, tile requests are
    /// clamped to `source_max_zoom` and the resulting visible tiles
    /// are treated as overzoomed -- the `VisibleTile::target` records
    /// the display-zoom tile ID while `VisibleTile::actual` records
    /// the source-zoom tile ID.  Texture region mapping correctly
    /// extracts the sub-tile rectangle for rendering.
    ///
    /// Defaults to 22 (the common Web Mercator maximum).
    pub source_max_zoom: u8,
    /// Duration in seconds over which a newly loaded tile fades from
    /// fully transparent to fully opaque.
    ///
    /// Set to `0.0` to disable fade-in (tiles appear at full opacity
    /// immediately).  Matches MapLibre's `rasterFadeDuration` concept.
    /// Defaults to 0.0 (disabled); set to e.g. 0.3 for 300 ms fade.
    pub raster_fade_duration: f32,
    /// Maximum number of ancestor zoom-level tiles that may participate
    /// in a cross-fade overlay while a child tile is fading in.
    ///
    /// Prevents excessive overlapping translucent tiles when many zoom
    /// levels are simultaneously loading.  Defaults to 3.
    pub max_fading_ancestor_levels: u8,
    /// Maximum number of zoom levels to descend when searching for cached
    /// child tiles to use as underzoom fallback.
    ///
    /// When the camera zooms out and a target tile is not yet loaded, the
    /// manager checks whether higher-zoom children that are already cached
    /// can cover the target's extent.  This is the inverse of the parent
    /// fallback: instead of showing a blurry parent, we compose sharper
    /// children.  Set to 0 to disable child fallback.  Defaults to 0
    /// (disabled); set to e.g. 2 to enable.
    pub max_child_depth: u8,
    /// Maximum number of new tile requests the manager may issue in a
    /// single `update` pass.
    ///
    /// This is set by the [`TileRequestCoordinator`](crate::TileRequestCoordinator)
    /// to enforce a global cross-source request budget.  When `usize::MAX`,
    /// the manager issues requests without limit (the default for
    /// backwards compatibility and when coordination is disabled).
    pub max_requests_per_frame: usize,
}

/// Speculative prefetch direction derived from camera zoom motion.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ZoomPrefetchDirection {
    /// Zooming in: prefetch children of centre-most current tiles.
    In,
    /// Zooming out: prefetch parents of the current tile set.
    Out,
}

impl TileSelectionConfig {
    /// Return the effective per-frame visible tile budget for a given cache.
    #[inline]
    pub fn effective_visible_tile_budget(&self, cache_capacity: usize) -> usize {
        let policy_budget = self.visible_tile_budget.max(1);
        let cache_budget = cache_capacity.saturating_sub(10).max(1);
        policy_budget.min(cache_budget)
    }
}

impl Default for TileSelectionConfig {
    fn default() -> Self {
        Self {
            visible_tile_budget: DEFAULT_VISIBLE_TILE_BUDGET,
            flat_view: FlatTileSelectionConfig::default(),
            source_min_zoom: 0,
            source_max_zoom: 22,
            // Fade is off by default so that tests and headless pipelines
            // get deterministic visible-tile counts.  Consumers should
            // set this to e.g. 0.3 (300 ms) for smooth tile transitions.
            raster_fade_duration: 0.0,
            max_fading_ancestor_levels: 3,
            // Child fallback enabled by default so cached higher-zoom
            // tiles can cover lower-zoom targets during zoom-out, avoiding
            // gaps while new tiles load.  Set to 0 to disable.
            max_child_depth: 2,
            // Unlimited by default -- the TileRequestCoordinator sets
            // this field when cross-source coordination is active.
            max_requests_per_frame: usize::MAX,
        }
    }
}

// ---------------------------------------------------------------------------
// Texture mapping helpers
// ---------------------------------------------------------------------------

/// Normalized texture-space region within an `actual` tile image that maps to
/// a `target` tile.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct TileTextureRegion {
    /// Minimum U in normalized texture coordinates.
    pub u_min: f32,
    /// Minimum V in normalized texture coordinates.
    pub v_min: f32,
    /// Maximum U in normalized texture coordinates.
    pub u_max: f32,
    /// Maximum V in normalized texture coordinates.
    pub v_max: f32,
}

impl TileTextureRegion {
    /// Full texture coverage.
    pub const FULL: Self = Self {
        u_min: 0.0,
        v_min: 0.0,
        u_max: 1.0,
        v_max: 1.0,
    };

    /// Compute the normalized texture-space region of `actual` needed to draw
    /// `target`.
    pub fn from_tiles(target: &TileId, actual: &TileId) -> Self {
        if target.zoom <= actual.zoom || *target == *actual {
            return Self::FULL;
        }

        let dz = target.zoom - actual.zoom;
        let scale = 1u32 << dz;

        if target.x / scale != actual.x || target.y / scale != actual.y {
            return Self::FULL;
        }

        let offset_x = target.x - actual.x * scale;
        let offset_y = target.y - actual.y * scale;
        let inv = 1.0 / scale as f32;

        Self {
            u_min: offset_x as f32 * inv,
            v_min: offset_y as f32 * inv,
            u_max: (offset_x + 1) as f32 * inv,
            v_max: (offset_y + 1) as f32 * inv,
        }
    }

    /// Whether this region covers the full source texture.
    #[inline]
    pub fn is_full(&self) -> bool {
        *self == Self::FULL
    }

    /// Compute the texture region for rendering a **child** tile (at a
    /// higher zoom) into the grid cell of a **target** tile (at a lower
    /// zoom).
    ///
    /// This is the inverse of [`from_tiles`](Self::from_tiles) which
    /// handles the parent-fallback (overzoom) case.  For child-fallback
    /// (underzoom), the child's full texture maps into a sub-region of the
    /// target's grid cell.
    ///
    /// # Returns
    ///
    /// `None` if `child` is not a descendant of `target`.
    pub fn from_child_tile(target: &TileId, child: &TileId) -> Option<Self> {
        if child.zoom <= target.zoom {
            return None;
        }

        let dz = child.zoom - target.zoom;
        let scale = 1u32 << dz;

        // Verify that the child is actually a descendant of the target.
        if child.x / scale != target.x || child.y / scale != target.y {
            return None;
        }

        let offset_x = child.x - target.x * scale;
        let offset_y = child.y - target.y * scale;
        let inv = 1.0 / scale as f32;

        Some(Self {
            u_min: offset_x as f32 * inv,
            v_min: offset_y as f32 * inv,
            u_max: (offset_x + 1) as f32 * inv,
            v_max: (offset_y + 1) as f32 * inv,
        })
    }
}

/// Integer pixel-space crop rectangle derived from a fallback texture region.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct TilePixelRect {
    /// Left pixel coordinate.
    pub x: u32,
    /// Top pixel coordinate.
    pub y: u32,
    /// Rectangle width in pixels.
    pub width: u32,
    /// Rectangle height in pixels.
    pub height: u32,
}

impl TilePixelRect {
    /// Full image coverage.
    #[inline]
    pub fn full(width: u32, height: u32) -> Self {
        Self {
            x: 0,
            y: 0,
            width,
            height,
        }
    }

    /// Compute the pixel crop rectangle of `actual` needed to draw `target`.
    pub fn from_tiles(target: &TileId, actual: &TileId, width: u32, height: u32) -> Option<Self> {
        if width == 0 || height == 0 {
            return None;
        }
        if target.zoom <= actual.zoom || *target == *actual {
            return Some(Self::full(width, height));
        }

        let dz = (target.zoom - actual.zoom) as u32;
        let scale = 1u32.checked_shl(dz)?;

        if target.x / scale != actual.x || target.y / scale != actual.y {
            return None;
        }

        let crop_w = width / scale;
        let crop_h = height / scale;
        if crop_w == 0 || crop_h == 0 {
            return None;
        }

        let offset_x = target.x.checked_sub(actual.x.checked_mul(scale)?)?;
        let offset_y = target.y.checked_sub(actual.y.checked_mul(scale)?)?;
        let x = offset_x.checked_mul(crop_w)?;
        let y = offset_y.checked_mul(crop_h)?;

        if x.checked_add(crop_w)? > width || y.checked_add(crop_h)? > height {
            return None;
        }

        Some(Self {
            x,
            y,
            width: crop_w,
            height: crop_h,
        })
    }
}

// ---------------------------------------------------------------------------
// Request priority helpers
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, Copy)]
enum RequestUrgency {
    Coverage,
    FallbackRefine,
    Refresh,
}

impl RequestUrgency {
    #[inline]
    fn rank(self) -> u8 {
        match self {
            Self::Coverage => 0,
            Self::FallbackRefine => 1,
            Self::Refresh => 2,
        }
    }
}

#[derive(Debug, Clone, Copy)]
struct RequestCandidate {
    tile: TileId,
    distance_sq: f64,
    urgency: RequestUrgency,
}

impl RequestCandidate {
    fn new(tile: TileId, camera_world: (f64, f64), urgency: RequestUrgency) -> Self {
        let bounds = tile_bounds_world(&tile);
        let center_x = (bounds.min.position.x + bounds.max.position.x) * 0.5;
        let center_y = (bounds.min.position.y + bounds.max.position.y) * 0.5;
        let dx = center_x - camera_world.0;
        let dy = center_y - camera_world.1;
        Self {
            tile,
            distance_sq: dx * dx + dy * dy,
            urgency,
        }
    }
}

fn sort_request_candidates(candidates: &mut [RequestCandidate]) {
    candidates.sort_by(|a, b| {
        a.urgency
            .rank()
            .cmp(&b.urgency.rank())
            .then_with(|| a.tile.zoom.cmp(&b.tile.zoom))
            .then_with(|| {
                a.distance_sq
                    .partial_cmp(&b.distance_sq)
                    .unwrap_or(Ordering::Equal)
            })
            .then_with(|| a.tile.y.cmp(&b.tile.y))
            .then_with(|| a.tile.x.cmp(&b.tile.x))
    });
}

fn desired_with_ancestor_retention<'a>(
    desired: impl IntoIterator<Item = &'a TileId>,
) -> HashSet<TileId> {
    let tiles: Vec<TileId> = desired.into_iter().copied().collect();
    let mut retained = HashSet::with_capacity(tiles.len() * 2);
    for tile in tiles {
        retained.insert(tile);
        let mut current = tile;
        let mut depth = 0u8;
        while depth < MAX_ANCESTOR_DEPTH {
            if let Some(parent) = current.parent() {
                retained.insert(parent);
                current = parent;
                depth += 1;
            } else {
                break;
            }
        }
    }
    retained
}

fn desired_with_temporal_retention(
    current_desired: &[TileId],
    previous_desired: &HashSet<TileId>,
) -> HashSet<TileId> {
    desired_with_ancestor_retention(current_desired.iter().chain(previous_desired.iter()))
}

fn tile_contains(ancestor: TileId, tile: TileId) -> bool {
    if tile.zoom < ancestor.zoom {
        return false;
    }

    let dz = tile.zoom - ancestor.zoom;
    if dz == 0 {
        return tile == ancestor;
    }

    (tile.x >> dz) == ancestor.x && (tile.y >> dz) == ancestor.y
}

fn tile_at_zoom(tile: TileId, zoom: u8) -> TileId {
    if zoom >= tile.zoom {
        return tile;
    }

    let dz = tile.zoom - zoom;
    TileId::new(zoom, tile.x >> dz, tile.y >> dz)
}

fn tiles_within_horizon(a: TileId, b: TileId, radius: u32) -> bool {
    a.x.abs_diff(b.x) <= radius && a.y.abs_diff(b.y) <= radius
}

fn pending_tile_relevant_to_desired(tile: TileId, desired: &HashSet<TileId>) -> bool {
    const DESCENDANT_RETENTION_DEPTH: u8 = 2;
    const NEIGHBOR_RETENTION_RADIUS: u32 = 1;

    desired.iter().copied().any(|desired_tile| {
        if tile == desired_tile || tile_contains(tile, desired_tile) {
            return true;
        }

        if tile.zoom > desired_tile.zoom
            && tile.zoom - desired_tile.zoom <= DESCENDANT_RETENTION_DEPTH
            && tile_contains(desired_tile, tile)
        {
            return true;
        }

        let common_zoom = tile.zoom.min(desired_tile.zoom);
        let tile_common = tile_at_zoom(tile, common_zoom);
        let desired_common = tile_at_zoom(desired_tile, common_zoom);
        if !tiles_within_horizon(tile_common, desired_common, NEIGHBOR_RETENTION_RADIUS) {
            return false;
        }

        tile.zoom <= desired_tile.zoom
            || tile.zoom - desired_tile.zoom <= DESCENDANT_RETENTION_DEPTH
    })
}

// ---------------------------------------------------------------------------
// Route-aware prefetch helpers
// ---------------------------------------------------------------------------

/// Walk a geographic polyline and collect unique tile IDs at the given zoom
/// level, ordered along the route starting from the segment closest to
/// `camera_world`.
///
/// The route is sampled at roughly tile-width intervals so that every tile
/// the polyline passes through is captured without excessive redundancy.
/// Only the portion of the route **ahead** of the camera (further along
/// the polyline from the nearest point) is returned.
fn tiles_along_route(route: &[GeoCoord], zoom: u8, camera_world: (f64, f64)) -> Vec<TileId> {
    if route.len() < 2 {
        return Vec::new();
    }

    // --- 1. Find the route vertex closest to the camera ---
    let mut best_seg = 0usize;
    let mut best_dist_sq = f64::MAX;
    for (i, coord) in route.iter().enumerate() {
        let w = WebMercator::project_clamped(coord);
        let dx = w.position.x - camera_world.0;
        let dy = w.position.y - camera_world.1;
        let d2 = dx * dx + dy * dy;
        if d2 < best_dist_sq {
            best_dist_sq = d2;
            best_seg = i;
        }
    }

    // --- 2. Walk forward from that vertex, sampling at tile-width steps ---
    // Tile width in world-space meters at this zoom:
    //   full_extent = 2 * WebMercator::max_extent()
    //   tile_width  = full_extent / 2^zoom
    let full_extent = 2.0 * WebMercator::max_extent();
    let n_tiles = (1u64 << zoom) as f64;
    let tile_width = full_extent / n_tiles;
    // Sample at half-tile intervals to avoid missing narrow diagonal crossings.
    let step = tile_width * 0.5;

    let mut seen = HashSet::new();
    let mut tiles = Vec::new();

    // Walk segments starting from the closest vertex.
    let start = best_seg.min(route.len().saturating_sub(2));
    for seg in start..route.len().saturating_sub(1) {
        let a = WebMercator::project_clamped(&route[seg]);
        let b = WebMercator::project_clamped(&route[seg + 1]);
        let dx = b.position.x - a.position.x;
        let dy = b.position.y - a.position.y;
        let seg_len = (dx * dx + dy * dy).sqrt();
        if seg_len < 1e-9 {
            continue;
        }
        let steps = (seg_len / step).ceil() as usize;
        for s in 0..=steps {
            let t = if steps == 0 {
                0.0
            } else {
                (s as f64) / (steps as f64)
            };
            let px = a.position.x + dx * t;
            let py = a.position.y + dy * t;
            let geo = WebMercator::unproject(&rustial_math::WorldCoord::new(px, py, 0.0));
            let tile = geo_to_tile(&geo, zoom).tile_id();
            if seen.insert(tile) {
                tiles.push(tile);
            }
        }
    }

    tiles
}

// ---------------------------------------------------------------------------
// Overzoom helpers
// ---------------------------------------------------------------------------

/// Given a source tile at a clamped zoom and a higher display zoom, compute
/// the set of display-zoom tile IDs that fall within the source tile's
/// geographic extent.
///
/// For example, if `source_tile` is at zoom 14 and `display_zoom` is 16,
/// this returns the 4 (= 2^(16-14) x 2^(16-14)) children at zoom 16.
fn overzoomed_display_targets(source_tile: &TileId, display_zoom: u8) -> Vec<TileId> {
    if display_zoom <= source_tile.zoom {
        return vec![*source_tile];
    }
    let dz = display_zoom - source_tile.zoom;
    let scale = 1u32 << dz;
    let base_x = source_tile.x * scale;
    let base_y = source_tile.y * scale;
    let mut targets = Vec::with_capacity((scale * scale) as usize);
    for dy in 0..scale {
        for dx in 0..scale {
            targets.push(TileId::new(display_zoom, base_x + dx, base_y + dy));
        }
    }
    targets
}

// ---------------------------------------------------------------------------
// Fade-in helpers
// ---------------------------------------------------------------------------

/// Compute the fade-in opacity for a tile that was loaded at `loaded_at`.
///
/// Returns `1.0` when fade is disabled (`fade_duration <= 0`) or the tile
/// has been loaded long enough to be fully opaque.
fn compute_fade_opacity(now: SystemTime, loaded_at: Option<SystemTime>, fade_duration: f32) -> f32 {
    if fade_duration <= 0.0 {
        return 1.0;
    }
    let Some(loaded) = loaded_at else {
        return 1.0;
    };
    let elapsed = now.duration_since(loaded).unwrap_or_default().as_secs_f32();
    (elapsed / fade_duration).clamp(0.0, 1.0)
}

/// Emit a cross-fade parent fallback tile into the visible set.
///
/// Walks up the tile ancestry (up to `max_levels` zoom levels) looking for
/// a loaded ancestor in the cache.  If found, a `VisibleTile` is pushed
/// with `fade_opacity` set to the complementary opacity of the fading
/// child so that the blend is seamless.
fn emit_crossfade_parent(
    visible: &mut VisibleTileSet,
    child_target: TileId,
    parent_opacity: f32,
    max_levels: u8,
    cache: &mut TileCache,
) {
    let mut current = child_target;
    let mut depth = 0u8;
    while depth < max_levels {
        if let Some(parent) = current.parent() {
            let loaded = cache.get(&parent).and_then(|entry| entry.data()).cloned();
            if let Some(data) = loaded {
                cache.touch(&parent);
                visible.tiles.push(VisibleTile {
                    target: child_target,
                    actual: parent,
                    data: Some(data),
                    fade_opacity: parent_opacity,
                });
                return;
            }
            current = parent;
            depth += 1;
        } else {
            break;
        }
    }
}

// ---------------------------------------------------------------------------
// Observability
// ---------------------------------------------------------------------------

/// Per-frame diagnostics for the most recent tile-selection/update pass.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct TileSelectionStats {
    /// Number of candidate tiles before budget capping.
    pub raw_candidate_tiles: usize,
    /// Number of visible tiles emitted for the frame.
    pub visible_tiles: usize,
    /// Number of visible tiles with exact imagery.
    pub exact_visible_tiles: usize,
    /// Number of visible tiles using fallback imagery.
    pub fallback_visible_tiles: usize,
    /// Number of visible tiles with no imagery available yet.
    pub missing_visible_tiles: usize,
    /// Number of visible tiles rendered as overzoomed (display zoom > source max zoom).
    pub overzoomed_visible_tiles: usize,
    /// Number of candidate tiles dropped due to the visible tile budget.
    pub dropped_by_budget: usize,
    /// Whether the visible tile budget was hit this frame.
    pub budget_hit: bool,
    /// Number of stale pending requests cancelled this frame.
    pub cancelled_stale_pending: usize,
    /// Number of new tile requests issued this frame.
    pub requested_tiles: usize,
    /// Number of speculative prefetch tile requests issued this frame.
    pub speculative_requested_tiles: usize,
    /// Number of cache hits on exact target tiles.
    pub exact_cache_hits: usize,
    /// Number of visible tiles satisfied by ancestor fallback.
    pub fallback_hits: usize,
    /// Number of desired tiles covered by cached child tiles (underzoom fallback).
    pub child_fallback_hits: usize,
    /// Number of individual child-fallback visible tiles emitted.
    pub child_fallback_visible_tiles: usize,
    /// Number of desired tiles that missed both exact and ancestor imagery.
    pub cache_misses: usize,
}

/// Cumulative counters for long-running tile-manager diagnostics.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct TileManagerCounters {
    /// Total number of frames processed by the manager.
    pub frames: u64,
    /// Total number of times the visible tile budget was hit.
    pub budget_hit_frames: u64,
    /// Total number of candidate tiles dropped by the budget.
    pub dropped_by_budget: u64,
    /// Total number of exact visible-tile cache hits.
    pub exact_cache_hits: u64,
    /// Total number of visible fallback hits.
    pub fallback_hits: u64,
    /// Total number of visible child-fallback hits.
    pub child_fallback_hits: u64,
    /// Total number of visible cache misses.
    pub cache_misses: u64,
    /// Total number of requested tiles.
    pub requested_tiles: u64,
    /// Total number of speculative prefetch tile requests.
    pub speculative_requested_tiles: u64,
    /// Total number of stale pending requests cancelled.
    pub cancelled_stale_pending: u64,
    /// Total number of pending requests cancelled because their entries were evicted.
    pub cancelled_evicted_pending: u64,
}

// ---------------------------------------------------------------------------
// VisibleTileSet
// ---------------------------------------------------------------------------

/// The complete set of tiles that should be rendered for the current frame.
#[derive(Debug, Default)]
pub struct VisibleTileSet {
    /// Tiles that should be displayed (loaded or fallback).
    pub tiles: Vec<VisibleTile>,
}

impl VisibleTileSet {
    /// Number of tiles in the set.
    #[inline]
    pub fn len(&self) -> usize {
        self.tiles.len()
    }

    /// Whether the set is empty.
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.tiles.is_empty()
    }

    /// Number of tiles that currently have imagery available.
    #[inline]
    pub fn loaded_count(&self) -> usize {
        self.tiles.iter().filter(|t| t.data.is_some()).count()
    }

    /// Iterate over the visible tiles.
    #[inline]
    pub fn iter(&self) -> std::slice::Iter<'_, VisibleTile> {
        self.tiles.iter()
    }
}

impl<'a> IntoIterator for &'a VisibleTileSet {
    type Item = &'a VisibleTile;
    type IntoIter = std::slice::Iter<'a, VisibleTile>;

    fn into_iter(self) -> Self::IntoIter {
        self.tiles.iter()
    }
}

// ---------------------------------------------------------------------------
// VisibleTile
// ---------------------------------------------------------------------------

/// A single visible tile, either the exact tile, a parent fallback, or a
/// child fallback (underzoom).
#[derive(Debug, Clone)]
pub struct VisibleTile {
    /// The tile ID that should be displayed at this position.
    pub target: TileId,
    /// The tile ID whose data is actually available.
    pub actual: TileId,
    /// Decoded pixel data for `actual`.
    pub data: Option<TileData>,
    /// Per-tile opacity for fade-in transitions (0.0 = fully transparent,
    /// 1.0 = fully opaque).
    ///
    /// Renderers should multiply the tile fragment alpha by this value.
    /// During cross-fade, parent fallback tiles are emitted with a
    /// complementary opacity so the overall blending is seamless.
    pub fade_opacity: f32,
}

impl VisibleTile {
    /// Whether this tile has data available for rendering.
    #[inline]
    pub fn is_loaded(&self) -> bool {
        self.data.is_some()
    }

    /// Whether this tile is using fallback imagery instead of the ideal tile.
    #[inline]
    pub fn is_fallback(&self) -> bool {
        self.target != self.actual
    }

    /// Whether this tile is overzoomed -- i.e. the display zoom exceeds
    /// the source's maximum zoom and the tile is being rendered from a
    /// lower-zoom source tile.
    #[inline]
    pub fn is_overzoomed(&self) -> bool {
        self.target.zoom > self.actual.zoom && self.data.is_some()
    }

    /// Whether this tile is using a higher-zoom child as underzoom fallback.
    ///
    /// True when the `actual` tile's zoom is greater than `target`'s zoom,
    /// meaning a cached child tile is composited into a sub-region of the
    /// target's grid cell while the target itself is still loading.
    #[inline]
    pub fn is_child_fallback(&self) -> bool {
        self.actual.zoom > self.target.zoom && self.data.is_some()
    }

    /// Normalized texture-space region within `actual` that should be used
    /// when rendering this visible tile.
    ///
    /// For parent fallback (overzoom), the returned region extracts the
    /// relevant sub-tile from the lower-zoom parent texture.  For child
    /// fallback (underzoom), the full child texture is used — the renderer
    /// is responsible for placing the geometry at the child's grid-cell
    /// bounds rather than the target's.
    #[inline]
    pub fn texture_region(&self) -> TileTextureRegion {
        if self.actual.zoom > self.target.zoom {
            // Child fallback: the child's entire texture is rendered into
            // the child's own grid-cell bounds (a sub-region of the target).
            TileTextureRegion::FULL
        } else {
            // Exact or parent fallback (overzoom).
            TileTextureRegion::from_tiles(&self.target, &self.actual)
        }
    }

    /// Pixel crop rectangle within an `actual` image of the given size that
    /// should be used when rendering this visible tile.
    #[inline]
    pub fn pixel_crop_rect(&self, width: u32, height: u32) -> Option<TilePixelRect> {
        TilePixelRect::from_tiles(&self.target, &self.actual, width, height)
    }
}

// ---------------------------------------------------------------------------
// TileManager
// ---------------------------------------------------------------------------

/// Orchestrates tile fetching, caching, and visible-set computation.
pub struct TileManager {
    source: Box<dyn TileSource>,
    cache: TileCache,
    lifecycle: TileLifecycleTracker,
    selection_config: TileSelectionConfig,
    last_selection_stats: TileSelectionStats,
    counters: TileManagerCounters,
    last_desired_tiles: HashSet<TileId>,
}

impl std::fmt::Debug for TileManager {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("TileManager")
            .field("cache_len", &self.cache.len())
            .field("cache_capacity", &self.cache.capacity())
            .finish_non_exhaustive()
    }
}

impl TileManager {
    /// Create a new tile manager with the given source and cache capacity.
    pub fn new(source: Box<dyn TileSource>, cache_capacity: usize) -> Self {
        Self::new_with_config(source, cache_capacity, TileSelectionConfig::default())
    }

    /// Create a new tile manager with an explicit tile-selection policy.
    pub fn new_with_config(
        source: Box<dyn TileSource>,
        cache_capacity: usize,
        selection_config: TileSelectionConfig,
    ) -> Self {
        Self {
            source,
            cache: TileCache::new(cache_capacity),
            lifecycle: TileLifecycleTracker::default(),
            selection_config,
            last_selection_stats: TileSelectionStats::default(),
            counters: TileManagerCounters::default(),
            last_desired_tiles: HashSet::new(),
        }
    }

    /// Update the tile manager for the current frame.
    pub fn update(
        &mut self,
        viewport_bounds: &WorldBounds,
        zoom: u8,
        camera_world: (f64, f64),
        camera_distance: f64,
    ) -> VisibleTileSet {
        self.update_with_view(viewport_bounds, zoom, camera_world, camera_distance, None)
    }

    /// Update the tile manager using frustum-based quadtree traversal.
    ///
    /// This is the MapLibre-equivalent covering-tiles path. Instead of
    /// enumerating a rectangular AABB tile range and then filtering against
    /// a sampled ground footprint, this performs a depth-first quadtree
    /// descent from zoom 0, pruning any subtree whose world-space AABB
    /// does not intersect the camera frustum.
    pub fn update_with_frustum(
        &mut self,
        frustum: &rustial_math::Frustum,
        zoom: u8,
        camera_world: (f64, f64),
    ) -> VisibleTileSet {
        self.begin_lifecycle_frame();
        self.poll_completed();

        let mut stats = TileSelectionStats::default();
        let max_tiles = self
            .selection_config
            .effective_visible_tile_budget(self.cache.capacity());

        let desired = rustial_math::visible_tiles_frustum(frustum, zoom, max_tiles, camera_world);
        self.last_desired_tiles = desired.iter().copied().collect();

        stats.raw_candidate_tiles = desired.len();

        let desired_set = desired_with_ancestor_retention(&desired);
        stats.cancelled_stale_pending = self.prune_stale_pending(&desired_set);

        let now = SystemTime::now();
        for id in self.cache.expired_ids_at(now) {
            let _ = self.cache.mark_expired(id);
        }

        let mut visible = VisibleTileSet {
            tiles: Vec::with_capacity(desired.len()),
        };
        let mut missing = Vec::new();
        let mut refresh = Vec::new();
        let mut bootstrap = Vec::new();
        let fade_duration = self.selection_config.raster_fade_duration;
        let max_ancestor_fade = self.selection_config.max_fading_ancestor_levels;
        let max_child_depth = self.selection_config.max_child_depth;

        for &target in &desired {
            self.lifecycle.record_selected(target);
            let cached = self.cache.get(&target).map(|entry| {
                (
                    entry.data().cloned(),
                    entry
                        .freshness()
                        .is_some_and(|freshness| freshness.is_expired_at(now)),
                    entry.is_reloading(),
                    entry.loaded_at(),
                    entry.is_pending(),
                )
            });

            match cached {
                Some((Some(data), is_expired, is_reloading, loaded_at, _)) => {
                    self.cache.touch(&target);
                    if is_expired && !is_reloading && self.cache.start_reload(target) {
                        refresh.push(RequestCandidate::new(
                            target,
                            camera_world,
                            RequestUrgency::Refresh,
                        ));
                    }
                    stats.exact_cache_hits += 1;
                    stats.exact_visible_tiles += 1;

                    let fade_opacity = compute_fade_opacity(now, loaded_at, fade_duration);
                    if fade_opacity < 1.0 {
                        emit_crossfade_parent(
                            &mut visible,
                            target,
                            1.0 - fade_opacity,
                            max_ancestor_fade,
                            &mut self.cache,
                        );
                    }

                    visible.tiles.push(VisibleTile {
                        target,
                        actual: target,
                        data: Some(data),
                        fade_opacity,
                    });
                    self.record_visible_tile_use(target, target, true);
                }
                Some((None, _, _, _, is_pending)) => {
                    self.cache.touch(&target);
                    // Try child fallback first (sharper), then ancestor.
                    let children = self.find_loaded_children(&target, max_child_depth);
                    if !children.is_empty() {
                        stats.child_fallback_hits += 1;
                        for (child_id, child_data) in children {
                            stats.child_fallback_visible_tiles += 1;
                            visible.tiles.push(VisibleTile {
                                target,
                                actual: child_id,
                                data: Some(child_data),
                                fade_opacity: 1.0,
                            });
                            self.record_visible_tile_use(target, child_id, true);
                        }
                    } else {
                        let (actual, data) = self.find_loaded_ancestor(&target);
                        if data.is_some() && actual != target {
                            stats.fallback_hits += 1;
                            stats.fallback_visible_tiles += 1;
                        } else if data.is_none() {
                            stats.cache_misses += 1;
                            stats.missing_visible_tiles += 1;
                            bootstrap.push(target);
                        }
                        visible.tiles.push(VisibleTile {
                            target,
                            actual,
                            data,
                            fade_opacity: 1.0,
                        });
                        self.record_visible_tile_use(
                            target,
                            actual,
                            visible.tiles.last().is_some_and(|tile| tile.data.is_some()),
                        );
                    }
                    // Failed tiles with no retained payload must be
                    // re-requested; genuinely pending tiles are already
                    // in-flight and just need to wait.
                    if !is_pending {
                        let urgency =
                            if visible.tiles.last().is_some_and(|tile| tile.data.is_none()) {
                                RequestUrgency::Coverage
                            } else {
                                RequestUrgency::FallbackRefine
                            };
                        self.cache.remove(&target);
                        missing.push(RequestCandidate::new(target, camera_world, urgency));
                    }
                }
                None => {
                    // Try child fallback first, then ancestor.
                    let children = self.find_loaded_children(&target, max_child_depth);
                    if !children.is_empty() {
                        stats.child_fallback_hits += 1;
                        for (child_id, child_data) in children {
                            stats.child_fallback_visible_tiles += 1;
                            visible.tiles.push(VisibleTile {
                                target,
                                actual: child_id,
                                data: Some(child_data),
                                fade_opacity: 1.0,
                            });
                            self.record_visible_tile_use(target, child_id, true);
                        }
                    } else {
                        let (actual, data) = self.find_loaded_ancestor(&target);
                        if data.is_some() && actual != target {
                            stats.fallback_hits += 1;
                            stats.fallback_visible_tiles += 1;
                        } else if data.is_none() {
                            stats.cache_misses += 1;
                            stats.missing_visible_tiles += 1;
                            bootstrap.push(target);
                        }
                        visible.tiles.push(VisibleTile {
                            target,
                            actual,
                            data,
                            fade_opacity: 1.0,
                        });
                        self.record_visible_tile_use(
                            target,
                            actual,
                            visible.tiles.last().is_some_and(|tile| tile.data.is_some()),
                        );
                    }
                    let urgency = if visible.tiles.last().is_some_and(|tile| tile.data.is_none()) {
                        RequestUrgency::Coverage
                    } else {
                        RequestUrgency::FallbackRefine
                    };
                    missing.push(RequestCandidate::new(target, camera_world, urgency));
                }
            }
        }

        let (requested, cancelled_evicted_pending) =
            self.request_tiles_with_bootstrap(&mut refresh, &mut missing, &bootstrap, camera_world);

        stats.requested_tiles = requested.len();
        stats.visible_tiles = visible.tiles.len();

        self.counters.frames += 1;
        if stats.budget_hit {
            self.counters.budget_hit_frames += 1;
        }
        self.counters.dropped_by_budget += stats.dropped_by_budget as u64;
        self.counters.exact_cache_hits += stats.exact_cache_hits as u64;
        self.counters.fallback_hits += stats.fallback_hits as u64;
        self.counters.child_fallback_hits += stats.child_fallback_hits as u64;
        self.counters.cache_misses += stats.cache_misses as u64;
        self.counters.requested_tiles += stats.requested_tiles as u64;
        self.counters.cancelled_stale_pending += stats.cancelled_stale_pending as u64;
        self.counters.cancelled_evicted_pending += cancelled_evicted_pending as u64;
        self.last_selection_stats = stats;

        visible
    }

    /// Update the tile manager using MapLibre-equivalent covering-tiles
    /// quadtree traversal with per-tile variable zoom heuristics.
    ///
    /// This is the preferred path for perspective cameras at steep pitch.
    /// It performs frustum-culled depth-first traversal where distant tiles
    /// may use lower zoom levels than near tiles, matching MapLibre's
    /// `coveringTiles()` behaviour.
    pub fn update_with_covering(
        &mut self,
        frustum: &rustial_math::Frustum,
        cam: &rustial_math::CoveringCamera,
        opts: &rustial_math::CoveringTilesOptions,
        camera_world: (f64, f64),
    ) -> VisibleTileSet {
        self.begin_lifecycle_frame();
        self.poll_completed();

        let mut stats = TileSelectionStats::default();
        let max_tiles = self
            .selection_config
            .effective_visible_tile_budget(self.cache.capacity())
            .min(opts.max_tiles);

        let effective_opts = rustial_math::CoveringTilesOptions {
            max_tiles,
            ..opts.clone()
        };
        let desired = rustial_math::visible_tiles_covering(frustum, cam, &effective_opts);
        let previous_desired = self.last_desired_tiles.clone();

        stats.raw_candidate_tiles = desired.len();

        let desired_set = desired_with_temporal_retention(&desired, &previous_desired);
        stats.cancelled_stale_pending = self.prune_stale_pending(&desired_set);
        self.last_desired_tiles = desired.iter().copied().collect();

        let now = SystemTime::now();
        for id in self.cache.expired_ids_at(now) {
            let _ = self.cache.mark_expired(id);
        }

        let mut visible = VisibleTileSet {
            tiles: Vec::with_capacity(desired.len()),
        };
        let mut missing = Vec::new();
        let mut refresh = Vec::new();
        let fade_duration = self.selection_config.raster_fade_duration;
        let max_ancestor_fade = self.selection_config.max_fading_ancestor_levels;
        let max_child_depth = self.selection_config.max_child_depth;

        let mut bootstrap = Vec::new();

        for &target in &desired {
            self.lifecycle.record_selected(target);
            let cached = self.cache.get(&target).map(|entry| {
                (
                    entry.data().cloned(),
                    entry
                        .freshness()
                        .is_some_and(|freshness| freshness.is_expired_at(now)),
                    entry.is_reloading(),
                    entry.loaded_at(),
                    entry.is_pending(),
                )
            });

            match cached {
                Some((Some(data), is_expired, is_reloading, loaded_at, _)) => {
                    self.cache.touch(&target);
                    if is_expired && !is_reloading && self.cache.start_reload(target) {
                        refresh.push(RequestCandidate::new(
                            target,
                            camera_world,
                            RequestUrgency::Refresh,
                        ));
                    }
                    stats.exact_cache_hits += 1;
                    stats.exact_visible_tiles += 1;

                    let fade_opacity = compute_fade_opacity(now, loaded_at, fade_duration);
                    if fade_opacity < 1.0 {
                        emit_crossfade_parent(
                            &mut visible,
                            target,
                            1.0 - fade_opacity,
                            max_ancestor_fade,
                            &mut self.cache,
                        );
                    }

                    visible.tiles.push(VisibleTile {
                        target,
                        actual: target,
                        data: Some(data),
                        fade_opacity,
                    });
                    self.record_visible_tile_use(target, target, true);
                }
                Some((None, _, _, _, is_pending)) => {
                    self.cache.touch(&target);
                    // Try child fallback first (sharper), then ancestor.
                    let children = self.find_loaded_children(&target, max_child_depth);
                    if !children.is_empty() {
                        stats.child_fallback_hits += 1;
                        for (child_id, child_data) in children {
                            stats.child_fallback_visible_tiles += 1;
                            visible.tiles.push(VisibleTile {
                                target,
                                actual: child_id,
                                data: Some(child_data),
                                fade_opacity: 1.0,
                            });
                            self.record_visible_tile_use(target, child_id, true);
                        }
                    } else {
                        let (actual, data) = self.find_loaded_ancestor(&target);
                        if data.is_some() && actual != target {
                            stats.fallback_hits += 1;
                            stats.fallback_visible_tiles += 1;
                        } else if data.is_none() {
                            stats.cache_misses += 1;
                            stats.missing_visible_tiles += 1;
                            bootstrap.push(target);
                        }
                        visible.tiles.push(VisibleTile {
                            target,
                            actual,
                            data,
                            fade_opacity: 1.0,
                        });
                        self.record_visible_tile_use(
                            target,
                            actual,
                            visible.tiles.last().is_some_and(|tile| tile.data.is_some()),
                        );
                    }
                    // Failed tiles with no retained payload must be
                    // re-requested; genuinely pending tiles are already
                    // in-flight and just need to wait.
                    if !is_pending {
                        let urgency =
                            if visible.tiles.last().is_some_and(|tile| tile.data.is_none()) {
                                RequestUrgency::Coverage
                            } else {
                                RequestUrgency::FallbackRefine
                            };
                        self.cache.remove(&target);
                        missing.push(RequestCandidate::new(target, camera_world, urgency));
                    }
                }
                None => {
                    // Try child fallback first, then ancestor.
                    let children = self.find_loaded_children(&target, max_child_depth);
                    if !children.is_empty() {
                        stats.child_fallback_hits += 1;
                        for (child_id, child_data) in children {
                            stats.child_fallback_visible_tiles += 1;
                            visible.tiles.push(VisibleTile {
                                target,
                                actual: child_id,
                                data: Some(child_data),
                                fade_opacity: 1.0,
                            });
                            self.record_visible_tile_use(target, child_id, true);
                        }
                    } else {
                        let (actual, data) = self.find_loaded_ancestor(&target);
                        if data.is_some() && actual != target {
                            stats.fallback_hits += 1;
                            stats.fallback_visible_tiles += 1;
                        } else if data.is_none() {
                            stats.cache_misses += 1;
                            stats.missing_visible_tiles += 1;
                            bootstrap.push(target);
                        }
                        visible.tiles.push(VisibleTile {
                            target,
                            actual,
                            data,
                            fade_opacity: 1.0,
                        });
                        self.record_visible_tile_use(
                            target,
                            actual,
                            visible.tiles.last().is_some_and(|tile| tile.data.is_some()),
                        );
                    }
                    let urgency = if visible.tiles.last().is_some_and(|tile| tile.data.is_none()) {
                        RequestUrgency::Coverage
                    } else {
                        RequestUrgency::FallbackRefine
                    };
                    missing.push(RequestCandidate::new(target, camera_world, urgency));
                }
            }
        }

        let (requested, cancelled_evicted_pending) =
            self.request_tiles_with_bootstrap(&mut refresh, &mut missing, &bootstrap, camera_world);

        stats.requested_tiles = requested.len();
        stats.visible_tiles = visible.tiles.len();

        self.counters.frames += 1;
        if stats.budget_hit {
            self.counters.budget_hit_frames += 1;
        }
        self.counters.dropped_by_budget += stats.dropped_by_budget as u64;
        self.counters.exact_cache_hits += stats.exact_cache_hits as u64;
        self.counters.fallback_hits += stats.fallback_hits as u64;
        self.counters.child_fallback_hits += stats.child_fallback_hits as u64;
        self.counters.cache_misses += stats.cache_misses as u64;
        self.counters.requested_tiles += stats.requested_tiles as u64;
        self.counters.cancelled_stale_pending += stats.cancelled_stale_pending as u64;
        self.counters.cancelled_evicted_pending += cancelled_evicted_pending as u64;
        self.last_selection_stats = stats;

        visible
    }

    /// Update the tile manager with optional shared flat-view selection
    /// parameters for pitched perspective raster rendering.
    pub fn update_with_view(
        &mut self,
        viewport_bounds: &WorldBounds,
        zoom: u8,
        camera_world: (f64, f64),
        _camera_distance: f64,
        flat_view: Option<&FlatTileView>,
    ) -> VisibleTileSet {
        self.begin_lifecycle_frame();
        self.poll_completed();

        // Source zoom range enforcement (MapLibre OverscaledTileID equivalent).
        if zoom < self.selection_config.source_min_zoom {
            self.last_desired_tiles.clear();
            self.last_selection_stats = TileSelectionStats::default();
            return VisibleTileSet::default();
        }

        let source_zoom = zoom.min(self.selection_config.source_max_zoom);
        let is_overzoomed = zoom > source_zoom;

        let mut stats = TileSelectionStats::default();
        let max_tiles = self
            .selection_config
            .effective_visible_tile_budget(self.cache.capacity());

        // Select tiles at the source zoom (clamped), not the display zoom.
        let mut source_tiles = if let Some(view) = flat_view {
            rustial_math::visible_tiles_flat_view_capped_with_config(
                viewport_bounds,
                source_zoom,
                view,
                &self.selection_config.flat_view,
                max_tiles,
            )
        } else {
            rustial_math::visible_tiles(viewport_bounds, source_zoom)
        };

        stats.raw_candidate_tiles = source_tiles.len();
        if source_tiles.len() > max_tiles {
            stats.budget_hit = true;
            stats.dropped_by_budget = stats.raw_candidate_tiles - max_tiles;
            source_tiles.truncate(max_tiles);
        }
        let previous_desired = self.last_desired_tiles.clone();

        // Build the desired set at source zoom for cache/pending tracking.
        // Include ancestors so that parent-chain bootstrap requests are not
        // immediately cancelled on the next frame before they can complete.
        // Also retain the immediately previous desired set so small pans,
        // yaw changes, and zoom transitions do not discard still-useful
        // in-flight work before the new frame has a chance to converge.
        let desired_set = desired_with_temporal_retention(&source_tiles, &previous_desired);
        stats.cancelled_stale_pending = self.prune_stale_pending(&desired_set);
        self.last_desired_tiles = source_tiles.iter().copied().collect();

        let now = SystemTime::now();
        for id in self.cache.expired_ids_at(now) {
            let _ = self.cache.mark_expired(id);
        }

        let mut visible = VisibleTileSet {
            tiles: Vec::with_capacity(source_tiles.len()),
        };
        let mut missing = Vec::new();
        let mut refresh = Vec::new();
        let mut bootstrap = Vec::new();
        let fade_duration = self.selection_config.raster_fade_duration;
        let max_ancestor_fade = self.selection_config.max_fading_ancestor_levels;
        let max_child_depth = self.selection_config.max_child_depth;

        for &source_tile in &source_tiles {
            self.lifecycle.record_selected(source_tile);
            // When overzoomed, derive display-zoom target tiles from the
            // source tile so `VisibleTile::target` records the display
            // position and `VisibleTile::actual` records the fetched tile.
            let display_targets = if is_overzoomed {
                overzoomed_display_targets(&source_tile, zoom)
            } else {
                vec![source_tile]
            };

            let cached = self.cache.get(&source_tile).map(|entry| {
                (
                    entry.data().cloned(),
                    entry
                        .freshness()
                        .is_some_and(|freshness| freshness.is_expired_at(now)),
                    entry.is_reloading(),
                    entry.loaded_at(),
                    entry.is_pending(),
                )
            });

            match cached {
                Some((Some(data), is_expired, is_reloading, loaded_at, _)) => {
                    self.cache.touch(&source_tile);
                    if is_expired && !is_reloading && self.cache.start_reload(source_tile) {
                        refresh.push(RequestCandidate::new(
                            source_tile,
                            camera_world,
                            RequestUrgency::Refresh,
                        ));
                    }
                    stats.exact_cache_hits += 1;

                    let fade_opacity = compute_fade_opacity(now, loaded_at, fade_duration);

                    for target in display_targets {
                        if is_overzoomed {
                            stats.overzoomed_visible_tiles += 1;
                        } else {
                            stats.exact_visible_tiles += 1;
                        }
                        if fade_opacity < 1.0 {
                            emit_crossfade_parent(
                                &mut visible,
                                target,
                                1.0 - fade_opacity,
                                max_ancestor_fade,
                                &mut self.cache,
                            );
                        }
                        visible.tiles.push(VisibleTile {
                            target,
                            actual: source_tile,
                            data: Some(data.clone()),
                            fade_opacity,
                        });
                        self.record_visible_tile_use(target, source_tile, true);
                    }
                }
                Some((None, _, _, _, is_pending)) => {
                    self.cache.touch(&source_tile);
                    // Try child fallback when not overzoomed (children
                    // beyond source_max_zoom don't exist in the source).
                    let children = if !is_overzoomed {
                        self.find_loaded_children(&source_tile, max_child_depth)
                    } else {
                        Vec::new()
                    };
                    if !children.is_empty() {
                        stats.child_fallback_hits += 1;
                        for (child_id, child_data) in children {
                            for target in &display_targets {
                                stats.child_fallback_visible_tiles += 1;
                                visible.tiles.push(VisibleTile {
                                    target: *target,
                                    actual: child_id,
                                    data: Some(child_data.clone()),
                                    fade_opacity: 1.0,
                                });
                                self.record_visible_tile_use(*target, child_id, true);
                            }
                        }
                    } else {
                        let (actual, data) = self.find_loaded_ancestor(&source_tile);
                        if data.is_some() && actual != source_tile {
                            stats.fallback_hits += 1;
                        } else if data.is_none() {
                            stats.cache_misses += 1;
                            bootstrap.push(source_tile);
                        }
                        for target in display_targets {
                            if data.is_some() && actual != source_tile {
                                stats.fallback_visible_tiles += 1;
                            } else if data.is_none() {
                                stats.missing_visible_tiles += 1;
                            }
                            visible.tiles.push(VisibleTile {
                                target,
                                actual,
                                data: data.clone(),
                                fade_opacity: 1.0,
                            });
                            self.record_visible_tile_use(
                                target,
                                actual,
                                visible.tiles.last().is_some_and(|tile| tile.data.is_some()),
                            );
                        }
                    }
                    // Failed tiles with no retained payload must be
                    // re-requested; genuinely pending tiles are already
                    // in-flight and just need to wait.
                    if !is_pending {
                        let urgency =
                            if visible.tiles.last().is_some_and(|tile| tile.data.is_none()) {
                                RequestUrgency::Coverage
                            } else {
                                RequestUrgency::FallbackRefine
                            };
                        self.cache.remove(&source_tile);
                        missing.push(RequestCandidate::new(source_tile, camera_world, urgency));
                    }
                }
                None => {
                    // Try child fallback when not overzoomed, then ancestor.
                    let children = if !is_overzoomed {
                        self.find_loaded_children(&source_tile, max_child_depth)
                    } else {
                        Vec::new()
                    };
                    if !children.is_empty() {
                        stats.child_fallback_hits += 1;
                        for (child_id, child_data) in children {
                            for target in &display_targets {
                                stats.child_fallback_visible_tiles += 1;
                                visible.tiles.push(VisibleTile {
                                    target: *target,
                                    actual: child_id,
                                    data: Some(child_data.clone()),
                                    fade_opacity: 1.0,
                                });
                                self.record_visible_tile_use(*target, child_id, true);
                            }
                        }
                    } else {
                        let (actual, data) = self.find_loaded_ancestor(&source_tile);
                        if data.is_some() && actual != source_tile {
                            stats.fallback_hits += 1;
                        } else if data.is_none() {
                            stats.cache_misses += 1;
                            bootstrap.push(source_tile);
                        }
                        for target in display_targets {
                            if data.is_some() && actual != source_tile {
                                stats.fallback_visible_tiles += 1;
                            } else if data.is_none() {
                                stats.missing_visible_tiles += 1;
                            }
                            visible.tiles.push(VisibleTile {
                                target,
                                actual,
                                data: data.clone(),
                                fade_opacity: 1.0,
                            });
                            self.record_visible_tile_use(
                                target,
                                actual,
                                visible.tiles.last().is_some_and(|tile| tile.data.is_some()),
                            );
                        }
                    }
                    let urgency = if visible.tiles.last().is_some_and(|tile| tile.data.is_none()) {
                        RequestUrgency::Coverage
                    } else {
                        RequestUrgency::FallbackRefine
                    };
                    missing.push(RequestCandidate::new(source_tile, camera_world, urgency));
                }
            }
        }

        let (requested, cancelled_evicted_pending) =
            self.request_tiles_with_bootstrap(&mut refresh, &mut missing, &bootstrap, camera_world);

        stats.requested_tiles = requested.len();
        stats.visible_tiles = visible.tiles.len();

        self.counters.frames += 1;
        if stats.budget_hit {
            self.counters.budget_hit_frames += 1;
        }
        self.counters.dropped_by_budget += stats.dropped_by_budget as u64;
        self.counters.exact_cache_hits += stats.exact_cache_hits as u64;
        self.counters.fallback_hits += stats.fallback_hits as u64;
        self.counters.child_fallback_hits += stats.child_fallback_hits as u64;
        self.counters.cache_misses += stats.cache_misses as u64;
        self.counters.requested_tiles += stats.requested_tiles as u64;
        self.counters.cancelled_stale_pending += stats.cancelled_stale_pending as u64;
        self.counters.cancelled_evicted_pending += cancelled_evicted_pending as u64;
        self.last_selection_stats = stats;

        visible
    }

    #[inline]
    /// Read-only access to the most recent tile-selection/update stats.
    pub fn last_selection_stats(&self) -> &TileSelectionStats {
        &self.last_selection_stats
    }

    #[inline]
    /// Read-only access to the last desired source-tile set used for request selection.
    pub fn desired_tiles(&self) -> &HashSet<TileId> {
        &self.last_desired_tiles
    }

    #[inline]
    /// Read-only access to cumulative tile-manager counters.
    pub fn counters(&self) -> &TileManagerCounters {
        &self.counters
    }

    #[inline]
    /// Read-only access to the current tile-selection policy.
    pub fn selection_config(&self) -> &TileSelectionConfig {
        &self.selection_config
    }

    #[inline]
    /// Replace the tile-selection policy used by future updates.
    pub fn set_selection_config(&mut self, config: TileSelectionConfig) {
        self.selection_config = config;
    }

    #[inline]
    /// Read-only access to the cache.
    pub fn cache(&self) -> &TileCache {
        &self.cache
    }

    #[inline]
    /// Snapshot counts of the current tile-cache state.
    pub fn cache_stats(&self) -> TileCacheStats {
        self.cache.stats()
    }

    #[inline]
    /// Optional runtime diagnostics from the underlying tile source.
    pub fn source_diagnostics(&self) -> Option<TileSourceDiagnostics> {
        self.source.diagnostics()
    }

    #[inline]
    /// Snapshot of recent tile lifecycle diagnostics.
    pub fn lifecycle_diagnostics(&self) -> TileLifecycleDiagnostics {
        self.lifecycle.diagnostics()
    }

    #[inline]
    /// The number of tiles currently cached in any state.
    pub fn cached_count(&self) -> usize {
        self.cache.len()
    }

    /// Speculatively prefetch tiles for a predicted viewport without affecting
    /// the visible tile set.
    ///
    /// Only tiles outside the current frame's `last_desired_tiles` are
    /// requested, and existing cached or pending entries are skipped.
    pub fn prefetch_with_view(
        &mut self,
        viewport_bounds: &WorldBounds,
        zoom: u8,
        camera_world: (f64, f64),
        flat_view: Option<&FlatTileView>,
        max_requests: usize,
    ) -> usize {
        if max_requests == 0 || zoom < self.selection_config.source_min_zoom {
            return 0;
        }

        let source_zoom = zoom.min(self.selection_config.source_max_zoom);
        let max_tiles = self
            .selection_config
            .effective_visible_tile_budget(self.cache.capacity());

        let mut predicted_tiles = if let Some(view) = flat_view {
            rustial_math::visible_tiles_flat_view_capped_with_config(
                viewport_bounds,
                source_zoom,
                view,
                &self.selection_config.flat_view,
                max_tiles,
            )
        } else {
            rustial_math::visible_tiles(viewport_bounds, source_zoom)
        };
        if predicted_tiles.len() > max_tiles {
            predicted_tiles.truncate(max_tiles);
        }

        self.prefetch_tiles(predicted_tiles, camera_world, max_requests)
    }

    /// Speculatively prefetch tiles implied by the current desired set and a
    /// zoom direction.
    pub fn prefetch_zoom_direction(
        &mut self,
        camera_world: (f64, f64),
        direction: ZoomPrefetchDirection,
        max_requests: usize,
    ) -> usize {
        if max_requests == 0 || self.last_desired_tiles.is_empty() {
            return 0;
        }

        let mut anchors: Vec<RequestCandidate> = self
            .last_desired_tiles
            .iter()
            .copied()
            .map(|tile| RequestCandidate::new(tile, camera_world, RequestUrgency::Refresh))
            .collect();
        sort_request_candidates(&mut anchors);

        let mut tiles = Vec::new();
        let mut seen = HashSet::new();

        for anchor in anchors {
            match direction {
                ZoomPrefetchDirection::In => {
                    if anchor.tile.zoom >= self.selection_config.source_max_zoom {
                        continue;
                    }
                    for child in anchor.tile.children() {
                        if seen.insert(child) {
                            tiles.push(child);
                        }
                    }
                }
                ZoomPrefetchDirection::Out => {
                    let Some(parent) = anchor.tile.parent() else {
                        continue;
                    };
                    if parent.zoom < self.selection_config.source_min_zoom {
                        continue;
                    }
                    if seen.insert(parent) {
                        tiles.push(parent);
                    }
                }
            }
        }

        self.prefetch_tiles(tiles, camera_world, max_requests)
    }

    /// Speculatively prefetch tiles along a geographic route polyline.
    ///
    /// The route is walked from the segment nearest to the camera position
    /// forward, sampling tile boundaries at the given zoom level.  Only
    /// tiles that are **ahead** of the camera (further along the route) and
    /// not already in the current desired set or cache are requested.
    ///
    /// Returns the number of new tile requests issued.
    pub fn prefetch_route(
        &mut self,
        route: &[GeoCoord],
        zoom: u8,
        camera_world: (f64, f64),
        max_requests: usize,
    ) -> usize {
        if max_requests == 0 || route.len() < 2 || zoom < self.selection_config.source_min_zoom {
            return 0;
        }

        let source_zoom = zoom.min(self.selection_config.source_max_zoom);
        let tiles = tiles_along_route(route, source_zoom, camera_world);
        self.prefetch_tiles(tiles, camera_world, max_requests)
    }

    fn prefetch_tiles<I>(
        &mut self,
        tiles: I,
        camera_world: (f64, f64),
        max_requests: usize,
    ) -> usize
    where
        I: IntoIterator<Item = TileId>,
    {
        if max_requests == 0 {
            return 0;
        }

        let mut candidates: Vec<RequestCandidate> = tiles
            .into_iter()
            .filter(|tile| !self.last_desired_tiles.contains(tile))
            .filter(|tile| self.cache.get(tile).is_none())
            .map(|tile| RequestCandidate::new(tile, camera_world, RequestUrgency::Refresh))
            .collect();

        if candidates.is_empty() {
            return 0;
        }

        sort_request_candidates(&mut candidates);
        let mut requested = Vec::new();
        for candidate in candidates.into_iter().take(max_requests) {
            let insert = self.cache.insert_pending_with_eviction(candidate.tile);
            self.record_evicted_tiles(&insert.evicted);
            self.counters.cancelled_evicted_pending +=
                self.cancel_evicted_pending(&insert.evicted) as u64;
            if insert.inserted {
                self.lifecycle.record_queued(candidate.tile);
                requested.push(candidate.tile);
            }
        }

        if !requested.is_empty() {
            for &tile in &requested {
                self.lifecycle.record_dispatched(tile);
            }
            self.source.request_many(&requested);
        }

        let requested_count = requested.len();
        self.last_selection_stats.speculative_requested_tiles += requested_count;
        self.counters.speculative_requested_tiles += requested_count as u64;
        requested_count
    }

    #[inline]
    fn begin_lifecycle_frame(&mut self) {
        self.lifecycle.begin_frame(self.counters.frames + 1);
    }

    #[inline]
    fn record_visible_tile_use(&mut self, target: TileId, actual: TileId, has_data: bool) {
        if !has_data {
            return;
        }

        if target == actual {
            self.lifecycle.record_used_as_exact(actual);
        } else {
            self.lifecycle.record_used_as_fallback(actual);
        }
    }

    fn record_evicted_tiles(&mut self, evicted: &[crate::tile_cache::EvictedTile]) {
        for tile in evicted {
            if tile.was_pending() {
                self.lifecycle.record_evicted_while_pending(tile.id);
            } else if tile.entry.is_renderable() {
                self.lifecycle.record_evicted_after_renderable_use(tile.id);
            }
        }
    }

    /// Promote externally decoded tiles into the cache.
    ///
    /// This is the integration point for the background MVT decode
    /// pipeline: after `poll()` returns a `TileData::RawVector` entry
    /// and the async pipeline decodes it, the decoded `TileResponse`
    /// is fed back here to replace the raw entry with a fully decoded
    /// `TileData::Vector` entry.
    pub fn promote_decoded(&mut self, decoded: Vec<(TileId, crate::tile_source::TileResponse)>) {
        for (id, response) in decoded {
            match response.data.validate() {
                Ok(()) => {
                    self.lifecycle.record_decoded(id);
                    let evicted = self.cache.promote_with_eviction(id, response);
                    self.lifecycle.record_promoted_to_cache(id);
                    self.record_evicted_tiles(&evicted);
                    let cancelled = self.cancel_evicted_pending(&evicted);
                    self.counters.cancelled_evicted_pending += cancelled as u64;
                }
                Err(err) => {
                    self.lifecycle.record_failed(id);
                    self.cache.mark_failed(id, &err)
                }
            }
        }
    }

    fn poll_completed(&mut self) {
        let completed = self.source.poll();
        for (id, result) in completed {
            match result {
                Ok(response) if response.not_modified => {
                    self.lifecycle.record_completed(id);
                    // 304 Not Modified: refresh the TTL without replacing data.
                    self.cache.refresh_ttl(id, response.freshness);
                }
                Ok(response) => match response.data.validate() {
                    Ok(()) => {
                        self.lifecycle.record_completed(id);
                        self.lifecycle.record_decoded(id);
                        let evicted = self.cache.promote_with_eviction(id, response);
                        self.lifecycle.record_promoted_to_cache(id);
                        self.record_evicted_tiles(&evicted);
                        let cancelled = self.cancel_evicted_pending(&evicted);
                        self.counters.cancelled_evicted_pending += cancelled as u64;
                    }
                    Err(err) => {
                        self.lifecycle.record_completed(id);
                        self.lifecycle.record_failed(id);
                        self.cache.mark_failed(id, &err)
                    }
                },
                Err(err) => {
                    self.lifecycle.record_completed(id);
                    self.lifecycle.record_failed(id);
                    self.cache.mark_failed(id, &err)
                }
            }
        }
    }

    /// Cancel pending requests that were evicted by the cache.
    fn cancel_evicted_pending(&self, evicted: &[crate::tile_cache::EvictedTile]) -> usize {
        let pending_ids: Vec<TileId> = evicted
            .iter()
            .filter(|tile| tile.was_pending())
            .map(|tile| tile.id)
            .collect();
        self.source.cancel_many(&pending_ids);
        pending_ids.len()
    }

    fn prune_stale_pending(&mut self, desired: &HashSet<TileId>) -> usize {
        let stale_pending: Vec<TileId> = self
            .cache
            .inflight_ids()
            .into_iter()
            .filter(|id| !pending_tile_relevant_to_desired(*id, desired))
            .collect();

        self.source.cancel_many(&stale_pending);
        for id in &stale_pending {
            self.lifecycle.record_cancelled_as_stale(*id);
            // Reloading entries carry renderable stale payload that may
            // still serve as fallback.  Demote them to Expired instead
            // of destroying the data.  Pure Pending entries have no
            // renderable payload and can be fully removed.
            if !self.cache.cancel_reload(id) {
                self.cache.remove(id);
            }
        }
        stale_pending.len()
    }

    fn find_loaded_ancestor(&mut self, tile: &TileId) -> (TileId, Option<TileData>) {
        let mut current = *tile;
        let mut depth = 0u8;
        while depth < MAX_ANCESTOR_DEPTH {
            if let Some(parent) = current.parent() {
                let loaded = self
                    .cache
                    .get(&parent)
                    .and_then(|entry| entry.data())
                    .cloned();
                if let Some(data) = loaded {
                    self.cache.touch(&parent);
                    return (parent, Some(data));
                }
                current = parent;
                depth += 1;
            } else {
                break;
            }
        }
        (*tile, None)
    }

    /// Search for cached child tiles that completely cover the given target
    /// tile's geographic extent.
    ///
    /// Walks one zoom level down at a time (up to `max_depth` levels) and
    /// checks whether **all** children at that level are loaded.  Returns
    /// the first complete set found — i.e. z+1 (4 children) is preferred
    /// over z+2 (16 grandchildren).
    ///
    /// Returns an empty vec when no complete child coverage exists.
    fn find_loaded_children(&mut self, target: &TileId, max_depth: u8) -> Vec<(TileId, TileData)> {
        if max_depth == 0 {
            return Vec::new();
        }

        // BFS: at each depth level, expand all current frontier tiles into
        // their 4 children and check whether every child is loaded.
        let mut frontier = vec![*target];

        for _depth in 0..max_depth {
            let mut next_frontier = Vec::with_capacity(frontier.len() * 4);
            let mut all_loaded = true;
            let mut children_data = Vec::with_capacity(frontier.len() * 4);

            for tile in &frontier {
                for child in tile.children() {
                    let loaded = self
                        .cache
                        .get(&child)
                        .and_then(|entry| entry.data())
                        .cloned();
                    if let Some(data) = loaded {
                        children_data.push((child, data));
                        next_frontier.push(child);
                    } else {
                        all_loaded = false;
                        break;
                    }
                }
                if !all_loaded {
                    break;
                }
            }

            if all_loaded && !children_data.is_empty() {
                // Touch all children so they are retained in the LRU.
                for (child_id, _) in &children_data {
                    self.cache.touch(child_id);
                }
                return children_data;
            }

            frontier = next_frontier;
        }

        Vec::new()
    }

    fn request_parent_chain(
        &mut self,
        tile: TileId,
        _camera_world: (f64, f64),
        requested: &mut Vec<TileId>,
        requested_set: &mut HashSet<TileId>,
        cancelled_evicted_pending: &mut usize,
    ) {
        let mut chain = Vec::new();
        let mut current = tile;
        let mut depth = 0u8;
        while depth < MAX_ANCESTOR_DEPTH {
            let Some(parent) = current.parent() else {
                break;
            };
            match self.cache.get(&parent) {
                Some(entry)
                    if entry.is_renderable() || entry.is_pending() || entry.is_reloading() =>
                {
                    break
                }
                Some(_) => {
                    current = parent;
                    depth += 1;
                }
                None => {
                    chain.push(parent);
                    current = parent;
                    depth += 1;
                }
            }
        }

        chain.reverse();
        for ancestor in chain {
            if !requested_set.insert(ancestor) {
                continue;
            }
            let insert = self.cache.insert_pending_with_eviction(ancestor);
            self.record_evicted_tiles(&insert.evicted);
            *cancelled_evicted_pending += self.cancel_evicted_pending(&insert.evicted);
            if insert.inserted {
                self.lifecycle.record_queued(ancestor);
                requested.push(ancestor);
            }
        }
    }

    fn request_tiles_with_bootstrap(
        &mut self,
        refresh: &mut Vec<RequestCandidate>,
        missing: &mut Vec<RequestCandidate>,
        bootstrap: &[TileId],
        camera_world: (f64, f64),
    ) -> (Vec<TileId>, usize) {
        sort_request_candidates(refresh);
        sort_request_candidates(missing);

        // Per-frame request budget from the cross-source coordinator.
        // When coordination is disabled this is usize::MAX (unlimited).
        let budget = self.selection_config.max_requests_per_frame;

        let mut requested = Vec::with_capacity(refresh.len() + missing.len() + bootstrap.len() * 2);
        let mut requested_set = HashSet::with_capacity(requested.capacity().max(1));
        let mut cancelled_evicted_pending = 0usize;

        // Collect revalidation pairs for expired tiles.
        // Revalidation requests are lightweight (conditional 304) and do
        // not count against the coordinator budget.
        let mut revalidate_pairs: Vec<(TileId, crate::tile_source::RevalidationHint)> =
            Vec::with_capacity(refresh.len());
        for candidate in refresh.drain(..) {
            if requested_set.insert(candidate.tile) {
                let hint = self
                    .cache
                    .revalidation_hint(&candidate.tile)
                    .unwrap_or_default();
                revalidate_pairs.push((candidate.tile, hint));
                requested.push(candidate.tile);
            }
        }

        // Track the count before bootstrap so we can slice the bootstrap
        // tiles out of `requested` later for plain request dispatch.
        let pre_bootstrap_len = requested.len();

        for &tile in bootstrap {
            self.request_parent_chain(
                tile,
                camera_world,
                &mut requested,
                &mut requested_set,
                &mut cancelled_evicted_pending,
            );
        }

        // Collect new (non-refresh) tile requests, respecting the
        // per-frame budget assigned by the TileRequestCoordinator.
        let mut new_request_ids: Vec<TileId> = requested[pre_bootstrap_len..].to_vec();
        for candidate in missing.drain(..) {
            // Stop issuing new requests once the coordinator budget is
            // exhausted.  Already-queued bootstrap parents are exempt
            // because they are critical for fallback rendering.
            if new_request_ids.len() >= budget {
                break;
            }
            if !requested_set.insert(candidate.tile) {
                continue;
            }
            let insert = self.cache.insert_pending_with_eviction(candidate.tile);
            self.record_evicted_tiles(&insert.evicted);
            cancelled_evicted_pending += self.cancel_evicted_pending(&insert.evicted);
            if insert.inserted {
                self.lifecycle.record_queued(candidate.tile);
                requested.push(candidate.tile);
                new_request_ids.push(candidate.tile);
            }
        }

        // Dispatch visible/bootstrap requests before background refresh
        // work so exact coverage and fallback promotion improve first.
        if !new_request_ids.is_empty() {
            for &tile in &new_request_ids {
                self.lifecycle.record_dispatched(tile);
            }
            self.source.request_many(&new_request_ids);
        }
        // Issue conditional revalidation requests (with If-None-Match /
        // If-Modified-Since headers) for expired tiles afterward.
        if !revalidate_pairs.is_empty() {
            for (tile, _) in &revalidate_pairs {
                self.lifecycle.record_dispatched(*tile);
            }
            self.source.request_revalidate_many(&revalidate_pairs);
        }
        (requested, cancelled_evicted_pending)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::tile_cache::TileCacheEntry;
    use crate::tile_lifecycle::TileLifecycleEventKind;
    use crate::tile_source::{DecodedImage, TileData, TileError, TileResponse, TileSource};
    use rustial_math::tile_bounds_world;
    use std::sync::{Arc, Mutex};

    struct MockSource {
        ready: Mutex<Vec<(TileId, Result<TileResponse, TileError>)>>,
    }

    impl MockSource {
        fn new() -> Self {
            Self {
                ready: Mutex::new(Vec::new()),
            }
        }
    }

    impl TileSource for MockSource {
        fn request(&self, id: TileId) {
            let data = TileData::Raster(DecodedImage {
                width: 256,
                height: 256,
                data: vec![128u8; 256 * 256 * 4].into(),
            });
            self.ready
                .lock()
                .unwrap()
                .push((id, Ok(TileResponse::from_data(data))));
        }

        fn poll(&self) -> Vec<(TileId, Result<TileResponse, TileError>)> {
            let mut ready = self.ready.lock().unwrap();
            std::mem::take(&mut *ready)
        }
    }

    struct FailingSource;

    impl TileSource for FailingSource {
        fn request(&self, _id: TileId) {}

        fn poll(&self) -> Vec<(TileId, Result<TileResponse, TileError>)> {
            Vec::new()
        }
    }

    struct DelayedFailSource {
        pending: Mutex<Vec<TileId>>,
    }

    impl DelayedFailSource {
        fn new() -> Self {
            Self {
                pending: Mutex::new(Vec::new()),
            }
        }
    }

    impl TileSource for DelayedFailSource {
        fn request(&self, id: TileId) {
            self.pending.lock().unwrap().push(id);
        }

        fn poll(&self) -> Vec<(TileId, Result<TileResponse, TileError>)> {
            let ids: Vec<TileId> = std::mem::take(&mut *self.pending.lock().unwrap());
            ids.into_iter()
                .map(|id| (id, Err(TileError::Network("timeout".into()))))
                .collect()
        }
    }

    #[derive(Clone, Default)]
    struct RecordingSource {
        requested: Arc<Mutex<Vec<TileId>>>,
        cancelled: Arc<Mutex<Vec<TileId>>>,
    }

    impl RecordingSource {
        fn requested_ids(&self) -> Vec<TileId> {
            self.requested.lock().unwrap().clone()
        }

        fn cancelled_ids(&self) -> Vec<TileId> {
            self.cancelled.lock().unwrap().clone()
        }
    }

    impl TileSource for RecordingSource {
        fn request(&self, id: TileId) {
            self.requested.lock().unwrap().push(id);
        }

        fn request_many(&self, ids: &[TileId]) {
            self.requested.lock().unwrap().extend_from_slice(ids);
        }

        fn poll(&self) -> Vec<(TileId, Result<TileResponse, TileError>)> {
            Vec::new()
        }

        fn cancel(&self, id: TileId) {
            self.cancelled.lock().unwrap().push(id);
        }

        fn cancel_many(&self, ids: &[TileId]) {
            self.cancelled.lock().unwrap().extend_from_slice(ids);
        }
    }

    struct InvalidImageSource {
        ready: Mutex<Vec<(TileId, Result<TileResponse, TileError>)>>,
    }

    impl InvalidImageSource {
        fn new() -> Self {
            Self {
                ready: Mutex::new(Vec::new()),
            }
        }
    }

    impl TileSource for InvalidImageSource {
        fn request(&self, id: TileId) {
            self.ready.lock().unwrap().push((
                id,
                Ok(TileResponse::from_data(TileData::Raster(DecodedImage {
                    width: 2,
                    height: 2,
                    data: vec![255u8; 15].into(),
                }))),
            ));
        }

        fn poll(&self) -> Vec<(TileId, Result<TileResponse, TileError>)> {
            std::mem::take(&mut *self.ready.lock().unwrap())
        }
    }

    fn full_world_bounds() -> WorldBounds {
        let extent = rustial_math::WebMercator::max_extent();
        WorldBounds::new(
            rustial_math::WorldCoord::new(-extent, -extent, 0.0),
            rustial_math::WorldCoord::new(extent, extent, 0.0),
        )
    }

    fn dummy_tile_data() -> TileData {
        TileData::Raster(DecodedImage {
            width: 256,
            height: 256,
            data: vec![0u8; 256 * 256 * 4].into(),
        })
    }

    fn dummy_tile_response() -> TileResponse {
        TileResponse::from_data(dummy_tile_data())
    }

    fn tile_center(tile: TileId) -> (f64, f64) {
        let bounds = tile_bounds_world(&tile);
        (
            (bounds.min.position.x + bounds.max.position.x) * 0.5,
            (bounds.min.position.y + bounds.max.position.y) * 0.5,
        )
    }

    fn inset_bounds(bounds: WorldBounds, inset: f64) -> WorldBounds {
        WorldBounds::new(
            rustial_math::WorldCoord::new(
                bounds.min.position.x + inset,
                bounds.min.position.y + inset,
                0.0,
            ),
            rustial_math::WorldCoord::new(
                bounds.max.position.x - inset,
                bounds.max.position.y - inset,
                0.0,
            ),
        )
    }

    #[test]
    fn zoom_0_one_tile() {
        let mut mgr = TileManager::new(Box::new(MockSource::new()), 100);

        let vis = mgr.update(&full_world_bounds(), 0, (0.0, 0.0), 0.0);
        assert_eq!(vis.len(), 1);
        assert!(vis.tiles[0].data.is_none());

        let vis = mgr.update(&full_world_bounds(), 0, (0.0, 0.0), 0.0);
        assert_eq!(vis.len(), 1);
        assert!(vis.tiles[0].is_loaded());
        assert!(!vis.tiles[0].is_fallback());
    }

    #[test]
    fn zoom_1_four_tiles() {
        let mut mgr = TileManager::new(Box::new(MockSource::new()), 100);

        let _ = mgr.update(&full_world_bounds(), 1, (0.0, 0.0), 0.0);
        let vis = mgr.update(&full_world_bounds(), 1, (0.0, 0.0), 0.0);
        assert_eq!(vis.len(), 4);
        for tile in &vis {
            assert!(tile.is_loaded());
        }
    }

    #[test]
    fn parent_fallback_when_pending() {
        let mut mgr = TileManager::new(Box::new(MockSource::new()), 100);

        let _ = mgr.update(&full_world_bounds(), 0, (0.0, 0.0), 0.0);
        let vis = mgr.update(&full_world_bounds(), 0, (0.0, 0.0), 0.0);
        assert!(vis.tiles[0].is_loaded());

        let vis = mgr.update(&full_world_bounds(), 1, (0.0, 0.0), 0.0);
        assert_eq!(vis.len(), 4);
        for tile in &vis {
            assert_eq!(tile.target.zoom, 1);
            assert_eq!(tile.actual.zoom, 0);
            assert!(tile.is_loaded());
            assert!(tile.is_fallback());
        }
    }

    #[test]
    fn no_fallback_when_no_ancestor_loaded() {
        let mut mgr = TileManager::new(Box::new(FailingSource), 100);

        let vis = mgr.update(&full_world_bounds(), 0, (0.0, 0.0), 0.0);
        assert_eq!(vis.len(), 1);
        assert!(!vis.tiles[0].is_loaded());
        assert!(!vis.tiles[0].is_fallback());
    }

    #[test]
    fn failed_tile_uses_parent_fallback() {
        let mut mgr = TileManager::new(Box::new(DelayedFailSource::new()), 100);

        let z0 = TileId::new(0, 0, 0);
        mgr.cache.insert_pending(z0);
        mgr.cache.promote(z0, dummy_tile_response());

        let _ = mgr.update(&full_world_bounds(), 1, (0.0, 0.0), 0.0);
        let vis = mgr.update(&full_world_bounds(), 1, (0.0, 0.0), 0.0);
        assert_eq!(vis.len(), 4);
        for tile in &vis {
            assert_eq!(tile.target.zoom, 1);
            assert_eq!(tile.actual.zoom, 0);
            assert!(tile.is_loaded());
            assert!(tile.is_fallback());
        }
    }

    #[test]
    fn cache_accessor() {
        let mgr = TileManager::new(Box::new(MockSource::new()), 50);
        assert!(mgr.cache().is_empty());
        assert_eq!(mgr.cache().capacity(), 50);
        assert_eq!(mgr.cached_count(), 0);
    }

    #[test]
    fn no_duplicate_requests() {
        let mut mgr = TileManager::new(Box::new(FailingSource), 100);

        let _ = mgr.update(&full_world_bounds(), 0, (0.0, 0.0), 0.0);
        let _ = mgr.update(&full_world_bounds(), 0, (0.0, 0.0), 0.0);
        assert_eq!(mgr.cached_count(), 1);
    }

    #[test]
    fn visible_tile_set_helpers() {
        let set = VisibleTileSet::default();
        assert!(set.is_empty());
        assert_eq!(set.len(), 0);
        assert_eq!(set.loaded_count(), 0);

        let mut mgr = TileManager::new(Box::new(MockSource::new()), 100);
        let _ = mgr.update(&full_world_bounds(), 0, (0.0, 0.0), 0.0);
        let vis = mgr.update(&full_world_bounds(), 0, (0.0, 0.0), 0.0);
        assert_eq!(vis.len(), 1);
        assert_eq!(vis.loaded_count(), 1);
        assert_eq!(vis.iter().count(), 1);
    }

    #[test]
    fn visible_tile_is_fallback() {
        let tile_exact = VisibleTile {
            target: TileId::new(1, 0, 0),
            actual: TileId::new(1, 0, 0),
            data: None,
            fade_opacity: 1.0,
        };
        assert!(!tile_exact.is_fallback());

        let tile_fallback = VisibleTile {
            target: TileId::new(1, 0, 0),
            actual: TileId::new(0, 0, 0),
            data: None,
            fade_opacity: 1.0,
        };
        assert!(tile_fallback.is_fallback());
    }

    #[test]
    fn visible_tile_texture_region_matches_parent_subrect() {
        let tile = VisibleTile {
            target: TileId::new(3, 4, 2),
            actual: TileId::new(1, 1, 0),
            data: None,
            fade_opacity: 1.0,
        };

        let region = tile.texture_region();
        assert!((region.u_min - 0.0).abs() < 1e-6);
        assert!((region.v_min - 0.5).abs() < 1e-6);
        assert!((region.u_max - 0.25).abs() < 1e-6);
        assert!((region.v_max - 0.75).abs() < 1e-6);
    }

    #[test]
    fn visible_tile_pixel_crop_rect_matches_parent_subrect() {
        let tile = VisibleTile {
            target: TileId::new(3, 4, 2),
            actual: TileId::new(1, 1, 0),
            data: None,
            fade_opacity: 1.0,
        };

        let crop = tile.pixel_crop_rect(256, 256).unwrap();
        assert_eq!(crop.x, 0);
        assert_eq!(crop.y, 128);
        assert_eq!(crop.width, 64);
        assert_eq!(crop.height, 64);
    }

    #[test]
    fn debug_impl() {
        let mgr = TileManager::new(Box::new(MockSource::new()), 100);
        let dbg = format!("{mgr:?}");
        assert!(dbg.contains("TileManager"));
        assert!(dbg.contains("cache_len"));
    }

    #[test]
    fn requests_missing_tiles_nearest_first_within_same_zoom() {
        let source = RecordingSource::default();
        let mut mgr = TileManager::new(Box::new(source.clone()), 100);
        let focus = TileId::new(1, 0, 0);

        let _ = mgr.update(&full_world_bounds(), 1, tile_center(focus), 0.0);

        let requested = source.requested_ids();
        assert_eq!(requested.len(), 5);
        assert_eq!(requested[0], TileId::new(0, 0, 0));
        assert_eq!(requested[1], focus);
    }

    #[test]
    fn coverage_requests_sort_ahead_of_refresh_requests() {
        let coverage = TileId::new(4, 8, 8);
        let refresh = TileId::new(4, 7, 7);
        let camera_world = tile_center(refresh);

        let mut candidates = vec![
            RequestCandidate::new(refresh, camera_world, RequestUrgency::Refresh),
            RequestCandidate::new(coverage, camera_world, RequestUrgency::Coverage),
        ];

        sort_request_candidates(&mut candidates);

        assert_eq!(candidates[0].tile, coverage);
        assert_eq!(candidates[1].tile, refresh);
    }

    #[test]
    fn coverage_requests_sort_ahead_of_fallback_refine_requests() {
        let coverage = TileId::new(4, 8, 8);
        let fallback_refine = TileId::new(4, 7, 7);
        let camera_world = tile_center(fallback_refine);

        let mut candidates = vec![
            RequestCandidate::new(
                fallback_refine,
                camera_world,
                RequestUrgency::FallbackRefine,
            ),
            RequestCandidate::new(coverage, camera_world, RequestUrgency::Coverage),
        ];

        sort_request_candidates(&mut candidates);

        assert_eq!(candidates[0].tile, coverage);
        assert_eq!(candidates[1].tile, fallback_refine);
    }

    #[test]
    fn fallback_refine_requests_sort_ahead_of_refresh_requests() {
        let fallback_refine = TileId::new(4, 8, 8);
        let refresh = TileId::new(4, 7, 7);
        let camera_world = tile_center(refresh);

        let mut candidates = vec![
            RequestCandidate::new(refresh, camera_world, RequestUrgency::Refresh),
            RequestCandidate::new(
                fallback_refine,
                camera_world,
                RequestUrgency::FallbackRefine,
            ),
        ];

        sort_request_candidates(&mut candidates);

        assert_eq!(candidates[0].tile, fallback_refine);
        assert_eq!(candidates[1].tile, refresh);
    }

    #[test]
    fn coarse_tiles_sort_first_within_same_priority_tier() {
        let coarse = TileId::new(3, 4, 4);
        let fine = TileId::new(5, 16, 16);
        let camera_world = tile_center(fine);

        let mut candidates = vec![
            RequestCandidate::new(fine, camera_world, RequestUrgency::FallbackRefine),
            RequestCandidate::new(coarse, camera_world, RequestUrgency::FallbackRefine),
        ];

        sort_request_candidates(&mut candidates);

        assert_eq!(candidates[0].tile, coarse);
        assert_eq!(candidates[1].tile, fine);
    }

    #[test]
    fn visible_requests_dispatch_before_refresh_revalidations() {
        let source = RecordingSource::default();
        let mut mgr = TileManager::new(Box::new(source.clone()), 64);
        let camera_world = (0.0, 0.0);
        let refresh_tile = TileId::new(4, 7, 7);
        let fallback_tile = TileId::new(4, 8, 8);

        let mut refresh = vec![RequestCandidate::new(
            refresh_tile,
            camera_world,
            RequestUrgency::Refresh,
        )];
        let mut missing = vec![RequestCandidate::new(
            fallback_tile,
            camera_world,
            RequestUrgency::FallbackRefine,
        )];

        let (requested, _) =
            mgr.request_tiles_with_bootstrap(&mut refresh, &mut missing, &[], camera_world);

        assert_eq!(requested, vec![refresh_tile, fallback_tile]);
        assert_eq!(source.requested_ids(), vec![fallback_tile, refresh_tile]);
    }

    #[test]
    fn cancels_pending_requests_that_scroll_out_of_view() {
        let source = RecordingSource::default();
        let mut mgr = TileManager::new(Box::new(source.clone()), 100);
        let keep = TileId::new(1, 0, 0);

        let _ = mgr.update(&full_world_bounds(), 1, tile_center(keep), 0.0);
        assert_eq!(mgr.cached_count(), 5);

        let narrow_bounds = inset_bounds(tile_bounds_world(&keep), 1.0);
        let vis = mgr.update(&narrow_bounds, 1, tile_center(keep), 0.0);

        assert_eq!(vis.len(), 1);
        assert_eq!(mgr.cached_count(), 5);

        let cancelled = source.cancelled_ids();
        assert!(cancelled.is_empty());
        assert!(!cancelled.contains(&keep));
    }

    #[test]
    fn invalid_completed_tile_is_retried_after_failure() {
        let mut mgr = TileManager::new(Box::new(InvalidImageSource::new()), 100);

        // Frame 1: tile requested.
        let _ = mgr.update(&full_world_bounds(), 0, (0.0, 0.0), 0.0);
        // Frame 2: poll returns invalid data -> mark_failed -> retry clears
        // the failed entry and re-requests.
        let vis = mgr.update(&full_world_bounds(), 0, (0.0, 0.0), 0.0);

        assert_eq!(vis.len(), 1);
        assert!(!vis.tiles[0].is_loaded());
        // The failed entry was removed and re-requested, so the cache
        // now holds a fresh Pending entry from the retry.
        assert!(matches!(
            mgr.cache.get(&TileId::new(0, 0, 0)),
            Some(TileCacheEntry::Pending)
        ));
    }

    #[test]
    fn tiny_cache_caps_requests_to_avoid_thrashing() {
        let source = RecordingSource::default();
        let mut mgr = TileManager::new_with_config(
            Box::new(source.clone()),
            1,
            TileSelectionConfig {
                visible_tile_budget: 1,
                ..TileSelectionConfig::default()
            },
        );

        let _ = mgr.update(
            &full_world_bounds(),
            1,
            tile_center(TileId::new(1, 0, 0)),
            0.0,
        );

        let requested = source.requested_ids();
        let cancelled = source.cancelled_ids();

        assert_eq!(requested.len(), 2);
        assert_eq!(requested[0], TileId::new(0, 0, 0));
        assert_eq!(cancelled.len(), 1);
        assert_eq!(cancelled[0], TileId::new(0, 0, 0));
        assert_eq!(mgr.cached_count(), 1);
    }

    #[test]
    fn explicit_visible_tile_budget_is_respected() {
        let mut mgr = TileManager::new_with_config(
            Box::new(FailingSource),
            512,
            TileSelectionConfig {
                visible_tile_budget: 1,
                ..TileSelectionConfig::default()
            },
        );

        let vis = mgr.update(&full_world_bounds(), 1, (0.0, 0.0), 0.0);
        assert_eq!(vis.len(), 1);
    }

    #[test]
    fn tiny_cache_still_caps_effective_budget_below_policy_budget() {
        let source = RecordingSource::default();
        let mut mgr = TileManager::new_with_config(
            Box::new(source.clone()),
            1,
            TileSelectionConfig {
                visible_tile_budget: 512,
                ..TileSelectionConfig::default()
            },
        );

        let _ = mgr.update(
            &full_world_bounds(),
            1,
            tile_center(TileId::new(1, 0, 0)),
            0.0,
        );

        let requested = source.requested_ids();
        assert_eq!(requested.len(), 2);
        assert_eq!(requested[0], TileId::new(0, 0, 0));
        assert_eq!(mgr.cached_count(), 1);
    }

    #[test]
    fn update_with_view_uses_shared_flat_tile_selection() {
        let source = RecordingSource::default();
        let mut mgr = TileManager::new(Box::new(source), 512);

        let center = rustial_math::GeoCoord::from_lat_lon(39.8180, 2.6514);
        let center_world = rustial_math::WebMercator::project(&center);
        let bounds = WorldBounds::new(
            rustial_math::WorldCoord::new(
                center_world.position.x - 220_000.0,
                center_world.position.y - 220_000.0,
                0.0,
            ),
            rustial_math::WorldCoord::new(
                center_world.position.x + 220_000.0,
                center_world.position.y + 220_000.0,
                0.0,
            ),
        );

        let view = rustial_math::FlatTileView::new(
            rustial_math::WorldCoord::new(
                center_world.position.x,
                center_world.position.y,
                center_world.position.z,
            ),
            26_001.0,
            76.5_f64.to_radians(),
            79.9_f64.to_radians(),
            std::f64::consts::FRAC_PI_4,
            1280,
            720,
        );

        let raw = rustial_math::visible_tiles(&bounds, 12);
        let vis = mgr.update_with_view(
            &bounds,
            12,
            (center_world.position.x, center_world.position.y),
            26_001.0,
            Some(&view),
        );

        assert!(raw.len() > vis.len());
        assert!(!vis.is_empty());
        assert!(vis.iter().all(|tile| tile.target.zoom == 12));
        assert!(vis.iter().all(|tile| tile.actual.zoom <= 12));
    }

    #[test]
    fn selection_stats_report_budget_hits_and_dropped_tiles() {
        let mut mgr = TileManager::new_with_config(
            Box::new(FailingSource),
            512,
            TileSelectionConfig {
                visible_tile_budget: 1,
                ..TileSelectionConfig::default()
            },
        );

        let vis = mgr.update(&full_world_bounds(), 1, (0.0, 0.0), 0.0);
        let stats = mgr.last_selection_stats();

        assert_eq!(vis.len(), 1);
        assert!(stats.budget_hit);
        assert_eq!(stats.raw_candidate_tiles, 4);
        assert_eq!(stats.visible_tiles, 1);
        assert_eq!(stats.dropped_by_budget, 3);
        assert_eq!(mgr.counters().budget_hit_frames, 1);
        assert_eq!(mgr.counters().dropped_by_budget, 3);
    }

    #[test]
    fn selection_stats_report_exact_hits_and_requests() {
        let mut mgr = TileManager::new(Box::new(MockSource::new()), 100);

        let _ = mgr.update(&full_world_bounds(), 0, (0.0, 0.0), 0.0);
        let _ = mgr.update(&full_world_bounds(), 0, (0.0, 0.0), 0.0);

        let stats = mgr.last_selection_stats();
        assert_eq!(stats.visible_tiles, 1);
        assert_eq!(stats.exact_visible_tiles, 1);
        assert_eq!(stats.fallback_visible_tiles, 0);
        assert_eq!(stats.missing_visible_tiles, 0);
        assert_eq!(stats.exact_cache_hits, 1);
        assert_eq!(stats.requested_tiles, 0);
        assert_eq!(mgr.counters().exact_cache_hits, 1);
    }

    #[test]
    fn selection_stats_report_fallback_hits_and_stale_cancellations() {
        let source = RecordingSource::default();
        let mut mgr = TileManager::new(Box::new(source.clone()), 100);

        let z0 = TileId::new(0, 0, 0);
        mgr.cache.insert_pending(z0);
        mgr.cache.promote(z0, dummy_tile_response());

        let _ = mgr.update(&full_world_bounds(), 1, (0.0, 0.0), 0.0);
        let keep = TileId::new(1, 0, 0);
        let narrow_bounds = inset_bounds(tile_bounds_world(&keep), 1.0);
        let _ = mgr.update(&narrow_bounds, 1, tile_center(keep), 0.0);

        let stats = mgr.last_selection_stats();
        assert_eq!(stats.visible_tiles, 1);
        assert_eq!(stats.fallback_visible_tiles, 1);
        assert_eq!(stats.missing_visible_tiles, 0);
        assert_eq!(stats.cancelled_stale_pending, 0);
        assert_eq!(mgr.counters().fallback_hits, 5);
        assert_eq!(mgr.counters().cancelled_stale_pending, 0);
        assert!(source.cancelled_ids().is_empty());
    }

    // -- Source zoom range (overzoom / underzoom) -------------------------

    #[test]
    fn zoom_below_source_min_returns_empty() {
        let source = MockSource::new();
        let config = TileSelectionConfig {
            source_min_zoom: 2,
            source_max_zoom: 14,
            ..TileSelectionConfig::default()
        };
        let mut mgr = TileManager::new_with_config(Box::new(source), 100, config);

        let result = mgr.update(&full_world_bounds(), 1, (0.0, 0.0), 0.0);
        assert!(
            result.is_empty(),
            "zoom 1 < source_min_zoom 2 should return empty"
        );
        assert_eq!(mgr.last_selection_stats().visible_tiles, 0);
    }

    #[test]
    fn zoom_at_source_min_returns_tiles() {
        let source = MockSource::new();
        let config = TileSelectionConfig {
            source_min_zoom: 2,
            source_max_zoom: 14,
            ..TileSelectionConfig::default()
        };
        let mut mgr = TileManager::new_with_config(Box::new(source), 100, config);

        let result = mgr.update(&full_world_bounds(), 2, (0.0, 0.0), 0.0);
        assert!(
            !result.is_empty(),
            "zoom == source_min_zoom should return tiles"
        );
    }

    #[test]
    fn overzoom_clamps_requests_to_source_max_zoom() {
        let source = MockSource::new();
        let config = TileSelectionConfig {
            source_min_zoom: 0,
            source_max_zoom: 1,
            ..TileSelectionConfig::default()
        };
        let mut mgr = TileManager::new_with_config(Box::new(source), 100, config);

        // First update requests tiles; second update polls the results.
        let _ = mgr.update(&full_world_bounds(), 2, (0.0, 0.0), 0.0);
        let result = mgr.update(&full_world_bounds(), 2, (0.0, 0.0), 0.0);

        // The visible tiles should be at display zoom 2 but fetched from
        // source zoom 1.
        assert!(!result.is_empty());
        for tile in result.iter() {
            // target is at display zoom
            assert_eq!(tile.target.zoom, 2);
            // actual is at source zoom
            assert_eq!(tile.actual.zoom, 1);
            // texture region should be a sub-tile rectangle
            let region = tile.texture_region();
            assert!(!region.is_full());
        }

        // Stats should report overzoomed tiles
        let stats = mgr.last_selection_stats();
        assert!(stats.overzoomed_visible_tiles > 0);
    }

    #[test]
    fn overzoom_texture_region_maps_correctly() {
        // When source_max_zoom=0 and display_zoom=1, we get 4 display tiles
        // all backed by the single zoom-0 tile.
        let source = MockSource::new();
        let config = TileSelectionConfig {
            source_min_zoom: 0,
            source_max_zoom: 0,
            ..TileSelectionConfig::default()
        };
        let mut mgr = TileManager::new_with_config(Box::new(source), 100, config);

        // First update requests; second polls.
        let _ = mgr.update(&full_world_bounds(), 1, (0.0, 0.0), 0.0);
        let result = mgr.update(&full_world_bounds(), 1, (0.0, 0.0), 0.0);
        assert_eq!(
            result.len(),
            4,
            "4 display tiles at zoom 1 from 1 source tile at zoom 0"
        );

        // Each display tile should map to a different quadrant of the source tile.
        let mut regions: Vec<_> = result.iter().map(|t| t.texture_region()).collect();
        regions.sort_by(|a, b| {
            a.u_min
                .partial_cmp(&b.u_min)
                .unwrap()
                .then(a.v_min.partial_cmp(&b.v_min).unwrap())
        });

        // All regions should be non-full (sub-tile)
        for region in &regions {
            assert!(!region.is_full());
            let u_size = region.u_max - region.u_min;
            let v_size = region.v_max - region.v_min;
            assert!(
                (u_size - 0.5).abs() < 1e-5,
                "each quadrant is half the tile"
            );
            assert!(
                (v_size - 0.5).abs() < 1e-5,
                "each quadrant is half the tile"
            );
        }
    }

    #[test]
    fn overzoomed_display_targets_computes_children() {
        let parent = TileId::new(1, 0, 0);
        let children = overzoomed_display_targets(&parent, 2);
        assert_eq!(children.len(), 4);
        assert!(children.contains(&TileId::new(2, 0, 0)));
        assert!(children.contains(&TileId::new(2, 1, 0)));
        assert!(children.contains(&TileId::new(2, 0, 1)));
        assert!(children.contains(&TileId::new(2, 1, 1)));
    }

    #[test]
    fn overzoomed_display_targets_same_zoom_returns_self() {
        let tile = TileId::new(3, 2, 1);
        let targets = overzoomed_display_targets(&tile, 3);
        assert_eq!(targets, vec![tile]);
    }

    #[test]
    fn missing_tile_requests_parent_chain_before_exact_tile() {
        let source = RecordingSource::default();
        let mut mgr = TileManager::new_with_config(
            Box::new(source.clone()),
            16,
            TileSelectionConfig {
                visible_tile_budget: 1,
                ..TileSelectionConfig::default()
            },
        );

        let target = TileId::new(2, 1, 1);
        let bounds = inset_bounds(tile_bounds_world(&target), 1.0);
        let _ = mgr.update(&bounds, 2, tile_center(target), 0.0);

        let requested = source.requested_ids();
        assert_eq!(
            requested,
            vec![TileId::new(0, 0, 0), TileId::new(1, 0, 0), target]
        );
    }

    #[test]
    fn desired_ancestor_retention_avoids_cancelling_bootstrap_parents() {
        let source = RecordingSource::default();
        let mut mgr = TileManager::new_with_config(
            Box::new(source.clone()),
            16,
            TileSelectionConfig {
                visible_tile_budget: 1,
                ..TileSelectionConfig::default()
            },
        );

        let target = TileId::new(2, 1, 1);
        let bounds = inset_bounds(tile_bounds_world(&target), 1.0);

        let _ = mgr.update(&bounds, 2, tile_center(target), 0.0);
        let _ = mgr.update(&bounds, 2, tile_center(target), 0.0);

        assert!(source.cancelled_ids().is_empty());
        assert_eq!(mgr.cached_count(), 3);
    }

    #[test]
    fn previous_desired_tile_gets_one_frame_retention_before_stale_cancel() {
        let source = RecordingSource::default();
        let mut mgr = TileManager::new(Box::new(source.clone()), 32);

        let first = TileId::new(14, 0, 0);
        let second = TileId::new(14, 4_096, 4_096);
        mgr.cache.insert_pending(first);
        mgr.cache.insert_pending(second);

        let previous_desired = HashSet::from([first]);
        let retained = desired_with_temporal_retention(&[second], &previous_desired);
        assert_eq!(mgr.prune_stale_pending(&retained), 0);

        assert!(
            !source.cancelled_ids().contains(&first),
            "the previous desired tile should survive one extra frame of camera motion"
        );

        let current_only = desired_with_temporal_retention(&[second], &HashSet::from([second]));
        assert_eq!(mgr.prune_stale_pending(&current_only), 1);

        assert!(
            source.cancelled_ids().contains(&first),
            "once the tile is outside both the current and immediately previous desired sets it should be cancelled"
        );
    }

    #[test]
    fn adjacent_same_zoom_pending_tile_survives_small_pan_horizon() {
        let source = RecordingSource::default();
        let mut mgr = TileManager::new(Box::new(source.clone()), 64);

        let adjacent = TileId::new(10, 100, 100);
        let desired = TileId::new(10, 101, 100);
        mgr.cache.insert_pending(adjacent);

        let desired_set = desired_with_ancestor_retention(&[desired]);
        let cancelled = mgr.prune_stale_pending(&desired_set);

        assert_eq!(cancelled, 0);
        assert!(source.cancelled_ids().is_empty());
        assert!(mgr.cache.get(&adjacent).is_some());
    }

    #[test]
    fn nearby_descendant_pending_tile_survives_zoom_in_horizon() {
        let source = RecordingSource::default();
        let mut mgr = TileManager::new(Box::new(source.clone()), 64);

        let pending_child = TileId::new(11, 204, 200);
        let desired = TileId::new(10, 101, 100);
        mgr.cache.insert_pending(pending_child);

        let desired_set = desired_with_ancestor_retention(&[desired]);
        let cancelled = mgr.prune_stale_pending(&desired_set);

        assert_eq!(cancelled, 0);
        assert!(source.cancelled_ids().is_empty());
        assert!(mgr.cache.get(&pending_child).is_some());
    }

    #[test]
    fn nearby_ancestor_pending_tile_survives_zoom_out_horizon() {
        let source = RecordingSource::default();
        let mut mgr = TileManager::new(Box::new(source.clone()), 64);

        let pending_parent = TileId::new(9, 51, 50);
        let desired = TileId::new(10, 101, 100);
        mgr.cache.insert_pending(pending_parent);

        let desired_set = desired_with_ancestor_retention(&[desired]);
        let cancelled = mgr.prune_stale_pending(&desired_set);

        assert_eq!(cancelled, 0);
        assert!(source.cancelled_ids().is_empty());
        assert!(mgr.cache.get(&pending_parent).is_some());
    }

    #[test]
    fn stale_prune_preserves_reloading_renderable_payload() {
        let source = RecordingSource::default();
        let mut mgr = TileManager::new(Box::new(source.clone()), 64);

        let reloading = TileId::new(10, 500, 500);
        let desired = TileId::new(10, 0, 0);

        mgr.cache.promote(reloading, dummy_tile_response());
        assert!(mgr.cache.start_reload(reloading));
        assert!(mgr.cache.get(&reloading).unwrap().is_reloading());

        let desired_set = desired_with_ancestor_retention(&[desired]);
        let cancelled = mgr.prune_stale_pending(&desired_set);

        assert_eq!(cancelled, 1);
        assert!(source.cancelled_ids().contains(&reloading));
        // The entry should be demoted to Expired, not removed.
        let entry = mgr
            .cache
            .get(&reloading)
            .expect("reloading entry should survive as expired");
        assert!(entry.is_expired());
        assert!(entry.is_renderable());
    }

    #[test]
    fn stale_prune_removes_pure_pending_entry() {
        let source = RecordingSource::default();
        let mut mgr = TileManager::new(Box::new(source.clone()), 64);

        let pending = TileId::new(10, 500, 500);
        let desired = TileId::new(10, 0, 0);
        mgr.cache.insert_pending(pending);

        let desired_set = desired_with_ancestor_retention(&[desired]);
        let cancelled = mgr.prune_stale_pending(&desired_set);

        assert_eq!(cancelled, 1);
        assert!(source.cancelled_ids().contains(&pending));
        assert!(!mgr.cache.contains(&pending));
    }

    #[test]
    fn speculative_prefetch_requests_only_tiles_outside_current_desired_set() {
        let source = RecordingSource::default();
        let mut mgr = TileManager::new_with_config(
            Box::new(source.clone()),
            32,
            TileSelectionConfig::default(),
        );

        let current = TileId::new(2, 1, 1);
        let predicted = TileId::new(2, 2, 1);
        let current_bounds = inset_bounds(tile_bounds_world(&current), 1.0);
        let predicted_bounds = inset_bounds(tile_bounds_world(&predicted), 1.0);

        let _ = mgr.update(&current_bounds, 2, tile_center(current), 0.0);
        let before = source.requested_ids().len();

        let prefetched =
            mgr.prefetch_with_view(&predicted_bounds, 2, tile_center(predicted), None, 2);
        let requested = source.requested_ids();

        assert_eq!(prefetched, 1);
        assert_eq!(requested.len(), before + 1);
        assert_eq!(requested.last().copied(), Some(predicted));
        assert_eq!(mgr.last_selection_stats().speculative_requested_tiles, 1);
        assert_eq!(mgr.counters().speculative_requested_tiles, 1);
    }

    #[test]
    fn speculative_prefetch_skips_when_prediction_matches_current_desired_tiles() {
        let source = RecordingSource::default();
        let mut mgr = TileManager::new_with_config(
            Box::new(source.clone()),
            32,
            TileSelectionConfig::default(),
        );

        let current = TileId::new(2, 1, 1);
        let current_bounds = inset_bounds(tile_bounds_world(&current), 1.0);

        let _ = mgr.update(&current_bounds, 2, tile_center(current), 0.0);
        let before = source.requested_ids().len();

        let prefetched = mgr.prefetch_with_view(&current_bounds, 2, tile_center(current), None, 2);

        assert_eq!(prefetched, 0);
        assert_eq!(source.requested_ids().len(), before);
    }

    #[test]
    fn zoom_in_prefetch_requests_children_of_centre_tiles() {
        let source = RecordingSource::default();
        let mut mgr = TileManager::new_with_config(
            Box::new(source.clone()),
            32,
            TileSelectionConfig::default(),
        );

        let current = TileId::new(2, 1, 1);
        let current_bounds = inset_bounds(tile_bounds_world(&current), 1.0);
        let _ = mgr.update(&current_bounds, 2, tile_center(current), 0.0);
        let before = source.requested_ids().len();

        let prefetched =
            mgr.prefetch_zoom_direction(tile_center(current), ZoomPrefetchDirection::In, 4);
        let requested = source.requested_ids();

        assert_eq!(prefetched, 4);
        assert_eq!(requested.len(), before + 4);
        assert!(requested[before..].contains(&TileId::new(3, 2, 2)));
        assert!(requested[before..].contains(&TileId::new(3, 3, 2)));
        assert!(requested[before..].contains(&TileId::new(3, 2, 3)));
        assert!(requested[before..].contains(&TileId::new(3, 3, 3)));
    }

    #[test]
    fn zoom_out_prefetch_requests_parent_tiles() {
        let source = RecordingSource::default();
        let mut mgr = TileManager::new_with_config(
            Box::new(source.clone()),
            32,
            TileSelectionConfig::default(),
        );

        let current = TileId::new(2, 1, 1);
        mgr.cache.insert_pending(current);
        mgr.cache.promote(current, dummy_tile_response());
        let current_bounds = inset_bounds(tile_bounds_world(&current), 1.0);
        let _ = mgr.update(&current_bounds, 2, tile_center(current), 0.0);
        let before = source.requested_ids().len();

        let prefetched =
            mgr.prefetch_zoom_direction(tile_center(current), ZoomPrefetchDirection::Out, 2);
        let requested = source.requested_ids();

        assert_eq!(prefetched, 1);
        assert_eq!(requested.len(), before + 1);
        assert_eq!(requested.last().copied(), Some(TileId::new(1, 0, 0)));
    }

    // -- Route-aware prefetch tests -----------------------------------

    #[test]
    fn route_prefetch_requests_tiles_along_polyline_ahead_of_camera() {
        let source = RecordingSource::default();
        let mut mgr = TileManager::new_with_config(
            Box::new(source.clone()),
            64,
            TileSelectionConfig::default(),
        );

        // Build a short east-west route at zoom 4.
        let route = vec![
            GeoCoord::from_lat_lon(0.0, 0.0),
            GeoCoord::from_lat_lon(0.0, 30.0),
            GeoCoord::from_lat_lon(0.0, 60.0),
        ];

        // Place the camera at the route start with a tight view.
        let cam = WebMercator::project_clamped(&route[0]);
        let camera_world = (cam.position.x, cam.position.y);

        // Use a single-tile tight bound so the desired set is small.
        let current = geo_to_tile(&route[0], 4).tile_id();
        let current_bounds = inset_bounds(tile_bounds_world(&current), 1.0);
        let _ = mgr.update(&current_bounds, 4, camera_world, 0.0);
        let before = source.requested_ids().len();

        let prefetched = mgr.prefetch_route(&route, 4, camera_world, 8);
        let requested = source.requested_ids();

        // Should have prefetched at least one tile beyond the camera's current view.
        assert!(prefetched > 0, "route prefetch should request tiles ahead");
        assert_eq!(requested.len(), before + prefetched);
    }

    #[test]
    fn route_prefetch_budget_is_respected() {
        let source = RecordingSource::default();
        let mut mgr = TileManager::new_with_config(
            Box::new(source.clone()),
            64,
            TileSelectionConfig::default(),
        );

        let route = vec![
            GeoCoord::from_lat_lon(0.0, 0.0),
            GeoCoord::from_lat_lon(0.0, 30.0),
            GeoCoord::from_lat_lon(0.0, 60.0),
        ];

        let cam = WebMercator::project_clamped(&route[0]);
        let camera_world = (cam.position.x, cam.position.y);

        let current = geo_to_tile(&route[0], 4).tile_id();
        let current_bounds = inset_bounds(tile_bounds_world(&current), 1.0);
        let _ = mgr.update(&current_bounds, 4, camera_world, 0.0);

        let prefetched = mgr.prefetch_route(&route, 4, camera_world, 2);
        assert!(
            prefetched <= 2,
            "route prefetch must respect max_requests budget"
        );
    }

    #[test]
    fn route_prefetch_empty_route_returns_zero() {
        let source = RecordingSource::default();
        let mut mgr = TileManager::new(Box::new(source.clone()), 32);

        assert_eq!(mgr.prefetch_route(&[], 4, (0.0, 0.0), 8), 0);
        assert_eq!(
            mgr.prefetch_route(&[GeoCoord::from_lat_lon(0.0, 0.0)], 4, (0.0, 0.0), 8,),
            0
        );
    }

    #[test]
    fn tiles_along_route_produces_ordered_unique_tiles() {
        let route = vec![
            GeoCoord::from_lat_lon(0.0, 0.0),
            GeoCoord::from_lat_lon(0.0, 10.0),
            GeoCoord::from_lat_lon(0.0, 20.0),
        ];

        let cam = WebMercator::project_clamped(&route[0]);
        let camera_world = (cam.position.x, cam.position.y);

        let tiles = tiles_along_route(&route, 4, camera_world);
        assert!(!tiles.is_empty());

        // All unique
        let unique: HashSet<_> = tiles.iter().copied().collect();
        assert_eq!(
            unique.len(),
            tiles.len(),
            "tiles_along_route must not produce duplicates"
        );

        // All at the correct zoom
        assert!(tiles.iter().all(|t| t.zoom == 4));
    }

    // -- Fade-in tests ------------------------------------------------

    #[test]
    fn compute_fade_opacity_disabled_returns_one() {
        let now = SystemTime::now();
        assert_eq!(compute_fade_opacity(now, Some(now), 0.0), 1.0);
    }

    #[test]
    fn compute_fade_opacity_no_loaded_at_returns_one() {
        let now = SystemTime::now();
        assert_eq!(compute_fade_opacity(now, None, 0.3), 1.0);
    }

    #[test]
    fn compute_fade_opacity_ramps_from_zero_to_one() {
        use std::time::Duration;

        let loaded = SystemTime::now();
        let half = loaded + Duration::from_millis(150);
        let full = loaded + Duration::from_millis(300);
        let over = loaded + Duration::from_millis(600);

        let at_zero = compute_fade_opacity(loaded, Some(loaded), 0.3);
        assert!((at_zero - 0.0).abs() < 0.01, "at load time: {at_zero}");

        let at_half = compute_fade_opacity(half, Some(loaded), 0.3);
        assert!((at_half - 0.5).abs() < 0.05, "at 150ms: {at_half}");

        let at_full = compute_fade_opacity(full, Some(loaded), 0.3);
        assert!((at_full - 1.0).abs() < 0.01, "at 300ms: {at_full}");

        let at_over = compute_fade_opacity(over, Some(loaded), 0.3);
        assert_eq!(at_over, 1.0, "past duration should clamp to 1.0");
    }

    #[test]
    fn crossfade_emits_parent_while_child_fading() {
        let source = MockSource::new();

        let config = TileSelectionConfig {
            raster_fade_duration: 10.0, // long duration to ensure fade < 1.0
            ..TileSelectionConfig::default()
        };
        let mut mgr = TileManager::new_with_config(Box::new(source), 100, config);

        let parent = TileId::new(0, 0, 0);
        let child = TileId::new(1, 0, 0);

        // Pre-load the parent as "old" (fully faded in).
        mgr.cache.insert_pending(parent);
        mgr.cache.promote(parent, dummy_tile_response());

        // Now load the child -- it will be freshly loaded, so fade_opacity < 1.0.
        mgr.cache.insert_pending(child);
        mgr.cache.promote(child, dummy_tile_response());

        let bounds = inset_bounds(tile_bounds_world(&child), 1.0);
        let vis = mgr.update(&bounds, 1, tile_center(child), 0.0);

        // With a 10-second fade, the child should have a very small
        // fade_opacity (practically 0).  The visible set should contain
        // both the fading child and a cross-fade parent entry.
        let child_tiles: Vec<_> = vis.tiles.iter().filter(|t| t.actual == child).collect();
        let parent_tiles: Vec<_> = vis.tiles.iter().filter(|t| t.actual == parent).collect();

        assert!(!child_tiles.is_empty(), "child tile should be present");
        let child_fade = child_tiles[0].fade_opacity;
        assert!(
            child_fade < 1.0,
            "child should be fading (got {child_fade})"
        );

        assert!(
            !parent_tiles.is_empty(),
            "cross-fade parent should be emitted while child fades"
        );
        let parent_fade = parent_tiles[0].fade_opacity;
        let sum = child_fade + parent_fade;
        assert!(
            (sum - 1.0).abs() < 0.05,
            "child + parent opacities should sum to ~1.0 (got {sum})"
        );
    }

    #[test]
    fn max_fading_ancestor_cap_respected() {
        let mut cache = TileCache::new(100);
        let mut visible = VisibleTileSet { tiles: Vec::new() };

        // Load ancestors at zoom 0..5
        for z in 0..5 {
            let id = TileId::new(z, 0, 0);
            cache.insert_pending(id);
            cache.promote(id, dummy_tile_response());
        }

        // max_fading_ancestor_levels = 2 means we walk at most 2 levels up.
        let target = TileId::new(4, 0, 0);
        emit_crossfade_parent(&mut visible, target, 0.5, 2, &mut cache);

        // Should find the parent at zoom 3 (1 level up).
        assert_eq!(visible.tiles.len(), 1);
        assert_eq!(visible.tiles[0].actual.zoom, 3);
    }

    // -- Child fallback (underzoom) tests ------------------------------

    #[test]
    fn from_child_tile_returns_correct_sub_region() {
        let parent = TileId::new(1, 0, 0);
        // Top-left child at zoom 2.
        let child_tl = TileId::new(2, 0, 0);
        let region = TileTextureRegion::from_child_tile(&parent, &child_tl).unwrap();
        assert!((region.u_min - 0.0).abs() < 1e-6);
        assert!((region.v_min - 0.0).abs() < 1e-6);
        assert!((region.u_max - 0.5).abs() < 1e-6);
        assert!((region.v_max - 0.5).abs() < 1e-6);

        // Bottom-right child at zoom 2.
        let child_br = TileId::new(2, 1, 1);
        let region = TileTextureRegion::from_child_tile(&parent, &child_br).unwrap();
        assert!((region.u_min - 0.5).abs() < 1e-6);
        assert!((region.v_min - 0.5).abs() < 1e-6);
        assert!((region.u_max - 1.0).abs() < 1e-6);
        assert!((region.v_max - 1.0).abs() < 1e-6);
    }

    #[test]
    fn from_child_tile_returns_none_for_non_descendant() {
        let parent = TileId::new(1, 0, 0);
        // This child belongs to a different parent.
        let wrong_child = TileId::new(2, 3, 3);
        assert!(TileTextureRegion::from_child_tile(&parent, &wrong_child).is_none());
    }

    #[test]
    fn from_child_tile_returns_none_when_child_zoom_lte_target() {
        let parent = TileId::new(2, 0, 0);
        let same = TileId::new(2, 0, 0);
        assert!(TileTextureRegion::from_child_tile(&parent, &same).is_none());

        let higher = TileId::new(1, 0, 0);
        assert!(TileTextureRegion::from_child_tile(&parent, &higher).is_none());
    }

    #[test]
    fn child_fallback_uses_cached_children() {
        // Set up: parent at z1 is not loaded, but all 4 children at z2 are.
        let source = MockSource::new();
        let config = TileSelectionConfig {
            max_child_depth: 2,
            ..TileSelectionConfig::default()
        };
        let mut mgr = TileManager::new_with_config(Box::new(source), 100, config);

        let parent = TileId::new(1, 0, 0);
        let children = parent.children();
        for child in &children {
            mgr.cache.insert_pending(*child);
            mgr.cache.promote(*child, dummy_tile_response());
        }

        // Request at zoom 1 — parent is missing, children are loaded.
        let bounds = inset_bounds(tile_bounds_world(&parent), 1.0);
        let vis = mgr.update(&bounds, 1, tile_center(parent), 0.0);

        // Should get 4 child-fallback visible tiles (one per child).
        let child_tiles: Vec<_> = vis.tiles.iter().filter(|t| t.is_child_fallback()).collect();
        assert_eq!(child_tiles.len(), 4, "expected 4 child-fallback tiles");

        // All should reference the parent as target.
        for ct in &child_tiles {
            assert_eq!(ct.target, parent);
            assert!(ct.data.is_some());
            assert_eq!(ct.actual.zoom, 2);
        }

        // Stats should reflect child fallback.
        let stats = mgr.last_selection_stats();
        assert_eq!(stats.child_fallback_hits, 1);
        assert_eq!(stats.child_fallback_visible_tiles, 4);
    }

    #[test]
    fn child_fallback_prefers_children_over_parent() {
        // Both parent (z0) and all children (z2) of z1 tile are loaded.
        let source = MockSource::new();
        let config = TileSelectionConfig {
            max_child_depth: 2,
            ..TileSelectionConfig::default()
        };
        let mut mgr = TileManager::new_with_config(Box::new(source), 100, config);

        let z0 = TileId::new(0, 0, 0);
        mgr.cache.insert_pending(z0);
        mgr.cache.promote(z0, dummy_tile_response());

        let target = TileId::new(1, 0, 0);
        let children = target.children();
        for child in &children {
            mgr.cache.insert_pending(*child);
            mgr.cache.promote(*child, dummy_tile_response());
        }

        let bounds = inset_bounds(tile_bounds_world(&target), 1.0);
        let vis = mgr.update(&bounds, 1, tile_center(target), 0.0);

        // Child fallback should be preferred: 4 tiles from children, not
        // 1 from the parent.
        let child_tiles: Vec<_> = vis.tiles.iter().filter(|t| t.is_child_fallback()).collect();
        let parent_tiles: Vec<_> = vis.tiles.iter().filter(|t| t.actual == z0).collect();
        assert_eq!(child_tiles.len(), 4, "expected child fallback tiles");
        assert_eq!(
            parent_tiles.len(),
            0,
            "should not use parent when children available"
        );
    }

    #[test]
    fn child_fallback_incomplete_children_falls_through_to_parent() {
        // Only 3 of 4 children loaded — should fall through to parent.
        let source = MockSource::new();
        let config = TileSelectionConfig {
            max_child_depth: 2,
            ..TileSelectionConfig::default()
        };
        let mut mgr = TileManager::new_with_config(Box::new(source), 100, config);

        let z0 = TileId::new(0, 0, 0);
        mgr.cache.insert_pending(z0);
        mgr.cache.promote(z0, dummy_tile_response());

        let target = TileId::new(1, 0, 0);
        let children = target.children();
        // Load only 3 of 4 children.
        for child in &children[..3] {
            mgr.cache.insert_pending(*child);
            mgr.cache.promote(*child, dummy_tile_response());
        }

        let bounds = inset_bounds(tile_bounds_world(&target), 1.0);
        let vis = mgr.update(&bounds, 1, tile_center(target), 0.0);

        // Should fall back to parent (z0), not emit partial children.
        let parent_tiles: Vec<_> = vis.tiles.iter().filter(|t| t.actual == z0).collect();
        assert!(!parent_tiles.is_empty(), "should fall back to z0 parent");
        let child_fb: Vec<_> = vis.tiles.iter().filter(|t| t.is_child_fallback()).collect();
        assert!(
            child_fb.is_empty(),
            "incomplete children should not be used"
        );
    }

    #[test]
    fn child_fallback_max_depth_cap_respected() {
        // Children at z+1 are not loaded, grandchildren at z+2 are.
        // max_child_depth=1 should NOT reach z+2.
        let source = MockSource::new();
        let config = TileSelectionConfig {
            max_child_depth: 1,
            ..TileSelectionConfig::default()
        };
        let mut mgr = TileManager::new_with_config(Box::new(source), 100, config);

        let target = TileId::new(1, 0, 0);
        // Load all 16 grandchildren (z+2).
        for child in target.children() {
            for grandchild in child.children() {
                mgr.cache.insert_pending(grandchild);
                mgr.cache.promote(grandchild, dummy_tile_response());
            }
        }

        let bounds = inset_bounds(tile_bounds_world(&target), 1.0);
        let vis = mgr.update(&bounds, 1, tile_center(target), 0.0);

        // max_child_depth=1 means only z+1 is checked, which has no loaded
        // tiles, so no child fallback should occur.
        let child_fb: Vec<_> = vis.tiles.iter().filter(|t| t.is_child_fallback()).collect();
        assert!(
            child_fb.is_empty(),
            "depth=1 should not reach grandchildren"
        );
    }

    #[test]
    fn child_fallback_disabled_when_max_child_depth_zero() {
        let source = MockSource::new();
        let config = TileSelectionConfig {
            max_child_depth: 0,
            ..TileSelectionConfig::default()
        };
        let mut mgr = TileManager::new_with_config(Box::new(source), 100, config);

        let target = TileId::new(1, 0, 0);
        for child in target.children() {
            mgr.cache.insert_pending(child);
            mgr.cache.promote(child, dummy_tile_response());
        }

        let bounds = inset_bounds(tile_bounds_world(&target), 1.0);
        let vis = mgr.update(&bounds, 1, tile_center(target), 0.0);

        let child_fb: Vec<_> = vis.tiles.iter().filter(|t| t.is_child_fallback()).collect();
        assert!(
            child_fb.is_empty(),
            "max_child_depth=0 should disable child fallback"
        );
    }

    #[test]
    fn stale_pending_same_zoom_tiles_are_pruned_when_unrelated_to_desired_view() {
        let source = RecordingSource::default();
        let mut mgr = TileManager::new(Box::new(source.clone()), 128);

        let stale = TileId::new(4, 0, 0);
        let desired = TileId::new(4, 8, 8);

        mgr.cache.insert_pending(stale);

        let desired_set = desired_with_ancestor_retention(&[desired]);
        let cancelled = mgr.prune_stale_pending(&desired_set);

        assert_eq!(cancelled, 1);
        assert_eq!(source.cancelled_ids(), vec![stale]);
        assert!(mgr.cache.get(&stale).is_none());
    }

    #[test]
    fn is_child_fallback_returns_true_for_child_actual() {
        let tile = VisibleTile {
            target: TileId::new(1, 0, 0),
            actual: TileId::new(2, 0, 0),
            data: Some(dummy_tile_response().data),
            fade_opacity: 1.0,
        };
        assert!(tile.is_child_fallback());
        assert!(!tile.is_overzoomed());
    }

    #[test]
    fn lifecycle_diagnostics_track_request_completion_and_exact_use() {
        let mut mgr = TileManager::new(Box::new(MockSource::new()), 100);

        let bounds = full_world_bounds();
        let _ = mgr.update(&bounds, 0, (0.0, 0.0), 0.0);
        let _ = mgr.update(&bounds, 0, (0.0, 0.0), 0.0);

        let diagnostics = mgr.lifecycle_diagnostics();
        let record = diagnostics
            .active_records
            .iter()
            .find(|record| record.tile == TileId::new(0, 0, 0))
            .expect("expected z0 lifecycle record");

        assert_eq!(record.first_selected_frame, Some(1));
        assert_eq!(record.first_queued_frame, Some(1));
        assert_eq!(record.first_dispatched_frame, Some(1));
        assert_eq!(record.first_completed_frame, Some(2));
        assert_eq!(record.first_decoded_frame, Some(2));
        assert_eq!(record.first_promoted_frame, Some(2));
        assert_eq!(record.first_renderable_frame, Some(2));
        assert_eq!(record.first_exact_frame, Some(2));
        assert_eq!(record.queued_frames_to_dispatch, Some(0));
        assert_eq!(record.in_flight_frames_to_complete, Some(1));
        assert_eq!(record.completion_to_visible_use_frames, Some(0));

        assert!(diagnostics
            .recent_events
            .iter()
            .any(|event| event.tile == TileId::new(0, 0, 0)
                && event.kind == TileLifecycleEventKind::Queued));
        assert!(diagnostics
            .recent_events
            .iter()
            .any(|event| event.tile == TileId::new(0, 0, 0)
                && event.kind == TileLifecycleEventKind::UsedAsExact));
    }

    #[test]
    fn lifecycle_diagnostics_track_stale_cancellation() {
        let source = RecordingSource::default();
        let mut mgr = TileManager::new(Box::new(source.clone()), 128);

        let first = TileId::new(4, 0, 0);
        let desired = TileId::new(4, 8, 8);

        mgr.begin_lifecycle_frame();
        mgr.cache.insert_pending(first);
        mgr.lifecycle.record_queued(first);
        let desired_set = desired_with_ancestor_retention(&[desired]);
        let cancelled_count = mgr.prune_stale_pending(&desired_set);

        let diagnostics = mgr.lifecycle_diagnostics();
        let cancelled = diagnostics
            .recent_terminal_records
            .iter()
            .find(|record| record.tile == first)
            .expect("expected stale-cancelled tile lifecycle record");

        assert_eq!(
            cancelled.terminal_event,
            Some(TileLifecycleEventKind::CancelledAsStale)
        );
        assert_eq!(cancelled.tile, first);
        assert_eq!(cancelled_count, 1);
        assert_eq!(source.cancelled_ids(), vec![first]);
        assert!(diagnostics
            .recent_events
            .iter()
            .any(|event| event.tile == first
                && event.kind == TileLifecycleEventKind::CancelledAsStale));
    }
}