Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / scripts / maps / tile_build / src / geom.rs
geom.rs437 lines · 16.5 KiBRaw
| 1 | //! Geometry in tile space: projection, bounds, tile ranges and quantisation. |
| 2 | //! |
| 3 | //! This is the front of the tiling pipeline. Each stage is a separate function so |
| 4 | //! each can be tested on its own, and they compose in one fixed order: |
| 5 | //! |
| 6 | //! ```text |
| 7 | //! lon/lat --project_geometry--> world (tile units x extent, per zoom) |
| 8 | //! world --simplify::annotate-> world (per-vertex significance, in place) |
| 9 | //! world --clip::clip_geometry-> world (against one tile's buffered rect) |
| 10 | //! world --simplify::filter----> world (fewer vertices) |
| 11 | //! world --translate-----------> tile (origin at the tile's corner) |
| 12 | //! tile --quantize------------> integer tile coordinates |
| 13 | //! integer --mvt::encode_*-------> command stream |
| 14 | //! ``` |
| 15 | //! |
| 16 | //! ## Why "world x extent" and not fractional tile units |
| 17 | //! |
| 18 | //! Projection is the only expensive step, and a coastline crossing a thousand |
| 19 | //! tiles must not be projected a thousand times. So a geometry is projected |
| 20 | //! **once per zoom** into coordinates already scaled to the tile extent: tile |
| 21 | //! `(tx, ty)` then occupies `[tx*extent, (tx+1)*extent]`, and moving into it is a |
| 22 | //! subtraction. Clipping happens in that same space, against a rect built by |
| 23 | //! [`tile_rect`], so only the small clipped result is ever translated. |
| 24 | //! |
| 25 | //! ## Why the clip runs before the quantisation |
| 26 | //! |
| 27 | //! A clip introduces new vertices where an edge crosses the tile boundary, and |
| 28 | //! those crossings are not on the integer grid. Clipping in floats and rounding |
| 29 | //! afterwards puts the crossing within half a unit of the true intersection; |
| 30 | //! rounding first and clipping the integer polyline moves the whole edge before |
| 31 | //! the intersection is even computed, and the error compounds along a long edge. |
| 32 | |
| 33 | use crate::mvt::DEFAULT_EXTENT; |
| 34 | |
| 35 | /// A vertex. Longitude/latitude before projection, world or tile coordinates |
| 36 | /// after -- see each function for which space it works in. |
| 37 | pub type Pt = (f64, f64); |
| 38 | |
| 39 | /// A vertex on the integer tile grid, ready to encode. |
| 40 | pub type IPt = (i32, i32); |
| 41 | |
| 42 | /// A world-space vertex carrying how much shape it is responsible for. |
| 43 | /// |
| 44 | /// `sig` is the squared distance the vertex deviates from the chord |
| 45 | /// [`crate::simplify::annotate`] measured it against, in the same world units as |
| 46 | /// `x` and `y`. It is the whole point of this type: significance is computed |
| 47 | /// **once** on the unclipped source ring and then compared against a per-zoom |
| 48 | /// threshold, so a vertex is kept or dropped identically in every ring and every |
| 49 | /// tile it appears in. Simplifying each clipped ring on its own is what let a |
| 50 | /// hole and the exterior it shared a tile-boundary edge with thin differently and |
| 51 | /// drift apart. |
| 52 | /// |
| 53 | /// A named struct rather than a three-wide tuple so the compiler names every site |
| 54 | /// that has to think about the extra field. |
| 55 | #[derive(Debug, Clone, Copy, PartialEq)] |
| 56 | pub struct SigPt { |
| 57 | pub x: f64, |
| 58 | pub y: f64, |
| 59 | pub sig: f64, |
| 60 | } |
| 61 | |
| 62 | /// The significance of a vertex no threshold may remove: a path's own endpoints, |
| 63 | /// and every vertex the clipper invents on a tile boundary. |
| 64 | pub const ALWAYS: f64 = f64::INFINITY; |
| 65 | |
| 66 | impl SigPt { |
| 67 | /// A vertex whose significance is not yet known. [`crate::simplify::annotate`] |
| 68 | /// overwrites this; a vertex it never chooses is genuinely worth nothing and |
| 69 | /// zero is the right answer. |
| 70 | pub fn new(x: f64, y: f64) -> SigPt { |
| 71 | SigPt { x, y, sig: 0.0 } |
| 72 | } |
| 73 | } |
| 74 | |
| 75 | /// A vertex the geometry pipeline can carry: enough to be clipped, translated and |
| 76 | /// quantised without knowing whether it also carries significance. |
| 77 | /// |
| 78 | /// [`Pt`] and [`SigPt`] both implement it, which is what lets [`clip`] and the |
| 79 | /// coordinate-only parts of this module be written once and tested on plain pairs. |
| 80 | /// |
| 81 | /// [`clip`]: crate::clip |
| 82 | pub trait Vertex: Copy { |
| 83 | fn xy(self) -> Pt; |
| 84 | |
| 85 | /// The same vertex moved to `to`, keeping everything else about it. |
| 86 | fn moved(self, to: Pt) -> Self; |
| 87 | |
| 88 | /// A vertex invented at `at`, where an edge crosses a clip boundary. |
| 89 | /// |
| 90 | /// It is not in the source, so no annotation pass ever measured it, and |
| 91 | /// nothing downstream may remove it: it is the only thing holding two rings |
| 92 | /// that share a boundary edge to the same vertex set. |
| 93 | fn boundary(at: Pt) -> Self; |
| 94 | } |
| 95 | |
| 96 | impl Vertex for Pt { |
| 97 | fn xy(self) -> Pt { |
| 98 | self |
| 99 | } |
| 100 | fn moved(self, to: Pt) -> Pt { |
| 101 | to |
| 102 | } |
| 103 | fn boundary(at: Pt) -> Pt { |
| 104 | at |
| 105 | } |
| 106 | } |
| 107 | |
| 108 | impl Vertex for SigPt { |
| 109 | fn xy(self) -> Pt { |
| 110 | (self.x, self.y) |
| 111 | } |
| 112 | fn moved(self, (x, y): Pt) -> SigPt { |
| 113 | SigPt { x, y, sig: self.sig } |
| 114 | } |
| 115 | fn boundary((x, y): Pt) -> SigPt { |
| 116 | SigPt { x, y, sig: ALWAYS } |
| 117 | } |
| 118 | } |
| 119 | |
| 120 | /// Tile-boundary overspill, in extent units at [`DEFAULT_EXTENT`]. |
| 121 | /// |
| 122 | /// Geometry is clipped to the tile rect grown by this much, so a line crossing a |
| 123 | /// tile edge is drawn to slightly beyond it. Without it a renderer stroking a |
| 124 | /// 2 px-wide road would show a seam at every tile boundary, because the join and |
| 125 | /// the cap would have nothing on the far side to align with. 5 units at extent |
| 126 | /// 4096 is tippecanoe's default and what the published archives were built with. |
| 127 | pub const DEFAULT_BUFFER: f64 = 5.0; |
| 128 | |
| 129 | /// [`DEFAULT_BUFFER`] scaled to an arbitrary extent, so the overspill stays the |
| 130 | /// same fraction of a tile. |
| 131 | pub fn buffer_for(extent: u32) -> f64 { |
| 132 | DEFAULT_BUFFER * extent as f64 / DEFAULT_EXTENT as f64 |
| 133 | } |
| 134 | |
| 135 | /// A geometry, in whichever coordinate space the producing function documents. |
| 136 | /// |
| 137 | /// The three variants are the multi- forms only: a single LineString is a |
| 138 | /// `Lines` of one, and a single Polygon a `Polygons` of one. Collapsing the |
| 139 | /// singular cases removes a whole layer of branching from the clipper and the |
| 140 | /// encoders, and MVT itself draws no distinction -- geometry type is per feature, |
| 141 | /// not per part. |
| 142 | /// |
| 143 | /// `V` is the vertex type: [`Pt`] in lon/lat, which is what a source and a spill |
| 144 | /// record hold, and [`SigPt`] from [`project_geometry`] onwards, where the |
| 145 | /// pipeline needs each vertex's significance. |
| 146 | #[derive(Debug, Clone, PartialEq)] |
| 147 | pub enum Geometry<V = Pt> { |
| 148 | Points(Vec<V>), |
| 149 | Lines(Vec<Vec<V>>), |
| 150 | /// Each polygon is `[exterior, hole, hole, ...]`. Ring orientation is *not* |
| 151 | /// significant here; [`crate::mvt::encode_polygons`] derives it from the |
| 152 | /// signed area rather than trusting the input. |
| 153 | Polygons(Vec<Vec<Vec<V>>>), |
| 154 | } |
| 155 | |
| 156 | /// The integer counterpart of [`Geometry`], always in one tile's coordinates. |
| 157 | #[derive(Debug, Clone, PartialEq)] |
| 158 | pub enum IntGeometry { |
| 159 | Points(Vec<IPt>), |
| 160 | Lines(Vec<Vec<IPt>>), |
| 161 | Polygons(Vec<Vec<Vec<IPt>>>), |
| 162 | } |
| 163 | |
| 164 | impl IntGeometry { |
| 165 | pub fn is_empty(&self) -> bool { |
| 166 | match self { |
| 167 | IntGeometry::Points(p) => p.is_empty(), |
| 168 | IntGeometry::Lines(l) => l.iter().all(|p| p.len() < 2), |
| 169 | IntGeometry::Polygons(p) => p.iter().all(|rings| { |
| 170 | rings.first().is_none_or(|r| r.len() < 3) |
| 171 | }), |
| 172 | } |
| 173 | } |
| 174 | } |
| 175 | |
| 176 | /// An axis-aligned box. |
| 177 | #[derive(Debug, Clone, Copy, PartialEq)] |
| 178 | pub struct Rect { |
| 179 | pub min_x: f64, |
| 180 | pub min_y: f64, |
| 181 | pub max_x: f64, |
| 182 | pub max_y: f64, |
| 183 | } |
| 184 | |
| 185 | impl Rect { |
| 186 | pub fn contains(&self, (x, y): Pt) -> bool { |
| 187 | x >= self.min_x && x <= self.max_x && y >= self.min_y && y <= self.max_y |
| 188 | } |
| 189 | |
| 190 | pub fn intersects(&self, other: &Rect) -> bool { |
| 191 | self.min_x <= other.max_x |
| 192 | && other.min_x <= self.max_x |
| 193 | && self.min_y <= other.max_y |
| 194 | && other.min_y <= self.max_y |
| 195 | } |
| 196 | } |
| 197 | |
| 198 | /// Web-Mercator project a lon/lat to fractional tile coordinates at `z`. |
| 199 | /// |
| 200 | /// Latitude is clamped to the Mercator limit: the projection diverges at the |
| 201 | /// poles, and a feed with a `0,0`-style placeholder coordinate would otherwise |
| 202 | /// produce an infinity. |
| 203 | /// |
| 204 | /// This is the single copy of the projection in the crate. Two copies that drift |
| 205 | /// apart would put a point layer and a line layer at subtly different places in |
| 206 | /// the same tile. |
| 207 | pub fn project(lon: f64, lat: f64, z: u8) -> Pt { |
| 208 | let n = (1u64 << z) as f64; |
| 209 | let lat = lat.clamp(-85.051_128_78, 85.051_128_78); |
| 210 | let x = (lon.clamp(-180.0, 180.0) + 180.0) / 360.0 * n; |
| 211 | let s = lat.to_radians().sin(); |
| 212 | let y = (0.5 - (((1.0 + s) / (1.0 - s)).ln()) / (4.0 * std::f64::consts::PI)) * n; |
| 213 | (x, y) |
| 214 | } |
| 215 | |
| 216 | /// [`project`], scaled so one tile spans `extent` units. This is "world" |
| 217 | /// coordinates: tile `(tx, ty)` occupies `[tx*extent, (tx+1)*extent]`. |
| 218 | pub fn project_scaled(lon: f64, lat: f64, z: u8, extent: u32) -> Pt { |
| 219 | let (x, y) = project(lon, lat, z); |
| 220 | (x * extent as f64, y * extent as f64) |
| 221 | } |
| 222 | |
| 223 | /// Project a whole lon/lat geometry into world coordinates for one zoom. |
| 224 | /// |
| 225 | /// The result's vertices carry no significance yet; [`crate::simplify::annotate`] |
| 226 | /// is what fills that in, and it is the next step in the pipeline. |
| 227 | pub fn project_geometry(g: &Geometry, z: u8, extent: u32) -> Geometry<SigPt> { |
| 228 | let p = |&(lon, lat): &Pt| { |
| 229 | let (x, y) = project_scaled(lon, lat, z, extent); |
| 230 | SigPt::new(x, y) |
| 231 | }; |
| 232 | match g { |
| 233 | Geometry::Points(pts) => Geometry::Points(pts.iter().map(p).collect()), |
| 234 | Geometry::Lines(lines) => { |
| 235 | Geometry::Lines(lines.iter().map(|l| l.iter().map(p).collect()).collect()) |
| 236 | } |
| 237 | Geometry::Polygons(polys) => Geometry::Polygons( |
| 238 | polys |
| 239 | .iter() |
| 240 | .map(|rings| rings.iter().map(|r| r.iter().map(p).collect()).collect()) |
| 241 | .collect(), |
| 242 | ), |
| 243 | } |
| 244 | } |
| 245 | |
| 246 | /// The bounding box of every vertex, or `None` when there are none. |
| 247 | /// |
| 248 | /// Non-finite vertices are skipped. They should not exist -- [`project`] clamps -- |
| 249 | /// but a `NaN` reaching [`tile_range`] would silently produce an empty range, |
| 250 | /// and dropping it here at least keeps the rest of the geometry. |
| 251 | pub fn bounds<V: Vertex>(g: &Geometry<V>) -> Option<Rect> { |
| 252 | let mut r: Option<Rect> = None; |
| 253 | let mut add = |(x, y): Pt| { |
| 254 | if !x.is_finite() || !y.is_finite() { |
| 255 | return; |
| 256 | } |
| 257 | r = Some(match r { |
| 258 | None => Rect { min_x: x, min_y: y, max_x: x, max_y: y }, |
| 259 | Some(b) => Rect { |
| 260 | min_x: b.min_x.min(x), |
| 261 | min_y: b.min_y.min(y), |
| 262 | max_x: b.max_x.max(x), |
| 263 | max_y: b.max_y.max(y), |
| 264 | }, |
| 265 | }); |
| 266 | }; |
| 267 | match g { |
| 268 | Geometry::Points(pts) => pts.iter().for_each(|p| add(p.xy())), |
| 269 | Geometry::Lines(lines) => lines.iter().flatten().for_each(|p| add(p.xy())), |
| 270 | Geometry::Polygons(polys) => polys.iter().flatten().flatten().for_each(|p| add(p.xy())), |
| 271 | } |
| 272 | r |
| 273 | } |
| 274 | |
| 275 | /// An inclusive range of tile coordinates. |
| 276 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 277 | pub struct TileRange { |
| 278 | pub x0: u64, |
| 279 | pub y0: u64, |
| 280 | pub x1: u64, |
| 281 | pub y1: u64, |
| 282 | } |
| 283 | |
| 284 | impl TileRange { |
| 285 | /// Every `(x, y)` in the range, row-major, so a tiling pass is deterministic. |
| 286 | pub fn iter(&self) -> impl Iterator<Item = (u64, u64)> + '_ { |
| 287 | (self.y0..=self.y1).flat_map(move |y| (self.x0..=self.x1).map(move |x| (x, y))) |
| 288 | } |
| 289 | |
| 290 | pub fn len(&self) -> u64 { |
| 291 | (self.x1 - self.x0 + 1) * (self.y1 - self.y0 + 1) |
| 292 | } |
| 293 | |
| 294 | pub fn is_empty(&self) -> bool { |
| 295 | false |
| 296 | } |
| 297 | } |
| 298 | |
| 299 | /// Every tile a geometry can reach at zoom `z`, sorted and deduplicated. |
| 300 | /// |
| 301 | /// **No longer the tiling path.** [`crate::subdivide`] replaced all three of this |
| 302 | /// function's callers, because finding the tiles and then clipping the whole feature |
| 303 | /// against each of them is `O(T · V)` however tight `T` is. What remains is its use as |
| 304 | /// that module's reference: a descent must not reach a tile this does not list, and the |
| 305 | /// two are compared over a corpus there. Kept for that, and for the safety property its |
| 306 | /// own tests below pin -- a conservative superset is a useful thing to have a name for. |
| 307 | /// |
| 308 | /// The point of it over `tile_range(bounds(g))` is long thin diagonal features. A |
| 309 | /// bounding box is a terrible approximation of a route. Measured on one |
| 310 | /// transcontinental rail relation (40° of longitude) at z16: |
| 311 | /// |
| 312 | /// | | tiles | |
| 313 | /// |---|---| |
| 314 | /// | its bounding box | 34,535,986 | |
| 315 | /// | tiles it actually crosses | 16,632 | |
| 316 | /// |
| 317 | /// A 2077x difference, and each of those 34.5 million tiles ran a full clip and |
| 318 | /// simplify of the whole geometry. That is why `transit_lines` at planet scale took |
| 319 | /// hours. |
| 320 | /// |
| 321 | /// Each SEGMENT's own box is used instead, and their union taken. A segment whose box |
| 322 | /// still spans many tiles is bisected until it does not, so the result does not depend |
| 323 | /// on the input's vertex density: the same path with only 2 vertices walks 16,626 |
| 324 | /// tiles, within 0.1% of the 2000-vertex version. Without bisection a sparse line's |
| 325 | /// segment boxes are nearly as bad as the whole feature's. |
| 326 | /// |
| 327 | /// It stays a conservative superset — a segment's box always contains the segment, and |
| 328 | /// bisecting preserves that — so no tile a feature reaches can be missed. A |
| 329 | /// line-walking algorithm would have to be exactly right to be safe; this only has to |
| 330 | /// be tight. |
| 331 | /// |
| 332 | /// Polygons keep whole-ring boxes: a polygon legitimately covers its interior tiles, |
| 333 | /// and per-segment boxes would drop every tile strictly inside the ring. |
| 334 | pub fn tiles_touched<V: Vertex>( |
| 335 | g: &Geometry<V>, |
| 336 | z: u8, |
| 337 | extent: u32, |
| 338 | pad: f64, |
| 339 | out: &mut Vec<(u64, u64)>, |
| 340 | ) { |
| 341 | out.clear(); |
| 342 | match g { |
| 343 | // A point's box is a point; one range call each is already tight. |
| 344 | Geometry::Points(pts) => { |
| 345 | for p in pts { |
| 346 | let (x, y) = p.xy(); |
| 347 | push_box(out, x, y, x, y, z, extent, pad); |
| 348 | } |
| 349 | } |
| 350 | Geometry::Lines(lines) => { |
| 351 | for line in lines { |
| 352 | match line.as_slice() { |
| 353 | [] => {} |
| 354 | // A degenerate one-point "line" still occupies a tile. |
| 355 | [p] => { |
| 356 | let (x, y) = p.xy(); |
| 357 | push_box(out, x, y, x, y, z, extent, pad) |
| 358 | } |
| 359 | _ => { |
| 360 | for seg in line.windows(2) { |
| 361 | push_segment(out, seg[0].xy(), seg[1].xy(), z, extent, pad, 0); |
| 362 | } |
| 363 | } |
| 364 | } |
| 365 | } |
| 366 | } |
| 367 | Geometry::Polygons(polys) => { |
| 368 | for rings in polys { |
| 369 | // The exterior ring's own box, which is the polygon's footprint -- |
| 370 | // interior tiles included, because the fill reaches them. |
| 371 | let Some(ext) = rings.first() else { continue }; |
| 372 | let mut min = (f64::INFINITY, f64::INFINITY); |
| 373 | let mut max = (f64::NEG_INFINITY, f64::NEG_INFINITY); |
| 374 | for p in ext { |
| 375 | let (x, y) = p.xy(); |
| 376 | if !x.is_finite() || !y.is_finite() { |
| 377 | continue; |
| 378 | } |
| 379 | min = (min.0.min(x), min.1.min(y)); |
| 380 | max = (max.0.max(x), max.1.max(y)); |
| 381 | } |
| 382 | push_box(out, min.0, min.1, max.0, max.1, z, extent, pad); |
| 383 | } |
| 384 | } |
| 385 | } |
| 386 | // A feature must appear in a tile's list exactly once: adjacent segments share |
| 387 | // tiles, and a duplicate would encode the whole geometry twice into one tile. |
| 388 | out.sort_unstable(); |
| 389 | out.dedup(); |
| 390 | } |
| 391 | |
| 392 | /// A segment box this wide or tall is worth bisecting rather than filling. |
| 393 | /// |
| 394 | /// 2 means "no more than a 2x2 tile block", which is the smallest box a segment |
| 395 | /// crossing a tile corner can have — so bisection stops as soon as it is tight rather |
| 396 | /// than recursing forever on a segment that genuinely straddles a corner. |
| 397 | const MAX_SEGMENT_TILES: u64 = 2; |
| 398 | |
| 399 | /// Recursion cap, so a pathological coordinate cannot spin. At depth 24 a segment has |
| 400 | /// been bisected into 16 million pieces; anything still too wide is a broken input and |
| 401 | /// filling its box is the safe answer. |
| 402 | const MAX_BISECT_DEPTH: u32 = 24; |
| 403 | |
| 404 | fn push_segment( |
| 405 | out: &mut Vec<(u64, u64)>, |
| 406 | a: Pt, |
| 407 | b: Pt, |
| 408 | z: u8, |
| 409 | extent: u32, |
| 410 | pad: f64, |
| 411 | depth: u32, |
| 412 | ) { |
| 413 | let (ax, ay) = a; |
| 414 | let (bx, by) = b; |
| 415 | if !ax.is_finite() || !ay.is_finite() || !bx.is_finite() || !by.is_finite() { |
| 416 | return; |
| 417 | } |
| 418 | let rect = Rect { |
| 419 | min_x: ax.min(bx), |
| 420 | min_y: ay.min(by), |
| 421 | max_x: ax.max(bx), |
| 422 | max_y: ay.max(by), |
| 423 | }; |
| 424 | let Some(r) = tile_range(&rect, z, extent, pad) else { return }; |
| 425 | let spans_many = (r.x1 - r.x0) >= MAX_SEGMENT_TILES || (r.y1 - r.y0) >= MAX_SEGMENT_TILES; |
| 426 | if spans_many && depth < MAX_BISECT_DEPTH { |
| 427 | // Bisecting at the midpoint keeps the superset property: the two halves |
| 428 | // together cover exactly the same line. |
| 429 | let mid = ((ax + bx) / 2.0, (ay + by) / 2.0); |
| 430 | push_segment(out, a, mid, z, extent, pad, depth + 1); |
| 431 | push_segment(out, mid, b, z, extent, pad, depth + 1); |
| 432 | return; |
| 433 | } |
| 434 | out.extend(r.iter()); |
| 435 | } |
| 436 | |
| 437 | include!("geom_part1.rs"); |