sl-map-apis 0.5.0

Wraps the SL map API to convert grid coordinates to region names and vice versa and to fetch map tiles
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
//! Contains functionality related to fetching map tiles
use std::path::PathBuf;

use image::GenericImageView as _;
use sl_types::map::{
    GridCoordinateOffset, GridCoordinates, GridRectangle, GridRectangleLike, MapTileDescriptor,
    RegionCoordinates, RegionName, USBNotecard, ZoomFitError, ZoomLevel, ZoomLevelError,
};

use crate::region::RegionNameToGridCoordinatesCache;

/// represents a map like image, e.g. a map tile or a map that covers
/// some `GridRectangle` of regions
pub trait MapLike: GridRectangleLike + image::GenericImage + image::GenericImageView {
    /// the image of the map
    #[must_use]
    fn image(&self) -> &image::DynamicImage;

    /// the mutable image of the map
    #[must_use]
    fn image_mut(&mut self) -> &mut image::DynamicImage;

    /// the zoom level of the map
    #[must_use]
    fn zoom_level(&self) -> ZoomLevel;

    /// pixels per meter
    #[must_use]
    fn pixels_per_meter(&self) -> f32 {
        self.zoom_level().pixels_per_meter()
    }

    /// pixels per region
    #[must_use]
    fn pixels_per_region(&self) -> f32 {
        self.pixels_per_meter() * 256f32
    }

    /// the pixel coordinates in the map that represent the given `GridCoordinates`
    /// and `RegionCoordinates`
    #[must_use]
    fn pixel_coordinates_for_coordinates(
        &self,
        grid_coordinates: &GridCoordinates,
        region_coordinates: &RegionCoordinates,
    ) -> Option<(u32, u32)> {
        if !self.contains(grid_coordinates) {
            return None;
        }
        #[expect(
            clippy::arithmetic_side_effects,
            reason = "this should never underflow since we already checked with contains that the grid coordinates are inside the map"
        )]
        let grid_offset = *grid_coordinates - self.lower_left_corner();
        #[expect(
            clippy::cast_possible_truncation,
            reason = "since we are dealing with image sizes here the numbers never get anywhere near the maximum values of either type"
        )]
        #[expect(
            clippy::cast_precision_loss,
            reason = "since we are dealing with image sizes here the numbers never get anywhere near the maximum values of either type"
        )]
        #[expect(
            clippy::cast_sign_loss,
            reason = "Since grid_offset is the difference between the lower left corner and a coordinate inside the map it is always positive"
        )]
        #[expect(
            clippy::as_conversions,
            reason = "For the reasons mentioned in the other expects this should be safe here"
        )]
        let x = (self.pixels_per_region() * grid_offset.x() as f32
            + self.pixels_per_meter() * region_coordinates.x()) as u32;
        #[expect(
            clippy::cast_possible_truncation,
            reason = "since we are dealing with image sizes here the numbers never get anywhere near the maximum values of either type"
        )]
        #[expect(
            clippy::cast_precision_loss,
            reason = "since we are dealing with image sizes here the numbers never get anywhere near the maximum values of either type"
        )]
        #[expect(
            clippy::cast_sign_loss,
            reason = "Since grid_offset is the difference between the lower left corner and a coordinate inside the map it is always positive"
        )]
        #[expect(
            clippy::as_conversions,
            reason = "For the reasons mentioned in the other expects this should be safe here"
        )]
        let y = (self.pixels_per_region() * grid_offset.y() as f32
            + self.pixels_per_meter() * region_coordinates.y()) as u32;
        #[expect(
            clippy::arithmetic_side_effects,
            reason = "since y is a coordinate within the image it should always be less than or equal to height and thus this subtraction should never underflow"
        )]
        let y = self.height() - y;
        Some((x, y))
    }

    /// the `GridCoordinates` and `RegionCoordinates` at the given pixel coordinates
    #[must_use]
    fn coordinates_for_pixel_coordinates(
        &self,
        x: u32,
        y: u32,
    ) -> Option<(GridCoordinates, RegionCoordinates)> {
        if !(x <= self.width() && y <= self.height()) {
            return None;
        }
        #[expect(
            clippy::arithmetic_side_effects,
            reason = "we just checked that y is less than or equal to height so this can not underflow"
        )]
        let y = self.height() - y;
        #[expect(
            clippy::arithmetic_side_effects,
            reason = "we just checked that x and y are less than width and height of this rectangle so this should not overflow if the upper right corner value did not"
        )]
        #[expect(
            clippy::cast_possible_truncation,
            reason = "we are dealing with grid coordinates so integers are fine"
        )]
        #[expect(
            clippy::cast_precision_loss,
            reason = "our pixel coordinates are not going to be anywhere near 2^23 or we should rethink our choices of types anyway"
        )]
        let grid_result = self.lower_left_corner()
            + GridCoordinateOffset::new(
                (x as f32 / self.pixels_per_region()) as i32,
                (y as f32 / self.pixels_per_region()) as i32,
            );
        #[expect(
            clippy::cast_possible_truncation,
            reason = "pixels_per_region are always an integer, even if they are represented as f32"
        )]
        #[expect(
            clippy::cast_sign_loss,
            reason = "pixels_per_region is always positive"
        )]
        #[expect(
            clippy::cast_precision_loss,
            reason = "x % pixels_per_region should be no larger than 255 (the largest pixels_per_region value is 256)"
        )]
        let region_result = RegionCoordinates::new(
            (x % self.pixels_per_region() as u32) as f32 / self.pixels_per_meter(),
            (y % self.pixels_per_region() as u32) as f32 / self.pixels_per_meter(),
            0f32,
        );
        Some((grid_result, region_result))
    }

    /// a crop of the map like image by coordinates and size
    #[must_use]
    fn crop_imm_grid_rectangle(
        &self,
        grid_rectangle: &GridRectangle,
    ) -> Option<image::SubImage<&Self>>
    where
        Self: Sized,
    {
        let lower_left_corner_pixels = self.pixel_coordinates_for_coordinates(
            &grid_rectangle.lower_left_corner(),
            &RegionCoordinates::new(0f32, 0f32, 0f32),
        )?;
        let upper_right_corner_pixels = self.pixel_coordinates_for_coordinates(
            &grid_rectangle.upper_right_corner(),
            &RegionCoordinates::new(256f32, 256f32, 0f32),
        )?;
        let x = std::cmp::min(lower_left_corner_pixels.0, upper_right_corner_pixels.0);
        let y = std::cmp::min(lower_left_corner_pixels.1, upper_right_corner_pixels.1);
        let width = lower_left_corner_pixels
            .0
            .abs_diff(upper_right_corner_pixels.0);
        let height = lower_left_corner_pixels
            .1
            .abs_diff(upper_right_corner_pixels.1);
        Some(image::imageops::crop_imm(self, x, y, width, height))
    }

    /// draw a waypoint at the given coordinates
    fn draw_waypoint(&mut self, x: u32, y: u32, color: image::Rgba<u8>) {
        #[expect(
            clippy::cast_possible_wrap,
            reason = "our pixel coordinates should be nowhere near i32::MAX"
        )]
        imageproc::drawing::draw_filled_rect_mut(
            self.image_mut(),
            imageproc::rect::Rect::at(x as i32 - 5i32, y as i32 - 5i32).of_size(10, 10),
            color,
        );
    }

    /// draw a hollow (1px outline) rectangle with its top-left corner at the
    /// given pixel coordinates and the given pixel size. Coordinates outside
    /// the image are clipped by the drawing routine. Used for the optional
    /// per-region grid overlay.
    fn draw_hollow_rect(
        &mut self,
        x: u32,
        y: u32,
        width: u32,
        height: u32,
        color: image::Rgba<u8>,
    ) {
        if width == 0 || height == 0 {
            return;
        }
        #[expect(
            clippy::cast_possible_wrap,
            reason = "our pixel coordinates should be nowhere near i32::MAX"
        )]
        let rect = imageproc::rect::Rect::at(x as i32, y as i32).of_size(width, height);
        imageproc::drawing::draw_hollow_rect_mut(self.image_mut(), rect, color);
    }

    /// fill a solid rectangle with its top-left corner at the given pixel
    /// coordinates and the given pixel size. Coordinates outside the image are
    /// clipped by the drawing routine. Used for the optional per-region
    /// missing-region fill overlay.
    fn draw_filled_rect(
        &mut self,
        x: u32,
        y: u32,
        width: u32,
        height: u32,
        color: image::Rgba<u8>,
    ) {
        if width == 0 || height == 0 {
            return;
        }
        #[expect(
            clippy::cast_possible_wrap,
            reason = "our pixel coordinates should be nowhere near i32::MAX"
        )]
        let rect = imageproc::rect::Rect::at(x as i32, y as i32).of_size(width, height);
        imageproc::drawing::draw_filled_rect_mut(self.image_mut(), rect, color);
    }

    /// draw a line from the given coordinates to the given coordinates
    fn draw_line(
        &mut self,
        from_x: u32,
        from_y: u32,
        to_x: u32,
        to_y: u32,
        color: image::Rgba<u8>,
    ) {
        if from_x == to_x && from_y == to_y {
            // if the start and the end of the line are identical we do not need to draw anything
            // also, the division for normalizing below would be a division by 0 in that case
            return;
        }
        #[expect(
            clippy::cast_precision_loss,
            reason = "if our pixel coordinates get anywhere near 2^23 we probably should reconsider all types anyway"
        )]
        let from_x = from_x as f32;
        #[expect(
            clippy::cast_precision_loss,
            reason = "if our pixel coordinates get anywhere near 2^23 we probably should reconsider all types anyway"
        )]
        let from_y = from_y as f32;
        #[expect(
            clippy::cast_precision_loss,
            reason = "if our pixel coordinates get anywhere near 2^23 we probably should reconsider all types anyway"
        )]
        let to_x = to_x as f32;
        #[expect(
            clippy::cast_precision_loss,
            reason = "if our pixel coordinates get anywhere near 2^23 we probably should reconsider all types anyway"
        )]
        let to_y = to_y as f32;
        let diff = (to_x - from_x, to_y - from_y);
        let perpendicular = (-diff.1, diff.0);
        let magnitude = (diff.0.powi(2) + diff.1.powi(2)).sqrt();
        let perpendicular_normalized = (perpendicular.0 / magnitude, perpendicular.1 / magnitude);
        #[expect(
            clippy::cast_possible_truncation,
            reason = "we want integer coordinates for use in Points"
        )]
        let points = vec![
            imageproc::point::Point::new(
                (from_x + perpendicular_normalized.0 * 5.0) as i32,
                (from_y + perpendicular_normalized.1 * 5.0) as i32,
            ),
            imageproc::point::Point::new(
                (to_x + perpendicular_normalized.0 * 5.0) as i32,
                (to_y + perpendicular_normalized.1 * 5.0) as i32,
            ),
            imageproc::point::Point::new(
                (to_x - perpendicular_normalized.0 * 5.0) as i32,
                (to_y - perpendicular_normalized.1 * 5.0) as i32,
            ),
            imageproc::point::Point::new(
                (from_x - perpendicular_normalized.0 * 5.0) as i32,
                (from_y - perpendicular_normalized.1 * 5.0) as i32,
            ),
        ];
        imageproc::drawing::draw_antialiased_polygon_mut(
            self.image_mut(),
            &points,
            color,
            imageproc::pixelops::interpolate,
        );
    }

    /// draw an arrow from the direction of the first point with the
    /// tip at the second point
    fn draw_arrow(&mut self, from: (f32, f32), tip: (f32, f32), color: image::Rgba<u8>) {
        /// length of the arrow at each waypoint from tip to base
        const ARROW_LENGTH: f32 = 15f32;
        /// width of the arrow from the center line (double this to get the length of the base side of the triangle)
        const ARROW_HALF_WIDTH: f32 = 5f32;
        if from == tip {
            // do not try to draw arrows from a point to itself
            return;
        }
        let arrow_direction = (tip.0 - from.0, tip.1 - from.1);
        let arrow_direction_magnitude =
            (arrow_direction.0.powf(2f32) + arrow_direction.1.powf(2f32)).sqrt();
        let arrow_direction = (
            arrow_direction.0 / arrow_direction_magnitude,
            arrow_direction.1 / arrow_direction_magnitude,
        );
        let arrow_base_middle = (
            tip.0 - (ARROW_LENGTH * arrow_direction.0),
            tip.1 - (ARROW_LENGTH * arrow_direction.1),
        );
        let arrow_base_side1 = (
            arrow_base_middle.0 + (ARROW_HALF_WIDTH * arrow_direction.1),
            arrow_base_middle.1 - (ARROW_HALF_WIDTH * arrow_direction.0),
        );
        let arrow_base_side2 = (
            arrow_base_middle.0 - (ARROW_HALF_WIDTH * arrow_direction.1),
            arrow_base_middle.1 + (ARROW_HALF_WIDTH * arrow_direction.0),
        );
        tracing::debug!(
            "Painting arrow with arrow direction {:?}, arrow tip {:?}, arrow base middle {:?}, arrow_base_side1 {:?}, arrow_base_side2 {:?} ",
            arrow_direction,
            tip,
            arrow_base_middle,
            arrow_base_side1,
            arrow_base_side2
        );
        #[expect(
            clippy::cast_possible_truncation,
            reason = "we want integer coordinates for use in Points"
        )]
        imageproc::drawing::draw_polygon_mut(
            self.image_mut(),
            &[
                imageproc::point::Point::new(arrow_base_side1.0 as i32, arrow_base_side1.1 as i32),
                imageproc::point::Point::new(tip.0 as i32, tip.1 as i32),
                imageproc::point::Point::new(arrow_base_side2.0 as i32, arrow_base_side2.1 as i32),
            ],
            color,
        );
    }

    /// draw an arbitrary multi-line text label with a drop shadow at the given
    /// top-left pixel `origin`, using a caller-supplied font and
    /// [`crate::text::LabelStyle`]. Lines stack downward. This is the building
    /// block for free-floating labels (legends, logos captions, manual labels)
    /// that are not tied to any particular overlay.
    fn draw_text_label<F: ab_glyph::Font>(
        &mut self,
        origin: (i32, i32),
        lines: &[String],
        style: &crate::text::LabelStyle,
        font: &F,
    ) {
        crate::text::draw_multi_line_with_shadow(self, origin.0, origin.1, style, font, lines);
    }
}

