sl-types 0.2.2

Some basic types for Second Life related tools
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
//! Map-related data types

#[cfg(feature = "chumsky")]
use chumsky::{
    IterParser as _, Parser,
    prelude::{any, just},
    text::whitespace,
};

#[cfg(feature = "chumsky")]
use crate::utils::{
    f32_parser, i16_parser, i32_parser, u8_parser, u16_parser, url_text_component_parser,
};

/// represents a Second Life distance in meters
#[derive(Debug, Clone, PartialEq, PartialOrd, serde::Serialize, serde::Deserialize)]
pub struct Distance(f64);

impl std::fmt::Display for Distance {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{} m", self.0)
    }
}

impl std::ops::Add for Distance {
    type Output = Self;

    fn add(self, rhs: Self) -> Self::Output {
        Self(self.0 + rhs.0)
    }
}

impl std::ops::Sub for Distance {
    type Output = Self;

    fn sub(self, rhs: Self) -> Self::Output {
        Self(self.0 - rhs.0)
    }
}

impl std::ops::Mul<u8> for Distance {
    type Output = Self;

    fn mul(self, rhs: u8) -> Self::Output {
        Self(self.0 * f64::from(rhs))
    }
}

impl std::ops::Mul<u16> for Distance {
    type Output = Self;

    fn mul(self, rhs: u16) -> Self::Output {
        Self(self.0 * f64::from(rhs))
    }
}

impl std::ops::Mul<u32> for Distance {
    type Output = Self;

    fn mul(self, rhs: u32) -> Self::Output {
        Self(self.0 * f64::from(rhs))
    }
}

impl std::ops::Mul<f32> for Distance {
    type Output = Self;

    fn mul(self, rhs: f32) -> Self::Output {
        Self(self.0 * f64::from(rhs))
    }
}

impl std::ops::Mul<f64> for Distance {
    type Output = Self;

    fn mul(self, rhs: f64) -> Self::Output {
        Self(self.0 * rhs)
    }
}

impl std::ops::Div<u8> for Distance {
    type Output = Self;

    fn div(self, rhs: u8) -> Self::Output {
        Self(self.0 / f64::from(rhs))
    }
}

impl std::ops::Div<u16> for Distance {
    type Output = Self;

    fn div(self, rhs: u16) -> Self::Output {
        Self(self.0 / f64::from(rhs))
    }
}

impl std::ops::Div<u32> for Distance {
    type Output = Self;

    fn div(self, rhs: u32) -> Self::Output {
        Self(self.0 / f64::from(rhs))
    }
}

impl std::ops::Div<f32> for Distance {
    type Output = Self;

    fn div(self, rhs: f32) -> Self::Output {
        Self(self.0 / f64::from(rhs))
    }
}

impl std::ops::Div<f64> for Distance {
    type Output = Self;

    fn div(self, rhs: f64) -> Self::Output {
        Self(self.0 / rhs)
    }
}

impl std::ops::Div for Distance {
    type Output = f64;

    fn div(self, rhs: Self) -> Self::Output {
        self.0 / rhs.0
    }
}

impl std::ops::Rem<u8> for Distance {
    type Output = Self;

    fn rem(self, rhs: u8) -> Self::Output {
        Self(self.0 % f64::from(rhs))
    }
}

impl std::ops::Rem<u16> for Distance {
    type Output = Self;

    fn rem(self, rhs: u16) -> Self::Output {
        Self(self.0 % f64::from(rhs))
    }
}

impl std::ops::Rem<u32> for Distance {
    type Output = Self;

    fn rem(self, rhs: u32) -> Self::Output {
        Self(self.0 % f64::from(rhs))
    }
}

impl std::ops::Rem<f32> for Distance {
    type Output = Self;

    fn rem(self, rhs: f32) -> Self::Output {
        Self(self.0 % f64::from(rhs))
    }
}

impl std::ops::Rem<f64> for Distance {
    type Output = Self;

    fn rem(self, rhs: f64) -> Self::Output {
        Self(self.0 % rhs)
    }
}

/// parse a distance
///
/// "235.23 m"
///
/// # Errors
///
/// returns an error if the string could not be parsed
#[cfg(feature = "chumsky")]
#[must_use]
pub fn distance_parser<'src>()
-> impl Parser<'src, &'src str, Distance, chumsky::extra::Err<chumsky::error::Rich<'src, char>>> {
    crate::utils::unsigned_f64_parser()
        .then_ignore(whitespace().or_not())
        .then_ignore(just('m'))
        .map(Distance)
}

/// Grid coordinates for the position of a region on the map
///
/// the first region, Da Boom is located at 1000, 1000
#[derive(
    Debug, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord, serde::Serialize, serde::Deserialize,
)]
pub struct GridCoordinates {
    /// the x coordinate of the region, this is basically the horizontal
    /// position of the region on the map increasing from west to east
    ///
    /// common values are between roughly 395 and 1358
    x: u16,
    /// the y coordinate of the region, this is basically the vertical
    /// position of the region on the map increasing from south to north
    ///
    /// common values are between roughly 479 and 1430
    y: u16,
}

impl GridCoordinates {
    /// Create a new `GridCoordinates`
    #[must_use]
    pub const fn new(x: u16, y: u16) -> Self {
        Self { x, y }
    }

    /// The x coordinate of the region
    #[must_use]
    pub const fn x(&self) -> u16 {
        self.x
    }

    /// The y coordinate of the region
    #[must_use]
    pub const fn y(&self) -> u16 {
        self.y
    }
}

/// an offset between two `GridCoordinates`
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct GridCoordinateOffset {
    /// the offset in the x direction
    x: i32,
    /// the offset in the y direction
    y: i32,
}

impl GridCoordinateOffset {
    /// creates a new `GridCoordinateOffset`
    #[must_use]
    pub const fn new(x: i32, y: i32) -> Self {
        Self { x, y }
    }

    /// the offset in the x direction
    #[must_use]
    pub const fn x(&self) -> i32 {
        self.x
    }

    /// the offset in the y direction
    #[must_use]
    pub const fn y(&self) -> i32 {
        self.y
    }
}

impl std::ops::Add<GridCoordinateOffset> for GridCoordinates {
    type Output = Self;

