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

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

rings.rs456 lines · 18.0 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>>> =
98 ways.filter(|w| w.refs.len() >= 2).map(|w| Some(w.refs.clone())).collect();
99
100 let mut rings: Vec<Vec<i64>> = Vec::new();
101 for start in 0..pool.len() {
102 let Some(first) = pool[start].take() else {
103 continue;
104 };
105 let mut ring = first;
106 loop {
107 if ring.len() > 2 && ring.first() == ring.last() {
108 rings.push(ring);
109 break;
110 }
111 let tail = *ring.last().expect("non-empty");
112 // Find any unused way starting or ending at the current tail.
113 let next = pool.iter().position(|w| {
114 w.as_ref().is_some_and(|r| r.first() == Some(&tail) || r.last() == Some(&tail))
115 });
116 let Some(i) = next else {
117 // Nothing joins on: this ring cannot close.
118 stats.unclosed += 1;
119 break;
120 };
121 let mut piece = pool[i].take().expect("just found");
122 if piece.first() != Some(&tail) {
123 piece.reverse();
124 }
125 // The shared endpoint is already the ring's tail.
126 ring.extend_from_slice(&piece[1..]);
127
128 // A way that closed the ring on its own, or a degenerate self-loop, is
129 // caught by the check at the top of the loop.
130 if ring.len() > 100_000_000 {
131 // Cannot happen with real data; guards against a pathological
132 // multimap cycle turning into an OOM rather than an error.
133 stats.unclosed += 1;
134 break;
135 }
136 }
137 }
138 rings
139}
140
141/// Resolve a ring of node ids to coordinates. `None` when too few resolve to
142/// enclose an area.
143///
144/// Unlike a line, a ring with a missing vertex is **not** kept with a gap: closing
145/// across the gap invents an edge, and for an area that changes what is inside it.
146fn resolve<L>(ring: &[i64], locate: &L) -> Option<Vec<Coord>>
147where
148 L: Fn(i64) -> Option<Coord>,
149{
150 let coords: Vec<Coord> = ring.iter().map(|id| locate(*id)).collect::<Option<_>>()?;
151 // Three distinct vertices plus the repeated close.
152 if coords.len() < 4 {
153 return None;
154 }
155 Some(coords)
156}
157
158/// Index of the smallest outer ring containing `hole`, if any.
159///
160/// Smallest, because boundaries nest: a city inside a county inside a state means
161/// several outer rings may contain the same hole, and the hole belongs to the
162/// tightest one.
163fn containing(polygons: &[Polygon], hole: &[Coord]) -> Option<usize> {
164 let probe = *hole.first()?;
165 let mut best: Option<(usize, f64)> = None;
166 for (i, poly) in polygons.iter().enumerate() {
167 let outer = &poly[0];
168 if !point_in_ring(probe, outer) {
169 continue;
170 }
171 let area = ring_area(outer).abs();
172 if best.is_none_or(|(_, b)| area < b) {
173 best = Some((i, area));
174 }
175 }
176 best.map(|(i, _)| i)
177}
178
179/// Twice the signed area of a ring, by the surveyor's formula.
180///
181/// In lon/lat degrees, so it is not an area on the ground -- but every use here is a
182/// comparison or a sign test, and for that a consistent planar measure is the right
183/// tool. A spherical area would cost a lot and change no decision.
184pub fn ring_area(ring: &[Coord]) -> f64 {
185 let n = ring.len();
186 if n < 3 {
187 return 0.0;
188 }
189 let mut sum = 0.0;
190 for i in 0..n {
191 let (x1, y1) = ring[i];
192 let (x2, y2) = ring[(i + 1) % n];
193 sum += x1 * y2 - x2 * y1;
194 }
195 sum
196}
197
198/// Ray-casting point-in-polygon. `true` when `p` is inside `ring`.
199///
200/// The half-open `(y1 > y) != (y2 > y)` test is what makes a vertex exactly at the
201/// probe's latitude count once rather than twice, so a ray grazing a vertex does not
202/// flip the answer.
203pub fn point_in_ring((x, y): Coord, ring: &[Coord]) -> bool {
204 let mut inside = false;
205 let n = ring.len();
206 if n < 3 {
207 return false;
208 }
209 for i in 0..n {
210 let (x1, y1) = ring[i];
211 let (x2, y2) = ring[(i + 1) % n];
212 if (y1 > y) != (y2 > y) {
213 let t = (y - y1) / (y2 - y1);
214 if x < x1 + t * (x2 - x1) {
215 inside = !inside;
216 }
217 }
218 }
219 inside
220}
221
222#[cfg(test)]
223mod tests {
224 use super::*;
225
226 fn way(refs: &[i64], outer: bool) -> MemberWay {
227 MemberWay { refs: refs.to_vec(), outer }
228 }
229
230 /// A 4x4 grid of nodes, ids 1..=16, so a ring can be described by ids alone.
231 /// Node `n` sits at `(lon, lat) = ((n-1) % 4, (n-1) / 4)`.
232 fn grid(id: i64) -> Option<Coord> {
233 (1..=16).contains(&id).then(|| {
234 let i = (id - 1) as f64;
235 ((i % 4.0), (i / 4.0).floor())
236 })
237 }
238
239 /// The unit square's corners, and a smaller square inside it.
240 fn square(min: f64, max: f64) -> Vec<Coord> {
241 vec![(min, min), (max, min), (max, max), (min, max), (min, min)]
242 }
243
244 #[test]
245 fn a_single_closed_way_is_already_a_ring() {
246 let mut stats = RingStats::default();
247 let polys = assemble(&[way(&[1, 4, 16, 13, 1], true)], grid, &mut stats);
248 assert_eq!(polys.len(), 1);
249 assert_eq!(polys[0].len(), 1, "no holes");
250 assert_eq!(polys[0][0].len(), 5);
251 assert_eq!(polys[0][0].first(), polys[0][0].last());
252 assert_eq!(stats, RingStats { outer_rings: 1, ..Default::default() });
253 }
254
255 #[test]
256 fn several_ways_stitch_into_one_ring() {
257 // The square 1-4-16-13 split into four ways, in a scrambled order and with
258 // two of them pointing the wrong way. This is what real boundary relations
259 // look like.
260 let mut stats = RingStats::default();
261 let members = vec![
262 way(&[16, 13], true), // reversed
263 way(&[1, 4], true),
264 way(&[13, 1], true),
265 way(&[16, 4], true), // reversed
266 ];
267 let polys = assemble(&members, grid, &mut stats);
268 assert_eq!(polys.len(), 1, "{stats:?}");
269 assert_eq!(stats.unclosed, 0);
270 // Four corners plus the close, whichever way round it came out.
271 assert_eq!(polys[0][0].len(), 5, "{:?}", polys[0][0]);
272 assert!(ring_area(&polys[0][0]).abs() > 0.0);
273 }
274
275 #[test]
276 fn a_way_is_reversed_when_its_far_end_is_the_match() {
277 // Two ways that only join if the second is flipped.
278 let mut stats = RingStats::default();
279 let members = vec![way(&[1, 4, 16], true), way(&[1, 13, 16], true)];
280 let polys = assemble(&members, grid, &mut stats);
281 assert_eq!(polys.len(), 1, "{stats:?}");
282 assert_eq!(polys[0][0].len(), 5);
283 }
284
285 #[test]
286 fn an_unclosed_ring_is_dropped_and_counted() {
287 // Three sides of a square: it cannot close, so emitting it would render as
288 // a wedge reaching to wherever the renderer chose to close it.
289 let mut stats = RingStats::default();
290 let members = vec![way(&[1, 4], true), way(&[4, 16], true)];
291 let polys = assemble(&members, grid, &mut stats);
292 assert!(polys.is_empty(), "{polys:?}");
293 assert_eq!(stats.unclosed, 1);
294 assert_eq!(stats.outer_rings, 0);
295 }
296
297 #[test]
298 fn one_bad_ring_does_not_take_a_good_one_with_it() {
299 let mut stats = RingStats::default();
300 let members = vec![
301 way(&[1, 4, 16, 13, 1], true), // closed on its own
302 way(&[2, 3], true), // a dangling fragment
303 ];
304 let polys = assemble(&members, grid, &mut stats);
305 assert_eq!(polys.len(), 1);
306 assert_eq!(stats.unclosed, 1);
307 assert_eq!(stats.outer_rings, 1);
308 }
309
310 #[test]
311 fn an_empty_role_counts_as_outer() {
312 // The OSM boundary convention, and what most real members carry. Treating an
313 // unroled way as "not outer" would leave nearly every boundary with no
314 // exterior at all.
315 let mut stats = RingStats::default();
316 let polys = assemble(&[way(&[1, 4, 16, 13, 1], true)], grid, &mut stats);
317 assert_eq!(polys.len(), 1);
318 }
319
320 #[test]
321 fn a_hole_attaches_to_the_ring_that_contains_it() {
322 let locate = |id: i64| -> Option<Coord> {
323 match id {
324 // Outer: a 10x10 square.
325 1 => Some((0.0, 0.0)),
326 2 => Some((10.0, 0.0)),
327 3 => Some((10.0, 10.0)),
328 4 => Some((0.0, 10.0)),
329 // Inner: a 2x2 square well inside it.
330 11 => Some((4.0, 4.0)),
331 12 => Some((6.0, 4.0)),
332 13 => Some((6.0, 6.0)),
333 14 => Some((4.0, 6.0)),
334 _ => None,
335 }
336 };
337 let mut stats = RingStats::default();
338 let members = vec![way(&[1, 2, 3, 4, 1], true), way(&[11, 12, 13, 14, 11], false)];
339 let polys = assemble(&members, locate, &mut stats);
340 assert_eq!(polys.len(), 1);
341 assert_eq!(polys[0].len(), 2, "exterior plus its hole");
342 assert!(ring_area(&polys[0][0]).abs() > ring_area(&polys[0][1]).abs());
343 assert_eq!(stats.inner_rings, 1);
344 assert_eq!(stats.orphan_inner, 0);
345 }
346
347 #[test]
348 fn a_hole_outside_every_outer_ring_is_dropped() {
349 let locate = |id: i64| -> Option<Coord> {
350 match id {
351 1 => Some((0.0, 0.0)),
352 2 => Some((10.0, 0.0)),
353 3 => Some((10.0, 10.0)),
354 4 => Some((0.0, 10.0)),
355 // Miles away.
356 21 => Some((100.0, 100.0)),
357 22 => Some((102.0, 100.0)),
358 23 => Some((102.0, 102.0)),
359 24 => Some((100.0, 102.0)),
360 _ => None,
361 }
362 };
363 let mut stats = RingStats::default();
364 let members = vec![way(&[1, 2, 3, 4, 1], true), way(&[21, 22, 23, 24, 21], false)];
365 let polys = assemble(&members, locate, &mut stats);
366 assert_eq!(polys.len(), 1);
367 assert_eq!(polys[0].len(), 1, "the orphan hole is not emitted");
368 assert_eq!(stats.orphan_inner, 1);
369 }
370
371 #[test]
372 fn a_hole_in_nested_outers_goes_to_the_smallest_containing_one() {
373 // Boundaries nest, so several outer rings can contain the same hole. It
374 // belongs to the tightest.
375 let big = square(0.0, 100.0);
376 let small = square(10.0, 50.0);
377 let hole = square(20.0, 30.0);
378 let polys = vec![vec![big], vec![small.clone()]];
379 let i = containing(&polys, &hole).expect("contained by both");
380 assert_eq!(polys[i][0], small, "the smaller outer ring wins");
381 // And order does not matter.
382 let polys = vec![vec![square(10.0, 50.0)], vec![square(0.0, 100.0)]];
383 assert_eq!(containing(&polys, &hole), Some(0));
384 }
385
386 #[test]
387 fn a_ring_with_an_unresolvable_vertex_is_dropped_not_bridged() {
388 // For a line, skipping a missing vertex keeps the rest. For an area, closing
389 // across the gap invents an edge and changes what is inside.
390 let mut stats = RingStats::default();
391 let polys = assemble(&[way(&[1, 4, 99, 13, 1], true)], grid, &mut stats);
392 assert!(polys.is_empty(), "{polys:?}");
393 }
394
395 #[test]
396 fn a_ring_too_small_to_enclose_anything_is_dropped() {
397 let mut stats = RingStats::default();
398 // Two distinct vertices, closed: a line, not an area.
399 let polys = assemble(&[way(&[1, 4, 1], true)], grid, &mut stats);
400 assert!(polys.is_empty());
401 // A single-vertex way is not even a way.
402 let polys = assemble(&[way(&[1], true)], grid, &mut stats);
403 assert!(polys.is_empty());
404 let polys = assemble(&[], grid, &mut stats);
405 assert!(polys.is_empty());
406 }
407
408 #[test]
409 fn vertex_order_is_preserved_which_is_the_whole_point() {
410 // poi_build sorts and dedups a relation's refs, which is fine for a centroid
411 // and fatal for geometry. This assembler must not: the two rings below have
412 // the same vertex SET and different shapes, and sorting would make them
413 // indistinguishable.
414 let mut stats = RingStats::default();
415 let convex = assemble(&[way(&[1, 4, 16, 13, 1], true)], grid, &mut stats);
416 let crossed = assemble(&[way(&[1, 16, 4, 13, 1], true)], grid, &mut stats);
417 assert_eq!(convex[0][0].len(), crossed[0][0].len());
418 assert_ne!(
419 convex[0][0], crossed[0][0],
420 "the same vertices in a different order are a different ring"
421 );
422 // The bow-tie encloses no net area; the square encloses 9.
423 assert!((ring_area(&convex[0][0]).abs() / 2.0 - 9.0).abs() < 1e-9);
424 assert!(ring_area(&crossed[0][0]).abs() < 1e-9);
425 }
426
427 #[test]
428 fn point_in_ring_handles_edges_and_vertices_without_double_counting() {
429 let sq = square(0.0, 10.0);
430 assert!(point_in_ring((5.0, 5.0), &sq));
431 assert!(!point_in_ring((15.0, 5.0), &sq));
432 assert!(!point_in_ring((5.0, 15.0), &sq));
433 // A ray leaving a vertex at exactly the probe's latitude must not flip the
434 // answer twice.
435 assert!(!point_in_ring((-1.0, 0.0), &sq));
436 assert!(!point_in_ring((-1.0, 10.0), &sq));
437 assert!(point_in_ring((5.0, 0.000001), &sq));
438 // Degenerate rings contain nothing.
439 assert!(!point_in_ring((0.0, 0.0), &[]));
440 assert!(!point_in_ring((0.0, 0.0), &[(0.0, 0.0), (1.0, 1.0)]));
441 }
442
443 #[test]
444 fn ring_area_signs_and_magnitudes() {
445 let ccw = square(0.0, 10.0);
446 let mut cw = ccw.clone();
447 cw.reverse();
448 assert!(ring_area(&ccw) > 0.0);
449 assert!(ring_area(&cw) < 0.0);
450 assert_eq!(ring_area(&ccw), -ring_area(&cw));
451 // Twice the area of a 10x10 square.
452 assert!((ring_area(&ccw).abs() - 200.0).abs() < 1e-9);
453 assert_eq!(ring_area(&[]), 0.0);
454 assert_eq!(ring_area(&[(0.0, 0.0), (1.0, 1.0)]), 0.0);
455 }
456}