/// where a map tile came from when fetched through the cache
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TileOutcome {
    /// found in the in-memory LRU cache
    LoadedFromMemoryCache,
    /// found in the on-disk cache
    LoadedFromDiskCache,
    /// fetched from the upstream server
    FetchedFromNetwork,
    /// the tile is known to not exist (either fetched and got 403,
    /// or a cached absence)
    Missing,
}

/// events emitted during map rendering for progress reporting
#[derive(Debug, Clone)]
pub enum MapProgressEvent {
    /// the rendering plan has been computed, lists the chosen zoom level
    /// and the total number of map tiles that will be processed
    PlanComputed {
        /// the zoom level chosen for this render
        zoom_level: ZoomLevel,
        /// the total number of map tiles that will be processed
        total_tiles: u32,
    },
    /// processing of a tile has started
    TileStarted {
        /// the descriptor of the tile being processed
        descriptor: MapTileDescriptor,
    },
    /// processing of a tile has finished
    TileFinished {
        /// the descriptor of the tile that was processed
        descriptor: MapTileDescriptor,
        /// where the tile came from
        outcome: TileOutcome,
    },
    /// the renderer will check every region inside each present tile for
    /// existence (this only happens when `fill_missing_regions` is set;
    /// each check may trigger several upstream fetches for higher-zoom
    /// tiles, so this phase often dominates the wall-clock time)
    RegionCheckPlanned {
        /// upper bound on how many region checks will be performed; the
        /// actual count can be lower if some primary tiles turn out to be
        /// missing entirely (those regions get the missing-tile colour
        /// instead of an individual check)
        total_regions: u32,
    },
    /// a region's existence has been determined
    RegionChecked {
        /// x grid coordinate of the region
        x: u16,
        /// y grid coordinate of the region
        y: u16,
        /// whether the region was found on at least one zoom level
        exists: bool,
    },
    /// the route drawing has been planned, lists the total number of
    /// waypoints to process
    RoutePlanned {
        /// total number of waypoints in the route
        total_waypoints: usize,
    },
    /// a waypoint in a route has been resolved to grid coordinates
    RouteWaypointResolved {
        /// the index of this waypoint (0-based)
        index: usize,
        /// the total number of waypoints
        total: usize,
        /// the region name of the waypoint
        region: RegionName,
    },
    /// resolving region names for the per-region annotation overlay is about to
    /// start, lists the total number of regions whose names will be looked up
    RegionNamesPlanned {
        /// total number of regions whose names will be resolved
        total_regions: u32,
    },
    /// one region's name has been resolved for the per-region annotation overlay
    RegionNameResolved {
        /// the index of this region (0-based)
        index: u32,
        /// the total number of regions whose names will be resolved
        total: u32,
    },
}

/// a best-effort progress reporter; emits an event on a `tokio::sync::mpsc`
/// channel, ignoring the error if the channel is closed or full so that
/// progress reporting never aborts a render
fn emit_progress(
    progress: Option<&tokio::sync::mpsc::Sender<MapProgressEvent>>,
    event: MapProgressEvent,
) {
    if let Some(sender) = progress {
        // best-effort: closed or full channel must not abort the render
        drop(sender.try_send(event));
    }
}

/// represents a map tile fetched from the server
#[derive(Debug, Clone)]
pub struct MapTile {
    /// describes the map tile by lower left corner and zoom level
    descriptor: MapTileDescriptor,

    /// the actual image data
    image: image::DynamicImage,
}

impl MapTile {
    /// the descriptor of the map tile
    #[must_use]
    pub const fn descriptor(&self) -> &MapTileDescriptor {
        &self.descriptor
    }
}

impl GridRectangleLike for MapTile {
    fn grid_rectangle(&self) -> GridRectangle {
        self.descriptor.grid_rectangle()
    }
}

impl image::GenericImageView for MapTile {
    type Pixel = <image::DynamicImage as image::GenericImageView>::Pixel;

    fn dimensions(&self) -> (u32, u32) {
        self.image.dimensions()
    }

    fn get_pixel(&self, x: u32, y: u32) -> Self::Pixel {
        self.image.get_pixel(x, y)
    }
}

impl image::GenericImage for MapTile {
    fn get_pixel_mut(&mut self, x: u32, y: u32) -> &mut Self::Pixel {
        #[expect(
            deprecated,
            reason = "we need to use this deprecated function to implement the deprecated function when passing it through"
        )]
        self.image.get_pixel_mut(x, y)
    }

    fn put_pixel(&mut self, x: u32, y: u32, pixel: Self::Pixel) {
        self.image.put_pixel(x, y, pixel);
    }

    fn blend_pixel(&mut self, x: u32, y: u32, pixel: Self::Pixel) {
        #[expect(
            deprecated,
            reason = "we need to use this deprecated function to implement the deprecated function when passing it through"
        )]
        self.image.blend_pixel(x, y, pixel);
    }
}

impl MapLike for MapTile {
    fn zoom_level(&self) -> ZoomLevel {
        self.descriptor.zoom_level().to_owned()
    }

    fn image(&self) -> &image::DynamicImage {
        &self.image
    }

    fn image_mut(&mut self) -> &mut image::DynamicImage {
        &mut self.image
    }
}

