geolith 0.1.0

Shared library of the geolith builders: source readers, conflation, admin areas, tile encoding and the PMTiles and MBTiles writers
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
//! Linestring merging for tile post-processing.
//!
//! A port of Planetiler's `LoopLineMerger`
//! (`planetiler-core/src/main/java/com/onthegomap/planetiler/util/LoopLineMerger.java`,
//! <https://github.com/onthegomap/planetiler>), ported and modified.
//! Planetiler is Copyright 2021 Michael Barry and Planetiler Contributors and
//! is licensed under the Apache License, Version 2.0; see `NOTICE.md`.
//!
//! Compared with a plain end-to-end join it:
//!
//! - splits lines where they touch another line at a midpoint,
//! - breaks loops shorter than `loop_min_length` so only the shortest path
//!   between the loop's endpoints remains,
//! - removes "hair" edges shorter than `stub_min_length` that hang off a line,
//! - simplifies each edge between junctions without moving the junctions,
//! - removes duplicate edges,
//! - joins, at each junction of three or more edges, the pairs of edges that
//!   form the straightest path,
//! - removes edges shorter than `min_length`.
//!
//! Coordinates are integer tile units, so they are already on Planetiler's
//! `TILE_PRECISION` grid (1/16 px) and need no snapping. Lengths and the
//! tolerance are in the same units.

use std::cmp::Ordering;
use std::collections::{BinaryHeap, HashMap};

/// A point in integer tile coordinates.
pub type Coord = (i32, i32);

/// Settings for [`merge_lines`].
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct LineMergeOptions {
    /// Edges shorter than this are removed at the end; `<= 0` disables it.
    pub min_length: f64,
    /// Loops shorter than this are broken; `<= 0` disables it.
    pub loop_min_length: f64,
    /// Dead-end edges shorter than this are removed; `<= 0` disables it.
    pub stub_min_length: f64,
    /// Douglas-Peucker tolerance per edge; `< 0` disables simplification.
    /// Zero still removes collinear points.
    pub tolerance: f64,
    /// Join the straightest pairs of edges at junctions of 3+ edges.
    pub merge_strokes: bool,
}

#[derive(Debug, Clone)]
struct Edge {
    from: usize,
    to: usize,
    length: f64,
    main: bool,
    removed: bool,
    reversed: usize,
    coords: Vec<Coord>,
}

#[derive(Debug, Default)]
struct Graph {
    nodes: Vec<Coord>,
    node_edges: Vec<Vec<usize>>,
    /// Node indexes in creation order; nodes left with no edges are dropped.
    output: Vec<usize>,
    edges: Vec<Edge>,
}

/// Merge `lines` and return the resulting linestrings.
///
/// Output order is deterministic: by node creation order, then by edge order
/// at each node, the same walk Planetiler's `getMergedLineStrings` does.
#[must_use]
pub fn merge_lines(lines: &[Vec<Coord>], options: &LineMergeOptions) -> Vec<Vec<Coord>> {
    let mut graph = Graph::default();
    graph.build(node_lines(lines));
    graph.degree_two_merge_all();

    if options.loop_min_length > 0.0 {
        graph.break_loops(options.loop_min_length);
        graph.degree_two_merge_all();
    }
    if options.stub_min_length > 0.0 {
        // Merges degree-2 nodes as it goes.
        graph.remove_short_stub_edges(options.stub_min_length);
    }
    if options.tolerance >= 0.0 {
        graph.simplify(options.tolerance);
        graph.remove_duplicated_edges();
        graph.degree_two_merge_all();
    }
    if options.merge_strokes {
        graph.stroke_merge();
        graph.degree_two_merge_all();
    }
    if options.min_length > 0.0 {
        graph.remove_short_edges(options.min_length);
    }

    let mut result = Vec::new();
    for &node in &graph.output {
        for &e in &graph.node_edges[node] {
            if graph.edges[e].main {
                result.push(graph.edges[e].coords.clone());
            }
        }
    }
    result
}