    fn add(self, rhs: GridCoordinateOffset) -> Self::Output {
        Self::new(
            (<u16 as Into<i32>>::into(self.x).saturating_add(rhs.x))
                .try_into()
                .unwrap_or(if rhs.x > 0 { u16::MAX } else { u16::MIN }),
            (<u16 as Into<i32>>::into(self.y).saturating_add(rhs.y))
                .try_into()
                .unwrap_or(if rhs.y > 0 { u16::MAX } else { u16::MIN }),
        )
    }
}

impl std::ops::Sub<Self> for GridCoordinates {
    type Output = GridCoordinateOffset;

    fn sub(self, rhs: Self) -> Self::Output {
        GridCoordinateOffset::new(
            <u16 as Into<i32>>::into(self.x).saturating_sub(<u16 as Into<i32>>::into(rhs.x)),
            <u16 as Into<i32>>::into(self.y).saturating_sub(<u16 as Into<i32>>::into(rhs.y)),
        )
    }
}

/// represents a rectangle of regions defined by the lower left (minimum coordinates)
/// and upper right (maximum coordinates) corners in `GridCoordinates`
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct GridRectangle {
    /// the lower left (minimum coordinates) corner of the rectangle
    lower_left_corner: GridCoordinates,
    /// the upper right (maximum coordinates) corner of the rectangle
    upper_right_corner: GridCoordinates,
}

impl GridRectangle {
    /// creates a new `GridRectangle` given any two corners
    #[must_use]
    pub fn new(corner1: GridCoordinates, corner2: GridCoordinates) -> Self {
        Self {
            lower_left_corner: GridCoordinates::new(
                corner1.x().min(corner2.x()),
                corner1.y().min(corner2.y()),
            ),
            upper_right_corner: GridCoordinates::new(
                corner1.x().max(corner2.x()),
                corner1.y().max(corner2.y()),
            ),
        }
    }
}

/// represents a grid rectangle like type (usually one that contains a
/// grid rectangle or one that contains a corner and is of a known size
pub trait GridRectangleLike {
    /// the `GridRectangle` represented by this map like image
    #[must_use]
    fn grid_rectangle(&self) -> GridRectangle;

    /// returns the lower left corner of the rectangle
    #[must_use]
    fn lower_left_corner(&self) -> GridCoordinates {
        self.grid_rectangle().lower_left_corner().to_owned()
    }

    /// returns the lower right corner of the rectangle
    #[must_use]
    fn lower_right_corner(&self) -> GridCoordinates {
        GridCoordinates::new(
            self.grid_rectangle().upper_right_corner().x(),
            self.grid_rectangle().lower_left_corner().y(),
        )
    }

    /// returns the upper left corner of the rectangle
    #[must_use]
    fn upper_left_corner(&self) -> GridCoordinates {
        GridCoordinates::new(
            self.grid_rectangle().lower_left_corner().x(),
            self.grid_rectangle().upper_right_corner().y(),
        )
    }

    /// returns the upper right corner of the rectangle
    #[must_use]
    fn upper_right_corner(&self) -> GridCoordinates {
        self.grid_rectangle().upper_right_corner().to_owned()
    }

    /// the size of the map like image in regions in the x direction (width)
    #[must_use]
    fn size_x(&self) -> u16 {
        self.grid_rectangle().size_x()
    }

    /// the size of the map like image in regions in the y direction (width)
    #[must_use]
    fn size_y(&self) -> u16 {
        self.grid_rectangle().size_y()
    }

    /// returns a range for the region x coordinates of this rectangle
    #[must_use]
    fn x_range(&self) -> std::ops::RangeInclusive<u16> {
        self.lower_left_corner().x()..=self.upper_right_corner().x()
    }

    /// returns a range for the region y coordinates of this rectangle
    #[must_use]
    fn y_range(&self) -> std::ops::RangeInclusive<u16> {
        self.lower_left_corner().y()..=self.upper_right_corner().y()
    }

    /// checks if a given set of `GridCoordinates` is within this `GridRectangle`
    #[must_use]
    fn contains(&self, grid_coordinates: &GridCoordinates) -> bool {
        self.lower_left_corner().x() <= grid_coordinates.x()
            && grid_coordinates.x() <= self.upper_right_corner().x()
            && self.lower_left_corner().y() <= grid_coordinates.y()
            && grid_coordinates.y() <= self.upper_right_corner().y()
    }

    /// returns a new `GridRectangle` which is the area where this `GridRectangle`
    /// and another intersect each other or None if there is no intersection
    #[must_use]
    fn intersect<O>(&self, other: &O) -> Option<GridRectangle>
    where
        O: GridRectangleLike,
    {
        let self_x_range: ranges::GenericRange<u16> = self.x_range().into();
        let self_y_range: ranges::GenericRange<u16> = self.y_range().into();
        let other_x_range: ranges::GenericRange<u16> = other.x_range().into();
        let other_y_range: ranges::GenericRange<u16> = other.y_range().into();
        let x_intersection = self_x_range.intersect(other_x_range);
        let y_intersection = self_y_range.intersect(other_y_range);
        match (x_intersection, y_intersection) {
            (
                ranges::OperationResult::Single(x_range),
                ranges::OperationResult::Single(y_range),
            ) => {
                use std::ops::Bound;
                use std::ops::RangeBounds as _;
                match (
                    x_range.start_bound(),
                    x_range.end_bound(),
                    y_range.start_bound(),
                    y_range.end_bound(),
                ) {
                    (
                        Bound::Included(start_x),
                        Bound::Included(end_x),
                        Bound::Included(start_y),
                        Bound::Included(end_y),
                    ) => Some(GridRectangle::new(
                        GridCoordinates::new(*start_x, *start_y),
                        GridCoordinates::new(*end_x, *end_y),
                    )),
                    _ => None,
                }
            }
            _ => None,
        }
    }