/// errors that can happen while fetching a map tile from the cache
#[derive(Debug, thiserror::Error)]
pub enum MapTileCacheError {
    /// error manipulating files in the cache directory
    #[error("error manipulating files in the cache directory: {0}")]
    CacheDirectoryFileError(std::io::Error),
    /// reqwest error when fetching the map tile from the server
    #[error("reqwest error when fetching the map tile from the server: {0}")]
    ReqwestError(#[from] reqwest::Error),
    /// HTTP request is not success
    #[error("HTTP request is not success: URL {0} response status {1} headers {2:#?} body {3}")]
    HttpError(
        String,
        reqwest::StatusCode,
        reqwest::header::HeaderMap,
        String,
    ),
    /// failed to clone request for cache policy use (which should not happen
    /// unless the body is a stream which it is not for us)
    #[error("failed to clone request for cache policy")]
    FailedToCloneRequest,
    /// the ratelimiter returned a non-retriable error (e.g. the requested
    /// token count exceeds its capacity)
    #[error("ratelimiter rejected request: {0:?}")]
    RatelimiterError(ratelimit::TryWaitError),
    /// error guessing image format
    #[error("error guessing image format: {0}")]
    ImageFormatGuessError(std::io::Error),
    /// error reading the raw map tile into an image
    #[error("error reading the raw map tile into an image: {0}")]
    ImageError(#[from] image::ImageError),
    /// error decoding the JSON serialized CachePolicy
    #[error("error decoding the JSON serialized CachePolicy: {0}")]
    CachePolicyJsonDecodeError(#[from] serde_json::Error),
    /// error creating a zoom level
    #[error("error creating a zoom level: {0}")]
    ZoomLevelError(#[from] ZoomLevelError),
    /// error when trying to load cache policy that we previously checked
    /// existed on disk
    #[error("error when trying to load cache policy that we previously checked existed on disk")]
    CachePolicyError,
}

/// a cache for map tiles on the local filesystem
#[derive(derive_more::Debug)]
pub struct MapTileCache {
    /// the client used to make HTTP requests for map tiles not in the local cache
    client: reqwest::Client,
    /// the rate limiter for map tile requests to the server
    #[debug(skip)]
    ratelimiter: Option<ratelimit::Ratelimiter>,
    /// the cache directory
    cache_directory: PathBuf,
    /// the in-memory cache
    #[debug(skip)]
    cache: lru::LruCache<MapTileDescriptor, (Option<MapTile>, http_cache_semantics::CachePolicy)>,
}

/// status of a cache entry on disk
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum MapTileCacheEntryStatus {
    /// no files at all related to a map tile in the cache
    Missing,
    /// an incomplete set of files related to a map tile in the cache
    Invalid,
    /// a usable set of files related to a map tile in the cache (cache policy + either a map tile or an absence marker)
    Valid,
}

/// a wrapper around response to force status from 403 to 404 for absent map
/// tiles so `http_cache_semantics::CachePolicy` becomes usable on those responses
#[derive(Debug)]
pub struct MapTileNegativeResponse(reqwest::Response);

impl http_cache_semantics::ResponseLike for MapTileNegativeResponse {
    fn status(&self) -> http::status::StatusCode {
        match self.0.status() {
            http::status::StatusCode::FORBIDDEN => http::status::StatusCode::NOT_FOUND,
            status => status,
        }
    }

    fn headers(&self) -> &http::header::HeaderMap {
        self.0.headers()
    }
}

impl MapTileCache {
    /// creates a new `MapTileCache`
    #[expect(clippy::missing_panics_doc, reason = "we know 16 is non-zero")]
    #[must_use]
    pub fn new(cache_directory: PathBuf, ratelimiter: Option<ratelimit::Ratelimiter>) -> Self {
        #[expect(clippy::unwrap_used, reason = "we know 16 is non-zero")]
        let cache = lru::LruCache::new(std::num::NonZeroUsize::new(16).unwrap());
        Self {
            client: reqwest::Client::new(),
            ratelimiter,
            cache_directory,
            cache,
        }
    }

    /// the file name of a map tile cache file
    #[must_use]
    fn map_tile_file_name(map_tile_descriptor: &MapTileDescriptor) -> String {
        format!(
            "map-{}-{}-{}-objects.jpg",
            map_tile_descriptor.zoom_level(),
            map_tile_descriptor.lower_left_corner().x(),
            map_tile_descriptor.lower_left_corner().y(),
        )
    }

    /// the file name of a map tile in the cache directory
    #[must_use]
    fn map_tile_cache_file_name(&self, map_tile_descriptor: &MapTileDescriptor) -> PathBuf {
        self.cache_directory
            .join(Self::map_tile_file_name(map_tile_descriptor))
    }

    /// the file name marking a negative response in the cache directory
    #[must_use]
    fn map_tile_cache_negative_response_file_name(
        &self,
        map_tile_descriptor: &MapTileDescriptor,
    ) -> PathBuf {
        self.cache_directory.join(format!(
            "{}.does-not-exist",
            Self::map_tile_file_name(map_tile_descriptor)
        ))
    }

    /// the file name of the cache policy file in the cache directory
    #[must_use]
    fn cache_policy_file_name(&self, map_tile_descriptor: &MapTileDescriptor) -> PathBuf {
        self.cache_directory.join(format!(
            "{}.cache-policy.json",
            Self::map_tile_file_name(map_tile_descriptor)
        ))
    }

    /// the URL of a map tile on the Second Life main map server
    #[must_use]
    fn map_tile_url(map_tile_descriptor: &MapTileDescriptor) -> String {
        format!(
            "https://secondlife-maps-cdn.akamaized.net/{}",
            Self::map_tile_file_name(map_tile_descriptor),
        )
    }

    /// check if a cache entry is missing, invalid or valid (either cache policy + map tile or cache policy + negative response)
    async fn cache_entry_status(
        &self,
        map_tile_descriptor: &MapTileDescriptor,
    ) -> Result<MapTileCacheEntryStatus, MapTileCacheError> {
        match (
            self.cache_policy_file_name(map_tile_descriptor).exists(),
            self.map_tile_cache_file_name(map_tile_descriptor).exists(),
            self.map_tile_cache_negative_response_file_name(map_tile_descriptor)
                .exists(),
        ) {
            (false, false, false) => Ok(MapTileCacheEntryStatus::Missing),
            (true, true, false) | (true, false, true) => Ok(MapTileCacheEntryStatus::Valid),
            (cp, tile, neg) => {
                tracing::warn!(
                    "cache entry status is invalid: cache policy file: {}, map tile file: {}, negative response file: {}",
                    cp,
                    tile,
                    neg
                );
                Ok(MapTileCacheEntryStatus::Invalid)
            }
        }
    }

    /// loads the cached `MapTile` and cache policy from the cache directory
    /// or from the in-memory LRU cache
    ///
    /// # Errors
    ///
    /// returns an error if file operations fail
    async fn fetch_cached_map_tile(
        &mut self,
        map_tile_descriptor: &MapTileDescriptor,
    ) -> Result<Option<(Option<MapTile>, http_cache_semantics::CachePolicy)>, MapTileCacheError>
    {
        if let Some(cache_entry) = self.cache.get(map_tile_descriptor) {
            return Ok(Some(cache_entry.to_owned()));
        }
        let cache_file = self.map_tile_cache_file_name(map_tile_descriptor);
        let cache_entry_status = self.cache_entry_status(map_tile_descriptor).await?;
        if cache_entry_status == MapTileCacheEntryStatus::Invalid {
            self.remove_cached_tile(map_tile_descriptor).await?;
            return Ok(None);
        }
        if cache_entry_status == MapTileCacheEntryStatus::Missing {
            return Ok(None);
        }
        let Some(cache_policy) = self.load_cache_policy(map_tile_descriptor).await? else {
            return Err(MapTileCacheError::CachePolicyError);
        };
        if cache_file.exists() {
            let cached_map_tile = image::ImageReader::open(cache_file)
                .map_err(MapTileCacheError::CacheDirectoryFileError)?
                .decode()?;
            Ok(Some((
                Some(MapTile {
                    descriptor: map_tile_descriptor.to_owned(),
                    image: cached_map_tile,
                }),
                cache_policy,
            )))
        } else {
            // since we know the cache entry status is valid and no map tile exists we must be dealing with a cached absence
            Ok(Some((None, cache_policy)))
        }
    }

    /// clears the data about a specific map tile from the cache
    async fn remove_cached_tile(
        &mut self,
        map_tile_descriptor: &MapTileDescriptor,
    ) -> Result<(), MapTileCacheError> {
        tracing::debug!("Removing {map_tile_descriptor:?} from map tile cache");
        self.cache.pop(map_tile_descriptor);
        let cache_file = self.map_tile_cache_file_name(map_tile_descriptor);
        let cache_file_negative_response =
            self.map_tile_cache_negative_response_file_name(map_tile_descriptor);
        let cache_policy_file = self.cache_policy_file_name(map_tile_descriptor);
        if cache_file.exists() {
            std::fs::remove_file(cache_file).map_err(MapTileCacheError::CacheDirectoryFileError)?;
        }
        if cache_file_negative_response.exists() {
            std::fs::remove_file(cache_file_negative_response)
                .map_err(MapTileCacheError::CacheDirectoryFileError)?;
        }
        if cache_policy_file.exists() {
            std::fs::remove_file(cache_policy_file)
                .map_err(MapTileCacheError::CacheDirectoryFileError)?;
        }
        Ok(())
    }

    /// loads the `http_cache_semantics::CachePolicy` for a cached map tile
    /// or absence from disk cache
    ///
    /// # Errors
    ///
    /// returns an error if file operations or JSON deserialization fail
    async fn load_cache_policy(
        &self,
        map_tile_descriptor: &MapTileDescriptor,
    ) -> Result<Option<http_cache_semantics::CachePolicy>, MapTileCacheError> {
        let cache_policy_file = self.cache_policy_file_name(map_tile_descriptor);
        if !cache_policy_file.exists() {
            return Ok(None);
        }
        let cache_policy = std::fs::read_to_string(cache_policy_file)
            .map_err(MapTileCacheError::CacheDirectoryFileError)?;
        Ok(serde_json::from_str(&cache_policy)?)
    }

    /// stores the cache policy in the disk cache
    ///
    /// # Errors
    ///
    /// returns an error if there was an error in the file operation or when
    /// serializing the cache policy
    async fn store_cache_policy(
        &self,
        map_tile_descriptor: &MapTileDescriptor,
        cache_policy: http_cache_semantics::CachePolicy,
    ) -> Result<(), MapTileCacheError> {
        if !self.cache_directory.exists() {
            std::fs::create_dir_all(&self.cache_directory)
                .map_err(MapTileCacheError::CacheDirectoryFileError)?;
        }
        let cache_policy = serde_json::to_string(&cache_policy)?;
        std::fs::write(
            self.cache_policy_file_name(map_tile_descriptor),
            cache_policy,
        )
        .map_err(MapTileCacheError::CacheDirectoryFileError)?;
        Ok(())
    }

    /// marks a tile as missing in the cache if the cache policy indicates
    /// it is storable
    ///
    /// # Errors
    ///
    /// returns an error if there was an error in the file operations
    /// or serialization of the cache policy
    async fn cache_missing_tile(
        &mut self,
        map_tile_descriptor: &MapTileDescriptor,
        cache_policy: http_cache_semantics::CachePolicy,
    ) -> Result<(), MapTileCacheError> {
        if cache_policy.is_storable() {
            tracing::debug!("Caching absence of map tile {map_tile_descriptor:?}");
            self.store_cache_policy(map_tile_descriptor, cache_policy.to_owned())
                .await?;
            let cache_file_negative_response =
                self.map_tile_cache_negative_response_file_name(map_tile_descriptor);
            std::fs::File::create(cache_file_negative_response)
                .map_err(MapTileCacheError::CacheDirectoryFileError)?;
            self.cache
                .put(map_tile_descriptor.clone(), (None, cache_policy));
        } else {
            tracing::warn!(
                "Absence of map tile {map_tile_descriptor:?} not storable according to cache policy"
            );
        }
        Ok(())
    }

    /// stores a tile in the cache if the cache policy indicates that
    /// it is storable
    ///
    /// # Errors
    ///
    /// returns an error if there was an error in the file operations
    /// or serialization of the cache policy
    async fn cache_tile(
        &mut self,
        map_tile_descriptor: &MapTileDescriptor,
        map_tile: &MapTile,
        cache_policy: http_cache_semantics::CachePolicy,
    ) -> Result<(), MapTileCacheError> {
        if cache_policy.is_storable() {
            tracing::debug!("Caching map tile {map_tile_descriptor:?}");
            self.store_cache_policy(map_tile_descriptor, cache_policy.to_owned())
                .await?;
            map_tile
                .image
                .save(self.map_tile_cache_file_name(map_tile_descriptor))?;
            self.cache.put(
                map_tile_descriptor.clone(),
                (Some(map_tile.to_owned()), cache_policy),
            );
        } else {
            tracing::warn!(
                "Map tile {map_tile_descriptor:?} not storable according to cache policy"
            );
        }
        Ok(())
    }

    /// fetches a map tile from the Second Life main map servers
    /// or the local cache
    ///
    /// # Errors
    ///
    /// returns an error if the HTTP request fails of if the result fails to be
    /// parsed as an image
    pub async fn get_map_tile(
        &mut self,
        map_tile_descriptor: &MapTileDescriptor,
    ) -> Result<Option<MapTile>, MapTileCacheError> {
        Ok(self.get_map_tile_with_outcome(map_tile_descriptor).await?.0)
    }

    /// fetches a map tile from the Second Life main map servers
    /// or the local cache and additionally reports where the tile came from
    /// (memory cache, disk cache, network, or known-missing) so callers can
    /// surface progress information
    ///
    /// # Errors
    ///
    /// returns an error if the HTTP request fails of if the result fails to be
    /// parsed as an image
    pub async fn get_map_tile_with_outcome(
        &mut self,
        map_tile_descriptor: &MapTileDescriptor,
    ) -> Result<(Option<MapTile>, TileOutcome), MapTileCacheError> {
        tracing::debug!("Map tile {map_tile_descriptor:?} requested");
        let url = Self::map_tile_url(map_tile_descriptor);
        let request = self.client.get(&url).build()?;
        let now = std::time::SystemTime::now();
        // peek without disturbing the LRU order so we can distinguish a
        // memory-cache hit from a disk-cache hit when classifying the outcome
        let memory_cache_hit = self.cache.peek(map_tile_descriptor).is_some();
        if let Some((cached_map_tile, cache_policy)) =
            self.fetch_cached_map_tile(map_tile_descriptor).await?
        {
            if cached_map_tile.is_some() {
                tracing::debug!("Found matching map tile in cache, checking freshness");
            } else {
                tracing::debug!("Found matching map tile absence in cache, checking freshness");
            }
            if let http_cache_semantics::BeforeRequest::Fresh(_) =
                cache_policy.before_request(&request, now)
            {
                if cached_map_tile.is_some() {
                    tracing::debug!("Using cached map tile");
                } else {
                    tracing::debug!("Using cached map tile absence");
                }
                let outcome = if cached_map_tile.is_none() {
                    TileOutcome::Missing
                } else if memory_cache_hit {
                    TileOutcome::LoadedFromMemoryCache
                } else {
                    TileOutcome::LoadedFromDiskCache
                };
                return Ok((cached_map_tile, outcome));
            }
            tracing::debug!("Map tile cache not fresh, removing from cache");
            self.remove_cached_tile(map_tile_descriptor).await?;
        }
        tracing::debug!("Waiting for ratelimiter to fetch map tile from server");
        if let Some(ratelimiter) = &self.ratelimiter {
            while let Err(err) = ratelimiter.try_wait() {
                match err {
                    ratelimit::TryWaitError::Insufficient(duration) => {
                        tokio::time::sleep(duration).await;
                    }
                    _ => {
                        return Err(MapTileCacheError::RatelimiterError(err));
                    }
                }
            }
        }
        tracing::debug!("Fetching map tile from server at {}", url);
        let response = self
            .client
            .execute(
                request
                    .try_clone()
                    .ok_or(MapTileCacheError::FailedToCloneRequest)?,
            )
            .await?;
        tracing::debug!(
            "Server response received: status {}, headers\n{:#?}",
            response.status(),
            response.headers()
        );
        if !response.status().is_success() {
            if response.status() == reqwest::StatusCode::FORBIDDEN {
                // FORBIDDEN (403) is returned when the file does not exist
                // which likely means there is no region/map tile
                tracing::debug!(
                    "Received 403 FORBIDDEN response, interpreting as no map tile for these grid coordinates"
                );
                let cache_policy = http_cache_semantics::CachePolicy::new(
                    &request,
                    &MapTileNegativeResponse(response),
                );
                self.cache_missing_tile(map_tile_descriptor, cache_policy)
                    .await?;
                return Ok((None, TileOutcome::Missing));
            }
            return Err(MapTileCacheError::HttpError(
                url.to_owned(),
                response.status(),
                response.headers().to_owned(),
                response.text().await?,
            ));
        }
        let cache_policy = http_cache_semantics::CachePolicy::new(&request, &response);
        let raw_response_body = response.bytes().await?;
        tracing::debug!("Parsing received map tile to image");
        let image = image::ImageReader::new(std::io::Cursor::new(raw_response_body))
            .with_guessed_format()
            .map_err(MapTileCacheError::ImageFormatGuessError)?
            .decode()?;
        let map_tile = MapTile {
            descriptor: map_tile_descriptor.to_owned(),
            image,
        };
        self.cache_tile(map_tile_descriptor, &map_tile, cache_policy)
            .await?;
        tracing::debug!("Returning freshly fetched map tile");
        Ok((Some(map_tile), TileOutcome::FetchedFromNetwork))
    }

    /// figures out if a map tile exist by checking the local in-memory and
    /// disk caches or fetching the map tile from the server
    ///
    /// # Errors
    ///
    /// returns an error if fetching the map tile from cache or remotely fails
    pub async fn does_map_tile_exist(
        &mut self,
        map_tile_descriptor: &MapTileDescriptor,
    ) -> Result<bool, MapTileCacheError> {
        let url = Self::map_tile_url(map_tile_descriptor);
        if let Some((map_tile, cache_policy)) = self.cache.get(map_tile_descriptor) {
            let request = self.client.get(&url).build()?;
            let now = std::time::SystemTime::now();
            if let http_cache_semantics::BeforeRequest::Fresh(_) =
                cache_policy.before_request(&request, now)
            {
                return Ok(map_tile.is_some());
            }
        }
        if self.cache_entry_status(map_tile_descriptor).await? == MapTileCacheEntryStatus::Valid
            && let Some(cache_policy) = self.load_cache_policy(map_tile_descriptor).await?
        {
            let request = self.client.get(&url).build()?;
            let now = std::time::SystemTime::now();
            if let http_cache_semantics::BeforeRequest::Fresh(_) =
                cache_policy.before_request(&request, now)
            {
                if self
                    .map_tile_cache_negative_response_file_name(map_tile_descriptor)
                    .exists()
                {
                    return Ok(false);
                }
                return Ok(true);
            }
        }
        Ok(self.get_map_tile(map_tile_descriptor).await?.is_some())
    }

    /// figures out if a region exists based on the existence of map tiles for it, starting with the lowest zoom level
    /// and potentially going up to the highest one if all the other zoom levels have a tile for that region
    ///
    /// # Errors
    ///
    /// returns an error if fetching map tiles from cache or remotely fails
    pub async fn does_region_exist(
        &mut self,
        grid_coordinates: &GridCoordinates,
    ) -> Result<bool, MapTileCacheError> {
        for zoom_level in (1..=8).rev() {
            tracing::debug!(
                "Checking if zoom level {zoom_level} map tile exists for region {grid_coordinates:?}"
            );
            let map_tile_descriptor = MapTileDescriptor::new(
                ZoomLevel::try_new(zoom_level)?,
                grid_coordinates.to_owned(),
            );
            if !self.does_map_tile_exist(&map_tile_descriptor).await? {
                tracing::debug!("No map tile found, region {grid_coordinates:?} does not exist");
                return Ok(false);
            }
            let cache_entry_status = self.cache_entry_status(&map_tile_descriptor).await?;
            if cache_entry_status == MapTileCacheEntryStatus::Valid {}
        }
        tracing::debug!(
            "Map tiles exist for {grid_coordinates:?} on all zoom levels, region exists"
        );
        Ok(true)
    }
}

/// represents a map assembled from map tiles
#[derive(Debug, Clone)]
pub struct Map {
    /// the zoom level of this map
    zoom_level: ZoomLevel,
    /// the grid rectangle of regions represented by this map
    grid_rectangle: GridRectangle,
    /// the actual map image
    image: image::DynamicImage,
}

/// represents errors that can occur while creating a map
#[derive(Debug, thiserror::Error)]
pub enum MapError {
    /// an error in the map tile cache
    #[error("error in map tile cache while assembling map: {0}")]
    MapTileCacheError(#[from] MapTileCacheError),
    /// an error occurred when trying to calculate the zoom level that fits the
    /// map grid rectangle into the output image
    #[error(
        "error when trying to calculate zoom level that fits the map grid rectangle into the output image: {0}"
    )]
    ZoomFitError(#[from] ZoomFitError),
    /// failed to crop a map tile to the required size
    #[error("error when cropping a map tile to the required size")]
    MapTileCropError,
    /// failed to calculate pixel coordinates where we want to place a map tile crop
    #[error("error when calculating pixel coordinates where we want to place a map tile crop")]
    MapCoordinateError,
    /// no overlap between map tile we fetched and output map (should not happen)
    #[error("no overlap between map tile we fetched and output map (should not happen)")]
    NoOverlapError,
    /// no grid coordinates were returned for one of the region names in the
    /// USB Notecard
    #[error("No grid coordinates were returned for one of the regions in the USB notecard: {0}")]
    NoGridCoordinatesForRegion(RegionName),
    /// error in region name to grid coordinate cache
    #[error("error in region name to grid coordinate cache: {0}")]
    RegionNameToGridCoordinateCacheError(#[from] crate::region::CacheError),
    /// error calculating spline
    #[error("error calculating spline: {0}")]
    SplineError(
        #[source]
        #[from]
        uniform_cubic_splines::SplineError,
    ),
}

impl Map {
    /// creates a new `Map`
    ///
    /// if we choose not to fill the missing map tiles they appear as black
    ///
    /// if we choose not to fill the missing regions they appear in a color
    /// similar to water but filling them in has some performance impact since
    /// we need to check if the region exists by fetching higher resolution
    /// map tiles for it.
    ///
    /// # Errors
    ///
    /// returns an error if fetching the map tiles fails
    ///
    /// # Arguments
    ///
    /// * `map_tile_cache` - the map tile cache to use to fetch the map tiles
    /// * `x` - the width of the map in pixels
    /// * `y` - the height of the map in pixels
    /// * `grid_rectangle` - the grid rectangle of regions represented by this map
    pub async fn new(
        map_tile_cache: &mut MapTileCache,
        x: u32,
        y: u32,
        grid_rectangle: GridRectangle,
        fill_missing_map_tiles: Option<image::Rgba<u8>>,
        fill_missing_regions: Option<image::Rgba<u8>>,
    ) -> Result<Self, MapError> {
        Self::new_with_progress(
            map_tile_cache,
            x,
            y,
            grid_rectangle,
            fill_missing_map_tiles,
            fill_missing_regions,
            None,
        )
        .await
    }

    /// creates a new `Map`, emitting per-tile progress events on the
    /// provided channel as it works (closed or full channels are tolerated
    /// silently, so the caller can drop the receiver at any time without
    /// aborting the render)
    ///
    /// See [`Self::new`] for the meaning of the other parameters.
    ///
    /// # Errors
    ///
    /// returns an error if fetching the map tiles fails
    pub async fn new_with_progress(
        map_tile_cache: &mut MapTileCache,
        x: u32,
        y: u32,
        grid_rectangle: GridRectangle,
        fill_missing_map_tiles: Option<image::Rgba<u8>>,
        fill_missing_regions: Option<image::Rgba<u8>>,
        progress: Option<&tokio::sync::mpsc::Sender<MapProgressEvent>>,
    ) -> Result<Self, MapError> {
        let zoom_level = ZoomLevel::max_zoom_level_to_fit_regions_into_output_image(
            grid_rectangle.size_x(),
            grid_rectangle.size_y(),
            x,
            y,
        )?;
        let actual_x = <u16 as Into<u32>>::into(zoom_level.pixels_per_region())
            * <u16 as Into<u32>>::into(grid_rectangle.size_x());
        let actual_y = <u16 as Into<u32>>::into(zoom_level.pixels_per_region())
            * <u16 as Into<u32>>::into(grid_rectangle.size_y());
        tracing::debug!(
            "Determined max zoom level for map of size ({x}, {y}) for {grid_rectangle:?} to be {zoom_level:?}, actual map size will be ({actual_x}, {actual_y})"
        );
        let x = actual_x;
        let y = actual_y;
        let image = image::DynamicImage::new_rgb8(x, y);
        let mut result = Self {
            zoom_level,
            grid_rectangle,
            image,
        };
        // count the unique tile descriptors we will process so the caller
        // can show a determinate progress indicator
        let mut total_tiles: u32 = 0;
        for region_x in result.x_range() {
            for region_y in result.y_range() {
                let grid_coordinates = GridCoordinates::new(region_x, region_y);
                let map_tile_descriptor = MapTileDescriptor::new(zoom_level, grid_coordinates);
                let Some(overlap) = result.intersect(&map_tile_descriptor) else {
                    return Err(MapError::NoOverlapError);
                };
                if overlap.lower_left_corner().x() == region_x
                    && overlap.lower_left_corner().y() == region_y
                {
                    total_tiles = total_tiles.saturating_add(1);
                }
            }
        }
        emit_progress(
            progress,
            MapProgressEvent::PlanComputed {
                zoom_level,
                total_tiles,
            },
        );
        if fill_missing_regions.is_some() {
            // upper bound: every region in the requested rectangle. The
            // actual count can be lower if some primary tiles turn out to
            // be missing (those regions get the missing-tile colour instead
            // of an individual check).
            let total_regions: u32 =
                u32::from(result.size_x()).saturating_mul(u32::from(result.size_y()));
            emit_progress(
                progress,
                MapProgressEvent::RegionCheckPlanned { total_regions },
            );
        }
        for region_x in result.x_range() {
            for region_y in result.y_range() {
                let grid_coordinates = GridCoordinates::new(region_x, region_y);
                let map_tile_descriptor = MapTileDescriptor::new(zoom_level, grid_coordinates);
                let Some(overlap) = result.intersect(&map_tile_descriptor) else {
                    return Err(MapError::NoOverlapError);
                };
                if overlap.lower_left_corner().x() != region_x
                    || overlap.lower_left_corner().y() != region_y
                {
                    // we should have already processed this map tile when
                    // we encountered the lower left corner of the overlap
                    continue;
                }
                tracing::debug!("Map tile for {grid_coordinates:?} is {map_tile_descriptor:?}");
                emit_progress(
                    progress,
                    MapProgressEvent::TileStarted {
                        descriptor: map_tile_descriptor.to_owned(),
                    },
                );
                let (fetched_tile, outcome) = map_tile_cache
                    .get_map_tile_with_outcome(&map_tile_descriptor)
                    .await?;
                emit_progress(
                    progress,
                    MapProgressEvent::TileFinished {
                        descriptor: map_tile_descriptor.to_owned(),
                        outcome,
                    },
                );
                if let Some(map_tile) = fetched_tile {
                    let crop = map_tile
                        .crop_imm_grid_rectangle(&overlap)
                        .ok_or(MapError::MapTileCropError)?;
                    tracing::debug!(
                        "Cropped map tile to ({}, {})+{}x{}",
                        crop.offsets().0,
                        crop.offsets().1,
                        (*crop).dimensions().0,
                        (*crop).dimensions().1
                    );
                    // we need to use y = 256 here since the crop is inserted by pixel coordinates which means
                    // we need the upper left corner, not the lower left one of the region as an origin
                    let (replace_x, replace_y) = result
                        .pixel_coordinates_for_coordinates(
                            &overlap.upper_left_corner(),
                            &RegionCoordinates::new(0f32, 256f32, 0f32),
                        )
                        .ok_or(MapError::MapCoordinateError)?;
                    tracing::debug!(
                        "Placing map tile crop at ({replace_x}, {replace_y}) in the output image"
                    );
                    image::imageops::replace(
                        &mut result,
                        &*crop,
                        replace_x.into(),
                        replace_y.into(),
                    );
                    if let Some(fill_color) = fill_missing_regions {
                        for overlap_region_x in overlap.x_range() {
                            for overlap_region_y in overlap.y_range() {
                                let grid_coordinates =
                                    GridCoordinates::new(overlap_region_x, overlap_region_y);
                                let exists =
                                    map_tile_cache.does_region_exist(&grid_coordinates).await?;
                                emit_progress(
                                    progress,
                                    MapProgressEvent::RegionChecked {
                                        x: overlap_region_x,
                                        y: overlap_region_y,
                                        exists,
                                    },
                                );
                                if !exists {
                                    let pixel_min = result.pixel_coordinates_for_coordinates(
                                        &grid_coordinates,
                                        &RegionCoordinates::new(0f32, 256f32, 0f32),
                                    );
                                    let pixel_max = result.pixel_coordinates_for_coordinates(
                                        &grid_coordinates,
                                        &RegionCoordinates::new(256f32, 0f32, 0f32),
                                    );
                                    if let (Some((min_x, min_y)), Some((max_x, max_y))) =
                                        (pixel_min, pixel_max)
                                    {
                                        for x in min_x..max_x {
                                            for y in min_y..max_y {
                                                <Self as image::GenericImage>::put_pixel(
                                                    &mut result,
                                                    x,
                                                    y,
                                                    fill_color,
                                                );
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                } else if let Some(fill_color) = fill_missing_map_tiles {
                    let (replace_x, replace_y) = result
                        .pixel_coordinates_for_coordinates(
                            &overlap.upper_left_corner(),
                            &RegionCoordinates::new(0f32, 256f32, 0f32),
                        )
                        .ok_or(MapError::MapCoordinateError)?;
                    let pixel_size_x =
                        u32::from(overlap.size_x()) * u32::from(zoom_level.pixels_per_region());
                    let pixel_size_y =
                        u32::from(overlap.size_y()) * u32::from(zoom_level.pixels_per_region());
                    for x in replace_x..replace_x + pixel_size_x {
                        for y in replace_y..replace_y + pixel_size_y {
                            <Self as image::GenericImage>::put_pixel(&mut result, x, y, fill_color);
                        }
                    }
                }
            }
        }
        Ok(result)
    }

    /// draws a route from a `USBNotecard` onto the map
    ///
    /// # Errors
    ///
    /// fails if the region name to grid coordinate conversion fails
    /// or the conversion of those into pixel coordinates
    pub async fn draw_route(
        &mut self,
        region_name_to_grid_coordinates_cache: &mut RegionNameToGridCoordinatesCache,
        usb_notecard: &USBNotecard,
        color: image::Rgba<u8>,
    ) -> Result<(), MapError> {
        self.draw_route_with_progress(
            region_name_to_grid_coordinates_cache,
            usb_notecard,
            color,
            None,
        )
        .await
    }

    /// draws a route from a `USBNotecard` onto the map, emitting progress
    /// events for each waypoint resolved on the provided channel
    ///
    /// See [`Self::draw_route`] for the meaning of the other parameters.
    ///
    /// # Errors
    ///
    /// fails if the region name to grid coordinate conversion fails
    /// or the conversion of those into pixel coordinates
    pub async fn draw_route_with_progress(
        &mut self,
        region_name_to_grid_coordinates_cache: &mut RegionNameToGridCoordinatesCache,
        usb_notecard: &USBNotecard,
        color: image::Rgba<u8>,
        progress: Option<&tokio::sync::mpsc::Sender<MapProgressEvent>>,
    ) -> Result<(), MapError> {
        tracing::debug!("Drawing route:\n{:#?}", usb_notecard);
        let waypoints = usb_notecard.waypoints();
        let total_waypoints = waypoints.len();
        emit_progress(progress, MapProgressEvent::RoutePlanned { total_waypoints });
        let mut pixel_waypoints = Vec::new();
        for (index, waypoint) in waypoints.iter().enumerate() {
            let Some(grid_coordinates) = region_name_to_grid_coordinates_cache
                .get_grid_coordinates(waypoint.location().region_name())
                .await?
            else {
                return Err(MapError::NoGridCoordinatesForRegion(
                    waypoint.location().region_name().to_owned(),
                ));
            };
            emit_progress(
                progress,
                MapProgressEvent::RouteWaypointResolved {
                    index,
                    total: total_waypoints,
                    region: waypoint.location().region_name().to_owned(),
                },
            );
            let (x, y) = self
                .pixel_coordinates_for_coordinates(
                    &grid_coordinates,
                    &waypoint.region_coordinates(),
                )
                .ok_or(MapError::MapCoordinateError)?;
            tracing::debug!(
                "Drawing waypoint at ({x}, {y}) for location {:?}",
                waypoint.location()
            );
            //self.draw_waypoint(x, y, color);
            #[expect(
                clippy::cast_precision_loss,
                reason = "if our pixel coordinates get anywhere near 2^23 we probably should reconsider all types anyway"
            )]
            pixel_waypoints.push((x as f32, y as f32));
        }
        self.draw_pixel_waypoint_route(&pixel_waypoints, color)?;
        Ok(())
    }

    /// draws a route through the given already-resolved pixel coordinates
    ///
    /// This is the pure geometry/rasterization half of
    /// [`Self::draw_route_with_progress`], split out so it can be unit tested
    /// without any network access (it only touches the image and the spline
    /// crate).
    ///
    /// It is public so callers that already hold resolved grid coordinates (for
    /// example to compute overlay occupancy via [`crate::coverage`]) can draw a
    /// route onto a [`Self::blank`] map without any network access, by first
    /// converting their coordinates with
    /// [`MapLike::pixel_coordinates_for_coordinates`].
    ///
    /// # Errors
    ///
    /// returns an error if the spline crate returns an error
    pub fn draw_pixel_waypoint_route(
        &mut self,
        pixel_waypoints: &[(f32, f32)],
        color: image::Rgba<u8>,
    ) -> Result<(), uniform_cubic_splines::SplineError> {
        let waypoint_count = pixel_waypoints.len();
        let Some((first, pixel_waypoints_all_but_first)) = pixel_waypoints.split_first() else {
            // no route if there are no waypoints
            return Ok(());
        };
        let Some((second, _pixel_waypoints_rest)) = pixel_waypoints_all_but_first.split_first()
        else {
            // no route if there is only one waypoint
            return Ok(());
        };
        let extra_before_start = (
            first.0 - (second.0 - first.0),
            first.1 - (second.1 - first.1),
        );
        let Some((last, pixel_waypoints_all_but_last)) = pixel_waypoints.split_last() else {
            // no route if there are no waypoints (but this should never happen since we already returned at the first split_first() above)
            return Ok(());
        };
        let Some((second_to_last, _pixel_waypoints_rest)) =
            pixel_waypoints_all_but_last.split_last()
        else {
            // no route if there is only one waypoint (but this should never happen since we already returned at the second split_first() above)
            return Ok(());
        };
        let extra_after_end = (
            last.0 + (last.0 - second_to_last.0),
            last.1 + (last.1 - second_to_last.1),
        );
        let mut knots = vec![extra_before_start];
        knots.extend(pixel_waypoints.to_owned());
        knots.push(extra_after_end);
        let (points_x, points_y): (Vec<f32>, Vec<f32>) = knots.into_iter().unzip();
        let sample = |v: f32| -> Result<(f32, f32), uniform_cubic_splines::SplineError> {
            let point_x =
                uniform_cubic_splines::spline::<uniform_cubic_splines::basis::CatmullRom, _, _>(
                    v, &points_x,
                )?;
            let point_y =
                uniform_cubic_splines::spline::<uniform_cubic_splines::basis::CatmullRom, _, _>(
                    v, &points_y,
                )?;
            Ok((point_x, point_y))
        };
        // For the common case (>= 3 waypoints) the parameter that lands on
        // waypoint `i` keeps its historical value `i / (waypoint_count - 2)` so
        // route rendering is unchanged. For exactly 2 waypoints the old
        // denominator was 0 (NaN/inf), so use the mathematically correct uniform
        // mapping `i / (waypoint_count - 1)` (= `i` for n == 2), which places
        // waypoint 0 at x = 0 and waypoint 1 at x = 1.
        #[expect(
            clippy::cast_precision_loss,
            reason = "if our waypoint counts get anywhere near 2^23 routes probably will not be finished anyway"
        )]
        let waypoint_parameter_denominator = if waypoint_count <= 2 {
            (waypoint_count as f32 - 1f32).max(1f32)
        } else {
            waypoint_count as f32 - 2f32
        };
        let spline_value_for_waypoint = |i: usize| -> f32 {
            #[expect(
                clippy::cast_precision_loss,
                reason = "if our waypoint counts get anywhere near 2^23 routes probably will not be finished anyway"
            )]
            let i = i as f32;
            i / waypoint_parameter_denominator
        };
        let spline_value_between_waypoints = spline_value_for_waypoint(1);
        let distance_between_points = |(x1, y1): (f32, f32), (x2, y2): (f32, f32)| -> f32 {
            ((x1 - x2).powi(2) + (y1 - y2).powi(2)).sqrt()
        };
        let mut last_point: Option<(f32, f32)> = None;
        // For >= 3 waypoints we iterate over all but the last waypoint (the
        // historical behaviour). For exactly 2 waypoints we must also reach the
        // second waypoint (i == 1) so that `last_point` is `Some` and the curve
        // between the two waypoints is actually drawn (otherwise nothing renders).
        let outer_loop_count = if waypoint_count <= 2 {
            waypoint_count
        } else {
            waypoint_count - 1
        };
        for (i, waypoint) in pixel_waypoints.iter().enumerate().take(outer_loop_count) {
            /// size of rectangles to use to draw the spline, should be odd
            /// or it won't be centered properly
            const SPLINE_RECT_SIZE: u8 = 3;
            tracing::debug!("Waypoint {}: {:?}", i, waypoint);
            let v = spline_value_for_waypoint(i);
            let point = sample(v)?;
            tracing::debug!("Sampled Catmull Rom curve {i} at point {v}: {point:?} for route");
            if let Some(last_point) = last_point {
                let distance_from_last_point = distance_between_points(point, last_point);
                tracing::debug!(
                    "Waypoint {i} is {:?} from last waypoint",
                    distance_from_last_point
                );
                #[expect(
                    clippy::cast_possible_truncation,
                    reason = "we want an integer count for the number of samples"
                )]
                #[expect(
                    clippy::cast_sign_loss,
                    reason = "we want a positive count for the number of samples"
                )]
                let samples_between_last_waypoint_and_this_one =
                    (0.5f32 * distance_from_last_point / f32::from(SPLINE_RECT_SIZE)) as u32;
                // The historical step uses `samples - 2` as the denominator so
                // that at j = samples - 1 the factor slightly exceeds 1 and the
                // drawing "overshoots" one sample past the previous waypoint for
                // gap-free coverage. That denominator is 0 when samples == 2
                // (NaN parameter -> stray rects at the clamped (0,0) corner), so
                // floor it to 1 in that single case. For samples >= 3 the value
                // is unchanged; samples <= 1 never enters this loop.
                #[expect(
                    clippy::cast_precision_loss,
                    reason = "if our waypoints are so far apart that we end up with 2^23 or more samples between two waypoints something is very broken anyway"
                )]
                let sample_step_denominator =
                    (samples_between_last_waypoint_and_this_one as f32 - 2f32).max(1f32);
                for j in (0..samples_between_last_waypoint_and_this_one).rev() {
                    #[expect(
                        clippy::cast_precision_loss,
                        reason = "if our waypoints are so far apart that we end up with 2^23 or more samples between two waypoints something is very broken anyway"
                    )]
                    let v =
                        v - spline_value_between_waypoints * (j as f32 / sample_step_denominator);
                    let sample_point = sample(v)?;
                    #[expect(
                        clippy::cast_possible_truncation,
                        reason = "we want integer pixel coordinates for use in the image library"
                    )]
                    imageproc::drawing::draw_filled_rect_mut(
                        self.image_mut(),
                        imageproc::rect::Rect::at(
                            sample_point.0 as i32 - ((i32::from(SPLINE_RECT_SIZE) - 1) / 2),
                            sample_point.1 as i32 - ((i32::from(SPLINE_RECT_SIZE) - 1) / 2),
                        )
                        .of_size(u32::from(SPLINE_RECT_SIZE), u32::from(SPLINE_RECT_SIZE)),
                        color,
                    );
                }
                self.draw_arrow(
                    sample(v - (0.1f32 * spline_value_between_waypoints))?,
                    point,
                    color,
                );
            }
            last_point = Some(point);
        }
        Ok(())
    }

    /// creates a blank `Map` with a fully transparent RGBA image sized for the
    /// given grid rectangle at the given zoom level, without any network access.
    ///
    /// Unlike [`Self::new`] (which builds an RGB8 base map from fetched tiles)
    /// this uses an RGBA8 image so untouched pixels have alpha 0. That is what
    /// the [`crate::coverage`] occupancy analysis relies on to tell pixels that
    /// were drawn on (route, GLW shapes/labels) apart from blank ones. The pixel
    /// geometry (dimensions and
    /// [`MapLike::pixel_coordinates_for_coordinates`]) depends only on the zoom
    /// level and grid rectangle, not the channel count, so drawing overlays onto
    /// this blank map yields exactly the same pixel positions as the real render.
    #[must_use]
    pub fn blank(grid_rectangle: GridRectangle, zoom_level: ZoomLevel) -> Self {
        let width = <u16 as Into<u32>>::into(zoom_level.pixels_per_region())
            * <u16 as Into<u32>>::into(grid_rectangle.size_x());
        let height = <u16 as Into<u32>>::into(zoom_level.pixels_per_region())
            * <u16 as Into<u32>>::into(grid_rectangle.size_y());
        Self {
            zoom_level,
            grid_rectangle,
            image: image::DynamicImage::ImageRgba8(image::RgbaImage::new(width, height)),
        }
    }

    /// creates a blank `Map` sized exactly as [`Self::new`] would size it for the
    /// given maximum output dimensions, without any network access.
    ///
    /// This reproduces the zoom-fit logic of [`Self::new_with_progress`] so the
    /// resulting blank map has the identical pixel dimensions the real render
    /// would have for the same `grid_rectangle` and the same caps. See
    /// [`Self::blank`] for why the image is RGBA8.
    ///
    /// # Errors
    ///
    /// returns an error if the zoom level that fits the rectangle into the
    /// output image cannot be calculated
    #[expect(
        clippy::result_large_err,
        reason = "returns the same large MapError as the other Map constructors for a consistent error type at call sites; the only failure here is the zoom-fit calculation"
    )]
    pub fn blank_fit(
        grid_rectangle: GridRectangle,
        max_width: u32,
        max_height: u32,
    ) -> Result<Self, MapError> {
        let zoom_level = ZoomLevel::max_zoom_level_to_fit_regions_into_output_image(
            grid_rectangle.size_x(),
            grid_rectangle.size_y(),
            max_width,
            max_height,
        )?;
        Ok(Self::blank(grid_rectangle, zoom_level))
    }

    /// creates a blank `Map` with a transparent image of the given size for
    /// use in tests that exercise the pure drawing geometry without any network
    /// access
    #[cfg(test)]
    fn new_blank_for_test(width: u32, height: u32) -> Self {
        #[expect(
            clippy::expect_used,
            reason = "zoom level 1 is a compile-time constant within the valid range"
        )]
        let zoom_level = ZoomLevel::try_new(1).expect("zoom level 1 is within the valid range");
        Self {
            zoom_level,
            grid_rectangle: GridRectangle::new(
                GridCoordinates::new(0, 0),
                GridCoordinates::new(0, 0),
            ),
            image: image::DynamicImage::ImageRgba8(image::RgbaImage::new(width, height)),
        }
    }

    /// saves the map to the specified path
    ///
    /// # Errors
    ///
    /// returns an error when the image libraries returns an error
    /// when saving the image
    pub fn save(&self, path: &std::path::Path) -> Result<(), image::ImageError> {
        self.image.save(path)
    }
}