/// Drop repeated points, then split each line at interior points that other
/// lines (or the same line) also pass through.
fn node_lines(lines: &[Vec<Coord>]) -> Vec<Vec<Coord>> {
    let mut counts: HashMap<Coord, u32> = HashMap::new();
    let mut deduped: Vec<Vec<Coord>> = Vec::with_capacity(lines.len());
    for line in lines {
        let mut out: Vec<Coord> = Vec::with_capacity(line.len());
        for &c in line {
            if out.last() != Some(&c) {
                out.push(c);
                *counts.entry(c).or_insert(0) += 1;
            }
        }
        if out.len() >= 2 {
            deduped.push(out);
        }
    }

    let mut result = Vec::with_capacity(deduped.len());
    for line in deduped {
        let mut start = 0;
        for i in 1..line.len().saturating_sub(1) {
            if counts.get(&line[i]).copied().unwrap_or(0) > 1 {
                result.push(line[start..=i].to_vec());
                start = i;
            }
        }
        result.push(line[start..].to_vec());
    }
    result
}

fn distance(a: Coord, b: Coord) -> f64 {
    let dx = f64::from(a.0) - f64::from(b.0);
    let dy = f64::from(a.1) - f64::from(b.1);
    dx.hypot(dy)
}

fn line_length(coords: &[Coord]) -> f64 {
    coords.windows(2).map(|w| distance(w[0], w[1])).sum()
}

/// A float that orders totally, for the priority queues.
#[derive(Debug, Clone, Copy, PartialEq)]
struct Key(f64);
impl Eq for Key {}
impl PartialOrd for Key {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}
impl Ord for Key {
    fn cmp(&self, other: &Self) -> Ordering {
        self.0.total_cmp(&other.0)
    }
}

impl Graph {
    fn build(&mut self, lines: Vec<Vec<Coord>>) {
        let mut index: HashMap<Coord, usize> = HashMap::with_capacity(lines.len() * 2);
        for coords in lines {
            let first = self.node_for(&mut index, coords[0]);
            let last = self.node_for(&mut index, coords[coords.len() - 1]);
            let length = line_length(&coords);
            let edge = self.new_edge(first, last, coords, length);
            self.add_edge(first, edge);
            if first != last {
                let reversed = self.edges[edge].reversed;
                self.add_edge(last, reversed);
            }
        }
    }

    fn node_for(&mut self, index: &mut HashMap<Coord, usize>, c: Coord) -> usize {
        *index.entry(c).or_insert_with(|| {
            self.nodes.push(c);
            self.node_edges.push(Vec::new());
            self.output.push(self.nodes.len() - 1);
            self.nodes.len() - 1
        })
    }

    /// Create an edge and its reverse; returns the forward (main) edge.
    fn new_edge(&mut self, from: usize, to: usize, coords: Vec<Coord>, length: f64) -> usize {
        let main = self.edges.len();
        let mut reversed_coords = coords.clone();
        reversed_coords.reverse();
        self.edges.push(Edge {
            from,
            to,
            length,
            main: true,
            removed: false,
            reversed: main + 1,
            coords,
        });
        self.edges.push(Edge {
            from: to,
            to: from,
            length,
            main: false,
            removed: false,
            reversed: main,
            coords: reversed_coords,
        });
        main
    }

    /// Attach `edge` to `node` unless an edge with the same coordinates is
    /// already there.
    fn add_edge(&mut self, node: usize, edge: usize) {
        let duplicate = self.node_edges[node]
            .iter()
            .any(|&other| self.edges[other].coords == self.edges[edge].coords);
        if !duplicate {
            self.node_edges[node].push(edge);
        }
    }

    fn remove_from_node(&mut self, node: usize, edge: usize) {
        if let Some(pos) = self.node_edges[node].iter().position(|&e| e == edge) {
            self.node_edges[node].remove(pos);
        }
    }

    fn remove_edge(&mut self, edge: usize) {
        if !self.edges[edge].removed {
            let (from, to, reversed) = {
                let e = &self.edges[edge];
                (e.from, e.to, e.reversed)
            };
            self.remove_from_node(from, edge);
            self.remove_from_node(to, reversed);
            self.edges[edge].removed = true;
        }
    }

    fn is_loop(&self, edge: usize) -> bool {
        self.edges[edge].from == self.edges[edge].to
    }

    fn degree_two_merge_all(&mut self) {
        for i in 0..self.output.len() {
            let node = self.output[i];
            self.degree_two_merge(node);
        }
        let node_edges = &self.node_edges;
        self.output.retain(|&n| !node_edges[n].is_empty());
    }

    fn degree_two_merge(&mut self, node: usize) -> Option<usize> {
        if let [a, b] = self.node_edges[node][..]
            && !self.is_loop(a)
            && !self.is_loop(b)
        {
            return Some(self.merge_two_edges(node, a, b));
        }
        None
    }