    /// returns a PPS HUD description string for this `GridRectangle`
    ///
    /// The PPS HUD is a map HUD commonly used in the SL sailing community
    /// and usually you need to configure it by clicking on the HUD while
    /// you are at the matching location in-world to calibrate the coordinates
    /// on the map texture.
    ///
    /// This string needs to be put in the description of the PPS HUD
    /// dot prim with "Edit linked objects" to avoid the need for manual
    /// calibration.
    #[must_use]
    fn pps_hud_config(&self) -> String {
        let lower_left_corner_x = 256f32 * f32::from(self.lower_left_corner().x());
        let lower_left_corner_y = 256f32 * f32::from(self.lower_left_corner().y());
        // this is basically the lower left corner as an LSL vector of meters from the grid coordinate origin
        // followed by the width and height of the map in regions
        // and a 0/1 for the locked state of the HUD
        // each of those is separated from the next by a slash character
        format!(
            "<{lower_left_corner_x},{lower_left_corner_y},0>/{}/{}/1",
            f32::from(self.size_x()),
            f32::from(self.size_y())
        )
    }
}

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

    fn lower_left_corner(&self) -> GridCoordinates {
        self.lower_left_corner.to_owned()
    }

    fn upper_right_corner(&self) -> GridCoordinates {
        self.upper_right_corner.to_owned()
    }

    fn size_x(&self) -> u16 {
        self.upper_right_corner
            .x()
            .saturating_sub(self.lower_left_corner().x())
            .saturating_add(1)
    }

    fn size_y(&self) -> u16 {
        self.upper_right_corner
            .y()
            .saturating_sub(self.lower_left_corner().y())
            .saturating_add(1)
    }

    fn x_range(&self) -> std::ops::RangeInclusive<u16> {
        self.lower_left_corner.x()..=self.upper_right_corner.x()
    }

    fn y_range(&self) -> std::ops::RangeInclusive<u16> {
        self.lower_left_corner.y()..=self.upper_right_corner.y()
    }
}

impl GridRectangleLike for MapTileDescriptor {
    fn grid_rectangle(&self) -> GridRectangle {
        GridRectangle::new(
            self.lower_left_corner,
            GridCoordinates::new(
                self.lower_left_corner
                    .x()
                    .saturating_add(self.zoom_level.tile_size())
                    .saturating_sub(1),
                self.lower_left_corner
                    .y()
                    .saturating_add(self.zoom_level.tile_size())
                    .saturating_sub(1),
            ),
        )
    }
}

/// A trait to allow adding methods to `Vec<GridCoordinates>`
pub trait GridCoordinatesExt {
    /// returns the coordinates of the lower left corner and the coordinates of
    /// the upper right corner of a rectangle of regions containing all the grid
    /// coordinates in this container
    ///
    /// returns None if the container is empty
    fn bounding_rectangle(&self) -> Option<GridRectangle>;
}

impl GridCoordinatesExt for Vec<GridCoordinates> {
    fn bounding_rectangle(&self) -> Option<GridRectangle> {
        if self.is_empty() {
            return None;
        }
        let (xs, ys): (Vec<u16>, Vec<u16>) = self.iter().map(|gc| (gc.x(), gc.y())).unzip();
        // unwrap is okay in these cases because we checked above that the container is non-empty
        #[expect(
            clippy::unwrap_used,
            reason = "we checked above that the container is non-empty"
        )]
        let (min_x, max_x) = (xs.iter().min().unwrap(), xs.iter().max().unwrap());
        #[expect(
            clippy::unwrap_used,
            reason = "we checked above that the container is non-empty"
        )]
        let (min_y, max_y) = (ys.iter().min().unwrap(), ys.iter().max().unwrap());
        Some(GridRectangle {
            lower_left_corner: GridCoordinates::new(*min_x, *min_y),
            upper_right_corner: GridCoordinates::new(*max_x, *max_y),
        })
    }
}

/// Region coordinates for the position of something inside a region
///
/// Usually limited to 0..256 for x and y and 0..4096 for z (height)
/// but values outside those ranges are possible for positions of objects
/// in the process of crossing from one region to another or in similar
/// situations where they belong to one simulator logically but are located
/// outside of that simulator's region
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, serde::Serialize, serde::Deserialize)]
pub struct RegionCoordinates {
    /// the x coordinate inside the region from the western edge (0) to the
    /// eastern edge (256)
    x: f32,
    /// the y coordinate inside the region from the southern edge (0) to the
    /// northern edge (256)
    y: f32,
    /// the z coordinate inside the region from the bottom (0) to the top (4096)
    /// higher values are possible but for objects can not be rezzed above 4096m
    /// and teleports are clamped to that as well
    z: f32,
}

/// parse region coordinates
///
/// "{ 1.234, 2.345, 3.456 }"
///
/// # Errors
///
/// returns an error if the string could not be parsed
#[cfg(feature = "chumsky")]
#[must_use]
pub fn region_coordinates_parser<'src>()
-> impl Parser<'src, &'src str, RegionCoordinates, chumsky::extra::Err<chumsky::error::Rich<'src, char>>>
{
    just('{')
        .ignore_then(whitespace().or_not())
        .ignore_then(f32_parser())
        .then_ignore(just(','))
        .then_ignore(whitespace().or_not())
        .then(f32_parser())
        .then_ignore(just(','))
        .then_ignore(whitespace().or_not())
        .then(f32_parser())
        .then_ignore(whitespace().or_not())
        .then_ignore(just('}'))
        .map(|((x, y), z)| RegionCoordinates::new(x, y, z))
}

impl RegionCoordinates {
    /// Create a new `RegionCoordinates`
    #[must_use]
    pub const fn new(x: f32, y: f32, z: f32) -> Self {
        Self { x, y, z }
    }

    /// The x coordinate inside the region
    #[must_use]
    pub const fn x(&self) -> f32 {
        self.x
    }

    /// The y coordinate inside the region
    #[must_use]
    pub const fn y(&self) -> f32 {
        self.y
    }

    /// The z coordinate inside the region
    #[must_use]
    pub const fn z(&self) -> f32 {
        self.z
    }

    /// checks if the coordinates are within bounds
    #[must_use]
    pub fn in_bounds(&self) -> bool {
        self.x >= 0f32
            && self.x < 256f32
            && self.y >= 0f32
            && self.y < 256f32
            && self.z >= 0f32
            && self.z < 4096f32
    }
}

impl From<crate::lsl::Vector> for RegionCoordinates {
    fn from(value: crate::lsl::Vector) -> Self {
        Self {
            x: value.x,
            y: value.y,
            z: value.z,
        }
    }
}

/// The name of a region
#[nutype::nutype(
    sanitize(trim),
    validate(len_char_min = 2, len_char_max = 35),
    derive(
        Debug,
        Clone,
        Display,
        Hash,
        PartialEq,
        Eq,
        PartialOrd,
        Ord,
        Serialize,
        Deserialize,
        AsRef
    )
)]
pub struct RegionName(String);

