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

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

rings.rs445 lines · 19.0 KiBRaw
1//! Stage C: normalise ring winding and hole containment, once, at build time.
2//!
3//! # Why this is worth a module
4//!
5//! The published z0 ocean tile is one polygon with **105 holes**, of which 40 overlap each other, 6
6//! straddle the exterior, 4 are entirely outside it and 13 are lakes nested inside other holes.
7//! `tess::fill` on device repairs all of that every time the tile is tessellated, under a frame
8//! budget, in `i32`. Doing it here instead costs nothing anyone waits for, runs in `f64`, and turns
9//! a per-frame repair into a one-time fact — which is what
10//! [`FLAG_RINGS_VALIDATED`](tilecodec::mamaps::header::FLAG_RINGS_VALIDATED) tells the renderer.
11//!
12//! # What "valid" means here
13//!
14//! Per part group, after this runs:
15//!
16//! 1. exactly one exterior, wound counter-clockwise;
17//! 2. every hole wound clockwise;
18//! 3. every hole strictly inside its exterior;
19//! 4. no two holes overlapping;
20//! 5. no zero-area ring.
21//!
22//! Those five are what `tess::fill` assumes and what the batch check in this module's tests asserts
23//! over every tile of a real build.
24//!
25//! # What it does not do
26//!
27//! It does not clip a straddling hole to its exterior or subtract one overlapping hole from another.
28//! Both need a real boolean operation, and getting one subtly wrong is worse than dropping the hole:
29//! a dropped hole paints a lake as land, which is visible and wrong; a botched intersection paints a
30//! wedge across a continent, which is visible and inexplicable. So a hole that cannot be placed
31//! cleanly is **dropped and counted**, and the count is in the build report.
32
33use tilecodec::mamaps::body::{BuildingAttrs, LaneTurns, Layer, Part, WINDING_HOLE, WINDING_OUTER};
34
35/// A kept ring with its bounding box `(min_x, min_y, max_x, max_y)`.
36type RingWithBox = (Vec<(i16, i16)>, (i16, i16, i16, i16));
37
38/// What normalising a build cost, for the report.
39#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
40pub struct Stats {
41 /// Rings whose winding disagreed with their stated role and was corrected.
42 pub rewound: u64,
43 /// Rings that enclosed no area at all.
44 pub zero_area: u64,
45 /// Holes dropped for being outside their exterior, straddling it, or overlapping another hole.
46 pub holes_dropped: u64,
47 pub groups: u64,
48}
49
50impl Stats {
51 pub fn add(&mut self, other: Stats) {
52 self.rewound += other.rewound;
53 self.zero_area += other.zero_area;
54 self.holes_dropped += other.holes_dropped;
55 self.groups += other.groups;
56 }
57
58 /// Did anything have to be corrected?
59 #[cfg_attr(not(test), allow(dead_code))]
60 pub fn clean(&self) -> bool {
61 self.rewound == 0 && self.zero_area == 0 && self.holes_dropped == 0
62 }
63}
64
65/// Normalise every polygon feature of a layer in place.
66///
67/// Rebuilds the parts table and the coordinate arena, because dropping a ring changes both and the
68/// encoder requires the parts to tile the arena exactly.
69#[cfg(test)]
70pub fn normalise(layer: &mut Layer) -> Stats {
71 normalise_with_ids(layer, None, None, None)
72}
73
74/// As [`normalise`], but also drops the id and turn-lane records of any feature it drops.
75///
76/// The side tables are indexed by feature position, so the retain at the end has to happen to all
77/// of them or every entry after the first casualty describes the wrong feature. This only started
78/// mattering when `boundaries` gained a table: `places` and `poi` are points, and a point never
79/// loses its single part, so the retain was a no-op for every layer that carried ids. A road's
80/// turn table rides along for the same discipline, though a road is a line and a line is never
81/// dropped here.
82pub fn normalise_with_ids(
83 layer: &mut Layer,
84 ids: Option<&mut Vec<u64>>,
85 turns: Option<&mut Vec<LaneTurns>>,
86 buildings: Option<&mut Vec<BuildingAttrs>>,
87) -> Stats {
88 let mut stats = Stats::default();
89 let mut parts: Vec<Part> = Vec::with_capacity(layer.parts.len());
90 let mut coords: Vec<(i16, i16)> = Vec::with_capacity(layer.coords.len());
91
92 for feature in &mut layer.features {
93 if feature.geom_type != tilecodec::mamaps::body::GEOM_POLYGON {
94 // A line's parts pass through untouched: winding means nothing on an open path.
95 let start = parts.len() as u32;
96 for part in layer.parts[feature.parts_offset as usize..]
97 .iter()
98 .take(feature.part_count as usize)
99 {
100 let points = ring_points(&layer.coords, part);
101 parts.push(Part {
102 coord_start: coords.len() as u32,
103 point_count: points.len() as u32,
104 winding: part.winding,
105 });
106 coords.extend_from_slice(points);
107 }
108 feature.parts_offset = start;
109 continue;
110 }
111 stats.groups += 1;
112 let group: Vec<(&Part, &[(i16, i16)])> = layer.parts[feature.parts_offset as usize..]
113 .iter()
114 .take(feature.part_count as usize)
115 .map(|part| (part, ring_points(&layer.coords, part)))
116 .collect();
117
118 // The exterior is the first part, by the format's own convention.
119 let Some((_, exterior)) = group.first().copied() else {
120 feature.part_count = 0;
121 continue;
122 };
123 let exterior_area = signed_area(exterior);
124 if exterior_area == 0.0 {
125 // A zero-area exterior takes its holes with it: there is nothing for them to be in.
126 stats.zero_area += 1;
127 feature.part_count = 0;
128 continue;
129 }
130
131 let start = parts.len() as u32;
132 let mut count = 0u32;
133 // An exterior is counter-clockwise. Reversed rather than re-labelled, because the winding
134 // field states a fact about the coordinates and the two must agree.
135 // `(ring, box)`, because every containment test below needs the box and computing it per
136 // comparison would put back the quadratic cost the boxes exist to remove.
137 let mut kept: Vec<RingWithBox> = Vec::with_capacity(group.len());
138 let mut exterior_ring = exterior.to_vec();
139 if exterior_area < 0.0 {
140 exterior_ring.reverse();
141 stats.rewound += 1;
142 }
143 push_ring(&mut parts, &mut coords, &exterior_ring, WINDING_OUTER);
144 count += 1;
145 let exterior_box = bounds(&exterior_ring);
146 kept.push((exterior_ring, exterior_box));
147
148 for (_, hole) in group.iter().skip(1) {
149 let area = signed_area(hole);
150 if area == 0.0 {
151 stats.zero_area += 1;
152 continue;
153 }
154 let hole_box = bounds(hole);
155 // Strictly inside its exterior. A straddling or outside hole is dropped rather than
156 // clipped: a dropped hole paints a lake as land, which is visible and explicable, and a
157 // botched clip paints a wedge across a continent, which is neither.
158 if !strictly_inside(hole, hole_box, &kept[0].0, exterior_box) {
159 stats.holes_dropped += 1;
160 continue;
161 }
162 // And not overlapping a hole already kept. Same reasoning: no boolean operations.
163 if kept
164 .iter()
165 .skip(1)
166 .any(|(other, other_box)| rings_overlap(hole, hole_box, other, *other_box))
167 {
168 stats.holes_dropped += 1;
169 continue;
170 }
171 let mut ring = hole.to_vec();
172 // A hole is clockwise, which is the opposite sign to its exterior.
173 if area > 0.0 {
174 ring.reverse();
175 stats.rewound += 1;
176 }
177 push_ring(&mut parts, &mut coords, &ring, WINDING_HOLE);
178 count += 1;
179 // Reversing a ring does not move it, so the box is still the one just computed.
180 kept.push((ring, hole_box));
181 }
182 feature.parts_offset = start;
183 feature.part_count = count;
184 }
185
186 // A feature whose exterior went takes no parts, so it draws nothing. Removed outright rather
187 // than left as an empty group, which the encoder refuses. The id table is indexed by feature
188 // position, so it is filtered by the same predicate, in the same order, first.
189 if let Some(ids) = ids {
190 if ids.len() == layer.features.len() {
191 let mut at = 0;
192 ids.retain(|_| {
193 let keep = layer.features[at].part_count > 0;
194 at += 1;
195 keep
196 });
197 }
198 }
199 if let Some(turns) = turns {
200 if turns.len() == layer.features.len() {
201 let mut at = 0;
202 turns.retain(|_| {
203 let keep = layer.features[at].part_count > 0;
204 at += 1;
205 keep
206 });
207 }
208 }
209 // The building side table is indexed by feature position too, so a dropped degenerate building
210 // must drop its attrs with it, in the same order and by the same predicate.
211 if let Some(buildings) = buildings {
212 if buildings.len() == layer.features.len() {
213 let mut at = 0;
214 buildings.retain(|_| {
215 let keep = layer.features[at].part_count > 0;
216 at += 1;
217 keep
218 });
219 }
220 }
221 layer.features.retain(|feature| feature.part_count > 0);
222 layer.parts = parts;
223 layer.coords = coords;
224 stats
225}
226
227fn ring_points<'a>(coords: &'a [(i16, i16)], part: &Part) -> &'a [(i16, i16)] {
228 let start = part.coord_start as usize;
229 &coords[start..start + part.point_count as usize]
230}
231
232fn push_ring(
233 parts: &mut Vec<Part>,
234 coords: &mut Vec<(i16, i16)>,
235 ring: &[(i16, i16)],
236 winding: u16,
237) {
238 parts.push(Part { coord_start: coords.len() as u32, point_count: ring.len() as u32, winding });
239 coords.extend_from_slice(ring);
240}
241
242/// A ring's signed area by the shoelace formula: positive counter-clockwise.
243///
244/// `f64` from `i64` terms. This is the whole reason the work belongs at build time: on device the
245/// same computation is done in `i32` under a frame budget, where a long ring's cross products
246/// overflow and a near-degenerate one rounds to the wrong sign.
247pub fn signed_area(ring: &[(i16, i16)]) -> f64 {
248 let mut twice = 0i64;
249 for pair in ring.windows(2) {
250 let ((x0, y0), (x1, y1)) = (pair[0], pair[1]);
251 twice += x0 as i64 * y1 as i64 - x1 as i64 * y0 as i64;
252 }
253 // An unclosed ring: close it implicitly rather than reporting a wrong area.
254 if let (Some(first), Some(last)) = (ring.first(), ring.last()) {
255 if first != last {
256 twice += last.0 as i64 * first.1 as i64 - first.0 as i64 * last.1 as i64;
257 }
258 }
259 twice as f64 / 2.0
260}
261
262/// Is every vertex of `inner` inside `outer`?
263///
264/// Vertex containment rather than a full geometric test. It is what distinguishes the three cases
265/// that matter — wholly inside, wholly outside, straddling — and it cannot be fooled by anything a
266/// clipped tile actually contains, because a hole that crosses its exterior has vertices on both
267/// sides by construction.
268/// A ring's bounding box as `(min_x, min_y, max_x, max_y)`.
269///
270/// Computed once per ring and threaded into the containment tests, because those are the whole cost
271/// of stage C. Measured on a California build with a coastline, `encode` — which is stage C plus
272/// serialise plus DEFLATE — was 432.7 s against 94.7 s without one. `earth` lands in ~529 k
273/// tile-layers and its polygons carry many holes, and both tests below are quadratic without a cheap
274/// way to say "these two are nowhere near each other".
275///
276/// Every use is **conservative**: a box test only ever rejects a case the exact test would also have
277/// rejected, so the answers are unchanged and the archive stays byte-identical.
278fn bounds(ring: &[(i16, i16)]) -> (i16, i16, i16, i16) {
279 let mut b = (i16::MAX, i16::MAX, i16::MIN, i16::MIN);
280 for &(x, y) in ring {
281 b.0 = b.0.min(x);
282 b.1 = b.1.min(y);
283 b.2 = b.2.max(x);
284 b.3 = b.3.max(y);
285 }
286 b
287}
288
289/// Is `inner`'s box entirely within `outer`'s?
290fn box_within(inner: (i16, i16, i16, i16), outer: (i16, i16, i16, i16)) -> bool {
291 inner.0 >= outer.0 && inner.1 >= outer.1 && inner.2 <= outer.2 && inner.3 <= outer.3
292}
293
294/// Do two boxes share any area?
295fn boxes_meet(a: (i16, i16, i16, i16), b: (i16, i16, i16, i16)) -> bool {
296 !(a.2 < b.0 || a.0 > b.2 || a.3 < b.1 || a.1 > b.3)
297}
298
299/// Is every vertex of `inner` inside `outer`?
300///
301/// Vertex containment rather than a full geometric test. It is what distinguishes the three cases
302/// that matter — wholly inside, wholly outside, straddling — and it cannot be fooled by anything a
303/// clipped tile actually contains, because a hole that crosses its exterior has vertices on both
304/// sides by construction.
305fn strictly_inside(
306 inner: &[(i16, i16)],
307 inner_box: (i16, i16, i16, i16),
308 outer: &[(i16, i16)],
309 outer_box: (i16, i16, i16, i16),
310) -> bool {
311 // If any of `inner` lies outside `outer`'s box then that vertex is outside `outer` itself, so the
312 // exact test would say no too. This is what makes a hole belonging to a different part of the
313 // world cost four comparisons instead of a scan of the exterior.
314 if !box_within(inner_box, outer_box) {
315 return false;
316 }
317 inner.iter().all(|&point| point_in_ring(point, outer, outer_box))
318}
319
320/// Do two rings overlap? Approximated by mutual vertex containment.
321///
322/// One ring having a vertex inside the other is the signature of every overlap a clipped tile
323/// produces. Two rings that merely touch at a vertex are not overlapping, and are left alone —
324/// `tess::fill` already handles a hole that touches its exterior.
325fn rings_overlap(
326 a: &[(i16, i16)],
327 a_box: (i16, i16, i16, i16),
328 b: &[(i16, i16)],
329 b_box: (i16, i16, i16, i16),
330) -> bool {
331 // Disjoint boxes cannot overlap, and most pairs of holes in a real polygon are disjoint. This is
332 // the test that takes the pairwise scan from quadratic-in-vertices to quadratic-in-holes.
333 if !boxes_meet(a_box, b_box) {
334 return false;
335 }
336 a.iter().filter(|&&p| point_in_ring(p, b, b_box)).count() > 1
337 || b.iter().filter(|&&p| point_in_ring(p, a, a_box)).count() > 1
338}
339
340/// Even-odd ray cast, with the boundary counting as inside.
341///
342/// That last clause is what keeps clipped islands: the tile clipper emits exterior and hole
343/// vertices onto the same tile-edge lines, so a hole clipped onto the tile edge touches its
344/// exterior there. Reading those vertices as outside dropped the hole — an island filled in
345/// solid on the fine tile while the coarse tile (hole fully inside) stayed pixel-perfect.
346/// The renderer's `tess::fill::geom::point_within_ring` already counts the boundary as inside
347/// for exactly this reason; stage C runs first and bakes its drops into the archive, so it
348/// has to agree with it — a stricter rule here deletes islands the renderer would otherwise
349/// have kept.
350///
351/// The leniency admits exactly coincident edges — a vertex ON the exterior — never a vertex
352/// genuinely outside it: those still fail every edge test and the hole still goes. And it is
353/// safe in this direction only: a hole the tiler keeps but the renderer drops costs one
354/// island, while a hole the tiler drops is gone for every reader.
355fn point_in_ring((x, y): (i16, i16), ring: &[(i16, i16)], ring_box: (i16, i16, i16, i16)) -> bool {
356 // A point outside the box is outside the ring, for the cost of four comparisons rather than a
357 // walk of every edge.
358 if x < ring_box.0 || x > ring_box.2 || y < ring_box.1 || y > ring_box.3 {
359 return false;
360 }
361 let (x, y) = (x as f64, y as f64);
362 let mut inside = false;
363 for pair in ring.windows(2) {
364 let ((x0, y0), (x1, y1)) = (pair[0], pair[1]);
365 let (x0, y0, x1, y1) = (x0 as f64, y0 as f64, x1 as f64, y1 as f64);
366 if (y0 > y) != (y1 > y) {
367 let t = (y - y0) / (y1 - y0);
368 if x < x0 + t * (x1 - x0) {
369 inside = !inside;
370 }
371 }
372 }
373 inside || on_boundary((x, y), ring)
374}
375
376/// Is the point exactly on one of the ring's edges?
377///
378/// The tile clipper emits exterior and hole vertices onto the same tile-edge lines, quantised
379/// to the same `i16` grid — a hole clipped onto the tile edge shares exact coordinates with
380/// the exterior's clipped edge there. An exact integer cross product (no division, so no
381/// truncation putting the two sides of one edge in disagreement), mirroring the renderer's
382/// `tess::fill::geom::on_boundary`.
383fn on_boundary((x, y): (f64, f64), ring: &[(i16, i16)]) -> bool {
384 for pair in ring.windows(2) {
385 let ((x0, y0), (x1, y1)) = (pair[0], pair[1]);
386 let (x0, y0, x1, y1) = (x0 as f64, y0 as f64, x1 as f64, y1 as f64);
387 let cross = (x - x0) * (y1 - y0) - (y - y0) * (x1 - x0);
388 if cross == 0.0 && x >= x0.min(x1) && x <= x0.max(x1) && y >= y0.min(y1) && y <= y0.max(y1)
389 {
390 return true;
391 }
392 }
393 false
394}
395
396/// **Verification item 6 of the plan's list.** Every ring of a layer must satisfy all five
397/// invariants.
398///
399/// Returned as a list of complaints rather than a bool, so a failing build says which polygon and
400/// why. Used by the generator's own tests over every tile of a real build.
401#[cfg_attr(not(test), allow(dead_code))]
402pub fn check(layer: &Layer) -> Vec<String> {
403 let mut problems = Vec::new();
404 for (index, feature) in layer.features.iter().enumerate() {
405 if feature.geom_type != tilecodec::mamaps::body::GEOM_POLYGON {
406 continue;
407 }
408 let parts = layer.parts_of(feature);
409 let Some(exterior) = parts.first() else {
410 problems.push(format!("feature {index} has no parts"));
411 continue;
412 };
413 if exterior.winding != WINDING_OUTER {
414 problems.push(format!("feature {index}'s first part is a hole"));
415 }
416 let exterior_points = layer.points(exterior);
417 let area = signed_area(exterior_points);
418 if area <= 0.0 {
419 problems.push(format!("feature {index}'s exterior is not counter-clockwise ({area})"));
420 }
421 let holes: Vec<&Part> = parts[1..].iter().collect();
422 if holes.iter().any(|part| part.winding != WINDING_HOLE) {
423 problems.push(format!("feature {index} has a second exterior"));
424 }
425 for (i, hole) in holes.iter().enumerate() {
426 let points = layer.points(hole);
427 let area = signed_area(points);
428 if area >= 0.0 {
429 problems.push(format!("feature {index}'s hole {i} is not clockwise ({area})"));
430 }
431 if !strictly_inside(points, bounds(points), exterior_points, bounds(exterior_points)) {
432 problems.push(format!("feature {index}'s hole {i} is not inside its exterior"));
433 }
434 for (j, other) in holes.iter().enumerate().skip(i + 1) {
435 let other_points = layer.points(other);
436 if rings_overlap(points, bounds(points), other_points, bounds(other_points)) {
437 problems.push(format!("feature {index}'s holes {i} and {j} overlap"));
438 }
439 }
440 }
441 }
442 problems
443}
444
445include!("rings_part1.rs");