    /// Join two edges that leave `node` into one edge through it, keeping
    /// the direction of the original line where possible.
    fn merge_two_edges(&mut self, node: usize, edge1: usize, edge2: usize) -> usize {
        let (a, b) = if self.edges[edge1].main {
            (edge2, edge1)
        } else {
            (edge1, edge2)
        };
        self.remove_from_node(node, a);
        self.remove_from_node(node, b);
        let mut coords: Vec<Coord> = self.edges[a].coords.iter().rev().copied().collect();
        coords.extend_from_slice(&self.edges[b].coords[1..]);
        let (a_to, b_to) = (self.edges[a].to, self.edges[b].to);
        let length = self.edges[a].length + self.edges[b].length;
        let c = self.new_edge(a_to, b_to, coords, length);
        let (a_rev, b_rev) = (self.edges[a].reversed, self.edges[b].reversed);
        self.remove_from_node(a_to, a_rev);
        self.remove_from_node(b_to, b_rev);
        self.add_edge(a_to, c);
        if a_to != b_to {
            let c_rev = self.edges[c].reversed;
            self.add_edge(b_to, c_rev);
        }
        c
    }

    /// The absolute angle between the first segments of two edges that
    /// leave the same node: `pi` is a straight line through the node.
    fn angle_between(&self, a: usize, b: usize) -> f64 {
        let first_angle = |e: usize| {
            let c = &self.edges[e].coords;
            f64::from(c[1].1 - c[0].1).atan2(f64::from(c[1].0 - c[0].0))
        };
        let mut delta = first_angle(a) - first_angle(b);
        // Normalise into (-pi, pi], as JTS `Angle.normalize` does.
        while delta > std::f64::consts::PI {
            delta -= 2.0 * std::f64::consts::PI;
        }
        while delta <= -std::f64::consts::PI {
            delta += 2.0 * std::f64::consts::PI;
        }
        delta.abs()
    }

    fn stroke_merge(&mut self) {
        for i in 0..self.output.len() {
            let node = self.output[i];
            let edges = self.node_edges[node].clone();
            if edges.len() < 2 {
                continue;
            }
            // A node never holds an edge and its reverse: only a loop has
            // both ends here, and a loop's reverse is never attached.
            let mut pairs: Vec<(usize, usize, f64)> =
                Vec::with_capacity(edges.len() * (edges.len() - 1) / 2);
            for (n, &a) in edges.iter().enumerate() {
                for &b in &edges[n + 1..] {
                    pairs.push((a, b, self.angle_between(a, b)));
                }
            }
            // A stable sort, walked from the straightest pair down, as
            // Planetiler does.
            pairs.sort_by(|x, y| x.2.total_cmp(&y.2));
            let mut merged: Vec<usize> = Vec::with_capacity(edges.len());
            for &(a, b, _) in pairs.iter().rev() {
                if merged.contains(&a) || merged.contains(&b) {
                    continue;
                }
                let from = self.edges[a].from;
                self.merge_two_edges(from, a, b);
                merged.push(a);
                merged.push(b);
            }
        }
    }

    fn break_loops(&mut self, loop_min_length: f64) {
        for i in 0..self.output.len() {
            let node = self.output[i];
            if self.node_edges[node].len() <= 1 {
                continue;
            }
            for current in self.node_edges[node].clone() {
                if !self.node_edges[node].contains(&current) {
                    continue;
                }
                let (cur_to, cur_from) = (self.edges[current].to, self.edges[current].from);
                let mut loops: Vec<(usize, f64)> = Vec::new();
                for &other in &self.node_edges[node] {
                    let other_length = self.edges[other].length;
                    let d = other_length
                        + self.shortest_distance(
                            self.edges[other].to,
                            cur_to,
                            cur_from,
                            loop_min_length - other_length,
                        );
                    if d <= loop_min_length {
                        loops.push((other, d));
                    }
                }
                if loops.len() > 1 {
                    // The first of the shortest, as Java's `Stream.min`.
                    let mut min = loops[0];
                    for &l in &loops[1..] {
                        if l.1 < min.1 {
                            min = l;
                        }
                    }
                    for &(edge, _) in &loops {
                        if edge != min.0 {
                            self.remove_edge(edge);
                        }
                    }
                }
            }
        }
    }