impl GridRectangleLike for Map {
    fn grid_rectangle(&self) -> GridRectangle {
        self.grid_rectangle.to_owned()
    }
}

impl image::GenericImageView for Map {
    type Pixel = <image::DynamicImage as image::GenericImageView>::Pixel;

    fn dimensions(&self) -> (u32, u32) {
        self.image.dimensions()
    }

    fn get_pixel(&self, x: u32, y: u32) -> Self::Pixel {
        self.image.get_pixel(x, y)
    }
}

impl image::GenericImage for Map {
    fn get_pixel_mut(&mut self, x: u32, y: u32) -> &mut Self::Pixel {
        #[expect(
            deprecated,
            reason = "we need to use this deprecated function to implement the deprecated function when passing it through"
        )]
        self.image.get_pixel_mut(x, y)
    }

    fn put_pixel(&mut self, x: u32, y: u32, pixel: Self::Pixel) {
        self.image.put_pixel(x, y, pixel);
    }

    fn blend_pixel(&mut self, x: u32, y: u32, pixel: Self::Pixel) {
        #[expect(
            deprecated,
            reason = "we need to use this deprecated function to implement the deprecated function when passing it through"
        )]
        self.image.blend_pixel(x, y, pixel);
    }
}

impl MapLike for Map {
    fn zoom_level(&self) -> ZoomLevel {
        self.zoom_level
    }

