geolith 0.1.4

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
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
//! Merging of same-attribute features within one tile layer.
//!
//! A port of Planetiler's `FeatureMerge`
//! (`planetiler-core/src/main/java/com/onthegomap/planetiler/FeatureMerge.java`):
//! [`merge_line_strings`] is `mergeLineStrings` and [`merge_nearby_polygons`]
//! is `mergeNearbyPolygons`. Parameters are in Planetiler's units, pixels of
//! a 256 px tile, so the per-layer numbers can be copied from the
//! protomaps basemap's `postProcess` methods; one pixel is
//! [`UNITS_PER_PIXEL`] tile units.
//!
//! Ported and modified from Planetiler
//! (<https://github.com/onthegomap/planetiler>), Copyright 2021 Michael Barry
//! and Planetiler Contributors, licensed under the Apache License, Version
//! 2.0; see `NOTICE.md`.
//!
//! Output order follows Planetiler: features that are not of the merged
//! geometry type keep their input order, then one feature per attribute
//! group, in order of each group's first feature. A merged feature keeps the
//! id and sort key of its group's first feature. (Planetiler rewrites the id
//! to end in 0 because its ids encode the OSM element type in the last
//! digit; geolith ids do not, so the id is kept as is.)

use std::collections::HashMap;
use std::sync::Arc;

use geo::{
    Area, BoundingRect, Buffer, Coord as GeoCoord, Distance, Euclidean, Intersects, LineString,
    MultiPolygon, Polygon, Validation, algorithm::buffer::BufferStyle, unary_union,
};
use rstar::{AABB, RTree, primitives::GeomWithData, primitives::Rectangle};

use crate::geometry::line_merge::{Coord, LineMergeOptions, merge_lines};
use crate::tile::feature::{GeomType, PropValue, TILE_EXTENT, TileFeature};
use crate::tile::mvt;

/// Tile units per Planetiler pixel: a 4096-unit tile is 256 px wide.
pub const UNITS_PER_PIXEL: f64 = TILE_EXTENT as f64 / 256.0;

/// JTS's default mitre limit of 5, as the minimum corner angle that
/// `i_overlay`'s `LineJoin::Miter` takes: a mitre is `1 / sin(angle / 2)`
/// half-widths long, so a limit of 5 is `2 * asin(1 / 5)`.
fn mitre_angle() -> f64 {
    2.0 * (0.2f64).asin()
}

/// Settings for [`merge_line_strings`], in pixels.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct LineMerge {
    /// Drop merged lines shorter than this.
    pub min_length: f64,
    /// Simplify merged lines with this tolerance.
    pub tolerance: f64,
    /// Drop detail more than this far outside the tile; negative keeps all.
    pub buffer: f64,
    /// Simplify a group even when it has only one feature.
    pub resimplify: bool,
}

/// Settings for [`merge_nearby_polygons`], in pixels.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct PolygonMerge {
    /// Drop polygons whose area is at most this, in square pixels.
    pub min_area: f64,
    /// Drop holes whose area is at most this, in square pixels.
    pub min_hole_area: f64,
    /// Merge polygons that are at most this far apart.
    pub min_dist: f64,
    /// Grow then shrink merged polygons by this much, joining near misses.
    pub buffer: f64,
}

/// A hashable view of a property value; floats compare by bits, as Java's
/// `Double.equals` does.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
enum ValueKey<'a> {
    Str(&'a str),
    F64(u64),
    I64(i64),
    U64(u64),
    Bool(bool),
}