    /// A* shortest path length from `start` to `end` that avoids `exclude`,
    /// or infinity when no path is at most `max_length` long.
    fn shortest_distance(&self, start: usize, end: usize, exclude: usize, max_length: f64) -> f64 {
        let mut best: HashMap<usize, f64> = HashMap::new();
        let mut frontier: BinaryHeap<(std::cmp::Reverse<Key>, std::cmp::Reverse<usize>, Key)> =
            BinaryHeap::new();
        if exclude != start {
            let estimate = distance(self.nodes[start], self.nodes[end]);
            frontier.push((
                std::cmp::Reverse(Key(estimate)),
                std::cmp::Reverse(start),
                Key(0.0),
            ));
        }
        while let Some((_, std::cmp::Reverse(current), Key(length))) = frontier.pop() {
            if current == end {
                return length;
            }
            for &edge in &self.node_edges[current] {
                let neighbor = self.edges[edge].to;
                if neighbor == exclude {
                    continue;
                }
                let new_dist = length + self.edges[edge].length;
                if new_dist < best.get(&neighbor).copied().unwrap_or(f64::INFINITY) {
                    best.insert(neighbor, new_dist);
                    let total = new_dist + distance(self.nodes[neighbor], self.nodes[end]);
                    if total <= max_length {
                        frontier.push((
                            std::cmp::Reverse(Key(total)),
                            std::cmp::Reverse(neighbor),
                            Key(new_dist),
                        ));
                    }
                }
            }
        }
        f64::INFINITY
    }

    fn is_short_stub(&self, edge: usize, stub_min_length: f64) -> bool {
        let e = &self.edges[edge];
        !e.removed
            && e.length < stub_min_length
            && (self.node_edges[e.from].len() == 1
                || self.node_edges[e.to].len() == 1
                || e.from == e.to)
    }

    fn remove_short_stub_edges(&mut self, stub_min_length: f64) {
        // Shortest first; the sequence number makes ties deterministic.
        let mut queue: BinaryHeap<(std::cmp::Reverse<Key>, std::cmp::Reverse<usize>)> =
            BinaryHeap::new();
        let push = |queue: &mut BinaryHeap<_>, graph: &Graph, edge: usize| {
            queue.push((
                std::cmp::Reverse(Key(graph.edges[edge].length)),
                std::cmp::Reverse(edge),
            ));
        };
        for &node in &self.output {
            for &edge in &self.node_edges[node] {
                if self.is_short_stub(edge, stub_min_length) {
                    push(&mut queue, self, edge);
                }
            }
        }
        while let Some((_, std::cmp::Reverse(edge))) = queue.pop() {
            if self.edges[edge].removed {
                continue;
            }
            if self.is_short_stub(edge, stub_min_length) {
                self.remove_edge(edge);
            }
            let (from, to) = (self.edges[edge].from, self.edges[edge].to);
            let ends: &[usize] = if from == to { &[from] } else { &[from, to] };
            for &end in ends {
                if let Some(merged) = self.degree_two_merge(end) {
                    push(&mut queue, self, merged);
                }
                if let [other] = self.node_edges[end][..]
                    && self.is_short_stub(other, stub_min_length)
                {
                    push(&mut queue, self, other);
                }
            }
        }
    }

    fn remove_short_edges(&mut self, min_length: f64) {
        for i in 0..self.output.len() {
            let node = self.output[i];
            for edge in self.node_edges[node].clone() {
                if self.edges[edge].length < min_length {
                    self.remove_edge(edge);
                }
            }
        }
    }

    fn simplify(&mut self, tolerance: f64) {
        let mut collapsed = Vec::new();
        for i in 0..self.output.len() {
            let node = self.output[i];
            for j in 0..self.node_edges[node].len() {
                let edge = self.node_edges[node][j];
                if !self.edges[edge].main {
                    continue;
                }
                let simplified = douglas_peucker(&self.edges[edge].coords, tolerance);
                let mut reversed = simplified.clone();
                reversed.reverse();
                let rev = self.edges[edge].reversed;
                self.edges[rev].coords = reversed;
                let is_collapsed = simplified.len() < 2
                    || (simplified.len() == 2 && simplified[0] == simplified[1]);
                self.edges[edge].coords = simplified;
                if is_collapsed {
                    collapsed.push(edge);
                }
            }
        }
        for edge in collapsed {
            self.remove_edge(edge);
        }
    }