    fn image(&self) -> &image::DynamicImage {
        &self.image
    }

    fn image_mut(&mut self) -> &mut image::DynamicImage {
        &mut self.image
    }
}

#[cfg(test)]
mod test {
    use image::GenericImageView as _;
    use tracing_test::traced_test;

    use super::*;

    #[tokio::test]
    async fn test_fetch_map_tile_highest_detail() -> Result<(), Box<dyn std::error::Error>> {
        let temp_dir = tempfile::tempdir()?;
        let mut map_tile_cache = MapTileCache::new(temp_dir.path().to_path_buf(), None);
        map_tile_cache
            .get_map_tile(&MapTileDescriptor::new(
                ZoomLevel::try_new(1)?,
                GridCoordinates::new(1136, 1075),
            ))
            .await?;
        Ok(())
    }

    #[tokio::test]
    async fn test_fetch_map_tile_highest_detail_twice() -> Result<(), Box<dyn std::error::Error>> {
        let temp_dir = tempfile::tempdir()?;
        let mut map_tile_cache = MapTileCache::new(temp_dir.path().to_path_buf(), None);
        map_tile_cache
            .get_map_tile(&MapTileDescriptor::new(
                ZoomLevel::try_new(1)?,
                GridCoordinates::new(1136, 1075),
            ))
            .await?;
        map_tile_cache
            .get_map_tile(&MapTileDescriptor::new(
                ZoomLevel::try_new(1)?,
                GridCoordinates::new(1136, 1075),
            ))
            .await?;
        Ok(())
    }

