geolith-dataset-builder 0.2.2

Raster datasets for geolith: district areas, normals, numbers and a map layer per period, and the steps that stage, verify and publish them to any S3-compatible bucket
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
//! Shared-border simplification of a polygon coverage (the district areas).
//!
//! The areas and gap pieces tile the land of a country edge to edge. Simplified
//! one polygon at a time, a border two neighbours share is simplified twice,
//! differently, and the tiles show gaps, overlaps and crossing rings. Here the
//! borders are built once as shared arcs and each arc is simplified once per
//! zoom, so both neighbours get the same simplified border:
//!
//! 1. Every vertex goes to a fine grid ([`FINE_BITS`] bits per world unit,
//!    about 4 cm at the equator). Vertices of different features closer than
//!    [`NODE_TOLERANCE`] fine units merge, and a vertex of one feature that
//!    lies within that tolerance of another feature's unshared edge is added to
//!    that edge, so near-coincident borders share their vertices.
//! 2. Rings are split into arcs at the nodes: vertices with other than two
//!    neighbours, or where the features on the two edges change. An arc shared
//!    by two features is stored once; a ring without a node is one closed arc.
//! 3. Per zoom (MVT units of that zoom, 4096 per tile, one grid for every
//!    tile), each arc is simplified with Douglas–Peucker at
//!    [`SIMPLIFY_UNITS`], its ends fixed. An arc that then crosses or touches
//!    itself or another arc anywhere but at a node is simplified again at
//!    half the tolerance, down to the source points.
//! 4. The arcs are snap-rounded to the grid (hot cells, see `snap_round`):
//!    no two segments cross on the grid; a sliver thinner than a cell
//!    collapses, and two arcs then share a segment.
//! 5. Each ring is rebuilt from its arcs; a ring that collapses to no area at a
//!    zoom is left out at that zoom. Exteriors run with positive area and holes
//!    with negative, so the tile cut (positive winding) gives a lobe where a
//!    border loops on itself to one side only.

use std::collections::{BTreeSet, HashMap, HashSet};

use geo::{LineString, Polygon};
use geolith::geometry::mercator::{MAX_LAT, MIN_LAT, wgs84_to_world};
use geolith::tile::feature::TILE_EXTENT;
use rstar::primitives::GeomWithData;
use rstar::{AABB, RTree};

/// A point on an integer grid.
pub type Pt = (i64, i64);

/// Bits of the fine grid per world unit (0..1).
pub const FINE_BITS: u32 = 30;

/// Vertices of different features this close (fine units, about 30 cm at the
/// equator) are one vertex; a vertex this close to another feature's unshared
/// edge is added to it.
///
/// Far below a pixel at any tiled zoom.
pub const NODE_TOLERANCE: i64 = 8;

/// Douglas–Peucker tolerance of an arc, in MVT units of its zoom (4096 per
/// tile): half a pixel of a 512 px display tile.
pub const SIMPLIFY_UNITS: f64 = 4.0;

/// Smallest tolerance a crossing arc is simplified at (MVT units): below a
/// unit the grid itself, not the simplification, makes the crossing.
pub const MIN_SIMPLIFY_UNITS: f64 = 1.0;

/// Highest zoom the fine grid can serve (MVT units must be whole fine units).
pub const MAX_ZOOM: u8 = (FINE_BITS - 12) as u8;

/// Rounds of re-simplification of crossing arcs.
const REPAIR_ROUNDS: usize = 8;

/// Grid cell of the crossing search, in zoom units.
const SEARCH_CELL: i64 = 64;

/// One use of an arc by a ring.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct ArcUse {
    arc: usize,
    reversed: bool,
}

/// A ring of the source, open (no closing point).
struct SourceRing {
    feature: u32,
    points: Vec<Pt>,
}

/// Counts of the border build, for the log and the report.
#[derive(Debug, Clone, Copy, Default, PartialEq)]
pub struct BorderStats {
    /// Edge length (fine units) shared exactly by two features, before and
    /// after merging near-coincident vertices.
    pub shared_before: f64,
    /// See `shared_before`.
    pub shared_after: f64,
    /// Total edge length (each shared edge counted once).
    pub total_before: f64,
    /// See `total_before`.
    pub total_after: f64,
    /// Vertices moved onto a vertex of another feature.
    pub merged: usize,
    /// Vertices added to an unshared edge.
    pub inserted: usize,
    /// Arcs.
    pub arcs: usize,
    /// Nodes (arc ends).
    pub nodes: usize,
}

/// Counts of one zoom of [`Coverage::rings_at_zoom`].
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct ZoomStats {
    /// Vertices of all arcs after simplification.
    pub vertices: usize,
    /// Arcs simplified at a smaller tolerance to stop a crossing.
    pub repaired: usize,
    /// Arcs still crossing or touching after the last round (only the bare
    /// grid points were left to give).
    pub crossing: usize,
    /// Rings left out because they have no area at this zoom.
    pub dropped_rings: usize,
}

/// Rings of one feature at one zoom: polygons, each exterior then holes,
/// open rings in the zoom's integer grid.
pub type FeatureRings = Vec<Vec<Vec<Pt>>>;

/// The features as shared arcs.
pub struct Coverage {
    /// Arcs on the fine grid; a closed arc ends at its first point.
    arcs: Vec<Vec<Pt>>,
    /// Per feature, per polygon, per ring (exterior first): its arcs.
    features: Vec<Vec<Vec<Vec<ArcUse>>>>,
    /// Counts of the build.
    pub stats: BorderStats,
}

/// `(x, y)` of WGS84 `(lon, lat)` on the fine grid.
fn to_fine(lon: f64, lat: f64) -> Pt {
    let (x, y) = wgs84_to_world(lon, lat.clamp(MIN_LAT, MAX_LAT));
    let scale = f64::from(1_u32 << FINE_BITS);
    ((x * scale).round() as i64, (y * scale).round() as i64)
}