    fn remove_duplicated_edges(&mut self) {
        for i in 0..self.output.len() {
            let node = self.output[i];
            let edges = &self.node_edges[node];
            let mut duplicates = Vec::new();
            for (n, &a) in edges.iter().enumerate() {
                for &b in &edges[n + 1..] {
                    if self.edges[b].to == self.edges[a].to
                        && self.edges[a].coords == self.edges[b].coords
                    {
                        duplicates.push(b);
                    }
                }
            }
            for edge in duplicates {
                self.remove_edge(edge);
            }
        }
    }
}

/// Douglas-Peucker that always keeps both endpoints.
///
/// A point is dropped when its distance to the chord is at most `tolerance`, as
/// in JTS `DouglasPeuckerLineSimplifier`, so zero still removes collinear
/// points.
#[must_use]
pub fn douglas_peucker(coords: &[Coord], tolerance: f64) -> Vec<Coord> {
    if coords.len() < 3 {
        return coords.to_vec();
    }
    let mut keep = vec![false; coords.len()];
    keep[0] = true;
    keep[coords.len() - 1] = true;
    let mut stack = vec![(0usize, coords.len() - 1)];
    while let Some((first, last)) = stack.pop() {
        if last <= first + 1 {
            continue;
        }
        let mut max_distance = -1.0f64;
        let mut max_index = first;
        for (k, &c) in coords.iter().enumerate().take(last).skip(first + 1) {
            let d = segment_distance(c, coords[first], coords[last]);
            if d > max_distance {
                max_distance = d;
                max_index = k;
            }
        }
        if max_distance > tolerance {
            keep[max_index] = true;
            stack.push((first, max_index));
            stack.push((max_index, last));
        }
    }
    coords
        .iter()
        .zip(keep)
        .filter_map(|(&c, k)| k.then_some(c))
        .collect()
}