    #[tokio::test]
    async fn test_fetch_map_tile_lowest_detail() -> Result<(), Box<dyn std::error::Error>> {
        let temp_dir = tempfile::tempdir()?;
        let mut map_tile_cache = MapTileCache::new(temp_dir.path().to_path_buf(), None);
        map_tile_cache
            .get_map_tile(&MapTileDescriptor::new(
                ZoomLevel::try_new(8)?,
                GridCoordinates::new(1136, 1075),
            ))
            .await?;
        Ok(())
    }

    #[traced_test]
    #[tokio::test]
    async fn test_fetch_map_zoom_level_1() -> Result<(), Box<dyn std::error::Error>> {
        let temp_dir = tempfile::tempdir()?;
        let ratelimiter = ratelimit::Ratelimiter::builder(1).build()?;
        let mut map_tile_cache =
            MapTileCache::new(temp_dir.path().to_path_buf(), Some(ratelimiter));
        let map = Map::new(
            &mut map_tile_cache,
            512,
            512,
            GridRectangle::new(
                GridCoordinates::new(1135, 1070),
                GridCoordinates::new(1136, 1071),
            ),
            None,
            None,
        )
        .await?;
        map.save(std::path::Path::new("/tmp/test_map_zoom_level_1.jpg"))?;
        Ok(())
    }