/// `ring` on the fine grid, open, without repeated points.
fn fine_ring(ring: &LineString<f64>) -> Vec<Pt> {
    let mut points: Vec<Pt> = ring.0.iter().map(|c| to_fine(c.x, c.y)).collect();
    points.dedup();
    while points.len() > 1 && points.first() == points.last() {
        points.pop();
    }
    points
}

/// Remove consecutive repeats, the closing one included.
fn dedup_ring(points: &mut Vec<Pt>) {
    points.dedup();
    while points.len() > 1 && points.first() == points.last() {
        points.pop();
    }
}

/// `(a, b)` with the smaller point first.
fn edge_key(a: Pt, b: Pt) -> (Pt, Pt) {
    if a <= b { (a, b) } else { (b, a) }
}

fn length(a: Pt, b: Pt) -> f64 {
    ((b.0 - a.0) as f64).hypot((b.1 - a.1) as f64)
}

/// The features on each edge of `rings`, sorted, with repeats.
fn edge_features(rings: &[SourceRing]) -> HashMap<(Pt, Pt), Vec<u32>> {
    let mut edges: HashMap<(Pt, Pt), Vec<u32>> = HashMap::new();
    for ring in rings {
        let n = ring.points.len();
        for i in 0..n {
            let key = edge_key(ring.points[i], ring.points[(i + 1) % n]);
            edges.entry(key).or_default().push(ring.feature);
        }
    }
    for features in edges.values_mut() {
        features.sort_unstable();
    }
    edges
}

/// Shared and total edge length.
fn share(edges: &HashMap<(Pt, Pt), Vec<u32>>) -> (f64, f64) {
    let (mut shared, mut total) = (0.0, 0.0);
    for (&(a, b), features) in edges {
        let len = length(a, b);
        total += len;
        if features.len() >= 2 {
            shared += len;
        }
    }
    (shared, total)
}

/// Vertices at an end of an unshared edge, with their feature, sorted.
fn loose_vertices(rings: &[SourceRing], edges: &HashMap<(Pt, Pt), Vec<u32>>) -> Vec<(Pt, u32)> {
    let mut loose: Vec<(Pt, u32)> = Vec::new();
    for ring in rings {
        let n = ring.points.len();
        for i in 0..n {
            let (a, b) = (ring.points[i], ring.points[(i + 1) % n]);
            if edges.get(&edge_key(a, b)).is_some_and(|f| f.len() == 1) {
                loose.push((a, ring.feature));
                loose.push((b, ring.feature));
            }
        }
    }
    loose.sort_unstable();
    loose.dedup();
    loose
}

type Indexed = GeomWithData<[i64; 2], usize>;

fn index(loose: &[(Pt, u32)]) -> RTree<Indexed> {
    RTree::bulk_load(
        loose
            .iter()
            .enumerate()
            .map(|(i, &((x, y), _))| GeomWithData::new([x, y], i))
            .collect(),
    )
}

const fn find(parent: &mut [usize], mut i: usize) -> usize {
    while parent[i] != i {
        parent[i] = parent[parent[i]];
        i = parent[i];
    }
    i
}

/// Merge vertices of different features closer than [`NODE_TOLERANCE`];
/// returns the number of vertices moved.
fn merge_vertices(rings: &mut [SourceRing]) -> usize {
    let edges = edge_features(rings);
    let loose = loose_vertices(rings, &edges);
    let tree = index(&loose);
    let mut parent: Vec<usize> = (0..loose.len()).collect();
    let t = NODE_TOLERANCE;
    for (i, &((x, y), feature)) in loose.iter().enumerate() {
        let envelope = AABB::from_corners([x - t, y - t], [x + t, y + t]);
        for near in tree.locate_in_envelope(envelope) {
            let j = near.data;
            let ((nx, ny), other) = loose[j];
            if other == feature || (nx - x).pow(2) + (ny - y).pow(2) > t * t {
                continue;
            }
            let (ri, rj) = (find(&mut parent, i), find(&mut parent, j));
            if ri != rj {
                parent[ri.max(rj)] = ri.min(rj);
            }
        }
    }
    // `loose` is sorted, so the root (the smallest index) is the smallest point.
    let mut remap: HashMap<Pt, Pt> = HashMap::new();
    for i in 0..loose.len() {
        let root = find(&mut parent, i);
        if loose[root].0 != loose[i].0 {
            remap.insert(loose[i].0, loose[root].0);
        }
    }
    let mut moved = 0;
    for ring in rings.iter_mut() {
        for p in &mut ring.points {
            if let Some(&to) = remap.get(p) {
                *p = to;
                moved += 1;
            }
        }
        dedup_ring(&mut ring.points);
    }
    moved
}

/// Add to every unshared edge the vertices of other features within
/// [`NODE_TOLERANCE`] of it; returns the number of vertices added.
fn insert_vertices(rings: &mut [SourceRing]) -> usize {
    let edges = edge_features(rings);
    let loose = loose_vertices(rings, &edges);
    let tree = index(&loose);
    let t = NODE_TOLERANCE as f64;
    let mut added = 0;
    for ring in rings.iter_mut() {
        let n = ring.points.len();
        let mut out: Vec<Pt> = Vec::with_capacity(n);
        for i in 0..n {
            let (a, b) = (ring.points[i], ring.points[(i + 1) % n]);
            out.push(a);
            if !edges.get(&edge_key(a, b)).is_some_and(|f| f.len() == 1) {
                continue;
            }
            let tl = NODE_TOLERANCE;
            let envelope = AABB::from_corners(
                [a.0.min(b.0) - tl, a.1.min(b.1) - tl],
                [a.0.max(b.0) + tl, a.1.max(b.1) + tl],
            );
            let (dx, dy) = ((b.0 - a.0) as f64, (b.1 - a.1) as f64);
            let len2 = dx * dx + dy * dy;
            if len2 == 0.0 {
                continue;
            }
            let mut on: Vec<(f64, Pt)> = tree
                .locate_in_envelope(envelope)
                .filter_map(|near| {
                    let (p, feature) = loose[near.data];
                    if feature == ring.feature || p == a || p == b {
                        return None;
                    }
                    let (px, py) = ((p.0 - a.0) as f64, (p.1 - a.1) as f64);
                    let s = (px * dx + py * dy) / len2;
                    if s <= 0.0 || s >= 1.0 {
                        return None;
                    }
                    let d = (px * dy - py * dx).abs() / len2.sqrt();
                    (d <= t).then_some((s, p))
                })
                .collect();
            on.sort_by(|x, y| x.0.total_cmp(&y.0).then(x.1.cmp(&y.1)));
            on.dedup_by(|x, y| x.1 == y.1);
            added += on.len();
            out.extend(on.into_iter().map(|(_, p)| p));
        }
        dedup_ring(&mut out);
        ring.points = out;
    }
    added
}