/// parse an url encoded string into a RegionName
///
/// # Errors
///
/// returns an error if the string could not be parsed
#[cfg(feature = "chumsky")]
#[must_use]
pub fn url_region_name_parser<'src>()
-> impl Parser<'src, &'src str, RegionName, chumsky::extra::Err<chumsky::error::Rich<'src, char>>> {
    url_text_component_parser().try_map(|region_name, span| {
        RegionName::try_new(region_name).map_err(|err| chumsky::error::Rich::custom(span, err))
    })
}

/// parse a string into a RegionName
///
/// # Errors
///
/// returns an error if the string could not be parsed
#[cfg(feature = "chumsky")]
#[must_use]
pub fn region_name_parser<'src>()
-> impl Parser<'src, &'src str, RegionName, chumsky::extra::Err<chumsky::error::Rich<'src, char>>> {
    any()
        .filter(|c: &char| {
            c.is_alphabetic() || c.is_numeric() || *c == ' ' || *c == '\'' || *c == '-'
        })
        .repeated()
        .at_least(2)
        .collect::<String>()
        .try_map(|region_name, span| {
            RegionName::try_new(region_name).map_err(|err| chumsky::error::Rich::custom(span, err))
        })
}

/// A location inside Second Life the way it is usually represented in
/// SLURLs or map URLs, based on a Region Name and integer coordinates
/// inside the region
#[derive(Debug, Clone, Hash, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct Location {
    /// the name of the region of the location
    pub region_name: RegionName,
    /// the x coordinate inside the region
    pub x: u8,
    /// the y coordinate inside the region
    pub y: u8,
    /// the z coordinate inside the region
    pub z: u16,
}

/// parse a string into a Location where no component is url-encoded
///
/// # Errors
///
/// returns an error if the string could not be parsed
#[cfg(feature = "chumsky")]
#[must_use]
pub fn location_parser<'src>()
-> impl Parser<'src, &'src str, Location, chumsky::extra::Err<chumsky::error::Rich<'src, char>>> {
    region_name_parser()
        .then_ignore(just('/'))
        .then(u8_parser())
        .then_ignore(just('/'))
        .then(u8_parser())
        .then_ignore(just('/'))
        .then(u16_parser())
        .map(|(((region_name, x), y), z)| Location::new(region_name, x, y, z))
}

/// parse a string into a Location where the region name is url encoded
/// but each component of the location is separated by an actual slash
///
/// # Errors
///
/// returns an error if the string could not be parsed
#[cfg(feature = "chumsky")]
#[must_use]
pub fn url_location_parser<'src>()
-> impl Parser<'src, &'src str, Location, chumsky::extra::Err<chumsky::error::Rich<'src, char>>> {
    url_region_name_parser()
        .then_ignore(just('/'))
        .then(u8_parser())
        .then_ignore(just('/'))
        .then(u8_parser())
        .then_ignore(just('/'))
        .then(u16_parser())
        .map(|(((region_name, x), y), z)| Location::new(region_name, x, y, z))
}

/// parse a string into a Location from a URL-encoded location (the slashes in
/// particular)
///
/// # Errors
///
/// returns an error if the string could not be parsed
#[cfg(feature = "chumsky")]
#[must_use]
pub fn url_encoded_location_parser<'src>()
-> impl Parser<'src, &'src str, Location, chumsky::extra::Err<chumsky::error::Rich<'src, char>>> {
    url_text_component_parser().try_map(|s, span| {
        location_parser().parse(&s).into_result().map_err(|err| {
            chumsky::error::Rich::custom(
                span,
                format!("Parsing {s} as location failed with: {err:#?}"),
            )
        })
    })
}

/// the possible errors that can occur when parsing a String to a `Location`
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error, strum::EnumIs)]
pub enum LocationParseError {
    /// unexpected number of /-separated components in the location URL
    #[error(
        "unexpected number of /-separated components in the location URL {0}, found {1} expected 4 (for a bare location) or 8 (for a URL)"
    )]
    UnexpectedComponentCount(String, usize),
    /// unexpected scheme in the location URL
    #[error("unexpected scheme in the location URL {0}, found {1}, expected http: or https:")]
    UnexpectedScheme(String, String),
    /// unexpected non-empty second component in location URL
    #[error(
        "unexpected non-empty second component in location URL {0}, found {1}, expected http or https"
    )]
    UnexpectedNonEmptySecondComponent(String, String),
    /// unexpected host in the location URL
    #[error(
        "unexpected host in the location URL {0}, found {1}, expected maps.secondlife.com or slurl.com"
    )]
    UnexpectedHost(String, String),
    /// unexpected path in the location URL
    #[error("unexpected path in the location URL {0}, found {1}, expected secondlife")]
    UnexpectedPath(String, String),
    /// error parsing the region name
    #[error("error parsing the region name {0}: {1}")]
    RegionName(String, RegionNameError),
    /// error parsing the X coordinate
    #[error("error parsing the X coordinate {0}: {1}")]
    X(String, std::num::ParseIntError),
    /// error parsing the Y coordinate
    #[error("error parsing the Y coordinate {0}: {1}")]
    Y(String, std::num::ParseIntError),
    /// error parsing the Z coordinate
    #[error("error parsing the Z coordinate {0}: {1}")]
    Z(String, std::num::ParseIntError),
}

