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

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

pyramid.rs436 lines · 19.2 KiBRaw
1//! The tile pyramid driver, and the drop policy.
2//!
3//! Turns a list of lon/lat features into a PMTiles archive:
4//!
5//! ```text
6//! per zoom, per feature: project -> annotate -> tile range
7//! per tile: clip -> filter -> to_tile -> encode -> drop policy
8//! -> gzip -> pmtiles::Builder
9//! ```
10//!
11//! # The drop policy
12//!
13//! tippecanoe keeps a tile under its size limit with `--drop-densest-as-needed`, a
14//! heuristic that removes whichever features are locally densest and whose result
15//! depends on the order it happened to visit them. We do not reproduce it. Instead:
16//!
17//! 1. Features in a tile are put in a **stable importance order**: largest bounding
18//! box first, ties broken by the feature's index in the input. Size is the best
19//! cheap proxy for "matters at this zoom" -- at z6 a state boundary should
20//! survive and a suburban street should not -- and the index makes it total, so
21//! two runs over the same input always drop the same features.
22//! 2. The largest prefix of that order which fits the gzipped byte budget is kept,
23//! found by binary search. A prefix, so the kept set is always the top-k most
24//! important, never a scattered subset.
25//! 3. If even one feature does not fit, that one feature is kept anyway and the
26//! tile is reported as over budget. An empty tile is a hole in the map; an
27//! oversized one is a slow tile.
28//!
29//! Consequences worth being explicit about:
30//!
31//! * **Per-tile feature counts will not match tippecanoe's.** That is the point of
32//! `test/diff_pmtiles.py --max-feature-delta`: the divergence is bounded and
33//! measured rather than unknown.
34//! * **`--extend-zooms-if-still-dropping` is deliberately not reproduced.** It can
35//! push an archive past its own `--maximum-zoom`, so an archive's advertised zoom
36//! range stops being a fact about its contents. Here `--maxzoom` is exactly the
37//! deepest zoom present.
38//! * **`--detect-shared-borders` is not implemented.** Two *different* admin
39//! polygons that share a border are simplified independently, so at low zoom the
40//! border can show as a hairline gap or a hairline overlap. Reproducing that needs
41//! a shared topology pass across features, which is a project of its own. The
42//! intra-feature case — a hole and the exterior it shares a clipped tile edge with
43//! — is not affected: [`crate::simplify`] annotates each vertex once on the
44//! unclipped source and filters per zoom, so both rings keep the same vertices
45//! along the edge.
46
47use crate::geom::{self, Geometry, IntGeometry};
48use crate::mvt::{self, FeatureRef as MvtFeature, GeomType, Value, DEFAULT_EXTENT};
49use crate::par;
50use crate::pmtiles::{self, Builder};
51use crate::progress::Progress;
52use crate::proto::{err, Error, Result};
53use crate::simplify;
54use crate::spill::{self, GeomKind};
55use crate::subdivide;
56use rayon::prelude::*;
57use std::path::Path;
58
59/// tippecanoe's default maximum gzipped tile size, and what the published
60/// archives were built against.
61pub const DEFAULT_MAX_TILE_BYTES: usize = 500_000;
62
63/// One feature to tile: geometry in lon/lat, plus its properties.
64#[derive(Debug, Clone)]
65pub struct Feature {
66 pub geometry: Geometry,
67 pub props: Vec<(String, Value)>,
68}
69
70pub struct Options {
71 pub layer: String,
72 pub min_zoom: u8,
73 pub max_zoom: u8,
74 pub extent: u32,
75 /// Simplification tolerance multiplier; 1.0 is the default policy.
76 pub simplification: f64,
77 pub max_tile_bytes: usize,
78 /// Print a per-zoom progress bar to stdout while tiling.
79 ///
80 /// Off by default so the library stays silent: the binaries turn it on, and the
81 /// tests would otherwise interleave bars with their output.
82 pub progress: bool,
83 /// Print how long each zoom's bucket and encode pass took, to stderr.
84 ///
85 /// Separate from `progress` and from [`ZoomStats`]: a duration cannot go in the
86 /// report, because the report is compared for equality by the byte-identity tests.
87 /// This is the measurement that says which phase to optimise next, and guessing
88 /// that from a total is how you end up optimising the wrong one.
89 pub timing: bool,
90}
91impl Options {
92 pub fn new(layer: impl Into<String>, min_zoom: u8, max_zoom: u8) -> Options {
93 Options {
94 layer: layer.into(),
95 min_zoom,
96 max_zoom,
97 extent: DEFAULT_EXTENT,
98 simplification: 1.0,
99 max_tile_bytes: DEFAULT_MAX_TILE_BYTES,
100 progress: false,
101 timing: false,
102 }
103 }
104
105 /// Show the tiling progress bar. What the `tile_*` binaries call.
106 pub fn with_progress(mut self) -> Options {
107 self.progress = true;
108 self
109 }
110}
111
112/// A one-line progress bar for one zoom's tile loop.
113///
114/// The count is the tiles that will be written. It used to be *candidate* tiles -- the
115/// tiles `geom::tiles_touched` listed, which was larger, because a candidate whose
116/// geometry clipped away to nothing was walked and then skipped. The quadtree descent
117/// does not reach those tiles at all, so the two numbers are now the same one and the
118/// bar agrees with the `tiles` column in the report below.
119const TILES: &str = "tile(s)";
120
121/// What one zoom cost, for the per-zoom report the drop policy owes the operator.
122#[derive(Debug, Default, Clone, PartialEq)]
123pub struct ZoomStats {
124 pub zoom: u8,
125 pub tiles: usize,
126 /// Feature instances placed into tiles before the drop policy ran. A feature
127 /// spanning four tiles counts four times, which is what the budget sees.
128 pub placed: usize,
129 pub kept: usize,
130 pub dropped: usize,
131 /// Tiles that could not be brought under budget even at one feature.
132 pub over_budget: usize,
133 pub largest_tile_bytes: usize,
134}
135
136/// One feature's contribution to one tile, ready for the drop policy.
137///
138/// Everything is borrowed. Both producers already own the geometry and the properties
139/// somewhere -- the in-memory one in a per-tile vector, the streaming one in a loaded
140/// bucket -- and a third copy per candidate would be the largest allocation in the
141/// tiler. `extent` is [`extent_of`] precomputed at construction rather than recomputed
142/// inside the importance sort, which would rescan every vertex `O(n log n)` times.
143struct TileCandidate<'a> {
144 /// The feature's position in the input, which is what makes the importance order
145 /// total and therefore the drop policy deterministic.
146 seq: u64,
147 geom: &'a IntGeometry,
148 props: &'a [(String, Value)],
149 extent: i64,
150}
151
152/// One encoded candidate tile, waiting for the sequential fold that writes it.
153///
154/// The parallel passes produce these and the fold consumes them in `tile_id` order;
155/// keeping the fields named is what makes that fold readable, since it has to update
156/// five different counters plus the archive.
157struct EncodedTile {
158 id: u64,
159 body: Vec<u8>,
160 kept: usize,
161 over_budget: bool,
162 /// Candidates the tile held before the drop policy ran.
163 placed: usize,
164}
165
166/// The stable importance order: largest bounding box first, input position breaking
167/// ties.
168///
169/// Taken as loose fields so the streaming producer can sort its records by
170/// `(tile_id, importance)` without first building candidates it cannot borrow from a
171/// vector it is still sorting. One function either way, so the two producers cannot
172/// disagree about which features a tight budget drops -- a disagreement no test
173/// comparing anything less than whole bytes would catch.
174fn by_importance_keys(
175 a_extent: i64,
176 a_seq: u64,
177 b_extent: i64,
178 b_seq: u64,
179) -> std::cmp::Ordering {
180 b_extent.cmp(&a_extent).then_with(|| a_seq.cmp(&b_seq))
181}
182
183fn by_importance(a: &TileCandidate, b: &TileCandidate) -> std::cmp::Ordering {
184 by_importance_keys(a.extent, a.seq, b.extent, b.seq)
185}
186
187/// One feature's contribution to one zoom's spill: every record it produces, in one
188/// allocation.
189///
190/// One `Vec` per feature rather than one per record, because a coastline at z16
191/// reaches thousands of tiles and a `Vec` each would make the allocator the hot
192/// path. `spans` indexes `blob`, so pushing is `set.push(id, &blob[at..at + len])`.
193struct BucketedFeature {
194 blob: Vec<u8>,
195 spans: Vec<(u64, usize, usize)>,
196}
197
198/// Project one feature, clip it into every tile it reaches, and encode a spill
199/// record per tile.
200///
201/// Pure: every argument is shared except `rec`, which is the caller's per-worker
202/// scratch buffer. That is what lets the bucket pass run this across the pool — and
203/// the reason the buffer is passed in rather than declared here is the one the serial
204/// loop had, unchanged: allocating it per feature would cost three million
205/// allocations a zoom.
206///
207/// The tile loop is [`subdivide::subdivide`], a quadtree descent, rather than a pass
208/// over every tile [`geom::tiles_touched`] lists. Filtering stays **after** the clip
209/// and per tile, which is where this crate has always done it and where
210/// [`build_archive`] still does it -- the two are compared byte for byte, so the step
211/// order has to match.
212///
213/// Takes the geometry and properties rather than a [`Feature`] so the chunked read path
214/// can pass a [`crate::spill::NormalizedFeature`]'s fields straight in. The two types
215/// hold the same two things, and converting would mean copying a geometry per feature
216/// per zoom to gain nothing.
217#[allow(clippy::too_many_arguments)]
218fn bucket_feature(
219 geometry: &Geometry,
220 props: &[(String, Value)],
221 seq: u64,
222 z: u8,
223 opts: &Options,
224 buffer: f64,
225 tolerance: f64,
226 rec: &mut Vec<u8>,
227) -> Result<BucketedFeature> {
228 let t0 = std::time::Instant::now();
229 // Project once per feature per zoom, not once per tile: a coastline can cross
230 // thousands of tiles and the projection is the expensive part. Annotating here
231 // for the same reason, and because it has to see the ring UNCLIPPED -- see
232 // `simplify`'s module docs.
233 let mut projected = geom::project_geometry(geometry, z, opts.extent);
234 simplify::annotate(&mut projected);
235 let mut out = BucketedFeature { blob: Vec::new(), spans: Vec::new() };
236 // `encode_record` can fail on a record too large to describe, and the descent's
237 // callback cannot return. The first failure is held and re-raised below rather
238 // than panicking: a `?` inside the closure is not available and unwinding out of
239 // it would cross the rayon boundary the callers put us behind.
240 let mut failed: Option<Error> = None;
241 subdivide::subdivide(&projected, z, opts.extent, buffer, &mut |tx, ty, clipped| {
242 if failed.is_some() {
243 return;
244 }
245 let filtered = simplify::filter(clipped, tolerance);
246 let local = geom::to_tile(&filtered, tx, ty, opts.extent);
247 if local.is_empty() {
248 return;
249 }
250 rec.clear();
251 let id = pmtiles::tile_id(z, tx, ty);
252 if let Err(e) = spill::encode_record(id, seq, extent_of(&local), &local, props, rec) {
253 failed = Some(e);
254 return;
255 }
256 let at = out.blob.len();
257 out.blob.extend_from_slice(rec);
258 out.spans.push((id, at, out.blob.len() - at));
259 });
260 BUCKET_NANOS.fetch_add(
261 t0.elapsed().as_nanos() as u64,
262 std::sync::atomic::Ordering::Relaxed,
263 );
264 match failed {
265 Some(e) => Err(e),
266 None => Ok(out),
267 }
268}
269
270/// Build the archive, and a per-zoom report.
271///
272/// **The in-memory oracle**, not the path for anything at scale. Per zoom this holds a
273/// clipped copy of every geometry for every tile it reaches, so peak memory tracks the
274/// zoom's output volume; [`build_archive_to`] is the streaming twin, produces the same
275/// bytes, and is what the `tile_*` binaries use. Keeping the clipped copies is what buys
276/// the quadtree descent — see [`crate::spill`]'s module docs for that trade.
277pub fn build_archive(features: &[Feature], opts: &Options) -> Result<(Vec<u8>, Vec<ZoomStats>)> {
278 if opts.min_zoom > opts.max_zoom {
279 return err("minzoom is above maxzoom");
280 }
281 if opts.extent == 0 {
282 return err("extent 0");
283 }
284
285 let geom_type = dominant_geom_type(features);
286 let buffer = geom::buffer_for(opts.extent);
287 let mut builder = Builder::new();
288 builder.min_zoom = opts.min_zoom;
289 builder.max_zoom = opts.max_zoom;
290 builder.center_zoom = opts.min_zoom;
291 builder.metadata = metadata(&opts.layer, opts.min_zoom, opts.max_zoom).into_bytes();
292 if let Some(b) = lonlat_bounds(features) {
293 builder.min_lon_e7 = e7(b.min_x);
294 builder.min_lat_e7 = e7(b.min_y);
295 builder.max_lon_e7 = e7(b.max_x);
296 builder.max_lat_e7 = e7(b.max_y);
297 builder.center_lon_e7 = e7((b.min_x + b.max_x) / 2.0);
298 builder.center_lat_e7 = e7((b.min_y + b.max_y) / 2.0);
299 }
300
301 let mut report = Vec::new();
302 for z in opts.min_zoom..=opts.max_zoom {
303 let mut stats = ZoomStats { zoom: z, ..Default::default() };
304 let tolerance = simplify::tolerance_for(z, opts.max_zoom, opts.simplification);
305
306 // Project, annotate, descend, clip, thin and move into the tile -- per feature,
307 // across the pool. `collect` into a Vec keeps the outer order the input's, which
308 // is what makes the drop policy's tie-break deterministic below.
309 //
310 // Step for step what `bucket_feature` does, on purpose: the byte-identity tests
311 // compare the two producers, so a step added to one and not the other is a test
312 // failure rather than a silent divergence. Projection and annotation are once
313 // per feature per zoom because projection is the expensive part and because
314 // significance has to be measured on the UNCLIPPED ring; the filter is per tile
315 // and AFTER the clip, which is this crate's order and not `tiler.rs`'s.
316 let placed: Vec<Vec<(u64, i64, IntGeometry)>> = par::install(|| {
317 features
318 .par_iter()
319 .map(|f| {
320 let mut p = geom::project_geometry(&f.geometry, z, opts.extent);
321 simplify::annotate(&mut p);
322 let mut out = Vec::new();
323 subdivide::subdivide(&p, z, opts.extent, buffer, &mut |tx, ty, clipped| {
324 let filtered = simplify::filter(clipped, tolerance);
325 let local = geom::to_tile(&filtered, tx, ty, opts.extent);
326 // Anything that vanishes here never reached the tile in the
327 // first place, so it is not a "drop".
328 if local.is_empty() {
329 return;
330 }
331 out.push((pmtiles::tile_id(z, tx, ty), extent_of(&local), local));
332 });
333 out
334 })
335 .collect()
336 });
337
338 // tile -> its candidates, in ascending feature index. Borrowed from `placed`
339 // rather than moved out of it: a tile's geometry is read once by `fit_tile` and
340 // a copy per candidate would be the largest allocation in the tiler.
341 let mut by_tile: std::collections::HashMap<u64, Vec<(u64, i64, &IntGeometry)>> =
342 std::collections::HashMap::new();
343 for (i, one) in placed.iter().enumerate() {
344 for (id, extent, local) in one {
345 by_tile.entry(*id).or_default().push((i as u64, *extent, local));
346 }
347 }
348
349 // Sorted on the id itself, so this is `tile_id` order by construction. Sorting
350 // on `(tx, ty)` would not be: at z1 the lexicographic walk gives ids 1, 2, 4, 3,
351 // and `pmtiles::StreamBuilder` hard-errors on a non-ascending id.
352 let mut tiles: Vec<u64> = by_tile.keys().copied().collect();
353 tiles.sort_unstable();
354 let mut bar = Progress::new(format!("{} z{z}", opts.layer), tiles.len(), TILES, opts.progress);
355 // Across tiles, not within one: a tile holds a handful of features, so mapping
356 // its encode over the pool costs more in scheduling than the encoding is worth.
357 // Tiles are independent and there are many, which is the seam. The fold below is
358 // sequential and in `tile_id` order, so `stats` and the archive are exactly what
359 // the serial version produced.
360 for chunk in tiles.chunks(par::batch_len()) {
361 let done: Vec<EncodedTile> = par::install(|| {
362 chunk
363 .par_iter()
364 .with_min_len(par::min_task_len(chunk.len()))
365 .map_init(crate::gz::Compressor::new, |gz, &id| {
366 let mut candidates: Vec<TileCandidate> = by_tile[&id]
367 .iter()
368 .map(|&(seq, extent, geom)| TileCandidate {
369 seq,
370 geom,
371 props: &features[seq as usize].props,
372 extent,
373 })
374 .collect();
375 candidates.sort_by(by_importance);
376
377 let (body, kept, over) =
378 fit_tile(&candidates, &opts.layer, geom_type, opts, gz)?;
379 Ok(EncodedTile {
380 id,
381 body,
382 kept,
383 over_budget: over,
384 placed: candidates.len(),
385 })
386 })
387 .collect::<Result<Vec<_>>>()
388 })?;
389
390 for t in done {
391 bar.tick(TILES);
392 stats.placed += t.placed;
393 stats.kept += t.kept;
394 stats.dropped += t.placed - t.kept;
395 if t.over_budget {
396 stats.over_budget += 1;
397 }
398 stats.largest_tile_bytes = stats.largest_tile_bytes.max(t.body.len());
399 stats.tiles += 1;
400 builder.add_tile_raw(t.id, t.body);
401 }
402 }
403 bar.finish(TILES);
404 report.push(stats);
405 }
406
407 Ok((builder.build()?, report))
408}
409
410/// Where the encode pass's time actually goes, accumulated across workers.
411///
412/// Nanoseconds, summed over every `fit_tile` probe. Only read under `--timing`, and
413/// the two `Instant::now()` calls are per PROBE (a handful per tile), not per feature,
414/// so leaving them in costs nothing measurable.
415///
416/// These exist because four rounds of plausible-sounding micro-optimisation to this
417/// function -- a galloping search, hoisting the geometry encode, borrowing the value
418/// dictionary key, boxing the compressor -- bought 3% between them. Splitting the
419/// measurement is what identified the real cost.
420static MVT_NANOS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
421static GZIP_NANOS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
422/// CPU spent inside [`bucket_feature`], summed over workers. Compared against the
423/// bucket pass's WALL time, this says whether that pass is bound by its parallel
424/// geometry work or by the serial stream read and spill write around it.
425static BUCKET_NANOS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
426
427include!("pyramid_part1.rs");
428include!("pyramid_part2.rs");
429include!("pyramid_part3.rs");
430include!("pyramid_part4.rs");
431#[cfg(test)]
432mod tests {
433 include!("pyramid_part5.rs");
434 include!("pyramid_part6.rs");
435 include!("pyramid_part7.rs");
436}