impl Coverage {
    /// The shared arcs of `features`: per feature, its polygons (lon/lat).
    #[must_use]
    pub fn build(features: &[Vec<&Polygon<f64>>]) -> Self {
        // Where each source ring goes: (feature, polygon, ring) by position.
        let mut slots: Vec<(usize, usize, usize)> = Vec::new();
        let mut rings: Vec<SourceRing> = Vec::new();
        for (f, polygons) in features.iter().enumerate() {
            for (p, polygon) in polygons.iter().enumerate() {
                let all = std::iter::once(polygon.exterior()).chain(polygon.interiors());
                for (r, ring) in all.enumerate() {
                    slots.push((f, p, r));
                    rings.push(SourceRing {
                        feature: f as u32,
                        points: fine_ring(ring),
                    });
                }
            }
        }
        let (shared_before, total_before) = share(&edge_features(&rings));
        let merged = merge_vertices(&mut rings);
        let inserted = insert_vertices(&mut rings);
        let edges = edge_features(&rings);
        let (shared_after, total_after) = share(&edges);

        // Nodes: other than two neighbours, or the features change.
        let mut neighbours: HashMap<Pt, Vec<Pt>> = HashMap::new();
        for &(a, b) in edges.keys() {
            neighbours.entry(a).or_default().push(b);
            neighbours.entry(b).or_default().push(a);
        }
        let is_node = |p: Pt| match neighbours.get(&p).map(Vec::as_slice) {
            Some(&[n0, n1]) => edges.get(&edge_key(p, n0)) != edges.get(&edge_key(p, n1)),
            _ => true,
        };

        let mut arcs: Vec<Vec<Pt>> = Vec::new();
        let mut lookup: HashMap<(Pt, Pt), ArcUse> = HashMap::new();
        let mut nodes: BTreeSet<Pt> = BTreeSet::new();
        let mut uses_of: Vec<Vec<ArcUse>> = Vec::with_capacity(rings.len());
        for ring in &rings {
            let points = &ring.points;
            let n = points.len();
            if n < 3 {
                uses_of.push(Vec::new());
                continue;
            }
            let starts: Vec<usize> = (0..n).filter(|&i| is_node(points[i])).collect();
            // Pieces, each with whether it runs against the ring.
            let mut pieces: Vec<(Vec<Pt>, bool)> = Vec::new();
            if let Some(&first) = starts.first() {
                nodes.extend(starts.iter().map(|&i| points[i]));
                let mut piece = vec![points[first]];
                for k in 1..=n {
                    let p = points[(first + k) % n];
                    piece.push(p);
                    if is_node(p) {
                        pieces.push((std::mem::replace(&mut piece, vec![p]), false));
                    }
                }
            } else {
                // A closed arc starts at its smallest point.
                let start = (0..n).min_by_key(|&i| points[i]).unwrap_or(0);
                let mut piece: Vec<Pt> = (0..=n).map(|k| points[(start + k) % n]).collect();
                // Both directions start at the start: run towards the
                // smaller second point so the two rings agree.
                let flipped = piece[n - 1] < piece[1];
                if flipped {
                    piece.reverse();
                }
                pieces.push((piece, flipped));
            }
            let mut uses = Vec::with_capacity(pieces.len());
            for (piece, flipped) in pieces {
                let m = piece.len();
                let key = (piece[0], piece[1]);
                let found = lookup.get(&key).copied().filter(|u| {
                    let arc = &arcs[u.arc];
                    arc.len() == m
                        && if u.reversed {
                            arc.iter().rev().eq(piece.iter())
                        } else {
                            *arc == piece
                        }
                });
                let used = if let Some(u) = found {
                    u
                } else {
                    let arc = arcs.len();
                    lookup.entry(key).or_insert(ArcUse {
                        arc,
                        reversed: false,
                    });
                    lookup
                        .entry((piece[m - 1], piece[m - 2]))
                        .or_insert(ArcUse {
                            arc,
                            reversed: true,
                        });
                    arcs.push(piece);
                    ArcUse {
                        arc,
                        reversed: false,
                    }
                };
                uses.push(ArcUse {
                    arc: used.arc,
                    reversed: used.reversed != flipped,
                });
            }
            uses_of.push(uses);
        }

        let mut out: Vec<Vec<Vec<Vec<ArcUse>>>> = features
            .iter()
            .map(|polygons| {
                polygons
                    .iter()
                    .map(|p| vec![Vec::new(); 1 + p.interiors().len()])
                    .collect()
            })
            .collect();
        // Exteriors run with positive area, holes with negative, so a lobe
        // where a simplified border loops goes to one side only (the tile cut
        // fills by positive winding).
        for ((&(f, p, r), mut uses), ring) in slots.iter().zip(uses_of).zip(&rings) {
            if (area2(&ring.points) > 0) != (r == 0) {
                uses.reverse();
                for u in &mut uses {
                    u.reversed = !u.reversed;
                }
            }
            out[f][p][r] = uses;
        }
        let stats = BorderStats {
            shared_before,
            shared_after,
            total_before,
            total_after,
            merged,
            inserted,
            arcs: arcs.len(),
            nodes: nodes.len(),
        };
        Self {
            arcs,
            features: out,
            stats,
        }
    }