impl std::str::FromStr for Location {
    type Err = LocationParseError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        // if the string is an USB-notecard line drop everything after the first comma
        let usb_location = s
            .split_once(',')
            .map_or(s, |(usb_location, _usb_comment)| usb_location);
        let parts = usb_location.split('/').collect::<Vec<_>>();
        if let [region_name, x, y, z] = parts.as_slice() {
            let region_name = RegionName::try_new(region_name.replace("%20", " "))
                .map_err(|err| LocationParseError::RegionName(s.to_owned(), err))?;
            let x = x
                .parse()
                .map_err(|err| LocationParseError::X(s.to_owned(), err))?;
            let y = y
                .parse()
                .map_err(|err| LocationParseError::Y(s.to_owned(), err))?;
            let z = z
                .parse()
                .map_err(|err| LocationParseError::Z(s.to_owned(), err))?;
            return Ok(Self {
                region_name,
                x,
                y,
                z,
            });
        }
        if let [scheme, second_component, host, path, region_name, x, y, z] = parts.as_slice() {
            if *scheme != "http:" && *scheme != "https:" {
                return Err(LocationParseError::UnexpectedScheme(
                    s.to_owned(),
                    scheme.to_string(),
                ));
            }
            if !second_component.is_empty() {
                return Err(LocationParseError::UnexpectedNonEmptySecondComponent(
                    s.to_owned(),
                    second_component.to_string(),
                ));
            }
            if *host != "maps.secondlife.com" && *host != "slurl.com" {
                return Err(LocationParseError::UnexpectedHost(
                    s.to_owned(),
                    host.to_string(),
                ));
            }
            if *path != "secondlife" {
                return Err(LocationParseError::UnexpectedPath(
                    s.to_owned(),
                    path.to_string(),
                ));
            }
            let region_name = RegionName::try_new(region_name.replace("%20", " "))
                .map_err(|err| LocationParseError::RegionName(s.to_owned(), err))?;
            let x = x
                .parse()
                .map_err(|err| LocationParseError::X(s.to_owned(), err))?;
            let y = y
                .parse()
                .map_err(|err| LocationParseError::Y(s.to_owned(), err))?;
            let z = z
                .parse()
                .map_err(|err| LocationParseError::Z(s.to_owned(), err))?;
            return Ok(Self {
                region_name,
                x,
                y,
                z,
            });
        }
        Err(LocationParseError::UnexpectedComponentCount(
            s.to_owned(),
            parts.len(),
        ))
    }
}

impl Location {
    /// Creates a new `Location`
    #[must_use]
    pub const fn new(region_name: RegionName, x: u8, y: u8, z: u16) -> Self {
        Self {
            region_name,
            x,
            y,
            z,
        }
    }

    /// The region name of this `Location`
    #[must_use]
    pub const fn region_name(&self) -> &RegionName {
        &self.region_name
    }

    /// The x coordinate of the `Location`
    #[must_use]
    pub const fn x(&self) -> u8 {
        self.x
    }

    /// The y coordinate of the `Location`
    #[must_use]
    pub const fn y(&self) -> u8 {
        self.y
    }

    /// The z coordinate of the `Location`
    #[must_use]
    pub const fn z(&self) -> u16 {
        self.z
    }

    /// returns a maps.secondlife.com URL for the `Location`
    #[must_use]
    pub fn as_maps_url(&self) -> String {
        format!(
            "https://maps.secondlife.com/secondlife/{}/{}/{}/{}",
            self.region_name, self.x, self.y, self.z
        )
    }
}

/// A location inside Second Life the way it is usually represented in
/// SLURLs or map URLs, based on a Region Name and integer coordinates
/// inside the region, this variant allows out of bounds coordinates
/// (negative and 256 or above for x and y and negative for z)
#[derive(Debug, Clone, Hash, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct UnconstrainedLocation {
    /// the name of the region of the location
    pub region_name: RegionName,
    /// the x coordinate inside the region
    pub x: i16,
    /// the y coordinate inside the region
    pub y: i16,
    /// the z coordinate inside the region
    pub z: i32,
}

impl UnconstrainedLocation {
    /// Creates a new `UnconstrainedLocation`
    #[must_use]
    pub const fn new(region_name: RegionName, x: i16, y: i16, z: i32) -> Self {
        Self {
            region_name,
            x,
            y,
            z,
        }
    }

    /// The region name of this `UnconstrainedLocation`
    #[must_use]
    pub const fn region_name(&self) -> &RegionName {
        &self.region_name
    }

    /// The x coordinate of the `UnconstrainedLocation`
    #[must_use]
    pub const fn x(&self) -> i16 {
        self.x
    }

    /// The y coordinate of the `UnconstrainedLocation`
    #[must_use]
    pub const fn y(&self) -> i16 {
        self.y
    }

    /// The z coordinate of the `UnconstrainedLocation`
    #[must_use]
    pub const fn z(&self) -> i32 {
        self.z
    }
}

/// parse a string into an UnconstrainedLocation where nothing is urlencoded
///
/// # Errors
///
/// returns an error if the string could not be parsed
#[cfg(feature = "chumsky")]
#[must_use]
pub fn unconstrained_location_parser<'src>() -> impl Parser<
    'src,
    &'src str,
    UnconstrainedLocation,
    chumsky::extra::Err<chumsky::error::Rich<'src, char>>,
> {
    region_name_parser()
        .then_ignore(just('/'))
        .then(i16_parser())
        .then_ignore(just('/'))
        .then(i16_parser())
        .then_ignore(just('/'))
        .then(i32_parser())
        .map(|(((region_name, x), y), z)| UnconstrainedLocation::new(region_name, x, y, z))
}

/// parse a string into an UnconstrainedLocation where the region is urlencoded
/// but the components are separated by actual slashes
///
/// # Errors
///
/// returns an error if the string could not be parsed
#[cfg(feature = "chumsky")]
#[must_use]
pub fn url_unconstrained_location_parser<'src>() -> impl Parser<
    'src,
    &'src str,
    UnconstrainedLocation,
    chumsky::extra::Err<chumsky::error::Rich<'src, char>>,
> {
    url_region_name_parser()
        .then_ignore(just('/'))
        .then(i16_parser())
        .then_ignore(just('/'))
        .then(i16_parser())
        .then_ignore(just('/'))
        .then(i32_parser())
        .map(|(((region_name, x), y), z)| UnconstrainedLocation::new(region_name, x, y, z))
}

/// parse a string into an UnconstrainedLocation where the entire location is
/// urlencoded with urlencoded slashes
///
/// # Errors
///
/// returns an error if the string could not be parsed
#[cfg(feature = "chumsky")]
#[must_use]
pub fn urlencoded_unconstrained_location_parser<'src>() -> impl Parser<
    'src,
    &'src str,
    UnconstrainedLocation,
    chumsky::extra::Err<chumsky::error::Rich<'src, char>>,
> {
    url_region_name_parser()
        .then_ignore(just('/'))
        .then(i16_parser())
        .then_ignore(just('/'))
        .then(i16_parser())
        .then_ignore(just('/'))
        .then(i32_parser())
        .map(|(((region_name, x), y), z)| UnconstrainedLocation::new(region_name, x, y, z))
}

impl TryFrom<UnconstrainedLocation> for Location {
    type Error = std::num::TryFromIntError;

    fn try_from(value: UnconstrainedLocation) -> Result<Self, Self::Error> {
        Ok(Self::new(
            value.region_name,
            value.x.try_into()?,
            value.y.try_into()?,
            value.z.try_into()?,
        ))
    }
}

