Skip to main content

mln_engine/tile/
geometry_tile_data.rs

1// Polygon fixup runs on i_overlay, where C++ uses wagyu. Ring classification
2// and the conversions to and from longitude/latitude are in
3// `mln_style::feature`, where expressions reach them.
4
5use std::f64::consts::PI;
6
7use geometry::Point;
8use i_overlay::core::fill_rule::FillRule;
9use i_overlay::core::overlay::{Overlay, ShapeType};
10use i_overlay::core::overlay_rule::OverlayRule;
11use i_overlay::i_float::int::point::IntPoint;
12use mln_style::constants::EXTENT;
13use mln_style::feature::{
14    Feature, GeometryCollection, GeometryCoordinates, GeometryTileFeature, convert_geometry, signed_area,
15};
16use mln_style::tile_id::CanonicalTileID;
17
18use crate::tile::TileError;
19
20/// Repairs the rings of a polygon from a version 1 vector tile, whose spec
21/// doesn't require them to be wound or simple: unions them with an even-odd
22/// fill. Gives each polygon's outer ring, wound clockwise with y down as
23/// version 2 wants, followed by its holes, wound the other way; every ring
24/// is closed.
25#[must_use]
26pub(crate) fn fixup_polygons(rings: &GeometryCollection) -> GeometryCollection {
27    let mut overlay = Overlay::new(rings.iter().map(Vec::len).sum());
28    for ring in rings.iter() {
29        overlay.add_path_iter(ring.iter().map(|p| IntPoint::new(i32::from(p.x), i32::from(p.y))), ShapeType::Subject);
30    }
31
32    let mut result = GeometryCollection::new();
33    for shape in overlay.overlay(OverlayRule::Subject, FillRule::EvenOdd) {
34        for contour in shape {
35            // The union's vertices lie within the input's bounding box, so
36            // they fit an i16.
37            let mut ring: GeometryCoordinates = contour.iter().map(|p| Point::new(p.x as i16, p.y as i16)).collect();
38            if let Some(&first) = ring.first() {
39                ring.push(first);
40            }
41            result.push(ring);
42        }
43    }
44    result
45}
46
47/// Truncates `polygon` to its `max_holes` largest inner rings by absolute
48/// area. The order of the kept rings is unspecified, and so is which of
49/// several rings tied at the cut is kept.
50pub fn limit_holes(polygon: &mut GeometryCollection, max_holes: u32) {
51    let max_holes = max_holes as usize;
52    if polygon.len() > 1 + max_holes {
53        polygon[1..].select_nth_unstable_by(max_holes, |a, b| signed_area(b).abs().total_cmp(&signed_area(a).abs()));
54        polygon.truncate(1 + max_holes);
55    }
56}
57
58/// Converts a feature of `tile_id` whose geometry is `geometries` to a
59/// `Feature` in longitude/latitude, with its properties and id. Fails as
60/// [`convert_geometry`] does.
61pub(crate) fn convert_feature(
62    feature: &dyn GeometryTileFeature,
63    geometries: &GeometryCollection,
64    tile_id: &CanonicalTileID,
65) -> Result<Feature<f64>, TileError> {
66    let mut converted = Feature::new(convert_geometry(feature.get_type(), geometries, tile_id)?);
67    converted.properties = feature.get_properties().into_owned();
68    converted.id = feature.get_id();
69    Ok(converted)
70}
71
72/// Whether the edge from `a` to `b` runs along a line the tile was clipped
73/// at. Clipping cuts on the buffer around the tile, so such an edge lies
74/// outside it, and belongs to the cut rather than to the feature.
75#[must_use]
76pub fn is_boundary_edge(a: Point<i16>, b: Point<i16>) -> bool {
77    let outside = |v: i16| v < 0 || i32::from(v) > EXTENT;
78    (a.x == b.x && outside(a.x)) || (a.y == b.y && outside(a.y))
79}
80
81/// Whether all of `ring` lies beyond one edge of the tile, in its buffer.
82#[must_use]
83pub fn is_entirely_outside(ring: &[Point<i16>]) -> bool {
84    let extent = |v: i16| i32::from(v);
85    ring.iter().all(|p| p.x < 0)
86        || ring.iter().all(|p| extent(p.x) > EXTENT)
87        || ring.iter().all(|p| p.y < 0)
88        || ring.iter().all(|p| extent(p.y) > EXTENT)
89}
90
91/// Replaces each corner of the rings of `polygon` with an arc whose ends
92/// lie `corner_distance` tile units from the corner along its edges, or 20%
93/// of the shorter edge if that is less, in steps of at most 30°.
94///
95/// Corners that turn by less than 5° or nearly reverse stay sharp, and so
96/// do corners on a line the tile was clipped at: the neighbouring tile cuts
97/// the feature elsewhere, and the two halves have to meet. The vertices are
98/// rounded to whole tile units, dropping any that then repeat the one
99/// before, since arcs finer than a unit would triangulate into spikes. A
100/// ring with fewer than three distinct vertices, before or after rounding,
101/// is kept as it is. Closed rings stay closed.
102#[must_use]
103pub fn round_polygon_corners(polygon: &GeometryCollection, corner_distance: f64) -> GeometryCollection {
104    GeometryCollection::from(polygon.iter().map(|ring| round_ring(ring, corner_distance)).collect::<Vec<_>>())
105}
106
107fn round_ring(ring: &GeometryCoordinates, corner_distance: f64) -> GeometryCoordinates {
108    let closed = ring.len() > 1 && ring.first() == ring.last();
109    let vertex_count = if closed { ring.len() - 1 } else { ring.len() };
110    if vertex_count < 3 {
111        return ring.clone();
112    }
113
114    let mut rounded = Vec::with_capacity(vertex_count * 4);
115    let mut previous_is_boundary = is_boundary_edge(ring[vertex_count - 1], ring[0]);
116    for i in 0..vertex_count {
117        let previous = ring[(i + vertex_count - 1) % vertex_count];
118        let corner = ring[i];
119        let next = ring[(i + 1) % vertex_count];
120        let next_is_boundary = is_boundary_edge(corner, next);
121        if previous_is_boundary || next_is_boundary {
122            rounded.push(Point::new(f64::from(corner.x), f64::from(corner.y)));
123        } else {
124            append_round_corner(&mut rounded, previous, corner, next, corner_distance);
125        }
126        previous_is_boundary = next_is_boundary;
127    }
128
129    // Halves round up, as in GL JS. The arcs lie within the corners they
130    // replace, so they fit an i16.
131    let snap = |v: f64| (v + 0.5).floor() as i16;
132    let mut snapped = GeometryCoordinates::with_capacity(rounded.len() + 1);
133    for p in rounded {
134        let p = Point::new(snap(p.x), snap(p.y));
135        if snapped.last() != Some(&p) {
136            snapped.push(p);
137        }
138    }
139    while snapped.len() > 1 && snapped.first() == snapped.last() {
140        snapped.pop();
141    }
142    if snapped.len() < 3 {
143        return ring.clone();
144    }
145    if closed {
146        snapped.push(snapped[0]);
147    }
148    snapped
149}
150
151/// Appends to `ring` the arc that replaces `corner`, between `previous` and
152/// `next`, or the corner itself when it is too shallow or too sharp to
153/// round.
154fn append_round_corner(
155    ring: &mut Vec<Point<f64>>,
156    previous: Point<i16>,
157    corner: Point<i16>,
158    next: Point<i16>,
159    corner_distance: f64,
160) {
161    const MAX_EDGE_FRACTION: f64 = 0.2;
162
163    let c = Point::new(f64::from(corner.x), f64::from(corner.y));
164    let towards = |p: Point<i16>| Point::new(f64::from(p.x) - c.x, f64::from(p.y) - c.y);
165    let (a, b) = (towards(previous), towards(next));
166    let (len_a, len_b) = (a.x.hypot(a.y), b.x.hypot(b.y));
167    if len_a == 0.0 || len_b == 0.0 {
168        ring.push(c);
169        return;
170    }
171    let ua = Point::new(a.x / len_a, a.y / len_a);
172    let ub = Point::new(b.x / len_b, b.y / len_b);
173
174    let dot = ua.x * ub.x + ua.y * ub.y;
175    if dot.abs() > mln_style::math::deg2rad(5.0).cos() {
176        ring.push(c);
177        return;
178    }
179
180    let r = corner_distance.min(len_a * MAX_EDGE_FRACTION).min(len_b * MAX_EDGE_FRACTION);
181    let tangent_a = Point::new(c.x + ua.x * r, c.y + ua.y * r);
182    let tangent_b = Point::new(c.x + ub.x * r, c.y + ub.y * r);
183
184    // The arc's center lies on the bisector, r / cos(θ/2) from the corner.
185    let bisector = Point::new(ua.x + ub.x, ua.y + ub.y);
186    let to_center = r / f64::midpoint(1.0, dot).sqrt() / bisector.x.hypot(bisector.y);
187    let center = Point::new(c.x + bisector.x * to_center, c.y + bisector.y * to_center);
188
189    // Rotates tangent A around the center onto tangent B, the short way.
190    let from = Point::new(tangent_a.x - center.x, tangent_a.y - center.y);
191    let to = Point::new(tangent_b.x - center.x, tangent_b.y - center.y);
192    let sweep = (from.x * to.y - from.y * to.x).atan2(from.x * to.x + from.y * to.y);
193    // The epsilon keeps rounding error from adding a step at a multiple of 30°.
194    let steps = ((sweep.abs() / (PI / 6.0) - 1e-6).ceil() as i32).max(2);
195    for step in 0..=steps {
196        let (sin, cos) = (sweep * f64::from(step) / f64::from(steps)).sin_cos();
197        ring.push(Point::new(center.x + cos * from.x - sin * from.y, center.y + sin * from.x + cos * from.y));
198    }
199}
200
201#[cfg(test)]
202mod tests {
203    use mln_style::feature::classify_rings;
204
205    use super::*;
206
207    fn ring(points: &[(i16, i16)]) -> GeometryCoordinates {
208        points.iter().map(|&(x, y)| Point::new(x, y)).collect()
209    }
210
211    fn collection(rings: &[&[(i16, i16)]]) -> GeometryCollection {
212        GeometryCollection::from(rings.iter().map(|r| ring(r)).collect::<Vec<_>>())
213    }
214
215    fn test_signed_area(ring: &GeometryCoordinates) -> f64 {
216        signed_area(ring)
217    }
218
219    /// The (outer ring, hole count) of each polygon, with every ring
220    /// closed and wound as `fixup_polygons` promises.
221    fn fixed_polygons(rings: &[&[(i16, i16)]]) -> Vec<(GeometryCoordinates, usize)> {
222        let fixed = fixup_polygons(&collection(rings));
223        let polygons = classify_rings(&fixed);
224        for polygon in &polygons {
225            for (i, ring) in polygon.iter().enumerate() {
226                assert_eq!(ring.first(), ring.last(), "{ring:?}");
227                assert_eq!(signed_area(ring) > 0.0, i == 0, "{ring:?}");
228            }
229        }
230        polygons.iter().map(|polygon| (polygon[0].clone(), polygon.len() - 1)).collect()
231    }
232
233    #[test]
234    fn fixup_polygons_rewinds_rings() {
235        // Two outer rings wound opposite ways, and a hole wound as its
236        // outer ring is.
237        let polygons = fixed_polygons(&[
238            &[(0, 0), (0, 40), (40, 40), (40, 0), (0, 0)],
239            &[(10, 10), (10, 20), (20, 20), (20, 10), (10, 10)],
240            &[(50, 0), (90, 0), (90, 40), (50, 40), (50, 0)],
241        ]);
242        assert_eq!(polygons.len(), 2);
243        let mut holes: Vec<usize> = polygons.iter().map(|(_, holes)| *holes).collect();
244        holes.sort_unstable();
245        assert_eq!(holes, [0, 1]);
246    }
247
248    #[test]
249    fn fixup_polygons_splits_a_self_intersecting_ring() {
250        let polygons = fixed_polygons(&[&[(0, 0), (20, 20), (20, 0), (0, 20), (0, 0)]]);
251        assert_eq!(polygons.len(), 2);
252        for (outer, holes) in &polygons {
253            assert_eq!(*holes, 0);
254            assert_eq!(outer.len(), 4, "a closed triangle: {outer:?}");
255            // Twice the triangle's area.
256            assert_eq!(signed_area(outer), 200.0);
257        }
258    }
259
260    // gtest: GeometryTileData.limitHoles1
261    #[test]
262    fn limit_holes1() {
263        let mut polygon = collection(&[
264            &[(0, 0), (0, 40), (40, 40), (40, 0), (0, 0)],
265            &[(30, 30), (32, 30), (32, 32), (30, 30)],
266            &[(10, 10), (20, 10), (20, 20), (10, 10)],
267        ]);
268
269        limit_holes(&mut polygon, 1);
270
271        // output: polygon 1 has 1 exterior, 1 interior
272        assert_eq!(polygon.len(), 2);
273
274        // ensure we've kept the right rings (ones with largest areas)
275        assert_eq!(polygon[0][0].x, 0);
276        assert_eq!(polygon[1][0].x, 10);
277    }
278
279    // gtest: GeometryTileData.limitHoles2
280    #[test]
281    fn limit_holes2() {
282        let mut polygon = collection(&[
283            &[(0, 0), (0, 40), (40, 40), (40, 0), (0, 0)],
284            &[(10, 10), (20, 10), (20, 20), (10, 10)],
285            &[(30, 30), (32, 30), (32, 32), (30, 30)],
286        ]);
287
288        limit_holes(&mut polygon, 1);
289
290        // output: polygon 1 has 1 exterior, 1 interior
291        assert_eq!(polygon.len(), 2);
292
293        // ensure we've kept the right rings (ones with largest areas)
294        assert_eq!(polygon[0][0].x, 0);
295        assert_eq!(polygon[1][0].x, 10);
296    }
297
298    // gtest: GeometryTileData.limitHoles3
299    #[test]
300    fn limit_holes3() {
301        // real world polygon with interior rings with negative areas
302        // that need to be sorted in `limitHoles` by comparing absolute
303        // area not signed
304        let mut polygon = collection(&[
305            &[
306                (7336, -248),
307                (7304, -248),
308                (7272, -168),
309                (7176, -200),
310                (7080, -136),
311                (7048, -56),
312                (7128, -8),
313                (7176, -56),
314                (7288, -56),
315                (7316, 0),
316                (6918, 0),
317                (6904, -40),
318                (6984, -72),
319                (6952, -88),
320                (6952, -168),
321                (6888, -88),
322                (6856, -88),
323                (6856, -8),
324                (6872, 0),
325                (6170, 0),
326                (6184, -40),
327                (6136, -72),
328                (6104, -56),
329                (6132, 0),
330                (6028, 0),
331                (6104, -152),
332                (6184, -200),
333                (6206, -256),
334                (6272, -256),
335                (6264, -248),
336                (6248, -120),
337                (6280, -136),
338                (6280, -232),
339                (6288, -256),
340                (6790, -256),
341                (6792, -248),
342                (6800, -256),
343                (7058, -256),
344                (7064, -248),
345                (7096, -256),
346                (7338, -256),
347                (7336, -248),
348            ],
349            &[(6344, -104), (6264, -8), (6392, -72), (6360, -200), (6344, -104)],
350            &[(6744, -24), (6760, -72), (6728, -104), (6744, -24)],
351            &[(6616, -104), (6648, -88), (6632, -72), (6664, -56), (6664, -120), (6616, -104)],
352        ]);
353
354        // make a copy for later testing
355        let original = polygon.clone();
356
357        assert_eq!(polygon.len(), 4);
358        assert_eq!(test_signed_area(&polygon[0]), 515_360.0); // exterior
359        assert_eq!(test_signed_area(&polygon[1]), -12288.0); // biggest interior ring
360        assert_eq!(test_signed_area(&polygon[2]), -2048.0); // smallest interior ring
361        assert_eq!(test_signed_area(&polygon[3]), -3072.0); // second largest interior ring
362
363        limit_holes(&mut polygon, 2);
364
365        // output: polygon 1 has 1 exterior, 2 interior
366        assert_eq!(polygon.len(), 3);
367
368        // ensure we've kept the exterior ring
369        assert_eq!(original[0], polygon[0]);
370
371        // ensure we've kept the two largest interior rings, in either order
372        assert!(polygon[1..].contains(&original[1]));
373        assert!(polygon[1..].contains(&original[3]));
374    }
375    fn points(ring: &GeometryCoordinates) -> Vec<(i16, i16)> {
376        ring.iter().map(|p| (p.x, p.y)).collect()
377    }
378
379    #[test]
380    fn round_polygon_corners_square() {
381        let polygon = collection(&[&[(0, 0), (100, 0), (100, 100), (0, 100), (0, 0)]]);
382        let rounded = round_polygon_corners(&polygon, 10.0);
383
384        // Each right angle turns in three 30° steps around a center 10 units
385        // in from the corner, and the vertices snap to whole units.
386        assert_eq!(
387            points(&rounded[0]),
388            [
389                (0, 10),
390                (1, 5),
391                (5, 1),
392                (10, 0),
393                (90, 0),
394                (95, 1),
395                (99, 5),
396                (100, 10),
397                (100, 90),
398                (99, 95),
399                (95, 99),
400                (90, 100),
401                (10, 100),
402                (5, 99),
403                (1, 95),
404                (0, 90),
405                (0, 10),
406            ]
407        );
408    }
409
410    #[test]
411    fn round_polygon_corners_clamps_to_a_fifth_of_the_shorter_edge() {
412        let polygon = collection(&[&[(0, 0), (100, 0), (100, 50), (0, 50), (0, 0)]]);
413        let rounded = round_polygon_corners(&polygon, 1000.0);
414
415        // The shorter edges are 50 long: every arc starts and ends 10 away.
416        assert_eq!(points(&rounded[0])[..5], [(0, 10), (1, 5), (5, 1), (10, 0), (90, 0)]);
417    }
418
419    #[test]
420    fn round_polygon_corners_keeps_corners_on_clip_lines_sharp() {
421        // The edge at x = -64 is where the tile's buffer clipped the feature.
422        let polygon = collection(&[&[(-64, 0), (100, 0), (100, 100), (-64, 100), (-64, 0)]]);
423        let rounded = round_polygon_corners(&polygon, 10.0);
424
425        let rounded = points(&rounded[0]);
426        assert_eq!(rounded.len(), 2 * 4 + 2 + 1);
427        assert_eq!(rounded[0], (-64, 0));
428        assert!(rounded.contains(&(-64, 100)));
429        assert!(!rounded.contains(&(100, 0)));
430    }
431
432    #[test]
433    fn round_polygon_corners_drops_vertices_that_snap_together() {
434        // Arcs under half a unit snap back onto their corners.
435        let polygon = collection(&[&[(0, 0), (100, 0), (100, 100), (0, 100), (0, 0)]]);
436        assert_eq!(round_polygon_corners(&polygon, 0.4), polygon);
437    }
438
439    #[test]
440    fn round_polygon_corners_rounds_every_ring() {
441        let polygon = collection(&[
442            &[(0, 0), (100, 0), (100, 100), (0, 100), (0, 0)],
443            &[(25, 25), (25, 75), (75, 75), (75, 25), (25, 25)],
444        ]);
445        let rounded = round_polygon_corners(&polygon, 5.0);
446
447        assert_eq!(rounded.len(), 2);
448        assert_eq!(rounded[0].len(), 17);
449        assert_eq!(rounded[1].len(), 17);
450        assert_eq!(rounded[1].first(), rounded[1].last());
451        assert_eq!(points(&rounded[1])[0], (30, 25));
452    }
453
454    #[test]
455    fn round_polygon_corners_keeps_straight_and_reversing_vertices() {
456        // (50, 0) lies on a straight edge; at (200, 1) the ring turns back.
457        let polygon = collection(&[&[(0, 0), (50, 0), (200, 1), (0, 2), (0, 0)]]);
458        let rounded = points(&round_polygon_corners(&polygon, 10.0)[0]);
459
460        assert!(rounded.contains(&(50, 0)));
461        assert!(rounded.contains(&(200, 1)));
462    }
463
464    #[test]
465    fn is_entirely_outside_needs_every_vertex_past_one_edge() {
466        assert!(is_entirely_outside(&ring(&[(8200, 0), (9000, 100), (8193, 9000)])));
467        assert!(is_entirely_outside(&ring(&[(0, -5), (100, -1), (50, -2000)])));
468        // Each vertex is outside, but past different edges.
469        assert!(!is_entirely_outside(&ring(&[(-10, 100), (100, -10), (-10, -10)])));
470        assert!(!is_entirely_outside(&ring(&[(8192, 0), (9000, 100), (9000, 9000)])));
471    }
472
473    #[test]
474    fn round_polygon_corners_keeps_degenerate_rings() {
475        let polygon = collection(&[&[], &[(1, 1)], &[(1, 1), (1, 1)], &[(0, 0), (9, 0), (0, 0)]]);
476        assert_eq!(round_polygon_corners(&polygon, 10.0), polygon);
477    }
478}