Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
cov/c3 ▾

Modern-Apps.git / scripts / maps / osm_ingest / src / rings.rs

rings.rs465 lines · 18.1 KiBRaw
1//! Assembling a boundary relation's member ways into closed rings, and those rings
2//! into polygons.
3//!
4//! This is the piece [`crate::poi_build`] deliberately did not do. It approximated a
5//! relation's outer ring by **sorting and deduplicating** the member ways' node ids,
6//! which is exact for a centroid -- averaging is order-independent -- and destroys
7//! the ring. Its own comment says so. Nothing built on that approximation can have
8//! an area, a winding order, or a point-in-polygon test.
9//!
10//! Two things follow, and both are load-bearing:
11//!
12//! * **This module must not sort or dedup refs.** Vertex order *is* the geometry.
13//! * **`poi_build` must be left alone.** Its centroids match the libosmium C++ they
14//! replaced, to within a documented 3.1 m worst case, and `poi_index.bin` is a
15//! published artefact. Changing how it derives a centroid would move POIs for no
16//! benefit to this layer.
17//!
18//! # The assembler
19//!
20//! 1. **Bucket members by role.** `outer` and the **empty role** are both outer:
21//! the OSM boundary convention is that an unroled way in a `boundary` relation is
22//! part of the outer edge, and in real data most of them are unroled. `inner` is
23//! a hole. Any other role is ignored.
24//! 2. **Stitch.** Ways in a relation are in no particular order and no particular
25//! direction, so a ring is found by walking an endpoint -> way multimap,
26//! reversing a way whenever its far end is the one that matches. This is what
27//! libosmium's `Assembler` does.
28//! 3. **Drop and log what will not close.** A ring that runs out of candidate ways
29//! before returning to its start is a data error -- a missing member, a way
30//! clipped away by the extract, a genuine tagging mistake. Emitting it as an
31//! open ring would render as a wedge of fill reaching to wherever the renderer
32//! decides to close it, which is far worse than the boundary being absent.
33//! 4. **Classify into polygons.** Inner rings are matched to the outer ring that
34//! contains them, by point-in-ring containment, and the outer ring is chosen by
35//! smallest area among those that contain the hole -- nesting means several may.
36
37use crate::geojson::Coord;
38
39/// A member way's ordered node refs, and the role it had in the relation.
40pub struct MemberWay {
41 pub refs: Vec<i64>,
42 pub outer: bool,
43}
44
45/// One assembled polygon: its exterior ring first, then its holes. Every ring is
46/// explicitly closed.
47pub type Polygon = Vec<Vec<Coord>>;
48
49/// What an assembly cost, for the report the operator is owed.
50#[derive(Debug, Default, Clone, PartialEq)]
51pub struct RingStats {
52 pub outer_rings: usize,
53 pub inner_rings: usize,
54 /// Rings that ran out of ways before closing, and were dropped.
55 pub unclosed: usize,
56 /// Holes with no containing outer ring, and were dropped.
57 pub orphan_inner: usize,
58}
59
60/// Assemble `members` into polygons. `locate` resolves a node id to `(lon, lat)`.
61///
62/// Returns the polygons and a report. An empty result means nothing closed.
63pub fn assemble<L>(members: &[MemberWay], locate: L, stats: &mut RingStats) -> Vec<Polygon>
64where
65 L: Fn(i64) -> Option<Coord>,
66{
67 let outer = stitch(members.iter().filter(|m| m.outer), stats);
68 let inner = stitch(members.iter().filter(|m| !m.outer), stats);
69 stats.outer_rings += outer.len();
70 stats.inner_rings += inner.len();
71
72 // Resolve to coordinates only once the topology is settled: stitching is about
73 // node identity, and comparing coordinates instead would weld two distinct
74 // nodes that happen to share a position.
75 let outer: Vec<Vec<Coord>> = outer.iter().filter_map(|r| resolve(r, &locate)).collect();
76 let inner: Vec<Vec<Coord>> = inner.iter().filter_map(|r| resolve(r, &locate)).collect();
77
78 let mut polygons: Vec<Polygon> = outer.into_iter().map(|r| vec![r]).collect();
79 for hole in inner {
80 match containing(&polygons, &hole) {
81 Some(i) => polygons[i].push(hole),
82 // A hole with nothing around it is not a shape, and emitting it would
83 // render as solid fill in the layer's colour.
84 None => stats.orphan_inner += 1,
85 }
86 }
87 polygons
88}
89
90/// Walk the ways into closed rings of node ids. Each returned ring is explicitly
91/// closed (first == last).
92fn stitch<'a, I>(ways: I, stats: &mut RingStats) -> Vec<Vec<i64>>
93where
94 I: Iterator<Item = &'a MemberWay>,
95{
96 // Index by both endpoints, since a way may be traversed either way round.
97 let mut pool: Vec<Option<Vec<i64>>> = ways
98 .filter(|w| w.refs.len() >= 2)
99 .map(|w| Some(w.refs.clone()))
100 .collect();
101
102 let mut rings: Vec<Vec<i64>> = Vec::new();
103 for start in 0..pool.len() {
104 let Some(first) = pool[start].take() else {
105 continue;
106 };
107 let mut ring = first;
108 loop {
109 if ring.len() > 2 && ring.first() == ring.last() {
110 rings.push(ring);
111 break;
112 }
113 let tail = *ring.last().expect("non-empty");
114 // Find any unused way starting or ending at the current tail.
115 let next = pool.iter().position(|w| {
116 w.as_ref()
117 .is_some_and(|r| r.first() == Some(&tail) || r.last() == Some(&tail))
118 });
119 let Some(i) = next else {
120 // Nothing joins on: this ring cannot close.
121 stats.unclosed += 1;
122 break;
123 };
124 let mut piece = pool[i].take().expect("just found");
125 if piece.first() != Some(&tail) {
126 piece.reverse();
127 }
128 // The shared endpoint is already the ring's tail.
129 ring.extend_from_slice(&piece[1..]);
130
131 // A way that closed the ring on its own, or a degenerate self-loop, is
132 // caught by the check at the top of the loop.
133 if ring.len() > 100_000_000 {
134 // Cannot happen with real data; guards against a pathological
135 // multimap cycle turning into an OOM rather than an error.
136 stats.unclosed += 1;
137 break;
138 }
139 }
140 }
141 rings
142}
143
144/// Resolve a ring of node ids to coordinates. `None` when too few resolve to
145/// enclose an area.
146///
147/// Unlike a line, a ring with a missing vertex is **not** kept with a gap: closing
148/// across the gap invents an edge, and for an area that changes what is inside it.
149fn resolve<L>(ring: &[i64], locate: &L) -> Option<Vec<Coord>>
150where
151 L: Fn(i64) -> Option<Coord>,
152{
153 let coords: Vec<Coord> = ring.iter().map(|id| locate(*id)).collect::<Option<_>>()?;
154 // Three distinct vertices plus the repeated close.
155 if coords.len() < 4 {
156 return None;
157 }
158 Some(coords)
159}
160
161/// Index of the smallest outer ring containing `hole`, if any.
162///
163/// Smallest, because boundaries nest: a city inside a county inside a state means
164/// several outer rings may contain the same hole, and the hole belongs to the
165/// tightest one.
166fn containing(polygons: &[Polygon], hole: &[Coord]) -> Option<usize> {
167 let probe = *hole.first()?;
168 let mut best: Option<(usize, f64)> = None;
169 for (i, poly) in polygons.iter().enumerate() {
170 let outer = &poly[0];
171 if !point_in_ring(probe, outer) {
172 continue;
173 }
174 let area = ring_area(outer).abs();
175 if best.is_none_or(|(_, b)| area < b) {
176 best = Some((i, area));
177 }
178 }
179 best.map(|(i, _)| i)
180}
181
182/// Twice the signed area of a ring, by the surveyor's formula.
183///
184/// In lon/lat degrees, so it is not an area on the ground -- but every use here is a
185/// comparison or a sign test, and for that a consistent planar measure is the right
186/// tool. A spherical area would cost a lot and change no decision.
187pub fn ring_area(ring: &[Coord]) -> f64 {
188 let n = ring.len();
189 if n < 3 {
190 return 0.0;
191 }
192 let mut sum = 0.0;
193 for i in 0..n {
194 let (x1, y1) = ring[i];
195 let (x2, y2) = ring[(i + 1) % n];
196 sum += x1 * y2 - x2 * y1;
197 }
198 sum
199}
200
201/// Ray-casting point-in-polygon. `true` when `p` is inside `ring`.
202///
203/// The half-open `(y1 > y) != (y2 > y)` test is what makes a vertex exactly at the
204/// probe's latitude count once rather than twice, so a ray grazing a vertex does not
205/// flip the answer.
206pub fn point_in_ring((x, y): Coord, ring: &[Coord]) -> bool {
207 let mut inside = false;
208 let n = ring.len();
209 if n < 3 {
210 return false;
211 }
212 for i in 0..n {
213 let (x1, y1) = ring[i];
214 let (x2, y2) = ring[(i + 1) % n];
215 if (y1 > y) != (y2 > y) {
216 let t = (y - y1) / (y2 - y1);
217 if x < x1 + t * (x2 - x1) {
218 inside = !inside;
219 }
220 }
221 }
222 inside
223}
224
225#[cfg(test)]
226mod tests {
227 use super::*;
228
229 fn way(refs: &[i64], outer: bool) -> MemberWay {
230 MemberWay { refs: refs.to_vec(), outer }
231 }
232
233 /// A 4x4 grid of nodes, ids 1..=16, so a ring can be described by ids alone.
234 /// Node `n` sits at `(lon, lat) = ((n-1) % 4, (n-1) / 4)`.
235 fn grid(id: i64) -> Option<Coord> {
236 (1..=16).contains(&id).then(|| {
237 let i = (id - 1) as f64;
238 ((i % 4.0), (i / 4.0).floor())
239 })
240 }
241
242 /// The unit square's corners, and a smaller square inside it.
243 fn square(min: f64, max: f64) -> Vec<Coord> {
244 vec![(min, min), (max, min), (max, max), (min, max), (min, min)]
245 }
246
247 #[test]
248 fn a_single_closed_way_is_already_a_ring() {
249 let mut stats = RingStats::default();
250 let polys = assemble(&[way(&[1, 4, 16, 13, 1], true)], grid, &mut stats);
251 assert_eq!(polys.len(), 1);
252 assert_eq!(polys[0].len(), 1, "no holes");
253 assert_eq!(polys[0][0].len(), 5);
254 assert_eq!(polys[0][0].first(), polys[0][0].last());
255 assert_eq!(stats, RingStats { outer_rings: 1, ..Default::default() });
256 }
257
258 #[test]
259 fn several_ways_stitch_into_one_ring() {
260 // The square 1-4-16-13 split into four ways, in a scrambled order and with
261 // two of them pointing the wrong way. This is what real boundary relations
262 // look like.
263 let mut stats = RingStats::default();
264 let members = vec![
265 way(&[16, 13], true), // reversed
266 way(&[1, 4], true),
267 way(&[13, 1], true),
268 way(&[16, 4], true), // reversed
269 ];
270 let polys = assemble(&members, grid, &mut stats);
271 assert_eq!(polys.len(), 1, "{stats:?}");
272 assert_eq!(stats.unclosed, 0);
273 // Four corners plus the close, whichever way round it came out.
274 assert_eq!(polys[0][0].len(), 5, "{:?}", polys[0][0]);
275 assert!(ring_area(&polys[0][0]).abs() > 0.0);
276 }
277
278 #[test]
279 fn a_way_is_reversed_when_its_far_end_is_the_match() {
280 // Two ways that only join if the second is flipped.
281 let mut stats = RingStats::default();
282 let members = vec![way(&[1, 4, 16], true), way(&[1, 13, 16], true)];
283 let polys = assemble(&members, grid, &mut stats);
284 assert_eq!(polys.len(), 1, "{stats:?}");
285 assert_eq!(polys[0][0].len(), 5);
286 }
287
288 #[test]
289 fn an_unclosed_ring_is_dropped_and_counted() {
290 // Three sides of a square: it cannot close, so emitting it would render as
291 // a wedge reaching to wherever the renderer chose to close it.
292 let mut stats = RingStats::default();
293 let members = vec![way(&[1, 4], true), way(&[4, 16], true)];
294 let polys = assemble(&members, grid, &mut stats);
295 assert!(polys.is_empty(), "{polys:?}");
296 assert_eq!(stats.unclosed, 1);
297 assert_eq!(stats.outer_rings, 0);
298 }
299
300 #[test]
301 fn one_bad_ring_does_not_take_a_good_one_with_it() {
302 let mut stats = RingStats::default();
303 let members = vec![
304 way(&[1, 4, 16, 13, 1], true), // closed on its own
305 way(&[2, 3], true), // a dangling fragment
306 ];
307 let polys = assemble(&members, grid, &mut stats);
308 assert_eq!(polys.len(), 1);
309 assert_eq!(stats.unclosed, 1);
310 assert_eq!(stats.outer_rings, 1);
311 }
312
313 #[test]
314 fn an_empty_role_counts_as_outer() {
315 // The OSM boundary convention, and what most real members carry. Treating an
316 // unroled way as "not outer" would leave nearly every boundary with no
317 // exterior at all.
318 let mut stats = RingStats::default();
319 let polys = assemble(&[way(&[1, 4, 16, 13, 1], true)], grid, &mut stats);
320 assert_eq!(polys.len(), 1);
321 }
322
323 #[test]
324 fn a_hole_attaches_to_the_ring_that_contains_it() {
325 let locate = |id: i64| -> Option<Coord> {
326 match id {
327 // Outer: a 10x10 square.
328 1 => Some((0.0, 0.0)),
329 2 => Some((10.0, 0.0)),
330 3 => Some((10.0, 10.0)),
331 4 => Some((0.0, 10.0)),
332 // Inner: a 2x2 square well inside it.
333 11 => Some((4.0, 4.0)),
334 12 => Some((6.0, 4.0)),
335 13 => Some((6.0, 6.0)),
336 14 => Some((4.0, 6.0)),
337 _ => None,
338 }
339 };
340 let mut stats = RingStats::default();
341 let members = vec![
342 way(&[1, 2, 3, 4, 1], true),
343 way(&[11, 12, 13, 14, 11], false),
344 ];
345 let polys = assemble(&members, locate, &mut stats);
346 assert_eq!(polys.len(), 1);
347 assert_eq!(polys[0].len(), 2, "exterior plus its hole");
348 assert!(ring_area(&polys[0][0]).abs() > ring_area(&polys[0][1]).abs());
349 assert_eq!(stats.inner_rings, 1);
350 assert_eq!(stats.orphan_inner, 0);
351 }
352
353 #[test]
354 fn a_hole_outside_every_outer_ring_is_dropped() {
355 let locate = |id: i64| -> Option<Coord> {
356 match id {
357 1 => Some((0.0, 0.0)),
358 2 => Some((10.0, 0.0)),
359 3 => Some((10.0, 10.0)),
360 4 => Some((0.0, 10.0)),
361 // Miles away.
362 21 => Some((100.0, 100.0)),
363 22 => Some((102.0, 100.0)),
364 23 => Some((102.0, 102.0)),
365 24 => Some((100.0, 102.0)),
366 _ => None,
367 }
368 };
369 let mut stats = RingStats::default();
370 let members = vec![
371 way(&[1, 2, 3, 4, 1], true),
372 way(&[21, 22, 23, 24, 21], false),
373 ];
374 let polys = assemble(&members, locate, &mut stats);
375 assert_eq!(polys.len(), 1);
376 assert_eq!(polys[0].len(), 1, "the orphan hole is not emitted");
377 assert_eq!(stats.orphan_inner, 1);
378 }
379
380 #[test]
381 fn a_hole_in_nested_outers_goes_to_the_smallest_containing_one() {
382 // Boundaries nest, so several outer rings can contain the same hole. It
383 // belongs to the tightest.
384 let big = square(0.0, 100.0);
385 let small = square(10.0, 50.0);
386 let hole = square(20.0, 30.0);
387 let polys = vec![vec![big], vec![small.clone()]];
388 let i = containing(&polys, &hole).expect("contained by both");
389 assert_eq!(polys[i][0], small, "the smaller outer ring wins");
390 // And order does not matter.
391 let polys = vec![vec![square(10.0, 50.0)], vec![square(0.0, 100.0)]];
392 assert_eq!(containing(&polys, &hole), Some(0));
393 }
394
395 #[test]
396 fn a_ring_with_an_unresolvable_vertex_is_dropped_not_bridged() {
397 // For a line, skipping a missing vertex keeps the rest. For an area, closing
398 // across the gap invents an edge and changes what is inside.
399 let mut stats = RingStats::default();
400 let polys = assemble(&[way(&[1, 4, 99, 13, 1], true)], grid, &mut stats);
401 assert!(polys.is_empty(), "{polys:?}");
402 }
403
404 #[test]
405 fn a_ring_too_small_to_enclose_anything_is_dropped() {
406 let mut stats = RingStats::default();
407 // Two distinct vertices, closed: a line, not an area.
408 let polys = assemble(&[way(&[1, 4, 1], true)], grid, &mut stats);
409 assert!(polys.is_empty());
410 // A single-vertex way is not even a way.
411 let polys = assemble(&[way(&[1], true)], grid, &mut stats);
412 assert!(polys.is_empty());
413 let polys = assemble(&[], grid, &mut stats);
414 assert!(polys.is_empty());
415 }
416
417 #[test]
418 fn vertex_order_is_preserved_which_is_the_whole_point() {
419 // poi_build sorts and dedups a relation's refs, which is fine for a centroid
420 // and fatal for geometry. This assembler must not: the two rings below have
421 // the same vertex SET and different shapes, and sorting would make them
422 // indistinguishable.
423 let mut stats = RingStats::default();
424 let convex = assemble(&[way(&[1, 4, 16, 13, 1], true)], grid, &mut stats);
425 let crossed = assemble(&[way(&[1, 16, 4, 13, 1], true)], grid, &mut stats);
426 assert_eq!(convex[0][0].len(), crossed[0][0].len());
427 assert_ne!(
428 convex[0][0], crossed[0][0],
429 "the same vertices in a different order are a different ring"
430 );
431 // The bow-tie encloses no net area; the square encloses 9.
432 assert!((ring_area(&convex[0][0]).abs() / 2.0 - 9.0).abs() < 1e-9);
433 assert!(ring_area(&crossed[0][0]).abs() < 1e-9);
434 }
435
436 #[test]
437 fn point_in_ring_handles_edges_and_vertices_without_double_counting() {
438 let sq = square(0.0, 10.0);
439 assert!(point_in_ring((5.0, 5.0), &sq));
440 assert!(!point_in_ring((15.0, 5.0), &sq));
441 assert!(!point_in_ring((5.0, 15.0), &sq));
442 // A ray leaving a vertex at exactly the probe's latitude must not flip the
443 // answer twice.
444 assert!(!point_in_ring((-1.0, 0.0), &sq));
445 assert!(!point_in_ring((-1.0, 10.0), &sq));
446 assert!(point_in_ring((5.0, 0.000001), &sq));
447 // Degenerate rings contain nothing.
448 assert!(!point_in_ring((0.0, 0.0), &[]));
449 assert!(!point_in_ring((0.0, 0.0), &[(0.0, 0.0), (1.0, 1.0)]));
450 }
451
452 #[test]
453 fn ring_area_signs_and_magnitudes() {
454 let ccw = square(0.0, 10.0);
455 let mut cw = ccw.clone();
456 cw.reverse();
457 assert!(ring_area(&ccw) > 0.0);
458 assert!(ring_area(&cw) < 0.0);
459 assert_eq!(ring_area(&ccw), -ring_area(&cw));
460 // Twice the area of a 10x10 square.
461 assert!((ring_area(&ccw).abs() - 200.0).abs() < 1e-9);
462 assert_eq!(ring_area(&[]), 0.0);
463 assert_eq!(ring_area(&[(0.0, 0.0), (1.0, 1.0)]), 0.0);
464 }
465}