impl From<Location> for UnconstrainedLocation {
    fn from(value: Location) -> Self {
        Self {
            region_name: value.region_name,
            x: value.x.into(),
            y: value.y.into(),
            z: value.z.into(),
        }
    }
}

/// The map tile zoom level for the Second Life main map
#[nutype::nutype(
    validate(greater_or_equal = 1, less_or_equal = 8),
    derive(
        Debug,
        Clone,
        Copy,
        Display,
        FromStr,
        Hash,
        PartialEq,
        Eq,
        PartialOrd,
        Ord,
        Serialize,
        Deserialize
    )
)]
pub struct ZoomLevel(u8);

/// Errors that can occur when trying to find the correct zoom level to fit
/// regions into an output image of a given size
#[derive(Debug, Clone, thiserror::Error, strum::EnumIs)]
pub enum ZoomFitError {
    /// The region size in the x direction can not be zero
    #[error("region size in x direction can not be zero")]
    RegionSizeXZero,

    /// The region size in the y direction can not be zero
    #[error("region size in y direction can not be zero")]
    RegionSizeYZero,

    /// The output image size in the x direction can not be zero
    #[error("output image size in x direction can not be zero")]
    OutputSizeXZero,

    /// The output image size in the y direction can not be zero
    #[error("output image size in y direction can not be zero")]
    OutputSizeYZero,

    /// Error converting a logarithm value into a `u8` (should never happen)
    #[error("error converting a logarithm value into a u8")]
    LogarithmConversionError(#[from] std::num::TryFromIntError),

    /// Error creating the zoom level from the calculated value
    /// (should never happen)
    #[error("error creating zoom level from calculated value")]
    ZoomLevelError(#[from] ZoomLevelError),
}

impl ZoomLevel {
    /// returns the map tile size in number of regions at this zoom level
    ///
    /// This applies to both dimensions equally since both regions and map tiles
    /// are square
    #[must_use]
    pub fn tile_size(&self) -> u16 {
        let exponent: u32 = self.into_inner().into();
        let exponent = exponent.saturating_sub(1);
        2u16.pow(exponent)
    }

    /// returns the map tile size in pixels at this zoom level
    ///
    /// This applies to both dimensions equally since both regions and map tiles
    /// are square
    #[expect(
        clippy::arithmetic_side_effects,
        reason = "both values we multiply here are u16 originally so their product should never overflow an u32"
    )]
    #[must_use]
    pub fn tile_size_in_pixels(&self) -> u32 {
        let tile_size: u32 = self.tile_size().into();
        let region_size_in_map_tile_in_pixels: u32 = self.pixels_per_region().into();
        tile_size * region_size_in_map_tile_in_pixels
    }

    /// returns the lower left (lowest coordinate for each axis) coordinate of
    /// the map tile containing the given grid coordinates at this zoom level
    ///
    /// That is the coordinates used for the file name of the map tile at this
    /// zoom level that contains the region (or gap where a region could be)
    /// given by the grid coordinates
    #[must_use]
    pub fn map_tile_corner(&self, GridCoordinates { x, y }: &GridCoordinates) -> GridCoordinates {
        let tile_size = self.tile_size();
        #[expect(
            clippy::arithmetic_side_effects,
            reason = "remainder should not have any side-effects since tile_size is never 0 (no division by zero issues) or negative (no issues with x or y being e.g. i16::MIN which overflows when the sign is flipped)"
        )]
        GridCoordinates {
            x: x.saturating_sub(x % tile_size),
            y: y.saturating_sub(y % tile_size),
        }
    }

    /// returns the size of a region in pixels in a map tile of this zoom level
    ///
    /// The size applies to both dimensions equally since both regions and map tiles
    /// are square
    #[must_use]
    pub fn pixels_per_region(&self) -> u16 {
        let exponent: u32 = self.into_inner().into();
        let exponent = exponent.saturating_sub(1);
        let exponent = 8u32.saturating_sub(exponent);
        2u16.pow(exponent)
    }

    /// returns the number of pixels per meter at this zoom level
    #[must_use]
    pub fn pixels_per_meter(&self) -> f32 {
        f32::from(self.pixels_per_region()) / 256f32
    }

    /// returns the zoom level that is the highest zoom level that makes sense
    /// to use if we want to fit a given area of regions into a given image size
    /// assuming we want to always have one map tile pixel on one output pixel
    ///
    /// # Errors
    ///
    /// returns an error if any of the parameters are zero or in the (theoretically
    /// impossible if the algorithm is correct) case that ZoomLevel::try_new()
    /// returns an error on the calculated value
    pub fn max_zoom_level_to_fit_regions_into_output_image(
        region_x: u16,
        region_y: u16,
        output_x: u32,
        output_y: u32,
    ) -> Result<Self, ZoomFitError> {
        if region_x == 0 {
            return Err(ZoomFitError::RegionSizeXZero);
        }
        if region_y == 0 {
            return Err(ZoomFitError::RegionSizeYZero);
        }
        if output_x == 0 {
            return Err(ZoomFitError::OutputSizeXZero);
        }
        if output_y == 0 {
            return Err(ZoomFitError::OutputSizeYZero);
        }
        let output_pixels_per_region_x: u32 = output_x.div_ceil(region_x.into());
        let output_pixels_per_region_y: u32 = output_y.div_ceil(region_y.into());
        let max_zoom_level_x: u8 = 9u8.saturating_sub(std::cmp::min(
            8,
            output_pixels_per_region_x
                .ilog2()
                .try_into()
                .map_err(ZoomFitError::LogarithmConversionError)?,
        ));
        let max_zoom_level_y: u8 = 9u8.saturating_sub(std::cmp::min(
            8,
            output_pixels_per_region_y
                .ilog2()
                .try_into()
                .map_err(ZoomFitError::LogarithmConversionError)?,
        ));
        Ok(Self::try_new(std::cmp::max(
            max_zoom_level_x,
            max_zoom_level_y,
        ))?)
    }
}

/// describes a map tile
#[derive(Debug, Clone, Hash, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[expect(
    clippy::module_name_repetitions,
    reason = "the type is used outside this module"
)]
pub struct MapTileDescriptor {
    /// the zoom level of the map tile
    zoom_level: ZoomLevel,
    /// the lower left corner of the map tile
    lower_left_corner: GridCoordinates,
}