    /// The arcs at zoom `z` on its grid, with the number of arcs simplified
    /// again to stop a crossing and the number of segment pairs still crossing
    /// on the grid (0 unless the source itself crosses).
    fn simplified_arcs(&self, z: u8) -> (Vec<Vec<Pt>>, usize, usize) {
        let shift = FINE_BITS - 12 - u32::from(z.min(MAX_ZOOM));
        let unsnapped: Vec<Vec<Fp>> = self.arcs.iter().map(|a| zoom_arc(a, shift)).collect();
        let mut tolerance = vec![SIMPLIFY_UNITS; unsnapped.len()];
        let mut simplified: Vec<Vec<Fp>> = unsnapped
            .iter()
            .map(|a| simplify_arc(a, SIMPLIFY_UNITS))
            .collect();
        let mut repaired: BTreeSet<usize> = BTreeSet::new();
        for _ in 0..REPAIR_ROUNDS {
            let crossing = crossing_arcs(&simplified);
            let mut changed = false;
            for &arc in &crossing {
                if tolerance[arc] > 0.0 {
                    tolerance[arc] = if tolerance[arc] <= MIN_SIMPLIFY_UNITS {
                        0.0
                    } else {
                        tolerance[arc] / 2.0
                    };
                    simplified[arc] = simplify_arc(&unsnapped[arc], tolerance[arc]);
                    repaired.insert(arc);
                    changed = true;
                }
            }
            if !changed {
                break;
            }
        }
        let snapped = snap_round(&simplified);
        let crossing = proper_crossings(&snapped);
        (snapped, repaired.len(), crossing)
    }

    /// The rings of every feature at zoom `z` (at most [`MAX_ZOOM`]), on the
    /// zoom's integer grid: `x = world_x * 2^z * 4096`.
    #[must_use]
    pub fn rings_at_zoom(&self, z: u8) -> (Vec<FeatureRings>, ZoomStats) {
        let (simplified, repaired, crossing) = self.simplified_arcs(z);
        let mut stats = ZoomStats {
            vertices: simplified.iter().map(Vec::len).sum(),
            repaired,
            crossing,
            dropped_rings: 0,
        };
        let features = self
            .features
            .iter()
            .map(|polygons| {
                let mut out: FeatureRings = Vec::new();
                for rings in polygons {
                    let built: Vec<Vec<Pt>> = rings
                        .iter()
                        .map(|uses| assemble(&simplified, uses))
                        .collect();
                    let has_area = |ring: &Vec<Pt>| ring.len() >= 3 && area2(ring) != 0;
                    // A polygon whose exterior has no area goes, holes too.
                    if !built.first().is_some_and(has_area) {
                        stats.dropped_rings += built.len();
                        continue;
                    }
                    let kept: Vec<Vec<Pt>> = built.into_iter().filter(has_area).collect();
                    stats.dropped_rings += rings.len() - kept.len();
                    out.push(kept);
                }
                out
            })
            .collect();
        (features, stats)
    }
}

/// A point in zoom units, not yet on the grid.
type Fp = [f64; 2];

/// `arc` (fine units) in zoom units of `2^shift` fine units, repeats removed.
fn zoom_arc(arc: &[Pt], shift: u32) -> Vec<Fp> {
    let unit = f64::from(1_u32 << shift);
    let mut out: Vec<Fp> = arc
        .iter()
        .map(|&(x, y)| [x as f64 / unit, y as f64 / unit])
        .collect();
    out.dedup();
    out
}

/// Distance of `p` from the segment `a`–`b`.
fn segment_distance(p: Fp, a: Fp, b: Fp) -> f64 {
    let (dx, dy) = (b[0] - a[0], b[1] - a[1]);
    let (px, py) = (p[0] - a[0], p[1] - a[1]);
    let len2 = dx * dx + dy * dy;
    if len2 == 0.0 {
        return px.hypot(py);
    }
    let s = ((px * dx + py * dy) / len2).clamp(0.0, 1.0);
    (px - s * dx).hypot(py - s * dy)
}

/// Douglas–Peucker keep flags of `points[from..=to]` at `tolerance`.
fn douglas_peucker(points: &[Fp], from: usize, to: usize, tolerance: f64, keep: &mut [bool]) {
    let mut stack = vec![(from, to)];
    while let Some((i, j)) = stack.pop() {
        if j <= i + 1 {
            continue;
        }
        let (mut far, mut far_d) = (i, -1.0);
        for k in i + 1..j {
            let d = segment_distance(points[k], points[i], points[j]);
            if d > far_d {
                (far, far_d) = (k, d);
            }
        }
        if far_d > tolerance {
            keep[far] = true;
            stack.push((i, far));
            stack.push((far, j));
        }
    }
}

/// Drop the tip of every spike (a point where the path turns straight back)
/// and repeated points, the ends kept.
fn despike(points: Vec<Pt>) -> Vec<Pt> {
    let mut out: Vec<Pt> = Vec::with_capacity(points.len());
    for p in points {
        if out.last() == Some(&p) {
            continue;
        }
        out.push(p);
        while out.len() >= 3 {
            let n = out.len();
            let (a, b, c) = (out[n - 3], out[n - 2], out[n - 1]);
            let back = (i128::from(b.0 - a.0) * i128::from(c.1 - a.1)
                == i128::from(b.1 - a.1) * i128::from(c.0 - a.0))
                && (b.0 - a.0) * (c.0 - b.0) + (b.1 - a.1) * (c.1 - b.1) <= 0;
            if !back {
                break;
            }
            out.remove(n - 2);
            if out[n - 3] == out[n - 2] {
                out.pop();
            }
        }
    }
    out
}