/// Distance from `p` to the segment `a`..`b`.
fn segment_distance(p: Coord, a: Coord, b: Coord) -> f64 {
    let (px, py) = (f64::from(p.0), f64::from(p.1));
    let (ax, ay) = (f64::from(a.0), f64::from(a.1));
    let (bx, by) = (f64::from(b.0), f64::from(b.1));
    let (dx, dy) = (bx - ax, by - ay);
    let len2 = dx * dx + dy * dy;
    if len2 == 0.0 {
        return (px - ax).hypot(py - ay);
    }
    let t = (((px - ax) * dx + (py - ay) * dy) / len2).clamp(0.0, 1.0);
    (px - (ax + t * dx)).hypot(py - (ay + t * dy))
}

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

    fn opts() -> LineMergeOptions {
        LineMergeOptions {
            min_length: 0.0,
            loop_min_length: 0.0,
            stub_min_length: 0.0,
            tolerance: -1.0,
            merge_strokes: false,
        }
    }

    /// The multiset of lines, each read in a canonical direction, so a test
    /// does not depend on output order or on which way a line runs.
    fn canonical(lines: Vec<Vec<Coord>>) -> Vec<Vec<Coord>> {
        let mut out: Vec<Vec<Coord>> = lines
            .into_iter()
            .map(|mut l| {
                if l.last() < l.first() {
                    l.reverse();
                }
                l
            })
            .collect();
        out.sort();
        out
    }

    /// S(0,0)–A(10,0)–E(20,0) with a detour S–B(0,10)–A. A* pops A before
    /// B, then reaches B again from A at 10 + 14.14, longer than the 10 it
    /// already holds, and must not re-queue it. The shortest S→E is S–A–E,
    /// 10 + 10 = 20.
    #[test]
    fn a_star_keeps_the_shorter_distance_when_a_node_is_reached_again() {
        let mut graph = Graph::default();
        graph.build(vec![
            vec![(0, 0), (10, 0)],
            vec![(0, 0), (0, 10)],
            vec![(0, 10), (10, 0)],
            vec![(10, 0), (20, 0)],
        ]);
        let (s, e) = (0, 3);
        assert_eq!(graph.nodes[e], (20, 0));
        let d = graph.shortest_distance(s, e, usize::MAX, 100.0);
        assert!((d - 20.0).abs() < 1e-9, "{d}");
        // A cap below 20 leaves no path.
        assert!(
            graph
                .shortest_distance(s, e, usize::MAX, 19.0)
                .is_infinite()
        );
    }

    #[test]
    fn end_to_end_lines_join_into_one() {
        let lines = vec![
            vec![(0, 0), (10, 0)],
            vec![(10, 0), (20, 0)],
            vec![(20, 0), (30, 5)],
        ];
        let merged = merge_lines(&lines, &opts());
        assert_eq!(
            canonical(merged),
            vec![vec![(0, 0), (10, 0), (20, 0), (30, 5)]]
        );
    }

    #[test]
    fn a_line_keeps_its_direction_through_a_join() {
        // Both inputs run left to right, so the joined line must too.
        let lines = vec![vec![(10, 0), (20, 0)], vec![(0, 0), (10, 0)]];
        assert_eq!(
            merge_lines(&lines, &opts()),
            vec![vec![(0, 0), (10, 0), (20, 0)]]
        );
    }

    #[test]
    fn a_line_touching_another_mid_way_splits_it_into_a_junction() {
        // A T junction: the stem ends on the bar's interior point (10, 0).
        let lines = vec![vec![(0, 0), (10, 0), (20, 0)], vec![(10, 0), (10, 10)]];
        let merged = canonical(merge_lines(&lines, &opts()));
        assert_eq!(
            merged,
            vec![
                vec![(0, 0), (10, 0)],
                vec![(10, 0), (10, 10)],
                vec![(10, 0), (20, 0)],
            ]
        );
    }

    #[test]
    fn stroke_merging_joins_the_straightest_pair_at_a_junction() {
        let lines = vec![vec![(0, 0), (10, 0), (20, 0)], vec![(10, 0), (10, 10)]];
        let merged = merge_lines(
            &lines,
            &LineMergeOptions {
                merge_strokes: true,
                ..opts()
            },
        );
        assert_eq!(
            canonical(merged),
            vec![vec![(0, 0), (10, 0), (20, 0)], vec![(10, 0), (10, 10)]]
        );
    }

    #[test]
    fn short_lines_are_dropped_and_long_ones_kept() {
        let lines = vec![vec![(0, 0), (3, 4)], vec![(100, 100), (100, 200)]];
        let merged = merge_lines(
            &lines,
            &LineMergeOptions {
                min_length: 6.0,
                ..opts()
            },
        );
        assert_eq!(canonical(merged), vec![vec![(100, 100), (100, 200)]]);
    }

    #[test]
    fn a_short_stub_off_a_line_is_removed() {
        // A 2-unit hair at (10, 0); the bar then merges back into one line.
        let lines = vec![vec![(0, 0), (10, 0), (20, 0)], vec![(10, 0), (10, 2)]];
        let merged = merge_lines(
            &lines,
            &LineMergeOptions {
                stub_min_length: 5.0,
                ..opts()
            },
        );
        assert_eq!(canonical(merged), vec![vec![(0, 0), (10, 0), (20, 0)]]);
    }

    #[test]
    fn a_short_loop_keeps_only_the_shortest_path() {
        // Two paths from (0, 0) to (10, 0): straight (10) and a detour
        // through (5, 5) (about 14.1). With a 20-unit loop limit only the
        // straight one survives, then joins with the tail, whichever of the
        // two comes first.
        let straight = vec![(0, 0), (10, 0)];
        let detour = vec![(0, 0), (5, 5), (10, 0)];
        for (first, second) in [(&straight, &detour), (&detour, &straight)] {
            let lines = vec![
                first.clone(),
                second.clone(),
                vec![(10, 0), (100, 0)],
                vec![(-90, 0), (0, 0)],
            ];
            let merged = merge_lines(
                &lines,
                &LineMergeOptions {
                    loop_min_length: 20.0,
                    ..opts()
                },
            );
            assert_eq!(
                canonical(merged),
                vec![vec![(-90, 0), (0, 0), (10, 0), (100, 0)]],
                "{first:?} first"
            );
        }
    }

    #[test]
    fn a_loop_of_three_junctions_loses_its_longer_way_round() {
        // Triangle A (0, 0), B (10, 0), C (5, 8), each corner also the end
        // of a long tail, so no corner is a degree-2 node. From A to B the
        // direct side is 10 and the way round through C is 2 * sqrt(89)
        // (about 18.9), both under the 30-unit limit, so side CA goes and
        // the corners A and C then join their two remaining edges.
        let lines = vec![
            vec![(0, 0), (10, 0)],
            vec![(10, 0), (5, 8)],
            vec![(5, 8), (0, 0)],
            vec![(-50, 0), (0, 0)],
            vec![(10, 0), (60, 0)],
            vec![(5, 8), (5, 60)],
        ];
        let merged = merge_lines(
            &lines,
            &LineMergeOptions {
                loop_min_length: 30.0,
                ..opts()
            },
        );
        assert_eq!(
            canonical(merged),
            vec![
                vec![(-50, 0), (0, 0), (10, 0)],
                vec![(5, 60), (5, 8), (10, 0)],
                vec![(10, 0), (60, 0)],
            ]
        );
    }

    #[test]
    fn a_closed_ring_stays_one_loop_and_a_tiny_one_collapses() {
        let ring = vec![(0, 0), (10, 0), (10, 10), (0, 10), (0, 0)];
        assert_eq!(
            merge_lines(std::slice::from_ref(&ring), &opts()),
            vec![ring]
        );

        // Every point of the 1-unit ring is within 2 units of its start, so
        // simplification leaves a single point and the ring is removed.
        let lines = vec![
            vec![(0, 0), (1, 0), (1, 1), (0, 0)],
            vec![(100, 0), (200, 0)],
        ];
        let merged = merge_lines(
            &lines,
            &LineMergeOptions {
                tolerance: 2.0,
                ..opts()
            },
        );
        assert_eq!(merged, vec![vec![(100, 0), (200, 0)]]);
    }

    #[test]
    fn two_paths_between_the_same_ends_close_into_a_loop() {
        // (0, 0) joins only the two paths, so it is merged away and leaves
        // one loop through it at (10, 0), next to the tail. The tail is
        // given right to left and keeps that direction.
        let lines = vec![
            vec![(0, 0), (5, 5), (10, 0)],
            vec![(0, 0), (5, -5), (10, 0)],
            vec![(20, 0), (10, 0)],
        ];
        let merged = merge_lines(&lines, &opts());
        assert!(merged.contains(&vec![(20, 0), (10, 0)]), "{merged:?}");
        assert_eq!(
            canonical(merged),
            vec![
                vec![(10, 0), (5, -5), (0, 0), (5, 5), (10, 0)],
                vec![(10, 0), (20, 0)],
            ]
        );
    }

    #[test]
    fn parallel_paths_that_simplify_to_one_chord_leave_one_line() {
        // Three paths from (0, 0) to (10, 0) whose midpoints are at most 2
        // units off the chord; with a 2.5 tolerance all three become the
        // chord, and the two copies are removed.
        let lines = vec![
            vec![(0, 0), (5, 1), (10, 0)],
            vec![(0, 0), (5, -1), (10, 0)],
            vec![(0, 0), (5, 2), (10, 0)],
        ];
        let merged = merge_lines(
            &lines,
            &LineMergeOptions {
                tolerance: 2.5,
                ..opts()
            },
        );
        assert_eq!(merged, vec![vec![(0, 0), (10, 0)]]);
    }

    #[test]
    fn stroke_angles_wrap_around_pi_before_they_are_compared() {
        // Bearings from the junction: (-10, 2) is 168.69 degrees, (10, 0)
        // is 0, (-10, -3) is -163.30 and (-10, -1) is -174.29. A raw
        // difference past +-180 degrees is a sharp V, not a straight line:
        // 168.69 - (-163.30) is 331.99, which wraps to 28.01, and -174.29 -
        // 168.69 is -342.98, which wraps to 17.02. Unwrapped, each V would
        // look straightest and be joined instead of the real through-line.
        let strokes = LineMergeOptions {
            merge_strokes: true,
            ..opts()
        };
        let lines = vec![
            vec![(0, 0), (-10, 2)],
            vec![(0, 0), (10, 0)],
            vec![(0, 0), (-10, -3)],
        ];
        assert_eq!(
            canonical(merge_lines(&lines, &strokes)),
            vec![vec![(-10, -3), (0, 0)], vec![(-10, 2), (0, 0), (10, 0)]]
        );
        let lines = vec![
            vec![(0, 0), (-10, -1)],
            vec![(0, 0), (-10, 2)],
            vec![(0, 0), (10, 0)],
        ];
        assert_eq!(
            canonical(merge_lines(&lines, &strokes)),
            vec![vec![(-10, -1), (0, 0), (10, 0)], vec![(-10, 2), (0, 0)]]
        );
    }

    #[test]
    fn a_short_loop_hanging_off_a_line_is_a_stub() {
        // A 3.4-unit loop at the end of a 100-unit line.
        let lines = vec![
            vec![(-100, 0), (0, 0)],
            vec![(0, 0), (1, 0), (1, 1), (0, 0)],
        ];
        let merged = merge_lines(
            &lines,
            &LineMergeOptions {
                stub_min_length: 5.0,
                ..opts()
            },
        );
        assert_eq!(merged, vec![vec![(-100, 0), (0, 0)]]);
    }

    #[test]
    fn loop_breaking_leaves_a_self_loop_alone() {
        // A self-loop has no second endpoint to find a shorter way to, so
        // only stub removal can take it: loop breaking keeps both loops,
        // and does not treat one as a longer way round the other.
        let lines = vec![
            vec![(-100, 0), (0, 0)],
            vec![(0, 0), (1, 0), (1, 1), (0, 0)],
            vec![(0, 0), (0, 2), (-2, 2), (0, 0)],
        ];
        let merged = merge_lines(
            &lines,
            &LineMergeOptions {
                loop_min_length: 20.0,
                ..opts()
            },
        );
        assert_eq!(canonical(merged), canonical(lines));
    }

    #[test]
    fn removing_a_stub_can_make_its_neighbour_a_stub() {
        // A 3-unit spur off a through road ends in a 4.8-unit loop. The
        // spur is no stub at first (neither end is a dead end), but once
        // the loop goes it is, and then the road joins back into one line.
        let lines = vec![
            vec![(-100, 0), (0, 0)],
            vec![(0, 0), (100, 0)],
            vec![(0, 0), (0, 3)],
            vec![(0, 3), (1, 4), (0, 5), (0, 3)],
        ];
        let merged = merge_lines(
            &lines,
            &LineMergeOptions {
                stub_min_length: 5.0,
                ..opts()
            },
        );
        assert_eq!(canonical(merged), vec![vec![(-100, 0), (0, 0), (100, 0)]]);
    }

    #[test]
    fn a_lollipop_shorter_than_the_stub_limit_vanishes_whole() {
        // A 3-unit stick ending in a 4.8-unit loop: removing the stick
        // leaves the loop a stub of its own, so both go. The unrelated
        // 100-unit line is untouched.
        let lines = vec![
            vec![(500, 0), (500, 3)],
            vec![(500, 3), (501, 4), (500, 5), (500, 3)],
            vec![(0, 0), (100, 0)],
        ];
        let merged = merge_lines(
            &lines,
            &LineMergeOptions {
                stub_min_length: 5.0,
                ..opts()
            },
        );
        assert_eq!(merged, vec![vec![(0, 0), (100, 0)]]);
    }

    #[test]
    fn duplicate_lines_collapse_to_one() {
        let lines = vec![vec![(0, 0), (10, 0)], vec![(10, 0), (0, 0)]];
        let merged = merge_lines(&lines, &opts());
        assert_eq!(canonical(merged), vec![vec![(0, 0), (10, 0)]]);
    }

    #[test]
    fn simplification_keeps_junctions_and_drops_inner_points() {
        // (5, 1) is within 2 units of the chord; the junction (10, 0) is an
        // endpoint of three edges and must survive.
        let lines = vec![
            vec![(0, 0), (5, 1), (10, 0)],
            vec![(10, 0), (20, 0)],
            vec![(10, 0), (10, 10)],
        ];
        let merged = merge_lines(
            &lines,
            &LineMergeOptions {
                tolerance: 2.0,
                ..opts()
            },
        );
        assert_eq!(
            canonical(merged),
            vec![
                vec![(0, 0), (10, 0)],
                vec![(10, 0), (10, 10)],
                vec![(10, 0), (20, 0)],
            ]
        );
    }

    #[test]
    fn repeated_points_and_degenerate_lines_are_ignored() {
        let lines = vec![vec![(5, 5), (5, 5)], vec![(0, 0), (0, 0), (0, 10)], vec![]];
        assert_eq!(merge_lines(&lines, &opts()), vec![vec![(0, 0), (0, 10)]]);
    }

    #[test]
    fn douglas_peucker_matches_a_hand_worked_case() {
        // The apex (5, 5) is 5 units off the chord; (2, 0) and (8, 0) lie on
        // the sub-chords once the apex is kept.
        let line = [(0, 0), (2, 0), (5, 5), (8, 0), (10, 0)];
        assert_eq!(
            douglas_peucker(&line, 1.0),
            vec![(0, 0), (2, 0), (5, 5), (8, 0), (10, 0)]
        );
        assert_eq!(douglas_peucker(&line, 6.0), vec![(0, 0), (10, 0)]);
        assert_eq!(
            douglas_peucker(&[(0, 0), (1, 0), (2, 0)], 0.0),
            vec![(0, 0), (2, 0)]
        );
    }
}