impl MapTileDescriptor {
    /// create a new `MapTileDescriptor`
    ///
    /// this will automatically normalize the given `GridCoordinates` to the
    /// lower left corner of a map tile at that zoom level
    #[must_use]
    pub fn new(zoom_level: ZoomLevel, grid_coordinates: GridCoordinates) -> Self {
        let lower_left_corner = zoom_level.map_tile_corner(&grid_coordinates);
        Self {
            zoom_level,
            lower_left_corner,
        }
    }

    /// the `ZoomLevel` of the map tile
    #[must_use]
    pub const fn zoom_level(&self) -> &ZoomLevel {
        &self.zoom_level
    }

    /// the `GridCoordinates` of the lower left corner of this map tile
    #[must_use]
    pub const fn lower_left_corner(&self) -> &GridCoordinates {
        &self.lower_left_corner
    }

    /// the size of this map tile in regions
    #[must_use]
    pub fn tile_size(&self) -> u16 {
        self.zoom_level.tile_size()
    }

    /// the size of this map tile in pixels
    #[must_use]
    pub fn tile_size_in_pixels(&self) -> u32 {
        self.zoom_level.tile_size_in_pixels()
    }

    /// the grid rectangle covered by this map tile
    #[must_use]
    pub fn grid_rectangle(&self) -> GridRectangle {
        GridRectangle::new(
            self.lower_left_corner,
            GridCoordinates::new(
                self.lower_left_corner
                    .x()
                    .saturating_add(self.zoom_level.tile_size())
                    .saturating_sub(1),
                self.lower_left_corner
                    .y()
                    .saturating_add(self.zoom_level.tile_size())
                    .saturating_sub(1),
            ),
        )
    }
}

/// A waypoint in the Universal Sailor Buddy (USB) notecard format
#[derive(Debug, Clone)]
pub struct USBWaypoint {
    /// the location of the waypoint
    location: Location,
    /// the comment for the waypoint if any
    comment: Option<String>,
}

impl USBWaypoint {
    /// Create a new USB waypoint
    #[must_use]
    pub const fn new(location: Location, comment: Option<String>) -> Self {
        Self { location, comment }
    }

    /// get the location of the waypoint
    #[must_use]
    pub const fn location(&self) -> &Location {
        &self.location
    }

    /// get the region coordinates of the waypoint
    #[must_use]
    pub fn region_coordinates(&self) -> RegionCoordinates {
        RegionCoordinates::new(
            f32::from(self.location.x()),
            f32::from(self.location.y()),
            f32::from(self.location.z()),
        )
    }

    /// get the comment for the waypoint if any
    #[must_use]
    pub const fn comment(&self) -> Option<&String> {
        self.comment.as_ref()
    }
}

impl std::fmt::Display for USBWaypoint {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.location.as_maps_url())?;
        if let Some(comment) = &self.comment {
            write!(f, ",{comment}")?;
        }
        Ok(())
    }
}

impl std::str::FromStr for USBWaypoint {
    type Err = LocationParseError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        if let Some((location, comment)) = s.split_once(',') {
            Ok(Self {
                location: location.parse()?,
                comment: Some(comment.to_owned()),
            })
        } else {
            Ok(Self {
                location: s.parse()?,
                comment: None,
            })
        }
    }
}

/// An Universal Sailor Buddy (USB) notecard
#[derive(Debug, Clone)]
pub struct USBNotecard {
    /// the waypoints in the notecard
    waypoints: Vec<USBWaypoint>,
}