/// `arc` (zoom units) simplified at `tolerance`, its ends kept. A closed arc
/// keeps at least three points besides its closing one when it has them.
fn simplify_arc(arc: &[Fp], tolerance: f64) -> Vec<Fp> {
    let n = arc.len();
    if n <= 2 {
        return arc.to_vec();
    }
    let mut keep = vec![false; n];
    keep[0] = true;
    keep[n - 1] = true;
    if arc[0] == arc[n - 1] {
        // Closed: split at the point farthest from the start.
        let dist = |k: usize| (arc[k][0] - arc[0][0]).hypot(arc[k][1] - arc[0][1]);
        let far = (1..n - 1)
            .max_by(|&a, &b| dist(a).total_cmp(&dist(b)).then(b.cmp(&a)))
            .unwrap_or(1);
        keep[far] = true;
        douglas_peucker(arc, 0, far, tolerance, &mut keep);
        douglas_peucker(arc, far, n - 1, tolerance, &mut keep);
        if keep.iter().filter(|&&k| k).count() < 4 && n >= 4 {
            let side = |k: usize| segment_distance(arc[k], arc[0], arc[far]);
            let third = (1..n - 1)
                .filter(|&k| k != far)
                .max_by(|&a, &b| side(a).total_cmp(&side(b)).then(b.cmp(&a)))
                .unwrap_or(far);
            keep[third] = true;
        }
    } else {
        douglas_peucker(arc, 0, n - 1, tolerance, &mut keep);
    }
    arc.iter()
        .zip(keep)
        .filter_map(|(&p, k)| k.then_some(p))
        .collect()
}

/// The grid point of `p`.
const fn round(p: Fp) -> Pt {
    (p[0].round() as i64, p[1].round() as i64)
}

/// The arcs snap-rounded to the grid: a grid cell holding a vertex or a
/// point where two segments meet is hot, and every segment runs through the
/// centre of each hot cell it passes. Snap rounding leaves no two segments
/// crossing; a sliver thinner than a cell collapses (two arcs then share a
/// segment, the ring between has no area). Spikes and repeats are removed.
fn snap_round(arcs: &[Vec<Fp>]) -> Vec<Vec<Pt>> {
    let mut hot: HashSet<Pt> = arcs.iter().flatten().map(|&p| round(p)).collect();
    for_each_close_pair(arcs, |a, i, b, j| {
        let (p, q) = (arcs[a][i], arcs[a][i + 1]);
        let (r, s) = (arcs[b][j], arcs[b][j + 1]);
        if let Some(x) = crossing_point(p, q, r, s) {
            hot.insert(round(x));
        }
    });
    arcs.iter()
        .map(|arc| {
            let mut out: Vec<Pt> = Vec::with_capacity(arc.len());
            if let Some(&first) = arc.first() {
                out.push(round(first));
            }
            for w in arc.windows(2) {
                let (a, b) = (w[0], w[1]);
                // Hot cells whose closed square the segment touches, in
                // order along it.
                let mut on: Vec<(f64, Pt)> = Vec::new();
                let mut seen: HashSet<Pt> = HashSet::new();
                let mut consider = |c: Pt| {
                    for dx in -1..=1 {
                        for dy in -1..=1 {
                            let h = (c.0 + dx, c.1 + dy);
                            if !seen.insert(h) || !hot.contains(&h) || !touches_cell(a, b, h) {
                                continue;
                            }
                            on.push((projection(a, b, h), h));
                        }
                    }
                };
                consider(round(a));
                cells_along(a, b, &mut consider);
                on.sort_by(|x, y| x.0.total_cmp(&y.0).then(x.1.cmp(&y.1)));
                out.extend(on.into_iter().map(|(_, h)| h));
                out.push(round(b));
            }
            despike(out)
        })
        .collect()
}

/// Whether the segment `a`–`b` touches the closed square of cell `c`.
fn touches_cell(a: Fp, b: Fp, c: Pt) -> bool {
    let (x0, x1) = (c.0 as f64 - 0.5, c.0 as f64 + 0.5);
    let (y0, y1) = (c.1 as f64 - 0.5, c.1 as f64 + 0.5);
    // Liang–Barsky clip of the segment to the square.
    let (dx, dy) = (b[0] - a[0], b[1] - a[1]);
    let (mut t0, mut t1) = (0.0_f64, 1.0_f64);
    for (p, q) in [
        (-dx, a[0] - x0),
        (dx, x1 - a[0]),
        (-dy, a[1] - y0),
        (dy, y1 - a[1]),
    ] {
        if p == 0.0 {
            if q < 0.0 {
                return false;
            }
        } else {
            let r = q / p;
            if p < 0.0 {
                t0 = t0.max(r);
            } else {
                t1 = t1.min(r);
            }
        }
    }
    t0 <= t1
}

/// The position along `a`–`b` (0 to 1) nearest the centre of cell `c`.
fn projection(a: Fp, b: Fp, c: Pt) -> f64 {
    let (dx, dy) = (b[0] - a[0], b[1] - a[1]);
    let len2 = dx * dx + dy * dy;
    if len2 == 0.0 {
        return 0.0;
    }
    (((c.0 as f64 - a[0]) * dx + (c.1 as f64 - a[1]) * dy) / len2).clamp(0.0, 1.0)
}

/// Where the segments `p`–`q` and `r`–`s` cross inside both, if they do.
fn crossing_point(p: Fp, q: Fp, r: Fp, s: Fp) -> Option<Fp> {
    let (d1, d2) = ([q[0] - p[0], q[1] - p[1]], [s[0] - r[0], s[1] - r[1]]);
    let den = d1[0] * d2[1] - d1[1] * d2[0];
    if den == 0.0 {
        return None;
    }
    let (ex, ey) = (r[0] - p[0], r[1] - p[1]);
    let t = (ex * d2[1] - ey * d2[0]) / den;
    let u = (ex * d1[1] - ey * d1[0]) / den;
    ((0.0..=1.0).contains(&t) && (0.0..=1.0).contains(&u))
        .then(|| [p[0] + t * d1[0], p[1] + t * d1[1]])
}