    #[traced_test]
    #[tokio::test]
    async fn test_fetch_map_zoom_level_2() -> Result<(), Box<dyn std::error::Error>> {
        let temp_dir = tempfile::tempdir()?;
        let ratelimiter = ratelimit::Ratelimiter::builder(1).build()?;
        let mut map_tile_cache =
            MapTileCache::new(temp_dir.path().to_path_buf(), Some(ratelimiter));
        let map = Map::new(
            &mut map_tile_cache,
            256,
            256,
            GridRectangle::new(
                GridCoordinates::new(1136, 1074),
                GridCoordinates::new(1137, 1075),
            ),
            None,
            None,
        )
        .await?;
        map.save(std::path::Path::new("/tmp/test_map_zoom_level_2.jpg"))?;
        Ok(())
    }

    #[traced_test]
    #[tokio::test]
    async fn test_fetch_map_zoom_level_3() -> Result<(), Box<dyn std::error::Error>> {
        let temp_dir = tempfile::tempdir()?;
        let ratelimiter = ratelimit::Ratelimiter::builder(1).build()?;
        let mut map_tile_cache =
            MapTileCache::new(temp_dir.path().to_path_buf(), Some(ratelimiter));
        let map = Map::new(
            &mut map_tile_cache,
            128,
            128,
            GridRectangle::new(
                GridCoordinates::new(1136, 1074),
                GridCoordinates::new(1137, 1075),
            ),
            None,
            None,
        )
        .await?;
        map.save(std::path::Path::new("/tmp/test_map_zoom_level_3.jpg"))?;
        Ok(())
    }

    #[traced_test]
    #[tokio::test]
    async fn test_fetch_map_zoom_level_1_ratelimiter() -> Result<(), Box<dyn std::error::Error>> {
        let temp_dir = tempfile::tempdir()?;
        let ratelimiter = ratelimit::Ratelimiter::builder(1).build()?;
        let mut map_tile_cache =
            MapTileCache::new(temp_dir.path().to_path_buf(), Some(ratelimiter));
        let map = Map::new(
            &mut map_tile_cache,
            2048,
            2048,
            GridRectangle::new(
                GridCoordinates::new(1131, 1068),
                GridCoordinates::new(1139, 1075),
            ),
            None,
            None,
        )
        .await?;
        map.save(std::path::Path::new(
            "/tmp/test_map_zoom_level_1_ratelimiter.jpg",
        ))?;
        Ok(())
    }