/// Errors that can happen when an USB notecard is read from a file
#[derive(Debug, thiserror::Error, strum::EnumIs)]
pub enum USBNotecardLoadError {
    /// I/O errors opening or reading the file
    #[error("I/O error opening or reading the file: {0}")]
    Io(#[from] std::io::Error),
    /// Parse error deserializing the USB notecard lines
    #[error("parse error deserializing the USB notecard lines: {0}")]
    LocationParseError(#[from] LocationParseError),
}

impl USBNotecard {
    /// Create a new USB notecard
    #[must_use]
    pub const fn new(waypoints: Vec<USBWaypoint>) -> Self {
        Self { waypoints }
    }

    /// get the waypoints in the notecard
    #[must_use]
    pub fn waypoints(&self) -> &[USBWaypoint] {
        &self.waypoints
    }

    /// load an USB Notecard from a text file
    ///
    /// # Errors
    ///
    /// this returns an error if either reading the file or parsing the content
    /// as a `USBNotecard` fail
    pub fn load_from_file(filename: &std::path::Path) -> Result<Self, USBNotecardLoadError> {
        let contents = std::fs::read_to_string(filename)?;
        Ok(contents.parse()?)
    }
}

impl std::fmt::Display for USBNotecard {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        for waypoint in &self.waypoints {
            writeln!(f, "{waypoint}")?;
        }
        Ok(())
    }
}

impl std::str::FromStr for USBNotecard {
    type Err = LocationParseError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        s.lines()
            .map(|line| line.parse::<USBWaypoint>())
            .collect::<Result<Vec<_>, _>>()
            .map(|waypoints| Self { waypoints })
    }
}

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

    #[test]
    fn test_parse_location_bare() -> Result<(), Box<dyn std::error::Error>> {
        assert_eq!(
            "Beach%20Valley/110/67/24".parse::<Location>(),
            Ok(Location {
                region_name: RegionName::try_new("Beach Valley")?,
                x: 110,
                y: 67,
                z: 24
            }),
        );
        Ok(())
    }

    #[test]
    fn test_parse_location_url_maps() -> Result<(), Box<dyn std::error::Error>> {
        assert_eq!(
            "http://maps.secondlife.com/secondlife/Beach%20Valley/110/67/24".parse::<Location>(),
            Ok(Location {
                region_name: RegionName::try_new("Beach Valley")?,
                x: 110,
                y: 67,
                z: 24
            }),
        );
        Ok(())
    }

    #[test]
    fn test_parse_location_url_slurl() -> Result<(), Box<dyn std::error::Error>> {
        assert_eq!(
            "http://slurl.com/secondlife/Beach%20Valley/110/67/24".parse::<Location>(),
            Ok(Location {
                region_name: RegionName::try_new("Beach Valley")?,
                x: 110,
                y: 67,
                z: 24
            }),
        );
        Ok(())
    }

    #[test]
    fn test_parse_location_bare_with_usb_comment() -> Result<(), Box<dyn std::error::Error>> {
        assert_eq!(
            "Beach%20Valley/110/67/24,MUSTER".parse::<Location>(),
            Ok(Location {
                region_name: RegionName::try_new("Beach Valley")?,
                x: 110,
                y: 67,
                z: 24
            }),
        );
        Ok(())
    }

    #[test]
    fn test_grid_rectangle_intersection_upper_right_corner()
    -> Result<(), Box<dyn std::error::Error>> {
        let rect1 = GridRectangle::new(GridCoordinates::new(10, 10), GridCoordinates::new(20, 20));
        let rect2 = GridRectangle::new(GridCoordinates::new(15, 15), GridCoordinates::new(25, 25));
        assert_eq!(
            rect1.intersect(&rect2),
            Some(GridRectangle::new(
                GridCoordinates::new(15, 15),
                GridCoordinates::new(20, 20),
            ))
        );
        Ok(())
    }

    #[test]
    fn test_grid_rectangle_intersection_upper_left_corner() -> Result<(), Box<dyn std::error::Error>>
    {
        let rect1 = GridRectangle::new(GridCoordinates::new(10, 10), GridCoordinates::new(20, 20));
        let rect2 = GridRectangle::new(GridCoordinates::new(5, 15), GridCoordinates::new(15, 25));
        assert_eq!(
            rect1.intersect(&rect2),
            Some(GridRectangle::new(
                GridCoordinates::new(10, 15),
                GridCoordinates::new(15, 20),
            ))
        );
        Ok(())
    }

    #[test]
    fn test_grid_rectangle_intersection_lower_left_corner() -> Result<(), Box<dyn std::error::Error>>
    {
        let rect1 = GridRectangle::new(GridCoordinates::new(10, 10), GridCoordinates::new(20, 20));
        let rect2 = GridRectangle::new(GridCoordinates::new(5, 5), GridCoordinates::new(15, 15));
        assert_eq!(
            rect1.intersect(&rect2),
            Some(GridRectangle::new(
                GridCoordinates::new(10, 10),
                GridCoordinates::new(15, 15),
            ))
        );
        Ok(())
    }

    #[test]
    fn test_grid_rectangle_intersection_lower_right_corner()
    -> Result<(), Box<dyn std::error::Error>> {
        let rect1 = GridRectangle::new(GridCoordinates::new(10, 10), GridCoordinates::new(20, 20));
        let rect2 = GridRectangle::new(GridCoordinates::new(15, 5), GridCoordinates::new(25, 15));
        assert_eq!(
            rect1.intersect(&rect2),
            Some(GridRectangle::new(
                GridCoordinates::new(15, 10),
                GridCoordinates::new(20, 15),
            ))
        );
        Ok(())
    }

    #[test]
    fn test_grid_rectangle_intersection_no_overlap() -> Result<(), Box<dyn std::error::Error>> {
        let rect1 = GridRectangle::new(GridCoordinates::new(10, 10), GridCoordinates::new(20, 20));
        let rect2 = GridRectangle::new(GridCoordinates::new(30, 30), GridCoordinates::new(40, 40));
        assert_eq!(rect1.intersect(&rect2), None);
        Ok(())
    }

    #[cfg(feature = "chumsky")]
    #[test]
    fn test_url_region_name_parser_no_whitespace() -> Result<(), Box<dyn std::error::Error>> {
        let region_name = "Viterbo";
        assert_eq!(
            url_region_name_parser().parse(region_name).into_result(),
            Ok(RegionName::try_new(region_name)?)
        );
        Ok(())
    }

    #[cfg(feature = "chumsky")]
    #[test]
    fn test_url_region_name_parser_url_whitespace() -> Result<(), Box<dyn std::error::Error>> {
        let region_name = "Da Boom";
        let input = region_name.replace(' ', "%20");
        assert_eq!(
            url_region_name_parser().parse(&input).into_result(),
            Ok(RegionName::try_new(region_name)?)
        );
        Ok(())
    }

    #[cfg(feature = "chumsky")]
    #[test]
    fn test_region_name_parser_whitespace() -> Result<(), Box<dyn std::error::Error>> {
        let region_name = "Da Boom";
        assert_eq!(
            region_name_parser().parse(region_name).into_result(),
            Ok(RegionName::try_new(region_name)?)
        );
        Ok(())
    }

    #[cfg(feature = "chumsky")]
    #[test]
    fn test_url_location_parser_no_whitespace() -> Result<(), Box<dyn std::error::Error>> {
        let region_name = "Viterbo";
        let input = format!("{region_name}/1/2/300");
        assert_eq!(
            url_location_parser().parse(&input).into_result(),
            Ok(Location {
                region_name: RegionName::try_new(region_name)?,
                x: 1,
                y: 2,
                z: 300
            })
        );
        Ok(())
    }

    #[cfg(feature = "chumsky")]
    #[test]
    fn test_url_location_parser_url_whitespace() -> Result<(), Box<dyn std::error::Error>> {
        let region_name = "Da Boom";
        let input = format!("{}/1/2/300", region_name.replace(' ', "%20"));
        assert_eq!(
            url_location_parser().parse(&input).into_result(),
            Ok(Location {
                region_name: RegionName::try_new(region_name)?,
                x: 1,
                y: 2,
                z: 300
            })
        );
        Ok(())
    }

    #[cfg(feature = "chumsky")]
    #[test]
    fn test_url_location_parser_url_whitespace_single_digit_after_space()
    -> Result<(), Box<dyn std::error::Error>> {
        let region_name = "Foo Bar 3";
        let input = format!("{}/1/2/300", region_name.replace(' ', "%20"));
        assert_eq!(
            url_location_parser().parse(&input).into_result(),
            Ok(Location {
                region_name: RegionName::try_new(region_name)?,
                x: 1,
                y: 2,
                z: 300
            })
        );
        Ok(())
    }

    #[cfg(feature = "chumsky")]
    #[test]
    fn test_region_coordinates_parser() -> Result<(), Box<dyn std::error::Error>> {
        assert_eq!(
            region_coordinates_parser()
                .parse("{ 63.0486, 45.2515, 1501.08 }")
                .into_result(),
            Ok(RegionCoordinates {
                x: 63.0486,
                y: 45.2515,
                z: 1501.08,
            })
        );
        Ok(())
    }
}