/// Visit the grid cells (cell `(i, j)` holds `[i - ½, i + ½) × [j - ½, j + ½)`)
/// the segment `a`–`b` passes after the cell of `a`, up to the cell of `b`.
fn cells_along(a: Fp, b: Fp, mut visit: impl FnMut(Pt)) {
    let cell = |v: f64| (v + 0.5).floor() as i64;
    let (mut x, mut y) = (cell(a[0]), cell(a[1]));
    let (end_x, end_y) = (cell(b[0]), cell(b[1]));
    let (dx, dy) = (b[0] - a[0], b[1] - a[1]);
    let (step_x, step_y) = (dx.signum() as i64, dy.signum() as i64);
    let next = |v: i64, step: i64| v as f64 + 0.5 * step as f64;
    let mut t_x = if dx == 0.0 {
        f64::INFINITY
    } else {
        (next(x, step_x) - a[0]) / dx
    };
    let mut t_y = if dy == 0.0 {
        f64::INFINITY
    } else {
        (next(y, step_y) - a[1]) / dy
    };
    let (dt_x, dt_y) = (1.0 / dx.abs(), 1.0 / dy.abs());
    let mut left = (end_x - x).abs() + (end_y - y).abs();
    while (x, y) != (end_x, end_y) && left > 0 {
        if t_x < t_y {
            x += step_x;
            t_x += dt_x;
        } else {
            y += step_y;
            t_y += dt_y;
        }
        left -= 1;
        visit((x, y));
    }
}

/// The sign of the turn `a` → `b` → `c`.
fn orient(a: Fp, b: Fp, c: Fp) -> f64 {
    ((b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0])).signum_or_zero()
}

/// `signum` with 0 for 0.
trait SignumOrZero {
    fn signum_or_zero(self) -> f64;
}

impl SignumOrZero for f64 {
    fn signum_or_zero(self) -> f64 {
        if self == 0.0 { 0.0 } else { self.signum() }
    }
}

/// Whether `p` (collinear with `a`–`b`) lies within the segment's box.
fn within(p: Fp, a: Fp, b: Fp) -> bool {
    p[0] >= a[0].min(b[0])
        && p[0] <= a[0].max(b[0])
        && p[1] >= a[1].min(b[1])
        && p[1] <= a[1].max(b[1])
}

/// How two segments meet.
#[derive(Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum Contact {
    /// Apart.
    None,
    /// At one point that is an end of both.
    SharedEnd,
    /// Anywhere else: a crossing, a touch inside a segment, or an overlap.
    Bad,
}

/// How the segments `a`–`b` and `c`–`d` (grid points) meet.
#[must_use]
pub fn contact(a: Pt, b: Pt, c: Pt, d: Pt) -> Contact {
    let f = |p: Pt| [p.0 as f64, p.1 as f64];
    contact_f(f(a), f(b), f(c), f(d))
}

/// How the segments `a`–`b` and `c`–`d` meet.
fn contact_f(a: Fp, b: Fp, c: Fp, d: Fp) -> Contact {
    if a[0].max(b[0]) < c[0].min(d[0])
        || c[0].max(d[0]) < a[0].min(b[0])
        || a[1].max(b[1]) < c[1].min(d[1])
        || c[1].max(d[1]) < a[1].min(b[1])
    {
        return Contact::None;
    }
    let (o1, o2) = (orient(a, b, c), orient(a, b, d));
    let (o3, o4) = (orient(c, d, a), orient(c, d, b));
    if o1 * o2 > 0.0 || o3 * o4 > 0.0 {
        return Contact::None;
    }
    if o1 == 0.0 && o2 == 0.0 {
        // Collinear: an overlap unless they only share an end.
        let mut touching: Vec<Fp> = [
            (c, within(c, a, b)),
            (d, within(d, a, b)),
            (a, within(a, c, d)),
            (b, within(b, c, d)),
        ]
        .into_iter()
        .filter_map(|(p, w)| w.then_some(p))
        .collect();
        touching.sort_by(|p, q| p[0].total_cmp(&q[0]).then(p[1].total_cmp(&q[1])));
        touching.dedup();
        return match touching.as_slice() {
            [] => Contact::None,
            [p] if (*p == a || *p == b) && (*p == c || *p == d) => Contact::SharedEnd,
            _ => Contact::Bad,
        };
    }
    // They meet at one point.
    if [a, b].iter().any(|p| *p == c || *p == d) {
        Contact::SharedEnd
    } else {
        Contact::Bad
    }
}

/// Call `f(arc, segment, arc, segment)` for every pair of segments whose
/// boxes share a search cell (a pair may come more than once).
fn for_each_close_pair(arcs: &[Vec<Fp>], mut f: impl FnMut(usize, usize, usize, usize)) {
    let cell = SEARCH_CELL as f64;
    let mut cells: HashMap<(i64, i64), Vec<(usize, usize)>> = HashMap::new();
    for (a, arc) in arcs.iter().enumerate() {
        for i in 0..arc.len().saturating_sub(1) {
            let (p, q) = (arc[i], arc[i + 1]);
            let (x0, x1) = (
                (p[0].min(q[0]) / cell).floor() as i64,
                (p[0].max(q[0]) / cell).floor() as i64,
            );
            let (y0, y1) = (
                (p[1].min(q[1]) / cell).floor() as i64,
                (p[1].max(q[1]) / cell).floor() as i64,
            );
            for x in x0..=x1 {
                for y in y0..=y1 {
                    cells.entry((x, y)).or_default().push((a, i));
                }
            }
        }
    }
    let mut keys: Vec<&(i64, i64)> = cells.keys().collect();
    keys.sort_unstable();
    for key in keys {
        let segments = &cells[key];
        for (k, &(a, i)) in segments.iter().enumerate() {
            for &(b, j) in &segments[k + 1..] {
                f(a, i, b, j);
            }
        }
    }
}