/// The attribute set of a feature, order-insensitive like a Java `Map`.
fn attr_key(properties: &[(String, PropValue)]) -> Vec<(&str, ValueKey<'_>)> {
    let mut key: Vec<(&str, ValueKey<'_>)> = properties
        .iter()
        .map(|(k, v)| {
            let value = match v {
                PropValue::Str(s) => ValueKey::Str(s),
                PropValue::F64(f) => ValueKey::F64(f.to_bits()),
                PropValue::I64(i) => ValueKey::I64(*i),
                PropValue::U64(u) => ValueKey::U64(*u),
                PropValue::Bool(b) => ValueKey::Bool(*b),
            };
            (k.as_str(), value)
        })
        .collect();
    key.sort_by(|a, b| a.0.cmp(b.0));
    key
}

/// Split `features` into those of `geom_type`, grouped by identical
/// attributes in order of first appearance, and all others in input order.
fn group_by_attrs(
    features: &[TileFeature],
    geom_type: GeomType,
) -> (Vec<&TileFeature>, Vec<Vec<&TileFeature>>) {
    let mut others = Vec::new();
    let mut groups: Vec<Vec<&TileFeature>> = Vec::new();
    let mut index: HashMap<Vec<(&str, ValueKey<'_>)>, usize> = HashMap::new();
    for feature in features {
        if feature.geom_type != geom_type {
            others.push(feature);
            continue;
        }
        let key = attr_key(&feature.properties);
        let slot = *index.entry(key).or_insert_with(|| {
            groups.push(Vec::new());
            groups.len() - 1
        });
        groups[slot].push(feature);
    }
    (others, groups)
}

fn with_geometry(feature: &TileFeature, geometry: Vec<u32>) -> TileFeature {
    TileFeature {
        layer: feature.layer,
        id: feature.id,
        geom_type: feature.geom_type,
        geometry,
        properties: Arc::clone(&feature.properties),
        sort_key: feature.sort_key,
    }
}

/// Planetiler's `Hilbert.hilbertXYToIndex`.
#[must_use]
const fn hilbert_xy_to_index(level: u32, x: u32, y: u32) -> u32 {
    let x = x << (16 - level);
    let y = y << (16 - level);

    let a1 = x ^ y;
    let b1 = 0xFFFF ^ a1;
    let c1 = 0xFFFF ^ (x | y);
    let d1 = x & (y ^ 0xFFFF);

    let mut ha = a1 | (b1 >> 1);
    let mut hb = (a1 >> 1) ^ a1;
    let mut hc = ((c1 >> 1) ^ (b1 & (d1 >> 1))) ^ c1;
    let mut hd = ((a1 & (c1 >> 1)) ^ (d1 >> 1)) ^ d1;

    let (a2, b2, c2, d2) = (ha, hb, hc, hd);
    ha = (a2 & (a2 >> 2)) ^ (b2 & (b2 >> 2));
    hb = (a2 & (b2 >> 2)) ^ (b2 & ((a2 ^ b2) >> 2));
    hc ^= (a2 & (c2 >> 2)) ^ (b2 & (d2 >> 2));
    hd ^= (b2 & (c2 >> 2)) ^ ((a2 ^ b2) & (d2 >> 2));

    let (a3, b3, c3, d3) = (ha, hb, hc, hd);
    ha = (a3 & (a3 >> 4)) ^ (b3 & (b3 >> 4));
    hb = (a3 & (b3 >> 4)) ^ (b3 & ((a3 ^ b3) >> 4));
    hc ^= (a3 & (c3 >> 4)) ^ (b3 & (d3 >> 4));
    hd ^= (b3 & (c3 >> 4)) ^ ((a3 ^ b3) & (d3 >> 4));

    let (a4, b4, c4, d4) = (ha, hb, hc, hd);
    hc ^= (a4 & (c4 >> 8)) ^ (b4 & (d4 >> 8));
    hd ^= (b4 & (c4 >> 8)) ^ ((a4 ^ b4) & (d4 >> 8));

    let a = hc ^ (hc >> 1);
    let b = hd ^ (hd >> 1);
    let i0 = x ^ y;
    let i1 = b | (0xFFFF ^ (i0 | a));
    ((interleave(i1) << 1) | interleave(i0)) >> (32 - 2 * level)
}

const fn interleave(mut t: u32) -> u32 {
    t = (t | (t << 8)) & 0x00FF_00FF;
    t = (t | (t << 4)) & 0x0F0F_0F0F;
    t = (t | (t << 2)) & 0x3333_3333;
    (t | (t << 1)) & 0x5555_5555
}

/// Planetiler's `VectorTile.hilbertIndex`: the order of a geometry's first
/// coordinate on a level-15 Hilbert curve.
fn hilbert_index(first: Coord) -> u32 {
    let zigzag = |v: i32| ((v << 1) ^ (v >> 31)) as u32;
    hilbert_xy_to_index(15, zigzag(first.0), zigzag(first.1))
}

/// Merge same-attribute linestrings: Planetiler's `mergeLineStrings`, with
/// stroke merging on and loops and stubs limited by `min_length`.
#[must_use]
pub fn merge_line_strings(features: &[TileFeature], params: &LineMerge) -> Vec<TileFeature> {
    let (others, groups) = group_by_attrs(features, GeomType::Line);
    let mut result: Vec<TileFeature> = Vec::with_capacity(others.len() + groups.len());
    result.extend(others.into_iter().cloned());

    let min_length = params.min_length * UNITS_PER_PIXEL;
    let options = LineMergeOptions {
        min_length,
        loop_min_length: min_length,
        stub_min_length: params.min_length.min(0.5) * UNITS_PER_PIXEL,
        tolerance: params.tolerance * UNITS_PER_PIXEL,
        merge_strokes: true,
    };
    let buffer = params.buffer * UNITS_PER_PIXEL;

    for group in groups {
        let first = group[0];
        if group.len() == 1
            && params.buffer <= 0.0
            && params.min_length <= 0.0
            && (!params.resimplify || params.tolerance <= 0.0)
        {
            result.push(first.clone());
            continue;
        }
        let lines: Vec<Vec<Coord>> = group
            .iter()
            .flat_map(|f| mvt::decode_commands(&f.geometry))
            .collect();
        let mut segments: Vec<Vec<Coord>> = Vec::new();
        for line in merge_lines(&lines, &options) {
            if params.buffer >= 0.0 {
                remove_detail_outside_tile(&line, buffer, &mut segments);
            } else {
                segments.push(line);
            }
        }
        if segments.is_empty() {
            continue;
        }
        segments.sort_by_key(|s| hilbert_index(s[0]));
        result.push(with_geometry(first, mvt::encode_multilinestring(&segments)));
    }
    result
}

/// Keep the parts of `line` with at least one end inside the tile grown by
/// `buffer` units; a run of segments with both ends outside is cut out.
fn remove_detail_outside_tile(line: &[Coord], buffer: f64, out: &mut Vec<Vec<Coord>>) {
    let (min, max) = (-buffer, f64::from(TILE_EXTENT) + buffer);
    let touches = |a: Coord, b: Coord| {
        let (x0, x1) = (f64::from(a.0.min(b.0)), f64::from(a.0.max(b.0)));
        let (y0, y1) = (f64::from(a.1.min(b.1)), f64::from(a.1.max(b.1)));
        x1 >= min && x0 <= max && y1 >= min && y0 <= max
    };
    let mut current: Vec<Coord> = Vec::new();
    let mut was_in = false;
    for w in line.windows(2) {
        let now_in = touches(w[0], w[1]);
        if now_in || was_in {
            current.push(w[0]);
        } else if !current.is_empty() {
            // The segment before this one touched the tile and pushed a
            // point after the one that opened the run, so it has two.
            out.push(std::mem::take(&mut current));
        }
        was_in = now_in;
    }
    if let [.., a, b] = line
        && (touches(*a, *b) || was_in)
    {
        current.push(*b);
    }
    if current.len() >= 2 {
        out.push(current);
    }
}

/// Decode polygon commands into polygons: each exterior ring (positive
/// area in the MVT formula) starts a polygon, and the rings after it until
/// the next exterior are its holes.
fn decode_polygons(geometry: &[u32]) -> Vec<Polygon<f64>> {
    let mut polygons: Vec<(Vec<Coord>, Vec<Vec<Coord>>)> = Vec::new();
    for ring in mvt::decode_commands(geometry) {
        if ring.len() < 3 {
            continue;
        }
        if shoelace(&ring) > 0 {
            polygons.push((ring, Vec::new()));
        } else if let Some((_, holes)) = polygons.last_mut() {
            holes.push(ring);
        }
    }
    polygons
        .into_iter()
        .map(|(exterior, holes)| {
            Polygon::new(
                to_line_string(&exterior),
                holes.iter().map(|h| to_line_string(h)).collect(),
            )
        })
        .collect()
}

fn to_line_string(ring: &[Coord]) -> LineString<f64> {
    LineString::from(
        ring.iter()
            .map(|&(x, y)| GeoCoord {
                x: f64::from(x),
                y: f64::from(y),
            })
            .collect::<Vec<_>>(),
    )
}

/// Twice the signed area by the MVT spec's surveyor's formula: positive for
/// an exterior ring (clockwise on screen, Y down).
fn shoelace(ring: &[Coord]) -> i64 {
    let n = ring.len();
    (0..n)
        .map(|i| {
            let (x0, y0) = ring[i];
            let (x1, y1) = ring[(i + 1) % n];
            i64::from(x0) * i64::from(y1) - i64::from(x1) * i64::from(y0)
        })
        .sum()
}

/// Round a ring to tile units, dropping repeats and the closing point.
fn snap_ring(ring: &LineString<f64>) -> Vec<Coord> {
    let mut out: Vec<Coord> = Vec::with_capacity(ring.0.len());
    for c in &ring.0 {
        let p = (c.x.round() as i32, c.y.round() as i32);
        if out.last() != Some(&p) {
            out.push(p);
        }
    }
    if out.len() > 1 && out.first() == out.last() {
        out.pop();
    }
    out
}

/// Planetiler's `snapAndFixPolygon`: round to the tile grid, and repair the
/// result if rounding made it invalid.
fn snap_and_fix(merged: &MultiPolygon<f64>) -> MultiPolygon<f64> {
    let snapped: Vec<Polygon<f64>> = merged
        .0
        .iter()
        .filter_map(|p| {
            let exterior = snap_ring(p.exterior());
            if exterior.len() < 3 {
                return None;
            }
            let holes = p
                .interiors()
                .iter()
                .map(snap_ring)
                .filter(|h| h.len() >= 3)
                .map(|h| to_line_string(&h))
                .collect();
            Some(Polygon::new(to_line_string(&exterior), holes))
        })
        .collect();
    let snapped = MultiPolygon(snapped);
    if snapped.is_valid() {
        snapped
    } else {
        // A self-union rebuilds the rings, the way JTS's GeometryFixer does.
        unary_union(snapped.0.iter())
    }
}

fn envelope_area(mp: &MultiPolygon<f64>) -> f64 {
    mp.bounding_rect().map_or(0.0, |r| r.width() * r.height())
}

/// Grow each polygon by `buffer`, union them, then shrink the union back:
/// Planetiler's `bufferUnionUnbuffer`, including its fallback when the
/// shrink loses area (see locationtech/jts#1183).
fn buffer_union_unbuffer(buffer: f64, group: &[&MultiPolygon<f64>]) -> MultiPolygon<f64> {
    let style = |d: f64| {
        BufferStyle::new(d).line_join(geo::algorithm::buffer::LineJoin::Miter(mitre_angle()))
    };
    buffer_union_unbuffer_with(buffer, group, |g, d| g.buffer_with_style(style(d)))
}

/// [`buffer_union_unbuffer`] with the buffer operation passed in, so the
/// fallback for a buffer that loses area can be tested: geo's buffer does
/// not have the JTS bug the fallback exists for.
fn buffer_union_unbuffer_with(
    buffer: f64,
    group: &[&MultiPolygon<f64>],
    buffer_by: impl Fn(&MultiPolygon<f64>, f64) -> MultiPolygon<f64>,
) -> MultiPolygon<f64> {
    let mut max_area_before = 0.0f64;
    let mut buffered: Vec<Polygon<f64>> = Vec::new();
    for geometry in group {
        max_area_before = max_area_before.max(geometry.unsigned_area());
        buffered.extend(buffer_by(geometry, buffer).0);
    }
    let before_union = MultiPolygon(buffered);
    let union = unary_union(before_union.0.iter());
    let mut merged = buffer_by(&union, -buffer);

    let px2 = UNITS_PER_PIXEL * UNITS_PER_PIXEL;
    if max_area_before > 100.0 * px2 {
        let area_after = merged.unsigned_area();
        if area_after < max_area_before * 0.95 {
            let merged2 = buffer_by(&before_union, -buffer);
            let area_after2 = merged2.unsigned_area();
            if area_after2 < max_area_before * 0.95 {
                return unary_union(group.iter().flat_map(|g| g.0.iter()));
            }
            // Planetiler also checks `area_after2 > area_after`, which holds
            // here: area_after2 is at least the 95% that area_after is under.
            merged = merged2;
        }
    }
    merged
}

/// Connected groups of geometries at most `min_dist` apart (Planetiler's
/// `groupPolygonsByProximity`), each group's members ascending and groups in
/// order of their lowest member.
///
/// A union-find replaces Planetiler's adjacency list: a pair already in one
/// group is never measured, and intersecting geometries are accepted before
/// any exact distance is computed, so dense layers (thousands of landcover
/// polygons in one low-zoom tile) do not pay for every pair.
fn group_by_proximity(geometries: &[MultiPolygon<f64>], min_dist: f64) -> Vec<Vec<usize>> {
    let envelopes: Vec<Option<AABB<[f64; 2]>>> = geometries
        .iter()
        .map(|g| {
            g.bounding_rect()
                .map(|r| AABB::from_corners([r.min().x, r.min().y], [r.max().x, r.max().y]))
        })
        .collect();
    let tree = RTree::bulk_load(
        envelopes
            .iter()
            .enumerate()
            .filter_map(|(i, e)| {
                e.map(|e| {
                    let (lo, hi) = (e.lower(), e.upper());
                    GeomWithData::new(
                        Rectangle::from_corners(
                            [lo[0] - min_dist, lo[1] - min_dist],
                            [hi[0] + min_dist, hi[1] + min_dist],
                        ),
                        i,
                    )
                })
            })
            .collect(),
    );

    let mut parent: Vec<usize> = (0..geometries.len()).collect();
    const fn find(parent: &mut [usize], mut i: usize) -> usize {
        while parent[i] != i {
            parent[i] = parent[parent[i]];
            i = parent[i];
        }
        i
    }
    for (i, envelope) in envelopes.iter().enumerate() {
        let Some(envelope) = envelope else { continue };
        for candidate in tree.locate_in_envelope_intersecting(*envelope) {
            let j = candidate.data;
            if j <= i {
                continue;
            }
            let (ri, rj) = (find(&mut parent, i), find(&mut parent, j));
            if ri == rj {
                continue;
            }
            let near = geometries[i].intersects(&geometries[j])
                || (min_dist > 0.0
                    && Euclidean.distance(&geometries[i], &geometries[j]) <= min_dist);
            if near {
                // The lower root wins, so a group's root is its lowest member.
                let (lo, hi) = if ri < rj { (ri, rj) } else { (rj, ri) };
                parent[hi] = lo;
            }
        }
    }

    let mut slot: HashMap<usize, usize> = HashMap::new();
    let mut groups: Vec<Vec<usize>> = Vec::new();
    for i in 0..geometries.len() {
        let root = find(&mut parent, i);
        let g = *slot.entry(root).or_insert_with(|| {
            groups.push(Vec::new());
            groups.len() - 1
        });
        groups[g].push(i);
    }
    groups
}

/// Planetiler's `extractPolygons`: keep polygons whose exterior area is
/// over `min_area` and holes over `min_hole_area` (both in units squared),
/// and replace an exterior that covers the whole tile with a canonical
/// square so filled tiles are byte-identical and deduplicate.
fn extract_polygons(
    merged: &MultiPolygon<f64>,
    min_area: f64,
    min_hole_area: f64,
) -> Vec<Vec<Vec<Coord>>> {
    let mut out = Vec::new();
    for polygon in &merged.0 {
        let mut exterior = snap_ring(polygon.exterior());
        let outer_area = (shoelace(&exterior) as f64 / 2.0).abs();
        if exterior.len() < 3 || outer_area <= min_area {
            continue;
        }
        if let Some(fill) = canonical_fill(outer_area, &exterior) {
            exterior = fill;
        }
        let mut rings = vec![orient(exterior, true)];
        for hole in polygon.interiors() {
            let hole = snap_ring(hole);
            let hole_area = (shoelace(&hole) as f64 / 2.0).abs();
            if hole.len() >= 3 && (min_hole_area <= 0.0 || hole_area > min_hole_area) {
                rings.push(orient(hole, false));
            }
        }
        out.push(rings);
    }
    out
}

/// Wind a ring per the MVT spec: exteriors positive, holes negative.
fn orient(mut ring: Vec<Coord>, exterior: bool) -> Vec<Coord> {
    if (shoelace(&ring) > 0) != exterior {
        ring.reverse();
    }
    ring
}

/// If `ring` covers the whole tile, the canonical square it should become:
/// Planetiler's `isFill` and `createFill`.
fn canonical_fill(outer_area: f64, ring: &[Coord]) -> Option<Vec<Coord>> {
    const LEFT: u8 = 1;
    const RIGHT: u8 = 2;
    const TOP: u8 = 4;
    const BOTTOM: u8 = 8;
    let extent = f64::from(TILE_EXTENT);
    if outer_area < extent * extent {
        return None;
    }
    let proposed = (outer_area.sqrt() - extent) / 2.0;
    let (min, max) = (-(proposed * 0.9), extent + proposed * 0.9);
    let side = |(x, y): Coord| {
        let (x, y) = (f64::from(x), f64::from(y));
        let horizontal = if x < min {
            LEFT
        } else if x > max {
            RIGHT
        } else {
            0
        };
        let vertical = if y < min {
            TOP
        } else if y > max {
            BOTTOM
        } else {
            0
        };
        horizontal | vertical
    };
    let mut visited = 0u8;
    let mut closed = ring.to_vec();
    closed.push(ring[0]);
    for w in closed.windows(2) {
        let (a, b) = (side(w[0]), side(w[1]));
        visited |= a;
        if a & b == 0 {
            // The segment crosses the tile, so the ring does not enclose it.
            return None;
        }
    }
    if visited != LEFT | RIGHT | TOP | BOTTOM {
        return None;
    }
    let (lo, hi) = (
        (-proposed).round() as i32,
        (extent + proposed).round() as i32,
    );
    Some(vec![(lo, lo), (hi, lo), (hi, hi), (lo, hi)])
}

/// Merge same-attribute polygons that are within `min_dist` of each other:
/// Planetiler's `mergeNearbyPolygons`.
#[must_use]
pub fn merge_nearby_polygons(features: &[TileFeature], params: &PolygonMerge) -> Vec<TileFeature> {
    let (others, groups) = group_by_attrs(features, GeomType::Polygon);
    let mut result: Vec<TileFeature> = Vec::with_capacity(others.len() + groups.len());
    result.extend(others.into_iter().cloned());

    let px2 = UNITS_PER_PIXEL * UNITS_PER_PIXEL;
    let min_area = params.min_area * px2;
    let min_hole_area = params.min_hole_area * px2;
    let min_dist = params.min_dist * UNITS_PER_PIXEL;
    let buffer = params.buffer * UNITS_PER_PIXEL;

    for group in groups {
        let first = group[0];
        let geometries: Vec<MultiPolygon<f64>> = group
            .iter()
            .map(|f| MultiPolygon(decode_polygons(&f.geometry)))
            .collect();
        let mut polygons: Vec<Vec<Vec<Coord>>> = Vec::new();
        for members in group_by_proximity(&geometries, min_dist) {
            let merged = if members.len() > 1 {
                let parts: Vec<&MultiPolygon<f64>> =
                    members.iter().map(|&i| &geometries[i]).collect();
                let merged = if buffer > 0.0 {
                    buffer_union_unbuffer(buffer, &parts)
                } else {
                    unary_union(parts.iter().flat_map(|g| g.0.iter()))
                };
                if envelope_area(&merged) < min_area {
                    continue;
                }
                snap_and_fix(&merged)
            } else {
                let single = geometries[members[0]].clone();
                if envelope_area(&single) < min_area {
                    continue;
                }
                single
            };
            polygons.extend(extract_polygons(&merged, min_area, min_hole_area));
        }
        if polygons.is_empty() {
            continue;
        }
        polygons.sort_by_key(|rings| hilbert_index(rings[0][0]));
        let rings: Vec<Vec<Coord>> = polygons.into_iter().flatten().collect();
        result.push(with_geometry(first, mvt::encode_polygon(&rings)));
    }
    result
}

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

    fn props(kind: &str) -> Arc<Vec<(String, PropValue)>> {
        Arc::new(vec![("kind".to_string(), PropValue::Str(kind.to_string()))])
    }

    fn line(id: u64, kind: &str, coords: &[Coord]) -> TileFeature {
        TileFeature {
            layer: Layer::Roads,
            id,
            geom_type: GeomType::Line,
            geometry: mvt::encode_linestring(coords),
            properties: props(kind),
            sort_key: id as i32,
        }
    }

    fn square(x: i32, y: i32, size: i32) -> Vec<Coord> {
        // Clockwise on screen: an exterior ring.
        vec![(x, y), (x + size, y), (x + size, y + size), (x, y + size)]
    }

    fn polygon(id: u64, kind: &str, rings: &[Vec<Coord>]) -> TileFeature {
        TileFeature {
            layer: Layer::Buildings,
            id,
            geom_type: GeomType::Polygon,
            geometry: mvt::encode_polygon(rings),
            properties: props(kind),
            sort_key: id as i32,
        }
    }

    fn is_kind(f: &TileFeature, kind: &str) -> bool {
        f.properties[0].1 == PropValue::Str(kind.to_string())
    }

    fn total_area(f: &TileFeature) -> f64 {
        decode_polygons(&f.geometry)
            .iter()
            .map(geo::Area::unsigned_area)
            .sum()
    }

    const NO_LIMITS: LineMerge = LineMerge {
        min_length: 0.0,
        tolerance: -1.0,
        buffer: -1.0,
        resimplify: false,
    };

    #[test]
    fn hilbert_index_matches_planetiler_for_the_level_1_quadrants() {
        // Level-1 Hilbert curve order: (0,0)=0, (0,1)=1, (1,1)=2, (1,0)=3.
        assert_eq!(hilbert_xy_to_index(1, 0, 0), 0);
        assert_eq!(hilbert_xy_to_index(1, 0, 1), 1);
        assert_eq!(hilbert_xy_to_index(1, 1, 1), 2);
        assert_eq!(hilbert_xy_to_index(1, 1, 0), 3);
    }

    #[test]
    fn lines_with_the_same_attributes_merge_into_one_feature() {
        let features = vec![
            line(1, "major", &[(0, 0), (100, 0)]),
            line(2, "minor", &[(0, 50), (100, 50)]),
            line(3, "major", &[(100, 0), (200, 0)]),
        ];
        let merged = merge_line_strings(&features, &NO_LIMITS);
        assert_eq!(merged.len(), 2);
        let major = merged.iter().find(|f| is_kind(f, "major")).expect("major");
        assert_eq!(major.id, 1, "the group keeps its first feature's id");
        let parts = mvt::decode_commands(&major.geometry);
        assert_eq!(parts, vec![vec![(0, 0), (100, 0), (200, 0)]]);
        let minor = merged.iter().find(|f| is_kind(f, "minor")).expect("minor");
        assert_eq!(
            mvt::decode_commands(&minor.geometry),
            vec![vec![(0, 50), (100, 50)]]
        );
    }

    #[test]
    fn attribute_order_does_not_split_a_group() {
        let a = Arc::new(vec![
            ("kind".to_string(), PropValue::Str("x".into())),
            ("level".to_string(), PropValue::I64(1)),
        ]);
        let b = Arc::new(vec![
            ("level".to_string(), PropValue::I64(1)),
            ("kind".to_string(), PropValue::Str("x".into())),
        ]);
        let mut first = line(1, "x", &[(0, 0), (10, 0)]);
        first.properties = a;
        let mut second = line(2, "x", &[(10, 0), (20, 0)]);
        second.properties = b;
        assert_eq!(merge_line_strings(&[first, second], &NO_LIMITS).len(), 1);
    }

    #[test]
    fn a_lone_line_is_passed_through_when_nothing_could_change_it() {
        let features = vec![line(7, "major", &[(0, 0), (5, 5), (10, 0)])];
        let merged = merge_line_strings(&features, &NO_LIMITS);
        assert_eq!(merged, features);
    }

    #[test]
    fn non_line_features_keep_their_place_ahead_of_the_merged_groups() {
        let point = TileFeature {
            layer: Layer::Roads,
            id: 9,
            geom_type: GeomType::Point,
            geometry: mvt::encode_points(&[(5, 5)]),
            properties: props("label"),
            sort_key: 0,
        };
        let features = vec![line(1, "major", &[(0, 0), (10, 0)]), point.clone()];
        let merged = merge_line_strings(&features, &NO_LIMITS);
        assert_eq!(
            merged[0], point,
            "Planetiler emits the pass-through features first"
        );
    }

    #[test]
    fn lines_shorter_than_the_minimum_are_dropped() {
        // 0.5 px = 8 units; a 4-unit line goes, an 80-unit line stays.
        let features = vec![
            line(1, "major", &[(0, 0), (4, 0)]),
            line(2, "major", &[(1000, 1000), (1080, 1000)]),
        ];
        let params = LineMerge {
            min_length: 0.5,
            ..NO_LIMITS
        };
        let merged = merge_line_strings(&features, &params);
        assert_eq!(merged.len(), 1);
        assert_eq!(
            mvt::decode_commands(&merged[0].geometry),
            vec![vec![(1000, 1000), (1080, 1000)]]
        );
    }

    #[test]
    fn detail_well_outside_the_tile_is_cut_but_edge_crossings_kept() {
        // Runs from inside the tile to 10,000 units past its right edge,
        // with a vertex every 1000. With a 4 px (64 unit) buffer only the
        // part up to the first vertex past the edge survives.
        let coords: Vec<Coord> = (0..15).map(|i| (3000 + i * 1000, 100)).collect();
        let params = LineMerge {
            buffer: 4.0,
            ..NO_LIMITS
        };
        let merged = merge_line_strings(&[line(1, "major", &coords)], &params);
        let parts = mvt::decode_commands(&merged[0].geometry);
        assert_eq!(parts, vec![vec![(3000, 100), (4000, 100), (5000, 100)]]);
    }

    #[test]
    fn touching_polygons_with_the_same_attributes_become_one() {
        let params = PolygonMerge {
            min_area: 0.0,
            min_hole_area: 0.0,
            min_dist: 0.0,
            buffer: 0.0,
        };
        let features = vec![
            polygon(1, "building", &[square(0, 0, 100)]),
            polygon(2, "building", &[square(100, 0, 100)]),
            polygon(3, "other", &[square(1000, 1000, 100)]),
        ];
        let merged = merge_nearby_polygons(&features, &params);
        assert_eq!(merged.len(), 2);
        let building = merged
            .iter()
            .find(|f| is_kind(f, "building"))
            .expect("building");
        let polygons = decode_polygons(&building.geometry);
        assert_eq!(polygons.len(), 1, "the two squares share an edge");
        assert!((total_area(building) - 20_000.0).abs() < 1e-6);
    }

    #[test]
    fn near_polygons_merge_through_the_buffer_and_keep_their_area() {
        // Two 160-unit squares 4 units apart (a quarter pixel). With a
        // 0.5 px buffer they join; the gap is filled, so the area grows by
        // the 4 x 160 strip and no more.
        let params = PolygonMerge {
            min_area: 0.0,
            min_hole_area: 0.0,
            min_dist: 0.5,
            buffer: 0.5,
        };
        let features = vec![
            polygon(1, "building", &[square(0, 0, 160)]),
            polygon(2, "building", &[square(164, 0, 160)]),
        ];
        let merged = merge_nearby_polygons(&features, &params);
        assert_eq!(merged.len(), 1);
        assert_eq!(decode_polygons(&merged[0].geometry).len(), 1);
        let area = total_area(&merged[0]);
        assert!(
            (area - (2.0 * 160.0 * 160.0 + 4.0 * 160.0)).abs() < 200.0,
            "{area}"
        );
    }

    #[test]
    fn far_polygons_stay_separate_parts_of_one_feature() {
        let params = PolygonMerge {
            min_area: 0.0,
            min_hole_area: 0.0,
            min_dist: 0.5,
            buffer: 0.5,
        };
        let features = vec![
            polygon(1, "building", &[square(0, 0, 160)]),
            polygon(2, "building", &[square(2000, 2000, 160)]),
        ];
        let merged = merge_nearby_polygons(&features, &params);
        assert_eq!(merged.len(), 1);
        assert_eq!(decode_polygons(&merged[0].geometry).len(), 2);
    }

    #[test]
    fn holes_survive_a_merge_and_tiny_ones_are_dropped() {
        let big_hole = vec![(100, 100), (100, 300), (300, 300), (300, 100)];
        let tiny_hole = vec![(500, 500), (500, 502), (502, 502), (502, 500)];
        let params = PolygonMerge {
            min_area: 1.0,
            min_hole_area: 1.0,
            min_dist: 0.0,
            buffer: 0.0,
        };
        let features = vec![
            polygon(
                1,
                "water",
                &[square(0, 0, 1000), big_hole.clone(), tiny_hole],
            ),
            polygon(2, "water", &[square(1000, 0, 1000)]),
        ];
        let merged = merge_nearby_polygons(&features, &params);
        let polygons = decode_polygons(&merged[0].geometry);
        assert_eq!(polygons.len(), 1);
        assert_eq!(
            polygons[0].interiors().len(),
            1,
            "only the 200 x 200 hole is kept"
        );
        // MVT winding: the exterior has positive area, the hole negative.
        let signs: Vec<bool> = mvt::decode_commands(&merged[0].geometry)
            .iter()
            .map(|ring| shoelace(ring) > 0)
            .collect();
        assert_eq!(signs, [true, false]);
        let expected = 2.0 * 1000.0 * 1000.0 - 200.0 * 200.0;
        assert!((total_area(&merged[0]) - expected).abs() < 1e-6);
    }

    #[test]
    fn polygons_at_or_under_the_minimum_area_are_dropped() {
        // 1 px^2 = 256 units^2; a 10 x 10 square (100) goes.
        let params = PolygonMerge {
            min_area: 1.0,
            min_hole_area: 1.0,
            min_dist: 0.0,
            buffer: 0.0,
        };
        let features = vec![polygon(1, "building", &[square(0, 0, 10)])];
        assert!(merge_nearby_polygons(&features, &params).is_empty());
    }

    fn params(min_area: f64, min_dist: f64, buffer: f64) -> PolygonMerge {
        PolygonMerge {
            min_area,
            min_hole_area: 0.0,
            min_dist,
            buffer,
        }
    }

    fn with_props(mut feature: TileFeature, value: PropValue) -> TileFeature {
        feature.properties = Arc::new(vec![("v".to_string(), value)]);
        feature
    }

    #[test]
    fn every_property_type_groups_by_value() {
        // Two lines with one value join; a third with another value, though
        // it touches them, stays apart. 0.0 and -0.0 differ, as Java's
        // `Double.equals` has them.
        let pairs = [
            (PropValue::Str("a".into()), PropValue::Str("b".into())),
            (PropValue::F64(0.0), PropValue::F64(-0.0)),
            (PropValue::I64(-1), PropValue::I64(1)),
            (PropValue::U64(1), PropValue::U64(2)),
            (PropValue::Bool(true), PropValue::Bool(false)),
        ];
        for (same, other) in pairs {
            let features = vec![
                with_props(line(1, "x", &[(0, 0), (10, 0)]), same.clone()),
                with_props(line(2, "x", &[(10, 0), (20, 0)]), same.clone()),
                with_props(line(3, "x", &[(20, 0), (30, 0)]), other.clone()),
            ];
            let merged = merge_line_strings(&features, &NO_LIMITS);
            assert_eq!(merged.len(), 2, "{same:?} vs {other:?}");
            let joined = merged
                .iter()
                .find(|f| f.properties[0].1 == same)
                .expect("the first group");
            assert_eq!(
                mvt::decode_commands(&joined.geometry),
                vec![vec![(0, 0), (10, 0), (20, 0)]],
                "{same:?}"
            );
        }
    }

    #[test]
    fn a_lone_line_is_resimplified_only_when_asked() {
        // The midpoint is 4 units off the chord, under the 1 px (16 unit)
        // tolerance.
        let features = vec![line(1, "major", &[(0, 0), (100, 4), (200, 0)])];
        let keep = LineMerge {
            tolerance: 1.0,
            ..NO_LIMITS
        };
        assert_eq!(merge_line_strings(&features, &keep), features);
        let resimplify = LineMerge {
            resimplify: true,
            ..keep
        };
        let merged = merge_line_strings(&features, &resimplify);
        assert_eq!(
            mvt::decode_commands(&merged[0].geometry),
            vec![vec![(0, 0), (200, 0)]]
        );
    }

    #[test]
    fn a_group_whose_lines_are_all_too_short_disappears() {
        // 0.5 px = 8 units; the 4-unit minor line is the whole minor group.
        let features = vec![
            line(1, "minor", &[(0, 0), (4, 0)]),
            line(2, "major", &[(0, 100), (80, 100)]),
        ];
        let params = LineMerge {
            min_length: 0.5,
            ..NO_LIMITS
        };
        let merged = merge_line_strings(&features, &params);
        assert_eq!(merged.len(), 1);
        assert!(is_kind(&merged[0], "major"));
    }

    #[test]
    fn rings_that_cannot_form_a_polygon_are_dropped() {
        // MVT ClosePath is command 7 with count 1: (1 << 3) | 7.
        const CLOSE_PATH: u32 = 15;
        let mut two_points = mvt::encode_linestring(&[(0, 0), (10, 0)]);
        two_points.push(CLOSE_PATH);
        // A hole (negative area) before any exterior has nothing to cut.
        let mut stray_hole_first = mvt::encode_polygon(&[vec![(0, 0), (0, 50), (50, 50), (50, 0)]]);
        stray_hole_first.extend(mvt::encode_polygon(&[square(0, 0, 100)]));
        // A two-point ring after an exterior is no hole either.
        stray_hole_first.extend(two_points.iter().copied());
        let polygons = decode_polygons(&stray_hole_first);
        assert_eq!(polygons.len(), 1);
        assert!(polygons[0].interiors().is_empty());
        assert!(decode_polygons(&two_points).is_empty());

        // A feature with no usable ring has no bounding box; it takes no
        // part in the merge and the other feature comes through whole.
        let mut degenerate = polygon(1, "building", &[]);
        degenerate.geometry = two_points;
        let features = vec![degenerate, polygon(2, "building", &[square(0, 0, 100)])];
        let merged = merge_nearby_polygons(&features, &params(0.0, 0.5, 0.0));
        assert_eq!(merged.len(), 1);
        assert!((total_area(&merged[0]) - 10_000.0).abs() < 1e-6);
    }

    #[test]
    fn snapping_rounds_drops_repeats_and_the_closing_point() {
        let ring = LineString::from(vec![
            (0.2, 0.1),
            (0.4, 0.3),
            (10.2, 0.0),
            (10.0, 9.8),
            (0.1, 0.2),
        ]);
        assert_eq!(snap_ring(&ring), vec![(0, 0), (10, 0), (10, 10)]);
        let dot = LineString::from(vec![(0.1, 0.1), (0.2, 0.2), (0.1, 0.1)]);
        assert_eq!(snap_ring(&dot), vec![(0, 0)]);
    }

    #[test]
    fn snapping_drops_slivers_and_repairs_rings_it_made_invalid() {
        let sliver = Polygon::new(
            LineString::from(vec![(0.0, 0.0), (10.0, 0.0), (10.0, 0.2), (0.0, 0.2)]),
            vec![],
        );
        let block = Polygon::new(
            LineString::from(vec![(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)]),
            vec![],
        );
        let fixed = snap_and_fix(&MultiPolygon(vec![sliver, block]));
        assert_eq!(fixed.0.len(), 1);
        assert!((fixed.unsigned_area() - 10_000.0).abs() < 1e-9);

        // The spike at (5.4, 0.4) clears the bottom edge, but rounds onto
        // it at (5, 0): the snapped ring touches itself. Repaired, it is the
        // two triangles either side of the touch, 25 square units each.
        let spike = Polygon::new(
            LineString::from(vec![
                (0.0, 0.0),
                (10.0, 0.0),
                (10.0, 10.0),
                (5.4, 0.4),
                (0.0, 10.0),
            ]),
            vec![],
        );
        assert!(spike.is_valid());
        let fixed = snap_and_fix(&MultiPolygon(vec![spike]));
        assert!(fixed.is_valid(), "{fixed:?}");
        assert!((fixed.unsigned_area() - 50.0).abs() < 1e-9, "{fixed:?}");
    }

    #[test]
    fn a_chain_of_touching_polygons_is_one_group_in_any_order() {
        // C touches A and B, but A and B are 100 units apart: A and B only
        // join through C, which comes last.
        let features = vec![
            polygon(1, "building", &[square(0, 0, 100)]),
            polygon(2, "building", &[square(200, 0, 100)]),
            polygon(3, "building", &[square(100, 0, 100)]),
        ];
        let merged = merge_nearby_polygons(&features, &params(0.0, 0.0, 0.0));
        assert_eq!(decode_polygons(&merged[0].geometry).len(), 1);
        assert!((total_area(&merged[0]) - 30_000.0).abs() < 1e-6);

        // B and C each share an edge with A and meet each other at a
        // corner, so by the time B and C are compared they are one group.
        let features = vec![
            polygon(1, "building", &[square(0, 0, 200)]),
            polygon(2, "building", &[square(200, 100, 100)]),
            polygon(3, "building", &[square(100, 200, 100)]),
        ];
        let merged = merge_nearby_polygons(&features, &params(0.0, 0.0, 0.0));
        assert_eq!(decode_polygons(&merged[0].geometry).len(), 1);
        assert!((total_area(&merged[0]) - 60_000.0).abs() < 1e-6);
    }

    #[test]
    fn diagonal_neighbours_farther_than_min_dist_stay_apart() {
        // With min_dist 0.5 px (8 units) the boxes are 6 units apart on each
        // axis, so they are candidates, but the nearest corners are
        // sqrt(6^2 + 6^2), about 8.49 units, apart.
        let features = vec![
            polygon(1, "building", &[square(0, 0, 100)]),
            polygon(2, "building", &[square(106, 106, 100)]),
        ];
        let merged = merge_nearby_polygons(&features, &params(0.0, 0.5, 0.0));
        assert_eq!(decode_polygons(&merged[0].geometry).len(), 2);
        assert!((total_area(&merged[0]) - 20_000.0).abs() < 1e-6);
    }

    #[test]
    fn proximity_is_the_true_distance_not_the_box_distance() {
        // The same diagonal pair: boxes 6 units apart on each axis, corners
        // sqrt(72), about 8.49, apart. They group at a min_dist of 8.5 but
        // not at 8.4, though both distances put the boxes in reach.
        let pair = [block(0.0, 0.0, 100.0), block(106.0, 106.0, 100.0)];
        assert_eq!(group_by_proximity(&pair, 8.4), vec![vec![0], vec![1]]);
        assert_eq!(group_by_proximity(&pair, 8.5), vec![vec![0, 1]]);
    }

    #[test]
    fn a_merge_under_the_minimum_area_is_dropped() {
        // Two 5 x 5 squares: merged, a 10 x 5 box of 50 units^2, under the
        // 1 px^2 (256 units^2) minimum.
        let tiny = vec![
            polygon(1, "building", &[square(0, 0, 5)]),
            polygon(2, "building", &[square(5, 0, 5)]),
        ];
        assert!(merge_nearby_polygons(&tiny, &params(1.0, 0.0, 0.0)).is_empty());

        // An L of two 100 x 2 bars: its 100 x 100 box passes the 2 px^2
        // (512 units^2) minimum, but its area, 2 * 200 - 4 = 396, does not.
        let bars = vec![
            polygon(1, "building", &[vec![(0, 0), (100, 0), (100, 2), (0, 2)]]),
            polygon(2, "building", &[vec![(0, 0), (2, 0), (2, 100), (0, 100)]]),
        ];
        assert!(merge_nearby_polygons(&bars, &params(2.0, 0.0, 0.0)).is_empty());
        let merged = merge_nearby_polygons(&bars, &params(1.0, 0.0, 0.0));
        assert!((total_area(&merged[0]) - 396.0).abs() < 1e-6);
    }

    #[test]
    fn rings_are_wound_as_the_mvt_spec_requires() {
        // Clockwise on screen (Y down) is positive by the surveyor's formula.
        let clockwise = square(0, 0, 10);
        let counter: Vec<Coord> = clockwise.iter().rev().copied().collect();
        assert_eq!(orient(counter.clone(), true), clockwise);
        assert_eq!(orient(clockwise.clone(), true), clockwise);
        assert_eq!(orient(clockwise.clone(), false), counter);
        assert_eq!(orient(counter.clone(), false), counter);
    }

    /// The real buffer, except that shrinking a single polygon loses it,
    /// or, with `always`, that every shrink does: the JTS failure the
    /// fallback guards against.
    fn lossy(always: bool) -> impl Fn(&MultiPolygon<f64>, f64) -> MultiPolygon<f64> {
        move |g, d| {
            if d < 0.0 && (always || g.0.len() == 1) {
                MultiPolygon(vec![])
            } else {
                g.buffer_with_style(
                    BufferStyle::new(d)
                        .line_join(geo::algorithm::buffer::LineJoin::Miter(mitre_angle())),
                )
            }
        }
    }

    fn block(x: f64, y: f64, size: f64) -> MultiPolygon<f64> {
        MultiPolygon(vec![Polygon::new(
            LineString::from(vec![
                (x, y),
                (x + size, y),
                (x + size, y + size),
                (x, y + size),
            ]),
            vec![],
        )])
    }

    #[test]
    fn a_shrink_that_loses_area_falls_back_as_planetiler_does() {
        // Two 200 x 200 squares (40,000 units^2, over the 100 px^2 =
        // 25,600 floor) 4 units apart, grown and shrunk by 8.
        let (a, b) = (block(0.0, 0.0, 200.0), block(204.0, 0.0, 200.0));

        // The union's shrink is lost; shrinking the grown squares one by
        // one keeps each square, so that is used instead.
        let merged = buffer_union_unbuffer_with(8.0, &[&a, &b], lossy(false));
        assert_eq!(merged.0.len(), 2);
        assert!(
            (merged.unsigned_area() - 80_000.0).abs() < 1.0,
            "{merged:?}"
        );

        // Both shrinks are lost: the plain union of the inputs is kept.
        let merged = buffer_union_unbuffer_with(8.0, &[&a, &b], lossy(true));
        assert_eq!(merged, unary_union(a.0.iter().chain(b.0.iter())));
        assert!((merged.unsigned_area() - 80_000.0).abs() < 1e-9);

        // Under the floor nothing is checked: 100 x 100 squares (10,000
        // units^2) keep the lossy result.
        let (a, b) = (block(0.0, 0.0, 100.0), block(104.0, 0.0, 100.0));
        assert!(
            buffer_union_unbuffer_with(8.0, &[&a, &b], lossy(true))
                .0
                .is_empty()
        );
    }

    #[test]
    fn only_a_ring_round_all_four_sides_is_a_fill() {
        // 4296 units square, 100 past each tile edge, with extra vertices
        // mid-way along the top and left edges: still a fill.
        let ring = vec![
            (-100, -100),
            (2000, -100),
            (4196, -100),
            (4196, 4196),
            (-100, 4196),
            (-100, 2000),
        ];
        let area = (shoelace(&ring) as f64 / 2.0).abs();
        assert_eq!(area, 4296.0 * 4296.0);
        assert_eq!(
            canonical_fill(area, &ring),
            Some(vec![(-100, -100), (4196, -100), (4196, 4196), (-100, 4196)])
        );

        // A notch down to (2000, 2000) crosses into the tile.
        let notched = vec![
            (-100, -100),
            (2000, -100),
            (2000, 2000),
            (2100, -100),
            (4196, -100),
            (4196, 4196),
            (-100, 4196),
        ];
        let area = (shoelace(&notched) as f64 / 2.0).abs();
        assert!(area >= 4096.0 * 4096.0);
        assert_eq!(canonical_fill(area, &notched), None);

        // Bigger than the tile, but wholly off its left side.
        let left = vec![
            (-100_000, 0),
            (-90_000, 0),
            (-90_000, 2000),
            (-100_000, 2000),
        ];
        let area = (shoelace(&left) as f64 / 2.0).abs();
        assert!(area >= 4096.0 * 4096.0);
        assert_eq!(canonical_fill(area, &left), None);
    }

    #[test]
    fn a_polygon_covering_the_tile_becomes_the_canonical_fill() {
        let params = PolygonMerge {
            min_area: 1.0,
            min_hole_area: 1.0,
            min_dist: 0.0,
            buffer: 0.0,
        };
        // Two halves of a square overhanging the tile by 100 units each
        // side, with an extra vertex on one edge.
        let left = vec![(-100, -100), (2048, -100), (2048, 4196), (-100, 4196)];
        let right = vec![
            (2048, -100),
            (3000, -100),
            (4196, -100),
            (4196, 4196),
            (2048, 4196),
        ];
        let features = vec![polygon(1, "earth", &[left]), polygon(2, "earth", &[right])];
        let merged = merge_nearby_polygons(&features, &params);
        let rings = mvt::decode_commands(&merged[0].geometry);
        assert_eq!(
            rings,
            vec![vec![(-100, -100), (4196, -100), (4196, 4196), (-100, 4196)]]
        );
    }
}