    #[traced_test]
    #[tokio::test]
    #[expect(clippy::panic, reason = "panic in test is intentional")]
    async fn test_map_tile_pixel_coordinates_for_coordinates_single_region()
    -> Result<(), Box<dyn std::error::Error>> {
        let temp_dir = tempfile::tempdir()?;
        let mut map_tile_cache = MapTileCache::new(temp_dir.path().to_path_buf(), None);
        let Some(map_tile) = map_tile_cache
            .get_map_tile(&MapTileDescriptor::new(
                ZoomLevel::try_new(1)?,
                GridCoordinates::new(1136, 1075),
            ))
            .await?
        else {
            panic!("Expected there to be a region at this location");
        };
        for in_region_x in 0..=256 {
            for in_region_y in 0..=256 {
                let grid_coordinates = GridCoordinates::new(1136, 1075);
                #[expect(
                    clippy::cast_precision_loss,
                    reason = "in_region_x and in_region_y are between 0 and 256, nowhere near 2^23"
                )]
                let region_coordinates =
                    RegionCoordinates::new(in_region_x as f32, in_region_y as f32, 0f32);
                tracing::debug!("Now checking {grid_coordinates:?}, {region_coordinates:?}");
                assert_eq!(
                    map_tile
                        .pixel_coordinates_for_coordinates(&grid_coordinates, &region_coordinates,),
                    Some((in_region_x, 256 - in_region_y)),
                );
            }
        }
        Ok(())
    }

    #[traced_test]
    #[tokio::test]
    async fn test_map_pixel_coordinates_for_coordinates_four_regions()
    -> Result<(), Box<dyn std::error::Error>> {
        let temp_dir = tempfile::tempdir()?;
        let ratelimiter = ratelimit::Ratelimiter::builder(1).build()?;
        let mut map_tile_cache =
            MapTileCache::new(temp_dir.path().to_path_buf(), Some(ratelimiter));
        let map = Map::new(
            &mut map_tile_cache,
            512,
            512,
            GridRectangle::new(
                GridCoordinates::new(1136, 1074),
                GridCoordinates::new(1137, 1075),
            ),
            None,
            None,
        )
        .await?;
        for region_offset_x in 0..=1 {
            for region_offset_y in 0..=1 {
                for in_region_x in 0..=256 {
                    for in_region_y in 0..=256 {
                        let grid_coordinates =
                            GridCoordinates::new(1136 + region_offset_x, 1074 + region_offset_y);
                        let region_coordinates = RegionCoordinates::new(
                            f32::from(in_region_x),
                            f32::from(in_region_y),
                            0f32,
                        );
                        tracing::debug!(
                            "Now checking {grid_coordinates:?}, {region_coordinates:?}"
                        );
                        assert_eq!(
                            map.pixel_coordinates_for_coordinates(
                                &grid_coordinates,
                                &region_coordinates,
                            ),
                            Some((
                                u32::from(region_offset_x * 256 + in_region_x),
                                u32::from(512 - (region_offset_y * 256 + in_region_y))
                            )),
                        );
                    }
                }
            }
        }
        Ok(())
    }

    #[traced_test]
    #[tokio::test]
    #[expect(clippy::panic, reason = "panic in test is intentional")]
    async fn test_map_tile_coordinates_for_pixel_coordinates_single_region()
    -> Result<(), Box<dyn std::error::Error>> {
        let temp_dir = tempfile::tempdir()?;
        let mut map_tile_cache = MapTileCache::new(temp_dir.path().to_path_buf(), None);
        let Some(map_tile) = map_tile_cache
            .get_map_tile(&MapTileDescriptor::new(
                ZoomLevel::try_new(1)?,
                GridCoordinates::new(1136, 1075),
            ))
            .await?
        else {
            panic!("Expected there to be a region at this location");
        };
        tracing::debug!("Dimensions of map tile are {:?}", map_tile.dimensions());
        #[expect(
            clippy::cast_precision_loss,
            reason = "in_region_x and in_region_y are between 0 and 256, nowhere near 2^23"
        )]
        for in_region_x in 0..=256 {
            for in_region_y in 0..=256 {
                let pixel_x = in_region_x;
                let pixel_y = 256 - in_region_y;
                tracing::debug!("Now checking ({pixel_x}, {pixel_y})");
                assert_eq!(
                    map_tile.coordinates_for_pixel_coordinates(pixel_x, pixel_y,),
                    Some((
                        GridCoordinates::new(
                            1136 + if in_region_x == 256 { 1 } else { 0 },
                            1075 + if in_region_y == 256 { 1 } else { 0 }
                        ),
                        RegionCoordinates::new(
                            (in_region_x % 256) as f32,
                            (in_region_y % 256) as f32,
                            0f32
                        ),
                    ))
                );
            }
        }
        Ok(())
    }

    #[traced_test]
    #[tokio::test]
    async fn test_map_coordinates_for_pixel_coordinates_four_regions()
    -> Result<(), Box<dyn std::error::Error>> {
        let temp_dir = tempfile::tempdir()?;
        let ratelimiter = ratelimit::Ratelimiter::builder(1).build()?;
        let mut map_tile_cache =
            MapTileCache::new(temp_dir.path().to_path_buf(), Some(ratelimiter));
        let map = Map::new(
            &mut map_tile_cache,
            512,
            512,
            GridRectangle::new(
                GridCoordinates::new(1136, 1074),
                GridCoordinates::new(1137, 1075),
            ),
            None,
            None,
        )
        .await?;
        tracing::debug!("Dimensions of map are {:?}", map.dimensions());
        for region_offset_x in 0..=1 {
            for region_offset_y in 0..=1 {
                for in_region_x in 0..=256 {
                    for in_region_y in 0..=256 {
                        let pixel_x = u32::from(region_offset_x * 256 + in_region_x);
                        let pixel_y = u32::from(512 - (region_offset_y * 256 + in_region_y));
                        tracing::debug!("Now checking ({pixel_x}, {pixel_y})");
                        assert_eq!(
                            map.coordinates_for_pixel_coordinates(pixel_x, pixel_y,),
                            Some((
                                GridCoordinates::new(
                                    1136 + region_offset_x + if in_region_x == 256 { 1 } else { 0 },
                                    1074 + region_offset_y + if in_region_y == 256 { 1 } else { 0 }
                                ),
                                RegionCoordinates::new(
                                    f32::from(in_region_x % 256),
                                    f32::from(in_region_y % 256),
                                    0f32
                                ),
                            )),
                        );
                    }
                }
            }
        }
        Ok(())
    }

    /// background (untouched) pixel of a [`Map::new_blank_for_test`] image
    #[cfg(test)]
    const BLANK_PIXEL: [u8; 4] = [0, 0, 0, 0];

    /// counts how many pixels of the map differ from the blank background
    #[cfg(test)]
    fn drawn_pixel_count(map: &Map) -> usize {
        map.image()
            .pixels()
            .filter(|(_, _, pixel)| pixel.0 != BLANK_PIXEL)
            .count()
    }

    /// Two identical consecutive notecard lines produce a zero-distance segment.
    /// This exercises the pure drawing geometry (no network) and asserts it
    /// neither errors/panics nor corrupts the (0,0) corner with a NaN-derived
    /// rectangle, while still drawing the rest of the route.
    #[test]
    fn test_draw_route_identical_consecutive_waypoints_is_safe()
    -> Result<(), Box<dyn std::error::Error>> {
        let route_color = image::Rgba([255u8, 0u8, 0u8, 255u8]);
        let mut map = Map::new_blank_for_test(256, 256);
        // the middle pair is identical -> zero-distance segment
        let pixel_waypoints = vec![
            (100f32, 100f32),
            (120f32, 120f32),
            (120f32, 120f32),
            (140f32, 100f32),
        ];
        map.draw_pixel_waypoint_route(&pixel_waypoints, route_color)?;
        assert!(
            drawn_pixel_count(&map) > 0,
            "the route should still draw at least one pixel"
        );
        assert_eq!(
            map.image().get_pixel(0, 0).0,
            BLANK_PIXEL,
            "the (0,0) corner must stay background (no NaN-derived rectangle)"
        );
        Ok(())
    }

    /// A two-waypoint route used to draw nothing because
    /// `spline_value_for_waypoint = i / (waypoint_count - 2)` divided by zero.
    /// It must now render a visible curve.
    #[test]
    fn test_draw_route_two_waypoints_renders() -> Result<(), Box<dyn std::error::Error>> {
        let route_color = image::Rgba([255u8, 0u8, 0u8, 255u8]);
        let mut map = Map::new_blank_for_test(256, 256);
        let pixel_waypoints = vec![(60f32, 60f32), (180f32, 180f32)];
        map.draw_pixel_waypoint_route(&pixel_waypoints, route_color)?;
        assert!(
            drawn_pixel_count(&map) > 0,
            "a two-waypoint route must draw a visible curve (regression for the waypoint_count - 2 == 0 bug)"
        );
        assert_eq!(
            map.image().get_pixel(0, 0).0,
            BLANK_PIXEL,
            "the (0,0) corner must stay background"
        );
        Ok(())
    }

    /// When a segment produces exactly two sub-samples the old inner loop
    /// divided by `(samples - 2) == 0`, yielding a NaN parameter that saturated
    /// to coordinate 0 and drew a stray rectangle in the (0,0) corner. Two
    /// waypoints ~14 px apart give `samples == 2`; assert no corner glitch.
    #[test]
    fn test_draw_route_two_sample_segment_has_no_corner_glitch()
    -> Result<(), Box<dyn std::error::Error>> {
        let route_color = image::Rgba([255u8, 0u8, 0u8, 255u8]);
        let mut map = Map::new_blank_for_test(256, 256);
        let pixel_waypoints = vec![(100f32, 100f32), (110f32, 110f32)];
        map.draw_pixel_waypoint_route(&pixel_waypoints, route_color)?;
        assert_eq!(
            map.image().get_pixel(0, 0).0,
            BLANK_PIXEL,
            "samples == 2 must not draw a NaN-derived rectangle at the (0,0) corner"
        );
        Ok(())
    }

    /// The bundled real route notecard contains an actual duplicate consecutive
    /// waypoint line; confirm the parser accepts it and the duplicate survives,
    /// since that is the real-world input that motivated the zero-distance work.
    #[test]
    fn test_real_notecard_with_duplicate_consecutive_lines_parses()
    -> Result<(), Box<dyn std::error::Error>> {
        let notecard: USBNotecard =
            include_str!("../tests/fixtures/tscc-2026-03-30.txt").parse()?;
        let has_identical_consecutive = notecard
            .waypoints()
            .windows(2)
            .any(|pair| matches!(pair, [first, second] if first.location() == second.location()));
        assert!(
            has_identical_consecutive,
            "tscc-2026-03-30.txt is expected to contain identical consecutive waypoints"
        );
        Ok(())
    }

    /// End-to-end (network) smoke test: drawing a real route notecard that
    /// contains identical consecutive lines must complete without error.
    #[tokio::test]
    async fn test_draw_real_route_with_duplicate_line() -> Result<(), Box<dyn std::error::Error>> {
        let notecard: USBNotecard =
            include_str!("../tests/fixtures/tscc-2026-03-30.txt").parse()?;
        let temp_dir = tempfile::tempdir()?;
        let mut map_tile_cache = MapTileCache::new(temp_dir.path().to_path_buf(), None);
        let mut region_cache =
            RegionNameToGridCoordinatesCache::new(temp_dir.path().to_path_buf())?;
        let grid_rectangle =
            crate::region::usb_notecard_to_grid_rectangle(&mut region_cache, &notecard).await?;
        let mut map = Map::new(&mut map_tile_cache, 512, 512, grid_rectangle, None, None).await?;
        map.draw_route_with_progress(
            &mut region_cache,
            &notecard,
            image::Rgba([255u8, 0u8, 0u8, 255u8]),
            None,
        )
        .await?;
        Ok(())
    }
}