/// Arcs that cross or touch themselves or another arc anywhere but where two
/// consecutive segments of an arc meet or at an arc end both share. A
/// segment two arcs both hold (what lay between collapsed) is allowed.
fn crossing_arcs(arcs: &[Vec<Fp>]) -> BTreeSet<usize> {
    let is_end = |arc: &[Fp], p: Fp| arc.first() == Some(&p) || arc.last() == Some(&p);
    let mut bad: BTreeSet<usize> = BTreeSet::new();
    for_each_close_pair(arcs, |a, i, b, j| {
        let (arc_a, arc_b) = (&arcs[a], &arcs[b]);
        let (p, q) = (arc_a[i], arc_a[i + 1]);
        let (r, s) = (arc_b[j], arc_b[j + 1]);
        if a != b && ((p, q) == (r, s) || (p, q) == (s, r)) {
            return;
        }
        let ok = match contact_f(p, q, r, s) {
            Contact::None => true,
            Contact::Bad => false,
            Contact::SharedEnd => {
                let shared = if p == r || p == s { p } else { q };
                if a == b {
                    let last = arc_a.len() - 2;
                    i.abs_diff(j) == 1
                        || (arc_a.first() == arc_a.last()
                            && is_end(arc_a, shared)
                            && i.min(j) == 0
                            && i.max(j) == last)
                } else {
                    is_end(arc_a, shared) && is_end(arc_b, shared)
                }
            }
        };
        if !ok {
            bad.insert(a);
            bad.insert(b);
        }
    });
    bad
}

/// Segment pairs of the grid arcs that cross at a point inside both.
fn proper_crossings(arcs: &[Vec<Pt>]) -> usize {
    let f: Vec<Vec<Fp>> = arcs
        .iter()
        .map(|a| a.iter().map(|p| [p.0 as f64, p.1 as f64]).collect())
        .collect();
    let mut pairs: BTreeSet<(usize, usize, usize, usize)> = BTreeSet::new();
    for_each_close_pair(&f, |a, i, b, j| {
        let (p, q, r, s) = (f[a][i], f[a][i + 1], f[b][j], f[b][j + 1]);
        let (o1, o2) = (orient(p, q, r), orient(p, q, s));
        let (o3, o4) = (orient(r, s, p), orient(r, s, q));
        if o1 * o2 < 0.0 && o3 * o4 < 0.0 {
            pairs.insert((a, i, b, j));
        }
    });
    pairs.len()
}

/// The open ring of `uses`.
fn assemble(arcs: &[Vec<Pt>], uses: &[ArcUse]) -> Vec<Pt> {
    let mut ring: Vec<Pt> = Vec::new();
    for u in uses {
        let arc = &arcs[u.arc];
        let Some((_, rest)) = arc.split_last() else {
            continue;
        };
        if u.reversed {
            let reversed: Vec<Pt> = arc.iter().rev().copied().collect();
            ring.extend_from_slice(&reversed[..reversed.len() - 1]);
        } else {
            ring.extend_from_slice(rest);
        }
    }
    dedup_ring(&mut ring);
    ring
}

/// Twice the signed area of an open ring.
#[must_use]
pub fn area2(ring: &[Pt]) -> i128 {
    let n = ring.len();
    (0..n)
        .map(|i| {
            let (a, b) = (ring[i], ring[(i + 1) % n]);
            i128::from(a.0) * i128::from(b.1) - i128::from(b.0) * i128::from(a.1)
        })
        .sum()
}

/// MVT units of a zoom per tile.
pub const EXTENT: i64 = TILE_EXTENT as i64;

#[cfg(test)]
mod tests {
    use super::*;
    use geo::{LineString, Polygon};

    /// A square of side `s` degrees at `(x, y)`.
    fn square(x: f64, y: f64, s: f64) -> LineString<f64> {
        LineString::from(vec![(x, y), (x + s, y), (x + s, y + s), (x, y + s), (x, y)])
    }

    /// Debug: the real India boundaries (`GEOLITH_AREAS_DIR`).
    #[test]
    #[ignore = "needs a real areas dir"]
    fn real_india_crossings() {
        let Some(dir) = crate::settings::current().run.areas_dir.clone() else {
            return;
        };
        let dir = dir.as_path();
        let file = crate::areas::read_areas_geojson(&dir.join("areas.geojson")).expect("areas");
        let bytes = std::fs::read(dir.join("gaps.geojson")).expect("gaps");
        let gaps: geojson::FeatureCollection = serde_json::from_slice(&bytes).expect("gaps json");
        let mut features: Vec<Vec<Polygon<f64>>> =
            file.areas.iter().map(|a| a.shape.0.clone()).collect();
        for g in gaps.features {
            let geometry = g.geometry.expect("geometry");
            match geo::Geometry::<f64>::try_from(geometry).expect("geo") {
                geo::Geometry::Polygon(p) => features.push(vec![p]),
                geo::Geometry::MultiPolygon(m) => features.push(m.0),
                _ => {}
            }
        }
        let coverage = build(&features);
        eprintln!("{:?}", coverage.stats);
        for z in 0..=8 {
            let (_, stats) = coverage.rings_at_zoom(z);
            eprintln!("z{z}: {stats:?}");
        }
    }

    #[test]
    fn contact_kinds() {
        assert_eq!(contact((0, 0), (4, 4), (0, 4), (4, 0)), Contact::Bad);
        assert_eq!(contact((0, 0), (4, 0), (4, 0), (4, 4)), Contact::SharedEnd);
        assert_eq!(contact((0, 0), (4, 0), (2, 0), (2, 4)), Contact::Bad);
        assert_eq!(contact((0, 0), (4, 0), (2, 0), (6, 0)), Contact::Bad);
        assert_eq!(contact((0, 0), (4, 0), (4, 0), (6, 0)), Contact::SharedEnd);
        assert_eq!(contact((0, 0), (4, 0), (0, 1), (4, 1)), Contact::None);
        assert_eq!(contact((0, 0), (4, 0), (4, 0), (2, 0)), Contact::Bad);
    }

    /// A square wound the other way, as a hole.
    fn hole(x: f64, y: f64, s: f64) -> LineString<f64> {
        let mut ring = square(x, y, s);
        ring.0.reverse();
        ring
    }

