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

Modern-Apps.git / scripts / maps / tile_build / src / subdivide.rs

subdivide.rs476 lines · 20.8 KiBRaw
1//! Tile one feature by descending the tile quadtree, instead of once per tile.
2//!
3//! The tiling loops used to have one shape: ask [`crate::geom::tiles_touched`] for
4//! every tile a feature reaches, then clip **the whole feature** against each of
5//! them. That is `O(T * V)`, and both factors grow with the feature's geographic
6//! extent: a state-sized polygon at z13 has `T` in the hundreds of thousands and
7//! `V` in the hundreds of thousands, and every one of those tiles paid a full
8//! vertex walk -- including the vast majority that are strictly interior and whose
9//! answer is just the tile rectangle.
10//!
11//! [`subdivide`] walks the quadtree instead:
12//!
13//! 1. Find the deepest cell that already contains the whole geometry. A building at
14//! z14 gets the leaf itself and no recursion at all, so the leaf clip is the only
15//! clip -- exactly what the old loop did. A coastline gets a shallow cell.
16//! 2. At each level, clip the geometry **already clipped to this cell** into each of
17//! the four children, and recurse into the ones that survive.
18//! 3. A level-`z` cell rect *is* [`crate::geom::tile_rect`], so the leaf sees the
19//! same rectangle as before.
20//!
21//! Cost becomes `O(V * (z - level))` for the vertex walks plus `O(T)` small clips at
22//! the bottom, rather than `O(V * T)`.
23//!
24//! ## Why clipping progressively is sound
25//!
26//! The buffer is the same world-unit constant at every level. A child cell is a
27//! subset of its parent, and growing both by the same Minkowski sum keeps that:
28//! `child (+) buffer` is a subset of `parent (+) buffer`. Clipping is intersection, so
29//! `clip(clip(g, A), B)` is `clip(g, B)` whenever `B` is inside `A`, and the whole
30//! descent is that identity applied `z - level` times.
31//!
32//! Sutherland-Hodgman makes that worth checking rather than assuming. It returns a
33//! clipped *concave* ring as a single self-touching ring joined by zero-width slivers
34//! (see [`crate::clip`]'s module docs), which is not the intersection as a simple
35//! polygon -- so composing through one is not obviously sound.
36//! `clipping_twice_is_clipping_once_for_a_nested_rect` searches for a counterexample
37//! over random concave rings, random holes and random nested rect pairs, and finds
38//! none: the sliver runs along the shared boundary and the next clip either keeps that
39//! boundary or removes the sliver with it.
40//!
41//! It is the same argument [`crate::geom::tiles_touched`]'s bisection rests on: a
42//! recursive subdivision is safe exactly when each step preserves what the next needs.
43//!
44//! ## Points do not descend
45//!
46//! [`crate::clip::clip_geometry`] on `Points` filters the whole list per tile, which
47//! is its own `O(T * V)`. A point's tiles are just the tiles its own padded box
48//! covers, so points are bucketed straight into them -- which is what
49//! `tiles_touched` followed by a `contains` test worked out to anyway, one point at a
50//! time.
51//!
52//! ## What this costs in output
53//!
54//! **Not byte-identity to a direct clip, and not the vertices that were expected to
55//! cost it.** Clipping to an ancestor cell does insert vertices on that ancestor's
56//! boundary, and [`crate::geom::Vertex::boundary`] does stamp them unremovable -- but
57//! none of them survive to a leaf as a vertex the leaf's own clip would not have
58//! invented. A child cell is a subset of its parent and both are grown by the *same*
59//! buffer, so a parent boundary line either coincides with the child's line on that
60//! side, when the child sits on that border, or lies strictly outside the child,
61//! where the next clip removes it. Coincident lines give coincident crossings.
62//!
63//! Measured over the corpus in this module's tests, the descent emits **fewer**
64//! vertices than a direct clip, not more, so there is no collinear-reduction pass and
65//! the archive does not grow. Three differences remain, none of them a shape:
66//!
67//! | difference | why | visible? |
68//! |---|---|---|
69//! | a ring's starting vertex | Sutherland-Hodgman keeps its input's rotation, and the descent's input is its parent's answer | same polygon; MVT re-states the start as a `MoveTo` |
70//! | fewer collinear spurs | a concave ring's zero-area run along a clip boundary is shorter when built in stages | zero-area either way |
71//! | last-bit drift on a line crossing | Liang-Barsky interpolates both coordinates, so a crossing taken off an already-interpolated vertex can land an ULP away | 1e-12 world units against a quantisation grid of 1 |
72//!
73//! The tests hold the descent to being the same *shape* -- same tiles, same parts,
74//! same corners up to rotation, same signed area, same length -- and record the byte
75//! divergence rather than asserting it away.
76
77use crate::clip::clip_geometry;
78use crate::geom::{self, Geometry, Pt, Rect, Vertex};
79
80/// Clip `g` into every tile of zoom `z` it reaches, calling `emit` once per tile.
81///
82/// `g` must already be in world coordinates for `z` (see [`crate::geom`]'s module
83/// docs). `buffer` is the same overspill the old per-tile loop passed to both
84/// `tiles_touched` and `tile_rect`, and it is applied at every level of the descent.
85///
86/// A tile whose clip is empty is not emitted. The old loop reached those tiles and
87/// then skipped them, so nothing downstream sees a difference.
88///
89/// Tiles arrive in quadtree order, which is neither the old `(x, y)` order nor
90/// `tile_id` order. Every caller either keys a map by tile or sorts afterwards, so
91/// the order is deterministic rather than significant.
92pub fn subdivide<V, F>(g: &Geometry<V>, z: u8, extent: u32, buffer: f64, emit: &mut F)
93where
94 V: Vertex,
95 F: FnMut(u64, u64, &Geometry<V>),
96{
97 if let Geometry::Points(pts) = g {
98 bucket_points(pts, z, extent, buffer, emit);
99 return;
100 }
101 let Some(box_) = geom::bounds(g) else { return };
102 // The same padded range the old loop's `tiles_touched` computed from, so a
103 // feature reaching only into a neighbour's buffer still descends towards it.
104 let Some(range) = geom::tile_range(&box_, z, extent, buffer) else { return };
105
106 // The deepest cell holding the whole range is the one whose tile indices agree
107 // once the low bits are dropped.
108 let mut shift = 0u32;
109 while (range.x0 >> shift) != (range.x1 >> shift) || (range.y0 >> shift) != (range.y1 >> shift) {
110 shift += 1;
111 }
112 let level = z - shift as u8;
113 let (cx, cy) = (range.x0 >> shift, range.y0 >> shift);
114
115 // The start cell already contains the geometry, so this clip inserts nothing
116 // unless the feature runs off the edge of the grid -- where the old loop's edge
117 // tile cut it at the same coordinate, because a cell on the grid's border shares
118 // that border with its leaves.
119 let clipped = clip_geometry(g, &cell_rect(level, cx, cy, z, extent, buffer));
120 if is_empty(&clipped) {
121 return;
122 }
123 walk(&clipped, level, cx, cy, z, extent, buffer, emit);
124}
125
126/// Vertices below which a cell's subtree is walked on one thread by [`subdivide_par`]. A
127/// cell this small clips in microseconds; above it, the four children are worth a hand-off.
128const PAR_WALK_MIN_VERTICES: usize = 4096;
129
130/// Every vertex in `g`, all parts and rings.
131pub fn vertex_count<V>(g: &Geometry<V>) -> usize {
132 match g {
133 Geometry::Points(p) => p.len(),
134 Geometry::Lines(l) => l.iter().map(Vec::len).sum(),
135 Geometry::Polygons(p) => p.iter().flatten().map(Vec::len).sum(),
136 }
137}
138
139/// [`subdivide`], with the four children of every large cell clipped and walked on the pool,
140/// returned rather than emitted.
141///
142/// For the one feature that would otherwise hold a whole zoom's map phase on one thread: a
143/// state- or country-sized polygon at z12-z14 is a descent through hundreds of thousands of
144/// cells, and a chunk carrying one finishes seconds after every other worker has gone idle
145/// (California, measured: z13's map ran 8.8 s at ~1.4 cores of tiling CPU, its tail one
146/// thread deep in `clip_geometry` under `walk`).
147///
148/// Same tiles, same clipped geometries, **in the same order** `subdivide` emits them: each
149/// child's subtree is the very `walk` the sequential descent runs (same clips of the same
150/// inputs -- the clipper is a pure function), and the four results are concatenated in the
151/// `(0,0), (1,0), (0,1), (1,1)` order the sequential loop visits them. So a caller that
152/// replays the result through its `emit` sees exactly the sequential call sequence.
153pub fn subdivide_par<V>(
154 g: &Geometry<V>,
155 z: u8,
156 extent: u32,
157 buffer: f64,
158) -> Vec<(u64, u64, Geometry<V>)>
159where
160 V: Vertex + Send + Sync,
161{
162 let mut out = Vec::new();
163 if let Geometry::Points(pts) = g {
164 bucket_points(pts, z, extent, buffer, &mut |x, y, leaf: &Geometry<V>| {
165 out.push((x, y, leaf.clone()))
166 });
167 return out;
168 }
169 let Some(box_) = geom::bounds(g) else { return out };
170 let Some(range) = geom::tile_range(&box_, z, extent, buffer) else { return out };
171 let mut shift = 0u32;
172 while (range.x0 >> shift) != (range.x1 >> shift) || (range.y0 >> shift) != (range.y1 >> shift) {
173 shift += 1;
174 }
175 let level = z - shift as u8;
176 let (cx, cy) = (range.x0 >> shift, range.y0 >> shift);
177 let clipped = clip_geometry(g, &cell_rect(level, cx, cy, z, extent, buffer));
178 if is_empty(&clipped) {
179 return out;
180 }
181 crate::par::install(|| walk_par(&clipped, level, cx, cy, z, extent, buffer, &mut out));
182 out
183}
184
185/// [`walk`], fanned out over the four children while the cell is large. See [`subdivide_par`].
186#[allow(clippy::too_many_arguments)]
187fn walk_par<V>(
188 g: &Geometry<V>,
189 level: u8,
190 cx: u64,
191 cy: u64,
192 z: u8,
193 extent: u32,
194 buffer: f64,
195 out: &mut Vec<(u64, u64, Geometry<V>)>,
196) where
197 V: Vertex + Send + Sync,
198{
199 if level == z || vertex_count(g) < PAR_WALK_MIN_VERTICES {
200 walk(g, level, cx, cy, z, extent, buffer, &mut |x, y, leaf: &Geometry<V>| {
201 out.push((x, y, leaf.clone()))
202 });
203 return;
204 }
205 use rayon::prelude::*;
206 let box_ = geom::bounds(g);
207 let children: Vec<Vec<(u64, u64, Geometry<V>)>> = [(0u64, 0u64), (1, 0), (0, 1), (1, 1)]
208 .par_iter()
209 .map(|&(dx, dy)| {
210 let (nx, ny) = (cx * 2 + dx, cy * 2 + dy);
211 let clipped =
212 clip_child(g, box_.as_ref(), &cell_rect(level + 1, nx, ny, z, extent, buffer));
213 let mut sub = Vec::new();
214 if !is_empty(&clipped) {
215 walk_par(&clipped, level + 1, nx, ny, z, extent, buffer, &mut sub);
216 }
217 sub
218 })
219 .collect();
220 for sub in children {
221 out.extend(sub);
222 }
223}
224
225/// One quadtree cell's clip rect in world coordinates, grown by `buffer`.
226///
227/// At `level == z` this is [`geom::tile_rect`] to the bit: `2^0` is 1, so the
228/// arithmetic below is the same arithmetic.
229fn cell_rect(level: u8, cx: u64, cy: u64, z: u8, extent: u32, buffer: f64) -> Rect {
230 let side = extent as f64 * (1u64 << (z - level)) as f64;
231 let (ox, oy) = (cx as f64 * side, cy as f64 * side);
232 Rect {
233 min_x: ox - buffer,
234 min_y: oy - buffer,
235 max_x: ox + side + buffer,
236 max_y: oy + side + buffer,
237 }
238}
239
240/// Descend from a cell whose clipped geometry is `g`, emitting at the leaves.
241#[allow(clippy::too_many_arguments)]
242fn walk<V, F>(
243 g: &Geometry<V>,
244 level: u8,
245 cx: u64,
246 cy: u64,
247 z: u8,
248 extent: u32,
249 buffer: f64,
250 emit: &mut F,
251) where
252 V: Vertex,
253 F: FnMut(u64, u64, &Geometry<V>),
254{
255 if level == z {
256 emit(cx, cy, g);
257 return;
258 }
259 // One bbox for the four child clips below: each child whose rect misses
260 // the box clips to empty without walking a vertex, and a child
261 // containing the whole box clips to a copy of `g` (see `clip_child`).
262 // Concentrated geometries — the common case below the top levels — pay
263 // one walk plus one real clip per level instead of four full clips.
264 let box_ = geom::bounds(g);
265 for (dx, dy) in [(0u64, 0u64), (1, 0), (0, 1), (1, 1)] {
266 let (nx, ny) = (cx * 2 + dx, cy * 2 + dy);
267 let clipped =
268 clip_child(g, box_.as_ref(), &cell_rect(level + 1, nx, ny, z, extent, buffer));
269 if is_empty(&clipped) {
270 continue;
271 }
272 walk(&clipped, level + 1, nx, ny, z, extent, buffer, emit);
273 }
274}
275
276/// Whether `outer` contains `inner` wholly (boundary-inclusive, matching the
277/// clipper's own `>=`/`<=` comparisons).
278fn contains_rect(outer: &Rect, inner: &Rect) -> bool {
279 outer.min_x <= inner.min_x
280 && inner.max_x <= outer.max_x
281 && outer.min_y <= inner.min_y
282 && inner.max_y <= outer.max_y
283}
284
285/// A vertex is finite iff both coordinates are.
286fn finite_pt((x, y): Pt) -> bool {
287 x.is_finite() && y.is_finite()
288}
289
290/// Clip `g` to one child cell, short-circuiting the two decided cases.
291///
292/// `box_` is `g`'s bbox (computed once per level by the caller, not per
293/// child): a child the box misses clips to empty, and a child containing the
294/// whole box clips to a copy. Both are exact — see below — and both skip the
295/// per-vertex clip walk.
296///
297/// Exactness: `clip_geometry` invents vertices only at boundary crossings
298/// (Liang-Barsky interpolates only moved endpoints; Sutherland-Hodgman pushes
299/// only crossings plus surviving vertices), and drops only non-finite
300/// vertices. With every vertex strictly inside the rect there are no
301/// crossings to invent; with the box missing the rect there is nothing to
302/// keep. The boundary-inclusive tests below (`contains_rect` uses `<=`, the
303/// miss test negates `intersects`) match the clipper's own inclusive
304/// comparisons (`inside` uses `>=`/`<=`, `clip_segment` keeps `q >= 0`), so
305/// a vertex exactly on a child edge takes the general path — where the
306/// crossing arithmetic (not the fast path) decides, exactly as before.
307fn clip_child<V>(g: &Geometry<V>, box_: Option<&Rect>, rect: &Rect) -> Geometry<V>
308where
309 V: Vertex,
310{
311 match box_ {
312 // No finite vertex at all: every clip path drops everything.
313 // `clip_geometry` on points filters to empty; lines partition into
314 // nothing; rings fail the 3-vertex floor. Same empty, no walk.
315 None => empty_like(g),
316 Some(b) => {
317 if !b.intersects(rect) {
318 return empty_like(g);
319 }
320 if contains_rect(rect, b) {
321 // Every finite vertex strictly inside: clone. Non-finite
322 // vertices are NOT cloned along — `clip_geometry` drops them
323 // (`finite` filter in every path), so keeping them would
324 // invent vertices the clip removes. The filter walk is O(V)
325 // like the bbox was, but allocation-free for the common
326 // all-finite case... it still walks. Cheaper than the clip's
327 // interpolations + allocs, and correct where clone is not.
328 return clone_finite(g);
329 }
330 clip_geometry(g, rect)
331 }
332 }
333}
334
335/// An empty geometry of `g`'s variant: what `clip_geometry` returns when
336/// nothing survives (empty vec, same variant — the drain tests part counts,
337/// never the variant... it tests `is_empty`, which is variant-agnostic, but
338/// matching the variant keeps the shape identical anyway).
339fn empty_like<V>(g: &Geometry<V>) -> Geometry<V>
340where
341 V: Vertex,
342{
343 match g {
344 Geometry::Points(_) => Geometry::Points(Vec::new()),
345 Geometry::Lines(_) => Geometry::Lines(Vec::new()),
346 Geometry::Polygons(_) => Geometry::Polygons(Vec::new()),
347 }
348}
349
350/// `g` with non-finite vertices dropped, otherwise verbatim.
351///
352/// What `clip_geometry` reduces to when every finite vertex sits inside the
353/// rect: no crossings invented (nothing crosses a boundary it never meets),
354/// nothing kept that the filter would drop.
355///
356/// Per-variant because the clip's drop granularity differs per path:
357/// - Points: the filter IS the clip (kept or dropped whole). Exact.
358/// - Lines: an all-inside line survives whole — `clip_line` welds one
359/// gapless run back into itself, and lines under 2 vertices never survive
360/// its push gates. Replicated below, including the degenerate floors.
361/// - Polygons: delegated to the real clip (see below).
362///
363/// The all-finite check rides the same walk as the filter: one pass, no
364/// second scan. When anything drops, lines still return the filtered form
365/// directly (exact, per above); only polygons delegate.
366fn clone_finite<V>(g: &Geometry<V>) -> Geometry<V>
367where
368 V: Vertex,
369{
370 match g {
371 Geometry::Points(pts) => {
372 // The filter is the whole clip for points: kept whole or dropped.
373 Geometry::Points(pts.iter().copied().filter(|p| finite_pt(p.xy())).collect())
374 }
375 Geometry::Lines(lines) => {
376 let mut out = Vec::with_capacity(lines.len());
377 for line in lines {
378 let kept: Vec<V> = line.iter().copied().filter(|p| finite_pt(p.xy())).collect();
379 // `clip_line`'s floors, replicated: a run under 2 vertices is
380 // never pushed (windows(2) yields nothing; the trailing push
381 // needs len > 1). An all-inside line is one gapless run, so
382 // the kept vec IS the clip output — no welding needed, since
383 // no gap ever opens.
384 if kept.len() >= 2 {
385 out.push(kept);
386 }
387 // 0 or 1 surviving vertices: dropped, exactly as the clip's
388 // `len() > 1` gates drop them (a lone vertex never forms a
389 // segment, and `current` never reaches pushable length).
390 }
391 Geometry::Lines(out)
392 }
393 Geometry::Polygons(_) => {
394 // Rings need the clip's own normalisation (explicit-close
395 // handling and consecutive-duplicate dedup interact with
396 // filtering in ways a hand replica would get subtly wrong), and
397 // rings hold a minority of map vertices (lines dominate:
398 // boundaries, roads, rivers). So polygons always take the
399 // general path. (Revisit with measurements if rings dominate a
400 // profile: replicate `clip_ring`'s normalisation on filtered
401 // rings, pinned by the shape tests below.)
402 clip_geometry(
403 g,
404 &Rect {
405 min_x: f64::NEG_INFINITY,
406 min_y: f64::NEG_INFINITY,
407 max_x: f64::INFINITY,
408 max_y: f64::INFINITY,
409 },
410 )
411 }
412 }
413}
414
415/// Whether a clip left anything at all.
416///
417/// A part-count test is enough: [`clip_geometry`] already drops lines below two
418/// vertices and rings below three, so a surviving part is a drawable part.
419fn is_empty<V>(g: &Geometry<V>) -> bool {
420 match g {
421 Geometry::Points(pts) => pts.is_empty(),
422 Geometry::Lines(lines) => lines.is_empty(),
423 Geometry::Polygons(polys) => polys.is_empty(),
424 }
425}
426
427/// Bucket points into the tiles whose buffered rects hold them.
428///
429/// Deliberately the padded box rather than just the tile the coordinate floors
430/// into: a point three units from a tile edge belongs in the neighbour's buffer too,
431/// which is what keeps a label from being clipped at a tile join. That is exactly
432/// the set `tiles_touched` listed and `clip_geometry`'s `contains` test then kept.
433///
434/// One `Vec` of `(tile, point)` pairs sorted into runs, rather than a map of tiles to
435/// point lists. A `Points` feature is usually a single point, and this crate's
436/// standard for a per-feature path is set by `bucket_feature` threading its record
437/// buffer through from the caller -- a `HashMap` plus a `Vec` per tile per feature
438/// would be three allocations to place one node. The sort is stable, so points keep
439/// their input order within a tile.
440fn bucket_points<V, F>(pts: &[V], z: u8, extent: u32, buffer: f64, emit: &mut F)
441where
442 V: Vertex,
443 F: FnMut(u64, u64, &Geometry<V>),
444{
445 let mut spread: Vec<((u64, u64), V)> = Vec::with_capacity(pts.len());
446 for p in pts {
447 let (x, y) = p.xy();
448 let box_ = Rect { min_x: x, min_y: y, max_x: x, max_y: y };
449 let Some(range) = geom::tile_range(&box_, z, extent, buffer) else { continue };
450 for tile in range.iter() {
451 spread.push((tile, *p));
452 }
453 }
454 spread.sort_by_key(|&(tile, _)| tile);
455 // One `Geometry` reused across tiles, its inner `Vec` refilled rather than
456 // reallocated: `emit` takes a borrow, so handing over an owned vector per tile
457 // would give the allocation away and leave nothing to reuse.
458 let mut holder = Geometry::Points(Vec::new());
459 let mut at = 0usize;
460 while at < spread.len() {
461 let tile = spread[at].0;
462 let end = at + spread[at..].partition_point(|&(t, _)| t == tile);
463 let Geometry::Points(one) = &mut holder else { unreachable!("built as points") };
464 one.clear();
465 one.extend(spread[at..end].iter().map(|&(_, p)| p));
466 emit(tile.0, tile.1, &holder);
467 at = end;
468 }
469}
470
471#[cfg(test)]
472mod tests {
473 include!("subdivide_part1.rs");
474 include!("subdivide_part2.rs");
475 include!("subdivide_part3.rs");
476}