Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / scripts / maps / tile_build / src / pyramid.rs
pyramid.rs429 lines · 19.1 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 | |
| 47 | use crate::geom::{self, Geometry, IntGeometry}; |
| 48 | use crate::mvt::{self, FeatureRef as MvtFeature, GeomType, Value, DEFAULT_EXTENT}; |
| 49 | use crate::par; |
| 50 | use crate::pmtiles::{self, Builder}; |
| 51 | use crate::progress::Progress; |
| 52 | use crate::proto::{err, Error, Result}; |
| 53 | use crate::simplify; |
| 54 | use crate::spill::{self, GeomKind}; |
| 55 | use crate::subdivide; |
| 56 | use rayon::prelude::*; |
| 57 | use std::path::Path; |
| 58 | |
| 59 | /// tippecanoe's default maximum gzipped tile size, and what the published |
| 60 | /// archives were built against. |
| 61 | pub 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)] |
| 65 | pub struct Feature { |
| 66 | pub geometry: Geometry, |
| 67 | pub props: Vec<(String, Value)>, |
| 68 | } |
| 69 | |
| 70 | pub 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 | } |
| 91 | impl 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. |
| 119 | const 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)] |
| 123 | pub 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. |
| 143 | struct 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. |
| 157 | struct 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. |
| 174 | fn by_importance_keys(a_extent: i64, a_seq: u64, b_extent: i64, b_seq: u64) -> std::cmp::Ordering { |
| 175 | b_extent.cmp(&a_extent).then_with(|| a_seq.cmp(&b_seq)) |
| 176 | } |
| 177 | |
| 178 | fn by_importance(a: &TileCandidate, b: &TileCandidate) -> std::cmp::Ordering { |
| 179 | by_importance_keys(a.extent, a.seq, b.extent, b.seq) |
| 180 | } |
| 181 | |
| 182 | /// One feature's contribution to one zoom's spill: every record it produces, in one |
| 183 | /// allocation. |
| 184 | /// |
| 185 | /// One `Vec` per feature rather than one per record, because a coastline at z16 |
| 186 | /// reaches thousands of tiles and a `Vec` each would make the allocator the hot |
| 187 | /// path. `spans` indexes `blob`, so pushing is `set.push(id, &blob[at..at + len])`. |
| 188 | struct BucketedFeature { |
| 189 | blob: Vec<u8>, |
| 190 | spans: Vec<(u64, usize, usize)>, |
| 191 | } |
| 192 | |
| 193 | /// Project one feature, clip it into every tile it reaches, and encode a spill |
| 194 | /// record per tile. |
| 195 | /// |
| 196 | /// Pure: every argument is shared except `rec`, which is the caller's per-worker |
| 197 | /// scratch buffer. That is what lets the bucket pass run this across the pool — and |
| 198 | /// the reason the buffer is passed in rather than declared here is the one the serial |
| 199 | /// loop had, unchanged: allocating it per feature would cost three million |
| 200 | /// allocations a zoom. |
| 201 | /// |
| 202 | /// The tile loop is [`subdivide::subdivide`], a quadtree descent, rather than a pass |
| 203 | /// over every tile [`geom::tiles_touched`] lists. Filtering stays **after** the clip |
| 204 | /// and per tile, which is where this crate has always done it and where |
| 205 | /// [`build_archive`] still does it -- the two are compared byte for byte, so the step |
| 206 | /// order has to match. |
| 207 | /// |
| 208 | /// Takes the geometry and properties rather than a [`Feature`] so the chunked read path |
| 209 | /// can pass a [`crate::spill::NormalizedFeature`]'s fields straight in. The two types |
| 210 | /// hold the same two things, and converting would mean copying a geometry per feature |
| 211 | /// per zoom to gain nothing. |
| 212 | #[allow(clippy::too_many_arguments)] |
| 213 | fn bucket_feature( |
| 214 | geometry: &Geometry, |
| 215 | props: &[(String, Value)], |
| 216 | seq: u64, |
| 217 | z: u8, |
| 218 | opts: &Options, |
| 219 | buffer: f64, |
| 220 | tolerance: f64, |
| 221 | rec: &mut Vec<u8>, |
| 222 | ) -> Result<BucketedFeature> { |
| 223 | let t0 = std::time::Instant::now(); |
| 224 | // Project once per feature per zoom, not once per tile: a coastline can cross |
| 225 | // thousands of tiles and the projection is the expensive part. Annotating here |
| 226 | // for the same reason, and because it has to see the ring UNCLIPPED -- see |
| 227 | // `simplify`'s module docs. |
| 228 | let mut projected = geom::project_geometry(geometry, z, opts.extent); |
| 229 | simplify::annotate(&mut projected); |
| 230 | let mut out = BucketedFeature { blob: Vec::new(), spans: Vec::new() }; |
| 231 | // `encode_record` can fail on a record too large to describe, and the descent's |
| 232 | // callback cannot return. The first failure is held and re-raised below rather |
| 233 | // than panicking: a `?` inside the closure is not available and unwinding out of |
| 234 | // it would cross the rayon boundary the callers put us behind. |
| 235 | let mut failed: Option<Error> = None; |
| 236 | subdivide::subdivide(&projected, z, opts.extent, buffer, &mut |tx, ty, clipped| { |
| 237 | if failed.is_some() { |
| 238 | return; |
| 239 | } |
| 240 | let filtered = simplify::filter(clipped, tolerance); |
| 241 | let local = geom::to_tile(&filtered, tx, ty, opts.extent); |
| 242 | if local.is_empty() { |
| 243 | return; |
| 244 | } |
| 245 | rec.clear(); |
| 246 | let id = pmtiles::tile_id(z, tx, ty); |
| 247 | if let Err(e) = spill::encode_record(id, seq, extent_of(&local), &local, props, rec) { |
| 248 | failed = Some(e); |
| 249 | return; |
| 250 | } |
| 251 | let at = out.blob.len(); |
| 252 | out.blob.extend_from_slice(rec); |
| 253 | out.spans.push((id, at, out.blob.len() - at)); |
| 254 | }); |
| 255 | BUCKET_NANOS.fetch_add(t0.elapsed().as_nanos() as u64, std::sync::atomic::Ordering::Relaxed); |
| 256 | match failed { |
| 257 | Some(e) => Err(e), |
| 258 | None => Ok(out), |
| 259 | } |
| 260 | } |
| 261 | |
| 262 | /// Build the archive, and a per-zoom report. |
| 263 | /// |
| 264 | /// **The in-memory oracle**, not the path for anything at scale. Per zoom this holds a |
| 265 | /// clipped copy of every geometry for every tile it reaches, so peak memory tracks the |
| 266 | /// zoom's output volume; [`build_archive_to`] is the streaming twin, produces the same |
| 267 | /// bytes, and is what the `tile_*` binaries use. Keeping the clipped copies is what buys |
| 268 | /// the quadtree descent — see [`crate::spill`]'s module docs for that trade. |
| 269 | pub fn build_archive(features: &[Feature], opts: &Options) -> Result<(Vec<u8>, Vec<ZoomStats>)> { |
| 270 | if opts.min_zoom > opts.max_zoom { |
| 271 | return err("minzoom is above maxzoom"); |
| 272 | } |
| 273 | if opts.extent == 0 { |
| 274 | return err("extent 0"); |
| 275 | } |
| 276 | |
| 277 | let geom_type = dominant_geom_type(features); |
| 278 | let buffer = geom::buffer_for(opts.extent); |
| 279 | let mut builder = Builder::new(); |
| 280 | builder.min_zoom = opts.min_zoom; |
| 281 | builder.max_zoom = opts.max_zoom; |
| 282 | builder.center_zoom = opts.min_zoom; |
| 283 | builder.metadata = metadata(&opts.layer, opts.min_zoom, opts.max_zoom).into_bytes(); |
| 284 | if let Some(b) = lonlat_bounds(features) { |
| 285 | builder.min_lon_e7 = e7(b.min_x); |
| 286 | builder.min_lat_e7 = e7(b.min_y); |
| 287 | builder.max_lon_e7 = e7(b.max_x); |
| 288 | builder.max_lat_e7 = e7(b.max_y); |
| 289 | builder.center_lon_e7 = e7((b.min_x + b.max_x) / 2.0); |
| 290 | builder.center_lat_e7 = e7((b.min_y + b.max_y) / 2.0); |
| 291 | } |
| 292 | |
| 293 | let mut report = Vec::new(); |
| 294 | for z in opts.min_zoom..=opts.max_zoom { |
| 295 | let mut stats = ZoomStats { zoom: z, ..Default::default() }; |
| 296 | let tolerance = simplify::tolerance_for(z, opts.max_zoom, opts.simplification); |
| 297 | |
| 298 | // Project, annotate, descend, clip, thin and move into the tile -- per feature, |
| 299 | // across the pool. `collect` into a Vec keeps the outer order the input's, which |
| 300 | // is what makes the drop policy's tie-break deterministic below. |
| 301 | // |
| 302 | // Step for step what `bucket_feature` does, on purpose: the byte-identity tests |
| 303 | // compare the two producers, so a step added to one and not the other is a test |
| 304 | // failure rather than a silent divergence. Projection and annotation are once |
| 305 | // per feature per zoom because projection is the expensive part and because |
| 306 | // significance has to be measured on the UNCLIPPED ring; the filter is per tile |
| 307 | // and AFTER the clip, which is this crate's order and not `tiler.rs`'s. |
| 308 | let placed: Vec<Vec<(u64, i64, IntGeometry)>> = par::install(|| { |
| 309 | features |
| 310 | .par_iter() |
| 311 | .map(|f| { |
| 312 | let mut p = geom::project_geometry(&f.geometry, z, opts.extent); |
| 313 | simplify::annotate(&mut p); |
| 314 | let mut out = Vec::new(); |
| 315 | subdivide::subdivide(&p, z, opts.extent, buffer, &mut |tx, ty, clipped| { |
| 316 | let filtered = simplify::filter(clipped, tolerance); |
| 317 | let local = geom::to_tile(&filtered, tx, ty, opts.extent); |
| 318 | // Anything that vanishes here never reached the tile in the |
| 319 | // first place, so it is not a "drop". |
| 320 | if local.is_empty() { |
| 321 | return; |
| 322 | } |
| 323 | out.push((pmtiles::tile_id(z, tx, ty), extent_of(&local), local)); |
| 324 | }); |
| 325 | out |
| 326 | }) |
| 327 | .collect() |
| 328 | }); |
| 329 | |
| 330 | // tile -> its candidates, in ascending feature index. Borrowed from `placed` |
| 331 | // rather than moved out of it: a tile's geometry is read once by `fit_tile` and |
| 332 | // a copy per candidate would be the largest allocation in the tiler. |
| 333 | let mut by_tile: std::collections::HashMap<u64, Vec<(u64, i64, &IntGeometry)>> = |
| 334 | std::collections::HashMap::new(); |
| 335 | for (i, one) in placed.iter().enumerate() { |
| 336 | for (id, extent, local) in one { |
| 337 | by_tile.entry(*id).or_default().push((i as u64, *extent, local)); |
| 338 | } |
| 339 | } |
| 340 | |
| 341 | // Sorted on the id itself, so this is `tile_id` order by construction. Sorting |
| 342 | // on `(tx, ty)` would not be: at z1 the lexicographic walk gives ids 1, 2, 4, 3, |
| 343 | // and `pmtiles::StreamBuilder` hard-errors on a non-ascending id. |
| 344 | let mut tiles: Vec<u64> = by_tile.keys().copied().collect(); |
| 345 | tiles.sort_unstable(); |
| 346 | let mut bar = |
| 347 | Progress::new(format!("{} z{z}", opts.layer), tiles.len(), TILES, opts.progress); |
| 348 | // Across tiles, not within one: a tile holds a handful of features, so mapping |
| 349 | // its encode over the pool costs more in scheduling than the encoding is worth. |
| 350 | // Tiles are independent and there are many, which is the seam. The fold below is |
| 351 | // sequential and in `tile_id` order, so `stats` and the archive are exactly what |
| 352 | // the serial version produced. |
| 353 | for chunk in tiles.chunks(par::batch_len()) { |
| 354 | let done: Vec<EncodedTile> = par::install(|| { |
| 355 | chunk |
| 356 | .par_iter() |
| 357 | .with_min_len(par::min_task_len(chunk.len())) |
| 358 | .map_init(crate::gz::Compressor::new, |gz, &id| { |
| 359 | let mut candidates: Vec<TileCandidate> = by_tile[&id] |
| 360 | .iter() |
| 361 | .map(|&(seq, extent, geom)| TileCandidate { |
| 362 | seq, |
| 363 | geom, |
| 364 | props: &features[seq as usize].props, |
| 365 | extent, |
| 366 | }) |
| 367 | .collect(); |
| 368 | candidates.sort_by(by_importance); |
| 369 | |
| 370 | let (body, kept, over) = |
| 371 | fit_tile(&candidates, &opts.layer, geom_type, opts, gz)?; |
| 372 | Ok(EncodedTile { |
| 373 | id, |
| 374 | body, |
| 375 | kept, |
| 376 | over_budget: over, |
| 377 | placed: candidates.len(), |
| 378 | }) |
| 379 | }) |
| 380 | .collect::<Result<Vec<_>>>() |
| 381 | })?; |
| 382 | |
| 383 | for t in done { |
| 384 | bar.tick(TILES); |
| 385 | stats.placed += t.placed; |
| 386 | stats.kept += t.kept; |
| 387 | stats.dropped += t.placed - t.kept; |
| 388 | if t.over_budget { |
| 389 | stats.over_budget += 1; |
| 390 | } |
| 391 | stats.largest_tile_bytes = stats.largest_tile_bytes.max(t.body.len()); |
| 392 | stats.tiles += 1; |
| 393 | builder.add_tile_raw(t.id, t.body); |
| 394 | } |
| 395 | } |
| 396 | bar.finish(TILES); |
| 397 | report.push(stats); |
| 398 | } |
| 399 | |
| 400 | Ok((builder.build()?, report)) |
| 401 | } |
| 402 | |
| 403 | /// Where the encode pass's time actually goes, accumulated across workers. |
| 404 | /// |
| 405 | /// Nanoseconds, summed over every `fit_tile` probe. Only read under `--timing`, and |
| 406 | /// the two `Instant::now()` calls are per PROBE (a handful per tile), not per feature, |
| 407 | /// so leaving them in costs nothing measurable. |
| 408 | /// |
| 409 | /// These exist because four rounds of plausible-sounding micro-optimisation to this |
| 410 | /// function -- a galloping search, hoisting the geometry encode, borrowing the value |
| 411 | /// dictionary key, boxing the compressor -- bought 3% between them. Splitting the |
| 412 | /// measurement is what identified the real cost. |
| 413 | static MVT_NANOS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); |
| 414 | static GZIP_NANOS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); |
| 415 | /// CPU spent inside [`bucket_feature`], summed over workers. Compared against the |
| 416 | /// bucket pass's WALL time, this says whether that pass is bound by its parallel |
| 417 | /// geometry work or by the serial stream read and spill write around it. |
| 418 | static BUCKET_NANOS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); |
| 419 | |
| 420 | include!("pyramid_part1.rs"); |
| 421 | include!("pyramid_part2.rs"); |
| 422 | include!("pyramid_part3.rs"); |
| 423 | include!("pyramid_part4.rs"); |
| 424 | #[cfg(test)] |
| 425 | mod tests { |
| 426 | include!("pyramid_part5.rs"); |
| 427 | include!("pyramid_part6.rs"); |
| 428 | include!("pyramid_part7.rs"); |
| 429 | } |