    /// Four squares in a 2×2 block, an enclave inside the first, an island
    /// apart, and a square with a hole.
    fn synthetic() -> Vec<Vec<Polygon<f64>>> {
        vec![
            vec![Polygon::new(
                square(0.0, 0.0, 1.0),
                vec![hole(0.25, 0.25, 0.5)],
            )],
            vec![Polygon::new(square(1.0, 0.0, 1.0), vec![])],
            vec![Polygon::new(square(0.0, 1.0, 1.0), vec![])],
            vec![Polygon::new(square(1.0, 1.0, 1.0), vec![])],
            vec![Polygon::new(square(0.25, 0.25, 0.5), vec![])],
            vec![
                Polygon::new(square(3.0, 3.0, 0.5), vec![]),
                Polygon::new(square(5.0, 0.0, 1.0), vec![square(5.25, 0.25, 0.5)]),
            ],
        ]
    }

    fn build(features: &[Vec<Polygon<f64>>]) -> Coverage {
        let refs: Vec<Vec<&Polygon<f64>>> = features.iter().map(|f| f.iter().collect()).collect();
        Coverage::build(&refs)
    }

    #[test]
    fn arcs_split_at_junctions() {
        let coverage = build(&synthetic());
        // The block's centre, its four border midpoints' ends: the block has
        // nodes at the centre and where each inner border meets the outside.
        assert_eq!(coverage.stats.nodes, 5, "{:?}", coverage.stats);
        // Four inner borders, four outer sides, the enclave loop, the island
        // loop, the holed square's outside and its hole.
        assert_eq!(coverage.stats.arcs, 12, "{:?}", coverage.stats);
        assert!((coverage.stats.shared_after - coverage.stats.shared_before).abs() < 1e-9);
    }

    #[test]
    fn a_shared_arc_is_stored_once_and_used_both_ways() {
        let coverage = build(&synthetic());
        let mut count: HashMap<usize, Vec<bool>> = HashMap::new();
        for feature in &coverage.features {
            for polygon in feature {
                for ring in polygon {
                    for u in ring {
                        count.entry(u.arc).or_default().push(u.reversed);
                    }
                }
            }
        }
        let mut shared: Vec<(&usize, &Vec<bool>)> =
            count.iter().filter(|v| v.1.len() == 2).collect();
        shared.sort();
        // Four inner borders and the enclave loop.
        assert_eq!(shared.len(), 5);
        for (arc, uses) in shared {
            assert_ne!(uses[0], uses[1], "arc {arc}: neighbours walk it both ways");
        }
    }

    #[test]
    fn rings_rebuild_with_holes_and_islands() {
        let coverage = build(&synthetic());
        for z in [0, 4, 8] {
            let (features, stats) = coverage.rings_at_zoom(z);
            assert_eq!(stats.crossing, 0, "z{z}");
            assert_eq!(features[0][0].len(), 2, "z{z}: exterior and hole");
            assert_eq!(features[5].len(), 2, "z{z}: island and holed square");
            assert_eq!(features[5][1].len(), 2, "z{z}");
            // The enclave's ring is the first square's hole, reversed.
            let mut hole = features[0][0][1].clone();
            let mut enclave = features[4][0][0].clone();
            hole.sort_unstable();
            enclave.sort_unstable();
            assert_eq!(hole, enclave, "z{z}");
            for f in &features {
                for polygon in f {
                    for ring in polygon {
                        assert!(area2(ring) != 0, "z{z}: ring with no area");
                    }
                }
            }
        }
    }

    #[test]
    fn near_coincident_borders_share_vertices() {
        // The right square's left side is 1e-8° off and has an extra vertex
        // the left square lacks.
        let left = Polygon::new(square(0.0, 0.0, 1.0), vec![]);
        let e = 1e-6;
        let right = Polygon::new(
            LineString::from(vec![
                (1.0 + e, 0.0),
                (2.0, 0.0),
                (2.0, 1.0),
                (1.0 - e, 1.0),
                (1.0, 0.5),
                (1.0 + e, 0.0),
            ]),
            vec![],
        );
        let coverage = build(&[vec![left], vec![right]]);
        let s = coverage.stats;
        assert!(s.shared_before < 1.0, "{s:?}");
        assert!(s.merged >= 2 && s.inserted >= 1, "{s:?}");
        let full = f64::from(1_u32 << FINE_BITS);
        let side = full / 360.0;
        assert!((s.shared_after - side).abs() < side * 1e-3, "{s:?}");
    }

    #[test]
    fn a_wiggly_shared_border_simplifies_once() {
        // Two areas share a border with many small wiggles.
        let wiggle: Vec<(f64, f64)> = (0..=200)
            .map(|i| {
                let y = f64::from(i) * 0.01;
                (1.0 + 0.003 * (f64::from(i) * 0.7).sin(), y)
            })
            .collect();
        let mut left: Vec<(f64, f64)> = vec![(0.0, 0.0)];
        left.extend(wiggle.iter().copied());
        left.extend([(0.0, 2.0), (0.0, 0.0)]);
        let mut right: Vec<(f64, f64)> = vec![(2.0, 0.0), (2.0, 2.0)];
        right.extend(wiggle.iter().rev().copied());
        right.push((2.0, 0.0));
        let features = vec![
            vec![Polygon::new(LineString::from(left), vec![])],
            vec![Polygon::new(LineString::from(right), vec![])],
        ];
        let coverage = build(&features);
        for z in 0..=8 {
            let (rings, stats) = coverage.rings_at_zoom(z);
            assert_eq!(stats.crossing, 0, "z{z}");
            let edges = |ring: &[Pt]| -> BTreeSet<(Pt, Pt)> {
                (0..ring.len())
                    .map(|i| edge_key(ring[i], ring[(i + 1) % ring.len()]))
                    .collect()
            };
            let (a, b) = (edges(&rings[0][0][0]), edges(&rings[1][0][0]));
            let common = a.intersection(&b).count();
            // The shared border: every left edge that is not one of its
            // three outside sides is a right edge.
            assert_eq!(common, a.len() - 3, "z{z}");
        }
    }
}