maps: add the tile_build vector geometry core
- Commit
c0d681e12f43618614c3f1c2d5508ee39392b637- Author
- vayun-mathur <[email protected]>
- When
- 2026-08-21 06:13 UTC (3 months ago)
- Parents
a367cd7
Diff
scripts/maps/README.md
diff --git a/scripts/maps/README.md b/scripts/maps/README.mdindex 2c689ce88b..07365b0435 100644--- a/scripts/maps/README.md+++ b/scripts/maps/README.md@@ -178,7 +178,7 @@ mutually consistent (same POI set, same coordinates). See | `build_transit_stops_layer.sh` | GTFS dirs → `gtfs_ingest` `transit_stops` → geojsonseq → `tile_build` `tile_points` → `transit_stops.pmtiles`. **No tippecanoe, no osmium** | | `build_transit_stops_layer.ps1` | **Windows** entry point for the same layer (cargo-only) | | `gtfs_ingest/` | Rust GTFS crate (detached): `gtfs_ingest` (the on-device `.transit` pack) and `transit_stops` (the basemap stop layer). TRX2 on-disk format documented in `src/index.rs` |-| `tile_build/` | Rust MVT + PMTiles v3 crate (detached), **replacing tippecanoe and tile-join**: `tile_points` (tile a point geojsonseq), `tile_join` (merge archives) and `pmtiles_dump` (canonical text dump, for the differential harness). Container layout documented in `src/pmtiles.rs` |+| `tile_build/` | Rust MVT + PMTiles v3 crate (detached), **replacing tippecanoe and tile-join**. Bins: `tile_points` (tile a point geojsonseq), `tile_join` (merge archives), `pmtiles_dump` (canonical text dump, for the differential harness). Library: `geom` (web-mercator projection, tile ranges, quantisation), `clip` (Liang-Barsky for lines, Sutherland-Hodgman for polygons), `simplify` (Douglas-Peucker in integer tile coordinates), `mvt` (line and polygon encoders beside the opaque passthrough that keeps `tile_join` lossless). Container layout documented in `src/pmtiles.rs`, the pipeline order in `src/geom.rs` | | `publish_r2.sh` | Upload built artifacts to Cloudflare R2 (creds from env vars only) | | `normalize_safety.py` | OSM tags → `safety` layer schema (pure stdlib, unit-tested). **Superseded** by `osm_ingest/src/safety.rs`; kept as the contract of record and as `--engine legacy` for the differential harness | | `normalize_maxspeed.py` | OSM maxspeed ways → `maxspeed` layer schema (pure stdlib, unit-tested) |
scripts/maps/tile_build/src/clip.rs
diff --git a/scripts/maps/tile_build/src/clip.rs b/scripts/maps/tile_build/src/clip.rsnew file mode 100644index 0000000000..c947c75403--- /dev/null+++ b/scripts/maps/tile_build/src/clip.rs@@ -0,0 +1,620 @@+//! Clipping geometry to a tile's buffered rect.+//!+//! Two different algorithms, because lines and polygons need different answers+//! from a clip:+//!+//! * **Lines use Liang-Barsky.** A polyline crossing a tile can leave and re-enter+//! it, so one input line yields **N output lines** -- the clip is a partition,+//! not a truncation. Joining the pieces back up would draw a road straight+//! across a bay it actually goes around.+//! * **Polygons use Sutherland-Hodgman.** A polygon must stay a closed area after+//! clipping, so the parts of the tile boundary that bound the clipped shape have+//! to become real edges. Liang-Barsky would give a set of disconnected arcs with+//! no interior.+//!+//! ## What Sutherland-Hodgman does and does not do+//!+//! It clips against each of the four half-planes in turn, and it is exact for a+//! convex polygon. For a **concave** polygon whose clipped result is two or more+//! disjoint pieces, it returns a single ring joined by a degenerate sliver running+//! along the boundary: zero area, so it renders correctly, but it is one ring+//! where a strict result would be two. Splitting them requires a general polygon+//! clipper (Vatti or Greiner-Hormann), which is a large piece of work for a defect+//! that is invisible at render time. Documented here rather than pretended away.+//!+//! ## The `NaN` question+//!+//! Both algorithms compare and divide. A non-finite vertex would make every+//! comparison false and could emit a `NaN` intersection, which+//! [`crate::geom::quantize`] then turns into a vertex at the tile origin. So+//! non-finite vertices are dropped on the way in; [`crate::geom::project`] clamps,+//! so they should not arise, but the clipper is the last place that can still tell+//! the difference between "outside" and "unknown".++use crate::geom::{Geometry, Pt, Rect};++/// Clip a geometry to `rect`, in the same coordinate space as the input.+///+/// Points are kept or dropped whole; lines are partitioned; polygon rings are+/// clipped into new rings. Parts that vanish entirely are removed, so an empty+/// result means the geometry does not touch the rect at all.+pub fn clip_geometry(g: &Geometry, rect: &Rect) -> Geometry {+ match g {+ Geometry::Points(pts) => {+ Geometry::Points(pts.iter().copied().filter(|p| finite(*p) && rect.contains(*p)).collect())+ }+ Geometry::Lines(lines) => {+ let mut out = Vec::new();+ for line in lines {+ out.extend(clip_line(line, rect));+ }+ Geometry::Lines(out)+ }+ Geometry::Polygons(polys) => {+ let mut out = Vec::new();+ for rings in polys {+ let clipped = clip_polygon(rings, rect);+ if !clipped.is_empty() {+ out.push(clipped);+ }+ }+ Geometry::Polygons(out)+ }+ }+}++fn finite((x, y): Pt) -> bool {+ x.is_finite() && y.is_finite()+}++/// Clip one polyline, returning the pieces that fall inside `rect`.+///+/// Consecutive segments that survive the clip and still meet are welded back into+/// one output line; a gap starts a new one. That is what makes the result a+/// partition of the original rather than a bag of segments.+pub fn clip_line(line: &[Pt], rect: &Rect) -> Vec<Vec<Pt>> {+ let mut out: Vec<Vec<Pt>> = Vec::new();+ let mut current: Vec<Pt> = Vec::new();++ for w in line.windows(2) {+ let (a, b) = (w[0], w[1]);+ if !finite(a) || !finite(b) {+ // Break the run: welding across a dropped vertex would invent an edge.+ if current.len() > 1 {+ out.push(std::mem::take(&mut current));+ } else {+ current.clear();+ }+ continue;+ }+ match clip_segment(a, b, rect) {+ None => {+ if current.len() > 1 {+ out.push(std::mem::take(&mut current));+ } else {+ current.clear();+ }+ }+ Some((ca, cb)) => {+ if current.last() == Some(&ca) {+ current.push(cb);+ } else {+ if current.len() > 1 {+ out.push(std::mem::take(&mut current));+ } else {+ current.clear();+ }+ current.push(ca);+ current.push(cb);+ }+ }+ }+ }+ if current.len() > 1 {+ out.push(current);+ }+ out+}++/// Liang-Barsky: clip the segment `a -> b` to `rect`.+///+/// Returns the surviving sub-segment, or `None` when the segment misses the rect.+/// The algorithm narrows a parameter interval `[t0, t1]` along the segment against+/// each of the four boundaries; the segment is outside as soon as the interval+/// closes.+///+/// A non-finite endpoint is `None`. Every comparison below would be false for a+/// `NaN`, so it would fall through as "inside" and emit a `NaN` intersection.+pub fn clip_segment(a: Pt, b: Pt, rect: &Rect) -> Option<(Pt, Pt)> {+ if !finite(a) || !finite(b) {+ return None;+ }+ let (dx, dy) = (b.0 - a.0, b.1 - a.1);+ let mut t0 = 0.0f64;+ let mut t1 = 1.0f64;++ // Each boundary is `p * t <= q`, where p is the direction component and q the+ // distance to the boundary.+ for &(p, q) in &[+ (-dx, a.0 - rect.min_x),+ (dx, rect.max_x - a.0),+ (-dy, a.1 - rect.min_y),+ (dy, rect.max_y - a.1),+ ] {+ if p == 0.0 {+ // Parallel to this boundary: inside iff already on the right side.+ if q < 0.0 {+ return None;+ }+ continue;+ }+ let t = q / p;+ if p < 0.0 {+ // Entering: raise the lower bound.+ if t > t1 {+ return None;+ }+ if t > t0 {+ t0 = t;+ }+ } else {+ // Leaving: lower the upper bound.+ if t < t0 {+ return None;+ }+ if t < t1 {+ t1 = t;+ }+ }+ }+ Some((+ (a.0 + t0 * dx, a.1 + t0 * dy),+ (a.0 + t1 * dx, a.1 + t1 * dy),+ ))+}++/// Clip a polygon's rings to `rect`.+///+/// A ring that clips away entirely is dropped. If the **exterior** ring+/// disappears the whole polygon does, holes included: a hole with no surrounding+/// area is not a shape, and emitting one would render as a solid patch of the+/// wrong colour.+pub fn clip_polygon(rings: &[Vec<Pt>], rect: &Rect) -> Vec<Vec<Pt>> {+ let mut out: Vec<Vec<Pt>> = Vec::new();+ for (i, ring) in rings.iter().enumerate() {+ let clipped = clip_ring(ring, rect);+ if clipped.len() < 3 {+ if i == 0 {+ return Vec::new();+ }+ continue;+ }+ out.push(clipped);+ }+ out+}++/// Sutherland-Hodgman: clip one ring against the four boundaries in turn.+///+/// The caller's closure convention is preserved: an explicitly closed ring+/// (first == last) is normalised on the way in and re-closed on the way out, and+/// an unclosed one stays unclosed. Fewer than three distinct vertices out means+/// the ring did not survive.+pub fn clip_ring(ring: &[Pt], rect: &Rect) -> Vec<Pt> {+ let was_closed = ring.len() > 1 && ring.first() == ring.last();+ let open: Vec<Pt> = ring[..ring.len() - usize::from(was_closed)]+ .iter()+ .copied()+ .filter(|p| finite(*p))+ .collect();+ if open.len() < 3 {+ return Vec::new();+ }++ let mut current = open;+ for edge in [+ Edge::Left(rect.min_x),+ Edge::Right(rect.max_x),+ Edge::Bottom(rect.min_y),+ Edge::Top(rect.max_y),+ ] {+ if current.len() < 3 {+ return Vec::new();+ }+ let mut next: Vec<Pt> = Vec::with_capacity(current.len() + 4);+ for i in 0..current.len() {+ let a = current[(i + current.len() - 1) % current.len()];+ let b = current[i];+ let (a_in, b_in) = (edge.inside(a), edge.inside(b));+ if b_in {+ // Entering: the crossing comes first, then the vertex itself.+ if !a_in {+ next.push(edge.intersect(a, b));+ }+ next.push(b);+ } else if a_in {+ // Leaving: only the crossing.+ next.push(edge.intersect(a, b));+ }+ }+ current = next;+ }++ // The clip can put two crossings on the same boundary point.+ current.dedup();+ if current.len() > 1 && current.first() == current.last() {+ current.pop();+ }+ if current.len() < 3 {+ return Vec::new();+ }+ if was_closed {+ let first = current[0];+ current.push(first);+ }+ current+}++/// Which side of a boundary a vertex is on, and where an edge crosses it.+#[derive(Clone, Copy)]+enum Edge {+ Left(f64),+ Right(f64),+ Bottom(f64),+ Top(f64),+}++impl Edge {+ fn inside(self, (x, y): Pt) -> bool {+ match self {+ Edge::Left(v) => x >= v,+ Edge::Right(v) => x <= v,+ Edge::Bottom(v) => y >= v,+ Edge::Top(v) => y <= v,+ }+ }++ /// Where `a -> b` crosses this boundary. Only called when the two vertices are+ /// on opposite sides, so the denominator cannot be zero.+ fn intersect(self, a: Pt, b: Pt) -> Pt {+ match self {+ Edge::Left(v) | Edge::Right(v) => {+ let t = (v - a.0) / (b.0 - a.0);+ (v, a.1 + t * (b.1 - a.1))+ }+ Edge::Bottom(v) | Edge::Top(v) => {+ let t = (v - a.1) / (b.1 - a.1);+ (a.0 + t * (b.0 - a.0), v)+ }+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ /// A 10x10 rect at the origin, so every expected coordinate is readable.+ fn r() -> Rect {+ Rect { min_x: 0.0, min_y: 0.0, max_x: 10.0, max_y: 10.0 }+ }++ fn close(a: Pt, b: Pt) -> bool {+ (a.0 - b.0).abs() < 1e-9 && (a.1 - b.1).abs() < 1e-9+ }++ fn seg(a: Pt, b: Pt) -> Option<(Pt, Pt)> {+ clip_segment(a, b, &r())+ }++ // --- the clip-region matrix -------------------------------------------++ #[test]+ fn a_segment_wholly_inside_is_untouched() {+ let (a, b) = ((2.0, 2.0), (8.0, 7.0));+ let (ca, cb) = seg(a, b).unwrap();+ assert!(close(ca, a) && close(cb, b));+ }++ #[test]+ fn a_segment_wholly_outside_is_rejected_from_every_direction() {+ // The eight regions around the rect, plus two that straddle an axis+ // without ever entering (the case a naive "both endpoints outside" test+ // gets wrong is covered separately below).+ for (a, b) in [+ ((-5.0, 5.0), (-1.0, 5.0)), // west+ ((11.0, 5.0), (20.0, 5.0)), // east+ ((5.0, -5.0), (5.0, -1.0)), // south+ ((5.0, 11.0), (5.0, 20.0)), // north+ ((-5.0, -5.0), (-1.0, -1.0)), // south-west+ ((11.0, -5.0), (20.0, -1.0)), // south-east+ ((-5.0, 11.0), (-1.0, 20.0)), // north-west+ ((11.0, 11.0), (20.0, 20.0)), // north-east+ // Spans the rect's x range entirely above it.+ ((-5.0, 15.0), (15.0, 15.0)),+ // Passes diagonally past the north-west corner without touching: it is+ // already above the rect by the time it reaches x = 0.+ ((-5.0, 8.0), (2.0, 15.0)),+ ] {+ assert!(seg(a, b).is_none(), "{a:?} -> {b:?} must miss the rect");+ }+ }++ #[test]+ fn a_segment_crossing_one_boundary_is_cut_at_it() {+ // In from the west.+ let (ca, cb) = seg((-5.0, 5.0), (5.0, 5.0)).unwrap();+ assert!(close(ca, (0.0, 5.0)) && close(cb, (5.0, 5.0)));+ // Out to the east.+ let (ca, cb) = seg((5.0, 5.0), (15.0, 5.0)).unwrap();+ assert!(close(ca, (5.0, 5.0)) && close(cb, (10.0, 5.0)));+ // In from the south.+ let (ca, cb) = seg((5.0, -5.0), (5.0, 5.0)).unwrap();+ assert!(close(ca, (5.0, 0.0)) && close(cb, (5.0, 5.0)));+ // Out to the north.+ let (ca, cb) = seg((5.0, 5.0), (5.0, 15.0)).unwrap();+ assert!(close(ca, (5.0, 5.0)) && close(cb, (5.0, 10.0)));+ }++ #[test]+ fn a_segment_spanning_the_rect_is_cut_at_both_ends() {+ let (ca, cb) = seg((-10.0, 5.0), (20.0, 5.0)).unwrap();+ assert!(close(ca, (0.0, 5.0)) && close(cb, (10.0, 5.0)));+ // Diagonally corner to corner, both endpoints well outside.+ let (ca, cb) = seg((-10.0, -10.0), (20.0, 20.0)).unwrap();+ assert!(close(ca, (0.0, 0.0)) && close(cb, (10.0, 10.0)));+ }++ #[test]+ fn a_segment_clipping_a_corner_keeps_only_the_corner_sliver() {+ // Passes through the north-east corner region, entering and leaving.+ let (ca, cb) = seg((5.0, 15.0), (15.0, 5.0)).unwrap();+ assert!(close(ca, (10.0, 10.0)), "{ca:?}");+ assert!(close(cb, (10.0, 10.0)), "{cb:?}");+ }++ #[test]+ fn a_segment_parallel_to_a_boundary_is_handled_without_dividing_by_zero() {+ // Exactly along the southern edge: inside (the rect is closed).+ let (ca, cb) = seg((-5.0, 0.0), (15.0, 0.0)).unwrap();+ assert!(close(ca, (0.0, 0.0)) && close(cb, (10.0, 0.0)));+ // Parallel but outside.+ assert!(seg((-5.0, -1.0), (15.0, -1.0)).is_none());+ // Vertical along the western edge.+ let (ca, cb) = seg((0.0, -5.0), (0.0, 15.0)).unwrap();+ assert!(close(ca, (0.0, 0.0)) && close(cb, (0.0, 10.0)));+ }++ #[test]+ fn a_degenerate_segment_is_kept_only_if_inside() {+ let (ca, cb) = seg((5.0, 5.0), (5.0, 5.0)).unwrap();+ assert!(close(ca, (5.0, 5.0)) && close(cb, (5.0, 5.0)));+ assert!(seg((-5.0, -5.0), (-5.0, -5.0)).is_none());+ // Exactly on a corner counts as inside.+ assert!(seg((0.0, 0.0), (0.0, 0.0)).is_some());+ }++ #[test]+ fn a_non_finite_segment_is_rejected_rather_than_producing_nan() {+ assert!(seg((f64::NAN, 5.0), (5.0, 5.0)).is_none());+ assert!(seg((5.0, 5.0), (f64::INFINITY, 5.0)).is_none());+ }++ // --- polylines ---------------------------------------------------------++ #[test]+ fn a_polyline_inside_survives_as_one_piece() {+ let line = vec![(1.0, 1.0), (5.0, 5.0), (9.0, 2.0)];+ let out = clip_line(&line, &r());+ assert_eq!(out.len(), 1);+ assert_eq!(out[0], line);+ }++ #[test]+ fn a_polyline_leaving_and_re_entering_yields_two_pieces() {+ // Out to the east and back: one input line, two output lines. Welding them+ // would draw a straight edge across ground the line never covered.+ let line = vec![(5.0, 2.0), (15.0, 2.0), (15.0, 8.0), (5.0, 8.0)];+ let out = clip_line(&line, &r());+ assert_eq!(out.len(), 2, "{out:?}");+ assert!(close(out[0][0], (5.0, 2.0)) && close(out[0][1], (10.0, 2.0)));+ assert!(close(out[1][0], (10.0, 8.0)) && close(out[1][1], (5.0, 8.0)));+ }++ #[test]+ fn consecutive_surviving_segments_are_welded_into_one_line() {+ // Three segments, all inside: the output must be one 4-vertex line, not+ // three 2-vertex ones.+ let line = vec![(1.0, 1.0), (3.0, 3.0), (5.0, 2.0), (7.0, 6.0)];+ let out = clip_line(&line, &r());+ assert_eq!(out.len(), 1);+ assert_eq!(out[0].len(), 4);+ }++ #[test]+ fn a_polyline_wholly_outside_yields_nothing() {+ let line = vec![(-5.0, -5.0), (-3.0, -4.0), (-1.0, -6.0)];+ assert!(clip_line(&line, &r()).is_empty());+ }++ #[test]+ fn a_polyline_that_only_grazes_a_corner_yields_a_degenerate_piece_or_nothing() {+ // A single touching point cannot make a line, so it must not be emitted as+ // a one-vertex "line" -- that encodes as a MoveTo with no LineTo.+ let line = vec![(5.0, 15.0), (15.0, 5.0)];+ for piece in clip_line(&line, &r()) {+ assert!(piece.len() >= 2, "no one-vertex lines: {piece:?}");+ }+ }++ #[test]+ fn a_dropped_vertex_breaks_the_run_rather_than_bridging_it() {+ let line = vec![(1.0, 1.0), (3.0, 3.0), (f64::NAN, 0.0), (7.0, 7.0), (9.0, 9.0)];+ let out = clip_line(&line, &r());+ assert_eq!(out.len(), 2, "{out:?}");+ assert_eq!(out[0], vec![(1.0, 1.0), (3.0, 3.0)]);+ assert_eq!(out[1], vec![(7.0, 7.0), (9.0, 9.0)]);+ }++ #[test]+ fn a_single_vertex_line_yields_nothing() {+ assert!(clip_line(&[(5.0, 5.0)], &r()).is_empty());+ assert!(clip_line(&[], &r()).is_empty());+ }++ // --- polygons ----------------------------------------------------------++ fn square(min: f64, max: f64) -> Vec<Pt> {+ vec![(min, min), (max, min), (max, max), (min, max), (min, min)]+ }++ fn area(ring: &[Pt]) -> f64 {+ let n = ring.len();+ let mut a = 0.0;+ for i in 0..n {+ let (x1, y1) = ring[i];+ let (x2, y2) = ring[(i + 1) % n];+ a += x1 * y2 - x2 * y1;+ }+ (a / 2.0).abs()+ }++ #[test]+ fn a_ring_inside_is_untouched_apart_from_its_closure_convention() {+ let ring = square(2.0, 8.0);+ let out = clip_ring(&ring, &r());+ assert_eq!(area(&out), area(&ring));+ assert_eq!(out.first(), out.last(), "a closed ring stays closed");+ }++ #[test]+ fn an_unclosed_ring_stays_unclosed() {+ let ring = vec![(2.0, 2.0), (8.0, 2.0), (8.0, 8.0), (2.0, 8.0)];+ let out = clip_ring(&ring, &r());+ assert_ne!(out.first(), out.last());+ assert_eq!(out.len(), 4);+ }++ #[test]+ fn a_ring_containing_the_rect_becomes_the_rect() {+ let ring = square(-100.0, 100.0);+ let out = clip_ring(&ring, &r());+ assert_eq!(area(&out), 100.0, "the whole 10x10 rect: {out:?}");+ }++ #[test]+ fn a_ring_half_outside_keeps_half_its_area() {+ // A 10x10 square offset 5 east: exactly half of it is in the rect.+ let ring = vec![(5.0, 0.0), (15.0, 0.0), (15.0, 10.0), (5.0, 10.0), (5.0, 0.0)];+ let out = clip_ring(&ring, &r());+ assert_eq!(area(&out), 50.0, "{out:?}");+ assert_eq!(out.first(), out.last());+ }++ #[test]+ fn a_ring_wholly_outside_disappears() {+ assert!(clip_ring(&square(20.0, 30.0), &r()).is_empty());+ // Touching the boundary but enclosing no area inside it.+ assert!(clip_ring(&square(10.0, 20.0), &r()).is_empty());+ }++ #[test]+ fn a_degenerate_ring_disappears() {+ assert!(clip_ring(&[], &r()).is_empty());+ assert!(clip_ring(&[(1.0, 1.0), (2.0, 2.0)], &r()).is_empty());+ // A closed ring of two distinct vertices is a line, not an area.+ assert!(clip_ring(&[(1.0, 1.0), (2.0, 2.0), (1.0, 1.0)], &r()).is_empty());+ }++ #[test]+ fn a_hole_survives_a_clip_that_does_not_reach_it() {+ let rings = vec![square(-5.0, 15.0), square(3.0, 6.0)];+ let out = clip_polygon(&rings, &r());+ assert_eq!(out.len(), 2, "exterior plus its hole");+ assert_eq!(area(&out[0]), 100.0, "the exterior became the rect");+ assert_eq!(area(&out[1]), 9.0, "the hole is untouched");+ }++ #[test]+ fn a_hole_clipped_away_is_dropped_but_the_polygon_stays() {+ let rings = vec![square(-5.0, 15.0), square(20.0, 25.0)];+ let out = clip_polygon(&rings, &r());+ assert_eq!(out.len(), 1, "only the exterior remains");+ assert_eq!(area(&out[0]), 100.0);+ }++ #[test]+ fn losing_the_exterior_ring_drops_the_holes_too() {+ // A hole with no surrounding area is not a shape. Emitting it would render+ // as a solid patch of whatever colour the layer paints.+ let rings = vec![square(20.0, 30.0), square(3.0, 6.0)];+ assert!(clip_polygon(&rings, &r()).is_empty());+ }++ #[test]+ fn a_concave_ring_clips_to_one_ring_with_the_right_total_area() {+ // A U shape straddling the eastern boundary: the clipped result is two+ // disjoint prongs, which Sutherland-Hodgman returns as ONE ring joined by a+ // zero-area sliver along the boundary. The area is still correct, which is+ // what the renderer cares about. See the module docs.+ let u = vec![+ (5.0, 0.0),+ (15.0, 0.0),+ (15.0, 3.0),+ (8.0, 3.0),+ (8.0, 7.0),+ (15.0, 7.0),+ (15.0, 10.0),+ (5.0, 10.0),+ (5.0, 0.0),+ ];+ let out = clip_ring(&u, &r());+ assert!(!out.is_empty());+ // Inside the rect: the left bar (5..10 x 0..10 = 50) minus the notch+ // (8..10 x 3..7 = 8) = 42.+ assert!((area(&out) - 42.0).abs() < 1e-9, "area {} from {out:?}", area(&out));+ }++ // --- the geometry-level entry point -----------------------------------++ #[test]+ fn clip_geometry_filters_points_whole() {+ let g = Geometry::Points(vec![(5.0, 5.0), (15.0, 5.0), (0.0, 0.0), (f64::NAN, 1.0)]);+ let Geometry::Points(out) = clip_geometry(&g, &r()) else { panic!() };+ assert_eq!(out, vec![(5.0, 5.0), (0.0, 0.0)]);+ }++ #[test]+ fn clip_geometry_flattens_partitioned_lines_into_one_list() {+ // Two input lines, the second of which splits in two: three parts out.+ let g = Geometry::Lines(vec![+ vec![(1.0, 1.0), (2.0, 2.0)],+ vec![(5.0, 2.0), (15.0, 2.0), (15.0, 8.0), (5.0, 8.0)],+ ]);+ let Geometry::Lines(out) = clip_geometry(&g, &r()) else { panic!() };+ assert_eq!(out.len(), 3);+ }++ #[test]+ fn clip_geometry_drops_polygons_that_vanish_entirely() {+ let g = Geometry::Polygons(vec![vec![square(2.0, 8.0)], vec![square(20.0, 30.0)]]);+ let Geometry::Polygons(out) = clip_geometry(&g, &r()) else { panic!() };+ assert_eq!(out.len(), 1);+ }++ #[test]+ fn clipping_to_a_buffered_tile_rect_keeps_the_overspill() {+ use crate::geom::{tile_rect, DEFAULT_BUFFER};+ // A line 3 units past tile 0's eastern edge, with a 5-unit buffer: the+ // overspill survives, which is what stops a seam at the tile join.+ let rect = tile_rect(0, 0, 4096, DEFAULT_BUFFER);+ let line = vec![(4090.0, 100.0), (4099.0, 100.0)];+ let out = clip_line(&line, &rect);+ assert_eq!(out.len(), 1);+ assert!(close(out[0][1], (4099.0, 100.0)), "inside the buffer: {out:?}");+ // Past the buffer, it is cut at buffer's edge.+ let line = vec![(4090.0, 100.0), (4200.0, 100.0)];+ let out = clip_line(&line, &rect);+ assert!(close(out[0][1], (4096.0 + DEFAULT_BUFFER, 100.0)), "{out:?}");+ }+}
scripts/maps/tile_build/src/geom.rs
diff --git a/scripts/maps/tile_build/src/geom.rs b/scripts/maps/tile_build/src/geom.rsnew file mode 100644index 0000000000..10d75ae6c7--- /dev/null+++ b/scripts/maps/tile_build/src/geom.rs@@ -0,0 +1,538 @@+//! Geometry in tile space: projection, bounds, tile ranges and quantisation.+//!+//! This is the front of the tiling pipeline. Each stage is a separate function so+//! each can be tested on its own, and they compose in one fixed order:+//!+//! ```text+//! lon/lat --project_geometry--> world (tile units x extent, per zoom)+//! world --clip::clip_geometry-> world (against one tile's buffered rect)+//! world --translate-----------> tile (origin at the tile's corner)+//! tile --quantize------------> integer tile coordinates+//! integer --simplify::simplify--> integer (fewer vertices)+//! integer --mvt::encode_*-------> command stream+//! ```+//!+//! ## Why "world x extent" and not fractional tile units+//!+//! Projection is the only expensive step, and a coastline crossing a thousand+//! tiles must not be projected a thousand times. So a geometry is projected+//! **once per zoom** into coordinates already scaled to the tile extent: tile+//! `(tx, ty)` then occupies `[tx*extent, (tx+1)*extent]`, and moving into it is a+//! subtraction. Clipping happens in that same space, against a rect built by+//! [`tile_rect`], so only the small clipped result is ever translated.+//!+//! ## Why the clip runs before the quantisation+//!+//! A clip introduces new vertices where an edge crosses the tile boundary, and+//! those crossings are not on the integer grid. Clipping in floats and rounding+//! afterwards puts the crossing within half a unit of the true intersection;+//! rounding first and clipping the integer polyline moves the whole edge before+//! the intersection is even computed, and the error compounds along a long edge.++use crate::mvt::DEFAULT_EXTENT;++/// A vertex. Longitude/latitude before projection, world or tile coordinates+/// after -- see each function for which space it works in.+pub type Pt = (f64, f64);++/// A vertex on the integer tile grid, ready to encode.+pub type IPt = (i32, i32);++/// Tile-boundary overspill, in extent units at [`DEFAULT_EXTENT`].+///+/// Geometry is clipped to the tile rect grown by this much, so a line crossing a+/// tile edge is drawn to slightly beyond it. Without it a renderer stroking a+/// 2 px-wide road would show a seam at every tile boundary, because the join and+/// the cap would have nothing on the far side to align with. 5 units at extent+/// 4096 is tippecanoe's default and what the published archives were built with.+pub const DEFAULT_BUFFER: f64 = 5.0;++/// [`DEFAULT_BUFFER`] scaled to an arbitrary extent, so the overspill stays the+/// same fraction of a tile.+pub fn buffer_for(extent: u32) -> f64 {+ DEFAULT_BUFFER * extent as f64 / DEFAULT_EXTENT as f64+}++/// A geometry, in whichever coordinate space the producing function documents.+///+/// The three variants are the multi- forms only: a single LineString is a+/// `Lines` of one, and a single Polygon a `Polygons` of one. Collapsing the+/// singular cases removes a whole layer of branching from the clipper and the+/// encoders, and MVT itself draws no distinction -- geometry type is per feature,+/// not per part.+#[derive(Debug, Clone, PartialEq)]+pub enum Geometry {+ Points(Vec<Pt>),+ Lines(Vec<Vec<Pt>>),+ /// Each polygon is `[exterior, hole, hole, ...]`. Ring orientation is *not*+ /// significant here; [`crate::mvt::encode_polygons`] derives it from the+ /// signed area rather than trusting the input.+ Polygons(Vec<Vec<Vec<Pt>>>),+}++/// The integer counterpart of [`Geometry`], always in one tile's coordinates.+#[derive(Debug, Clone, PartialEq)]+pub enum IntGeometry {+ Points(Vec<IPt>),+ Lines(Vec<Vec<IPt>>),+ Polygons(Vec<Vec<Vec<IPt>>>),+}++impl IntGeometry {+ pub fn is_empty(&self) -> bool {+ match self {+ IntGeometry::Points(p) => p.is_empty(),+ IntGeometry::Lines(l) => l.iter().all(|p| p.len() < 2),+ IntGeometry::Polygons(p) => p.iter().all(|rings| {+ rings.first().is_none_or(|r| r.len() < 3)+ }),+ }+ }+}++/// An axis-aligned box.+#[derive(Debug, Clone, Copy, PartialEq)]+pub struct Rect {+ pub min_x: f64,+ pub min_y: f64,+ pub max_x: f64,+ pub max_y: f64,+}++impl Rect {+ pub fn contains(&self, (x, y): Pt) -> bool {+ x >= self.min_x && x <= self.max_x && y >= self.min_y && y <= self.max_y+ }++ pub fn intersects(&self, other: &Rect) -> bool {+ self.min_x <= other.max_x+ && other.min_x <= self.max_x+ && self.min_y <= other.max_y+ && other.min_y <= self.max_y+ }+}++/// Web-Mercator project a lon/lat to fractional tile coordinates at `z`.+///+/// Latitude is clamped to the Mercator limit: the projection diverges at the+/// poles, and a feed with a `0,0`-style placeholder coordinate would otherwise+/// produce an infinity.+///+/// This is the single copy of the projection in the crate. Two copies that drift+/// apart would put a point layer and a line layer at subtly different places in+/// the same tile.+pub fn project(lon: f64, lat: f64, z: u8) -> Pt {+ let n = (1u64 << z) as f64;+ let lat = lat.clamp(-85.051_128_78, 85.051_128_78);+ let x = (lon.clamp(-180.0, 180.0) + 180.0) / 360.0 * n;+ let s = lat.to_radians().sin();+ let y = (0.5 - (((1.0 + s) / (1.0 - s)).ln()) / (4.0 * std::f64::consts::PI)) * n;+ (x, y)+}++/// [`project`], scaled so one tile spans `extent` units. This is "world"+/// coordinates: tile `(tx, ty)` occupies `[tx*extent, (tx+1)*extent]`.+pub fn project_scaled(lon: f64, lat: f64, z: u8, extent: u32) -> Pt {+ let (x, y) = project(lon, lat, z);+ (x * extent as f64, y * extent as f64)+}++/// Project a whole lon/lat geometry into world coordinates for one zoom.+pub fn project_geometry(g: &Geometry, z: u8, extent: u32) -> Geometry {+ let p = |&(lon, lat): &Pt| project_scaled(lon, lat, z, extent);+ match g {+ Geometry::Points(pts) => Geometry::Points(pts.iter().map(p).collect()),+ Geometry::Lines(lines) => {+ Geometry::Lines(lines.iter().map(|l| l.iter().map(p).collect()).collect())+ }+ Geometry::Polygons(polys) => Geometry::Polygons(+ polys+ .iter()+ .map(|rings| rings.iter().map(|r| r.iter().map(p).collect()).collect())+ .collect(),+ ),+ }+}++/// The bounding box of every vertex, or `None` when there are none.+///+/// Non-finite vertices are skipped. They should not exist -- [`project`] clamps --+/// but a `NaN` reaching [`tile_range`] would silently produce an empty range,+/// and dropping it here at least keeps the rest of the geometry.+pub fn bounds(g: &Geometry) -> Option<Rect> {+ let mut r: Option<Rect> = None;+ let mut add = |(x, y): Pt| {+ if !x.is_finite() || !y.is_finite() {+ return;+ }+ r = Some(match r {+ None => Rect { min_x: x, min_y: y, max_x: x, max_y: y },+ Some(b) => Rect {+ min_x: b.min_x.min(x),+ min_y: b.min_y.min(y),+ max_x: b.max_x.max(x),+ max_y: b.max_y.max(y),+ },+ });+ };+ match g {+ Geometry::Points(pts) => pts.iter().for_each(|p| add(*p)),+ Geometry::Lines(lines) => lines.iter().flatten().for_each(|p| add(*p)),+ Geometry::Polygons(polys) => polys.iter().flatten().flatten().for_each(|p| add(*p)),+ }+ r+}++/// An inclusive range of tile coordinates.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub struct TileRange {+ pub x0: u64,+ pub y0: u64,+ pub x1: u64,+ pub y1: u64,+}++impl TileRange {+ /// Every `(x, y)` in the range, row-major, so a tiling pass is deterministic.+ pub fn iter(&self) -> impl Iterator<Item = (u64, u64)> + '_ {+ (self.y0..=self.y1).flat_map(move |y| (self.x0..=self.x1).map(move |x| (x, y)))+ }++ pub fn len(&self) -> u64 {+ (self.x1 - self.x0 + 1) * (self.y1 - self.y0 + 1)+ }++ pub fn is_empty(&self) -> bool {+ false+ }+}++/// The tiles a world-space bounding box touches at zoom `z`, grown by `pad`+/// world units so a feature just outside a tile still reaches into its buffer.+///+/// Returns `None` when the box lies entirely off the grid. It is otherwise+/// clamped to the grid: a geometry straddling the antimeridian is truncated+/// rather than wrapped, which is what the published archives do and what the+/// renderer expects.+pub fn tile_range(b: &Rect, z: u8, extent: u32, pad: f64) -> Option<TileRange> {+ let n = 1u64 << z;+ let e = extent as f64;+ let last = (n - 1) as f64;++ let fx0 = ((b.min_x - pad) / e).floor();+ let fy0 = ((b.min_y - pad) / e).floor();+ let fx1 = ((b.max_x + pad) / e).floor();+ let fy1 = ((b.max_y + pad) / e).floor();+ if !fx0.is_finite() || !fy0.is_finite() || !fx1.is_finite() || !fy1.is_finite() {+ return None;+ }+ // Entirely off the grid on either axis: no tile can hold it.+ if fx1 < 0.0 || fy1 < 0.0 || fx0 > last || fy0 > last {+ return None;+ }+ Some(TileRange {+ x0: fx0.max(0.0) as u64,+ y0: fy0.max(0.0) as u64,+ x1: fx1.min(last) as u64,+ y1: fy1.min(last) as u64,+ })+}++/// One tile's clip rect in **world** coordinates, grown by `buffer`.+pub fn tile_rect(tx: u64, ty: u64, extent: u32, buffer: f64) -> Rect {+ let e = extent as f64;+ let (ox, oy) = (tx as f64 * e, ty as f64 * e);+ Rect {+ min_x: ox - buffer,+ min_y: oy - buffer,+ max_x: ox + e + buffer,+ max_y: oy + e + buffer,+ }+}++/// Shift a geometry by `(dx, dy)`. Applied after the clip, with the tile's world+/// origin negated, to put the geometry in tile coordinates.+pub fn translate(g: &Geometry, dx: f64, dy: f64) -> Geometry {+ let t = |&(x, y): &Pt| (x + dx, y + dy);+ match g {+ Geometry::Points(pts) => Geometry::Points(pts.iter().map(t).collect()),+ Geometry::Lines(lines) => {+ Geometry::Lines(lines.iter().map(|l| l.iter().map(t).collect()).collect())+ }+ Geometry::Polygons(polys) => Geometry::Polygons(+ polys+ .iter()+ .map(|rings| rings.iter().map(|r| r.iter().map(t).collect()).collect())+ .collect(),+ ),+ }+}++/// Convenience for the two steps that always follow a clip: translate into the+/// tile, then round onto the integer grid.+pub fn to_tile(g: &Geometry, tx: u64, ty: u64, extent: u32) -> IntGeometry {+ let e = extent as f64;+ quantize(&translate(g, -(tx as f64 * e), -(ty as f64 * e)))+}++/// Round onto the integer tile grid, dropping consecutive duplicates.+///+/// Quantisation is what creates duplicates: two vertices a thousandth of a unit+/// apart become the same integer, and an MVT `LineTo` with a zero delta is a+/// wasted three bytes that some renderers treat as a degenerate segment. Rings+/// keep their explicit closing vertex here; [`crate::mvt::encode_polygons`]+/// strips it, since `ClosePath` implies it.+pub fn quantize(g: &Geometry) -> IntGeometry {+ match g {+ Geometry::Points(pts) => IntGeometry::Points(pts.iter().map(round_pt).collect()),+ Geometry::Lines(lines) => {+ IntGeometry::Lines(lines.iter().map(|l| dedup(l.iter().map(round_pt))).collect())+ }+ Geometry::Polygons(polys) => IntGeometry::Polygons(+ polys+ .iter()+ .map(|rings| rings.iter().map(|r| dedup(r.iter().map(round_pt))).collect())+ .collect(),+ ),+ }+}++fn round_pt(&(x, y): &Pt) -> IPt {+ (round_i32(x), round_i32(y))+}++/// Round to the nearest integer, saturating rather than wrapping.+///+/// Quantisation runs after the clip, so a coordinate here is always within a+/// buffered tile and nowhere near the `i32` limits. If one is not, `as i32` on a+/// `NaN` is silently `0` and on a huge float is silently the saturated bound --+/// both plausible-looking coordinates. Saturating deliberately keeps the bogus+/// value bogus, so it shows up as an obviously wrong vertex rather than a subtly+/// wrong one.+fn round_i32(v: f64) -> i32 {+ if v.is_nan() {+ return 0;+ }+ v.round().clamp(i32::MIN as f64, i32::MAX as f64) as i32+}++fn dedup(it: impl Iterator<Item = IPt>) -> Vec<IPt> {+ let mut out: Vec<IPt> = Vec::new();+ for p in it {+ if out.last() != Some(&p) {+ out.push(p);+ }+ }+ out+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn projection_anchors_are_right() {+ // z0: the whole world is one tile, and 0,0 sits at its centre.+ let (x, y) = project(0.0, 0.0, 0);+ assert!((x - 0.5).abs() < 1e-9, "lon 0 -> x 0.5, got {x}");+ assert!((y - 0.5).abs() < 1e-9, "lat 0 -> y 0.5, got {y}");+ let (x, _) = project(-180.0, 0.0, 0);+ assert!(x.abs() < 1e-9);+ let (_, y) = project(0.0, 85.051_128_78, 0);+ assert!(y.abs() < 1e-6, "Mercator top -> y 0, got {y}");+ // A pole must clamp rather than diverge.+ let (_, y) = project(0.0, 90.0, 4);+ assert!(y.is_finite(), "lat 90 must clamp, got {y}");+ // San Francisco at z11 is a well-known tile.+ let (fx, fy) = project(-122.4194, 37.7749, 11);+ assert_eq!((fx.floor() as u64, fy.floor() as u64), (327, 791));+ }++ #[test]+ fn scaling_puts_a_point_inside_its_own_tile() {+ let extent = DEFAULT_EXTENT;+ let (wx, wy) = project_scaled(-122.4194, 37.7749, 11, extent);+ let (tx, ty) = (327u64, 791u64);+ let local = (wx - tx as f64 * extent as f64, wy - ty as f64 * extent as f64);+ assert!(+ (0.0..=extent as f64).contains(&local.0) && (0.0..=extent as f64).contains(&local.1),+ "{local:?} must be inside [0,{extent}]"+ );+ }++ #[test]+ fn buffer_scales_with_the_extent() {+ assert_eq!(buffer_for(DEFAULT_EXTENT), DEFAULT_BUFFER);+ assert_eq!(buffer_for(8192), DEFAULT_BUFFER * 2.0);+ assert_eq!(buffer_for(2048), DEFAULT_BUFFER / 2.0);+ }++ #[test]+ fn bounds_cover_every_part_and_ignore_non_finite() {+ let g = Geometry::Lines(vec![+ vec![(0.0, 0.0), (10.0, 5.0)],+ vec![(-3.0, 20.0), (4.0, 1.0)],+ ]);+ assert_eq!(+ bounds(&g),+ Some(Rect { min_x: -3.0, min_y: 0.0, max_x: 10.0, max_y: 20.0 })+ );+ assert_eq!(bounds(&Geometry::Points(vec![])), None);++ // A NaN vertex is skipped rather than poisoning the whole box.+ let g = Geometry::Points(vec![(1.0, 2.0), (f64::NAN, 0.0), (3.0, 4.0)]);+ assert_eq!(+ bounds(&g),+ Some(Rect { min_x: 1.0, min_y: 2.0, max_x: 3.0, max_y: 4.0 })+ );+ assert_eq!(bounds(&Geometry::Points(vec![(f64::NAN, f64::NAN)])), None);+ }++ #[test]+ fn a_tile_range_covers_exactly_the_tiles_touched() {+ let e = 4096u32;+ // Entirely inside tile (1,1).+ let b = Rect { min_x: 1.5 * e as f64, min_y: 1.5 * e as f64, max_x: 1.6 * e as f64, max_y: 1.6 * e as f64 };+ assert_eq!(+ tile_range(&b, 4, e, 0.0),+ Some(TileRange { x0: 1, y0: 1, x1: 1, y1: 1 })+ );+ // Straddling into (2,2).+ let b = Rect { min_x: 1.5 * e as f64, min_y: 1.5 * e as f64, max_x: 2.5 * e as f64, max_y: 2.5 * e as f64 };+ assert_eq!(+ tile_range(&b, 4, e, 0.0),+ Some(TileRange { x0: 1, y0: 1, x1: 2, y1: 2 })+ );+ }++ #[test]+ fn the_pad_pulls_in_the_neighbouring_tile() {+ let e = 4096u32;+ // Two units inside tile 1's left edge. With no pad it touches only tile 1;+ // with a 5-unit pad it also reaches into tile 0's buffer, which is the+ // whole reason the buffer exists.+ let x = e as f64 + 2.0;+ let b = Rect { min_x: x, min_y: x, max_x: x, max_y: x };+ assert_eq!(+ tile_range(&b, 4, e, 0.0),+ Some(TileRange { x0: 1, y0: 1, x1: 1, y1: 1 })+ );+ assert_eq!(+ tile_range(&b, 4, e, 5.0),+ Some(TileRange { x0: 0, y0: 0, x1: 1, y1: 1 })+ );+ }++ #[test]+ fn a_tile_range_clamps_to_the_grid_and_rejects_the_wholly_outside() {+ let e = 4096u32;+ let n = 1u64 << 4;+ // Overhanging both ends is clamped, not wrapped.+ let b = Rect { min_x: -100.0, min_y: -100.0, max_x: (n as f64 + 3.0) * e as f64, max_y: (n as f64 + 3.0) * e as f64 };+ assert_eq!(+ tile_range(&b, 4, e, 0.0),+ Some(TileRange { x0: 0, y0: 0, x1: n - 1, y1: n - 1 })+ );+ // Wholly off the grid.+ let b = Rect { min_x: -10.0 * e as f64, min_y: 0.0, max_x: -9.0 * e as f64, max_y: e as f64 };+ assert_eq!(tile_range(&b, 4, e, 0.0), None);+ // NaN in, None out.+ let b = Rect { min_x: f64::NAN, min_y: 0.0, max_x: 1.0, max_y: 1.0 };+ assert_eq!(tile_range(&b, 4, e, 0.0), None);+ }++ #[test]+ fn tile_range_iterates_row_major() {+ let r = TileRange { x0: 2, y0: 5, x1: 3, y1: 6 };+ assert_eq!(r.len(), 4);+ assert_eq!(+ r.iter().collect::<Vec<_>>(),+ vec![(2, 5), (3, 5), (2, 6), (3, 6)]+ );+ }++ #[test]+ fn a_tile_rect_is_the_tile_plus_its_buffer() {+ let r = tile_rect(2, 3, 4096, 5.0);+ assert_eq!(+ r,+ Rect { min_x: 8192.0 - 5.0, min_y: 12288.0 - 5.0, max_x: 12288.0 + 5.0, max_y: 16384.0 + 5.0 }+ );+ assert!(r.contains((8192.0, 12288.0)));+ assert!(r.contains((8192.0 - 4.0, 12288.0 - 4.0)), "inside the buffer");+ assert!(!r.contains((8192.0 - 6.0, 12288.0)), "beyond the buffer");+ }++ #[test]+ fn to_tile_translates_then_rounds() {+ // A vertex at world (4096.4, 8191.6) is (0.4, 4095.6) inside tile (1,1),+ // which rounds to (0, 4096).+ let g = Geometry::Lines(vec![vec![(4096.4, 8191.6), (5000.0, 9000.0)]]);+ let IntGeometry::Lines(lines) = to_tile(&g, 1, 1, 4096) else {+ panic!("lines in, lines out")+ };+ assert_eq!(lines[0][0], (0, 4096));+ assert_eq!(lines[0][1], (904, 4904));+ }++ #[test]+ fn quantisation_drops_the_duplicates_it_creates() {+ // Three vertices within a rounding unit of each other collapse to one.+ let g = Geometry::Lines(vec![vec![+ (10.1, 10.1),+ (10.2, 10.3),+ (9.9, 10.0),+ (20.0, 20.0),+ ]]);+ let IntGeometry::Lines(lines) = quantize(&g) else { panic!() };+ assert_eq!(lines[0], vec![(10, 10), (20, 20)]);++ // Non-adjacent repeats are kept: a line that doubles back is a real shape.+ let g = Geometry::Lines(vec![vec![(0.0, 0.0), (5.0, 0.0), (0.0, 0.0)]]);+ let IntGeometry::Lines(lines) = quantize(&g) else { panic!() };+ assert_eq!(lines[0], vec![(0, 0), (5, 0), (0, 0)]);+ }++ #[test]+ fn quantisation_keeps_a_rings_closing_vertex() {+ // ClosePath is applied by the encoder, not here, so the ring stays closed+ // through simplification -- which needs the closure to measure against.+ let ring = vec![(0.0, 0.0), (4.0, 0.0), (4.0, 4.0), (0.0, 4.0), (0.0, 0.0)];+ let IntGeometry::Polygons(polys) = quantize(&Geometry::Polygons(vec![vec![ring]])) else {+ panic!()+ };+ assert_eq!(polys[0][0].len(), 5);+ assert_eq!(polys[0][0].first(), polys[0][0].last());+ }++ #[test]+ fn a_non_finite_vertex_saturates_rather_than_wrapping() {+ // `f64::NAN as i32` is 0 in Rust and `1e300 as i32` is the saturated bound,+ // but both are silent. Keeping the saturation explicit means an out-of-range+ // vertex stays obviously out of range instead of landing somewhere+ // plausible; a NaN has no meaningful bound, so it becomes the origin.+ let g = Geometry::Points(vec![(f64::NAN, 1e300), (-1e300, 5.0)]);+ let IntGeometry::Points(pts) = quantize(&g) else { panic!() };+ assert_eq!(pts, vec![(0, i32::MAX), (i32::MIN, 5)]);+ }++ #[test]+ fn emptiness_is_judged_per_geometry_kind() {+ assert!(IntGeometry::Points(vec![]).is_empty());+ assert!(!IntGeometry::Points(vec![(0, 0)]).is_empty());+ assert!(IntGeometry::Lines(vec![vec![(0, 0)]]).is_empty());+ assert!(!IntGeometry::Lines(vec![vec![(0, 0), (1, 1)]]).is_empty());+ // Three distinct vertices are the least that can enclose an area.+ assert!(IntGeometry::Polygons(vec![vec![vec![(0, 0), (1, 0)]]]).is_empty());+ assert!(!IntGeometry::Polygons(vec![vec![vec![(0, 0), (1, 0), (1, 1)]]]).is_empty());+ }++ #[test]+ fn rects_intersect_symmetrically_and_touch_counts() {+ let a = Rect { min_x: 0.0, min_y: 0.0, max_x: 10.0, max_y: 10.0 };+ let b = Rect { min_x: 10.0, min_y: 10.0, max_x: 20.0, max_y: 20.0 };+ let c = Rect { min_x: 11.0, min_y: 0.0, max_x: 20.0, max_y: 10.0 };+ assert!(a.intersects(&b) && b.intersects(&a), "touching corners overlap");+ assert!(!a.intersects(&c) && !c.intersects(&a));+ }+}
scripts/maps/tile_build/src/lib.rs
diff --git a/scripts/maps/tile_build/src/lib.rs b/scripts/maps/tile_build/src/lib.rsindex 7b1bdd4663..a07c9b390a 100644--- a/scripts/maps/tile_build/src/lib.rs+++ b/scripts/maps/tile_build/src/lib.rs@@ -8,24 +8,45 @@ //! //! * [`proto`] — protobuf wire codec. Read half mirrors `osm_ingest`'s //! decode-only reader; write half is new.-//! * [`mvt`] — vector tile 2.1 decode/encode. Geometry stays as raw command-//! integers, so lines and polygons pass through without a clipper.+//! * [`mvt`] — vector tile 2.1 decode/encode. A feature's geometry is stored as+//! raw command integers, so anything we are merely compositing passes through+//! untouched; the `encode_*`/`decode_*` functions beside that path are for the+//! layers we build ourselves. //! * [`gz`] — gzip framing over `miniz_oxide`'s raw DEFLATE, which PMTiles needs //! for both its directories and its tiles. //! * [`pmtiles`] — the v3 container, read and write, including Hilbert tile ids //! and the root/leaf directory split.-//! * [`tiling`] — project and bucket points into tiles, and merge tilesets.+//! * [`geom`] — projection, bounds, tile ranges and quantisation: lon/lat in,+//! integer tile coordinates out.+//! * [`clip`] — Liang-Barsky for lines, Sutherland-Hodgman for polygons, against+//! a tile's buffered rect.+//! * [`simplify`] — Douglas-Peucker in integer tile coordinates.+//! * [`tiling`] — bucket points into tiles, and merge tilesets. //!-//! Two binaries sit on top: `tile_points` (the `tippecanoe` replacement, for point-//! layers) and `tile_join` (the `tile-join` replacement).+//! [`geom`], [`clip`] and [`simplify`] compose in one fixed order; [`geom`]'s module+//! docs give the pipeline.+//!+//! Three binaries sit on top: `tile_points` (the `tippecanoe` replacement for point+//! layers), `tile_join` (the `tile-join` replacement) and `pmtiles_dump` (a+//! canonical text dump, for the differential harness). //! //! Verified against the published `v5-ca.pmtiles` during development: its header, //! gzipped root directory and gzipped leaf directories all decode with byte-exact //! payload consumption, and a real tile's layers decode to the same names, //! extents and feature counts tippecanoe wrote.+//!+//! **Output is not byte-identical to tippecanoe, by design.** Its+//! `--drop-densest-as-needed` is a lossy per-tile heuristic and+//! `--extend-zooms-if-still-dropping` can push an archive past its own maximum+//! zoom; we implement a deterministic policy and a fixed max zoom instead. Tests+//! assert our own invariants — ring closure, winding order, Douglas-Peucker+//! monotonicity, a PMTiles round trip — never equality with tippecanoe. +pub mod clip;+pub mod geom; pub mod gz; pub mod mvt; pub mod pmtiles; pub mod proto;+pub mod simplify; pub mod tiling;
scripts/maps/tile_build/src/mvt.rs
diff --git a/scripts/maps/tile_build/src/mvt.rs b/scripts/maps/tile_build/src/mvt.rsindex c103c81865..e4be5c9ea9 100644--- a/scripts/maps/tile_build/src/mvt.rs+++ b/scripts/maps/tile_build/src/mvt.rs@@ -1,11 +1,35 @@ //! Mapbox Vector Tile 2.1 codec — decode, edit, re-encode. //!-//! Enough of the spec to composite tilesets. Geometry is kept as the **raw-//! command-integer stream** rather than decoded into rings, because the tile-join-//! step only ever has to move features between tiles, never reshape them: our own-//! writer emits points, while the base tileset's lines and polygons must pass-//! through untouched. Keeping them opaque means no clipper, no winding-order-//! rules, and no way to corrupt geometry we do not understand.+//! ## The geometry contract, and how it changed+//!+//! [`Feature::geometry`] is the **raw command-integer stream**, never a decoded+//! ring. That is deliberate and it has not changed: [`crate::tiling::merge_tiles`]+//! only ever moves features between tiles, so carrying the stream through verbatim+//! means a re-encode cannot corrupt geometry we did not produce. That opaque path+//! is what makes the composite lossless, and it is load-bearing for the base+//! tileset's lines and polygons.+//!+//! What changed is that this module now also **builds and reads** those streams,+//! for the layers we tile ourselves: [`encode_points`], [`encode_lines`] and+//! [`encode_polygons`] on the way in, and [`decode_points`], [`decode_lines`] and+//! [`decode_polygons`] on the way out. The encoders sit *beside* the passthrough+//! rather than replacing it — a feature either came from a stream we are copying,+//! or from vertices we are encoding, and the two never meet.+//!+//! ## Polygon winding order+//!+//! The spec states it as signed area, not as a direction: applying the surveyor's+//! formula to a ring, an **exterior ring must come out positive and an interior+//! ring negative**. (Equivalently: clockwise and counter-clockwise on screen,+//! since tile `y` grows downward — which is why quoting the direction instead of+//! the sign is such a reliable way to get it backwards.)+//!+//! [`encode_polygons`] therefore computes [`signed_area`] and reverses the ring+//! when the sign is wrong, rather than trusting the caller. Input rings arrive from+//! a clipper and a simplifier, neither of which preserves orientation, so trusting+//! them would produce holes that render as fill and fills that render as holes.+//!+//! ## Property dictionaries //! //! Properties *are* decoded, since re-encoding rebuilds each layer's key/value //! dictionaries. A re-encode is therefore semantically identical but not@@ -389,6 +413,249 @@ pub fn decode_points(geometry: &[u32]) -> Option<Vec<(i32, i32)>> { Some(out) } +/// Twice the signed area of a ring, by the surveyor's (shoelace) formula.+///+/// Doubled and kept as an integer so there is no division and no rounding: only+/// the **sign** decides winding order, and only zero decides degeneracy, so the+/// factor of two is irrelevant and dropping it would introduce a rounding step+/// into a decision that must be exact.+///+/// Per the MVT spec, a positive result means an exterior ring and a negative one+/// an interior ring. An explicit closing vertex is optional: the sum wraps from+/// the last vertex to the first either way, and a repeated vertex contributes+/// nothing.+///+/// `i64` throughout: two `i32` spans multiply to 62 bits, and a ring long enough+/// to overflow the accumulator would need more vertices than a tile can hold.+pub fn signed_area(ring: &[(i32, i32)]) -> i64 {+ let n = ring.len();+ if n < 3 {+ return 0;+ }+ let mut sum = 0i64;+ for i in 0..n {+ let (x1, y1) = ring[i];+ let (x2, y2) = ring[(i + 1) % n];+ sum += x1 as i64 * y2 as i64 - x2 as i64 * y1 as i64;+ }+ sum+}++/// Build the geometry stream for a line layer.+///+/// Each part is `MoveTo(1)` then `LineTo(n-1)`, with zigzagged deltas and the+/// cursor carried across parts, as the spec requires. Parts with fewer than two+/// distinct vertices are skipped: a `LineTo(0)` is illegal, and a lone `MoveTo`+/// would encode a point inside a line layer.+pub fn encode_lines(lines: &[Vec<(i32, i32)>]) -> Vec<u32> {+ let mut out = Vec::new();+ let (mut cx, mut cy) = (0i32, 0i32);+ for line in lines {+ if line.len() < 2 {+ continue;+ }+ out.push(command(CMD_MOVE_TO, 1));+ push_delta(&mut out, line[0], &mut cx, &mut cy);+ out.push(command(CMD_LINE_TO, (line.len() - 1) as u32));+ for p in &line[1..] {+ push_delta(&mut out, *p, &mut cx, &mut cy);+ }+ }+ out+}++/// One polygon: its exterior ring first, then its holes.+pub type PolygonRings = Vec<Vec<(i32, i32)>>;++/// Build the geometry stream for a polygon layer.+///+/// Per polygon, the exterior ring comes first and its holes follow, each as+/// `MoveTo(1)`, `LineTo(n-1)`, `ClosePath`. Three things this function does that+/// the caller must not have to think about:+///+/// * **Closure is implicit.** `ClosePath` re-draws the edge back to the ring's+/// start, so an explicit closing vertex is stripped. Leaving it in emits a+/// zero-length segment, and some renderers treat that as a degenerate ring.+/// * **Orientation is derived, not trusted.** [`signed_area`] decides, and the ring+/// is reversed when the sign is wrong. The clipper and the simplifier upstream do+/// not preserve orientation, so the input's own winding means nothing.+/// * **Zero-area rings are dropped.** They cannot be oriented, and a hole with no+/// area is invisible at best.+///+/// A polygon whose exterior ring is dropped is dropped entirely, holes included: a+/// hole with nothing around it renders as solid fill.+pub fn encode_polygons(polygons: &[PolygonRings]) -> Vec<u32> {+ let mut out = Vec::new();+ let (mut cx, mut cy) = (0i32, 0i32);+ for rings in polygons {+ // Held back until the exterior is known good, so a dropped exterior takes+ // its holes with it instead of emitting orphans.+ let mut staged: Vec<Vec<(i32, i32)>> = Vec::with_capacity(rings.len());+ for (i, ring) in rings.iter().enumerate() {+ let mut open = ring.as_slice();+ while open.len() > 1 && open.first() == open.last() {+ open = &open[..open.len() - 1];+ }+ if open.len() < 3 {+ if i == 0 {+ staged.clear();+ break;+ }+ continue;+ }+ let area = signed_area(open);+ if area == 0 {+ if i == 0 {+ staged.clear();+ break;+ }+ continue;+ }+ // Exterior positive, interior negative, per the spec.+ let want_positive = i == 0;+ let mut ring: Vec<(i32, i32)> = open.to_vec();+ if (area > 0) != want_positive {+ ring.reverse();+ }+ staged.push(ring);+ }+ for ring in &staged {+ out.push(command(CMD_MOVE_TO, 1));+ push_delta(&mut out, ring[0], &mut cx, &mut cy);+ out.push(command(CMD_LINE_TO, (ring.len() - 1) as u32));+ for p in &ring[1..] {+ push_delta(&mut out, *p, &mut cx, &mut cy);+ }+ out.push(command(CMD_CLOSE_PATH, 1));+ // ClosePath moves the cursor back to the ring's start, so the next+ // ring's MoveTo delta is measured from there, not from the last vertex.+ cx = ring[0].0;+ cy = ring[0].1;+ }+ }+ out+}++#[inline]+fn push_delta(out: &mut Vec<u32>, (x, y): (i32, i32), cx: &mut i32, cy: &mut i32) {+ out.push(proto::zigzag_encode((x - *cx) as i64) as u32);+ out.push(proto::zigzag_encode((y - *cy) as i64) as u32);+ *cx = x;+ *cy = y;+}++/// Decode a line layer's geometry stream. `None` on anything that is not a+/// sequence of `MoveTo(1)` + `LineTo(n)` parts.+pub fn decode_lines(geometry: &[u32]) -> Option<Vec<Vec<(i32, i32)>>> {+ let mut out: Vec<Vec<(i32, i32)>> = Vec::new();+ let mut cursor = Cursor::new(geometry);+ while let Some((cmd, count)) = cursor.next_command() {+ match cmd {+ CMD_MOVE_TO => {+ if count != 1 {+ return None;+ }+ out.push(vec![cursor.next_point()?]);+ }+ CMD_LINE_TO => {+ let line = out.last_mut()?;+ if count == 0 {+ return None;+ }+ for _ in 0..count {+ line.push(cursor.next_point()?);+ }+ }+ _ => return None,+ }+ }+ Some(out)+}++/// Decode a polygon layer's geometry stream into `[polygon][ring][vertex]`, with+/// each ring closed explicitly.+///+/// Rings are grouped into polygons by orientation, as the spec prescribes: a+/// positive-area ring starts a new polygon and negative-area rings attach to the+/// one before them. A stream that opens with a hole is rejected rather than+/// guessed at.+pub fn decode_polygons(geometry: &[u32]) -> Option<Vec<PolygonRings>> {+ let mut out: Vec<PolygonRings> = Vec::new();+ let mut current: Vec<(i32, i32)> = Vec::new();+ let mut cursor = Cursor::new(geometry);+ while let Some((cmd, count)) = cursor.next_command() {+ match cmd {+ CMD_MOVE_TO => {+ if count != 1 || !current.is_empty() {+ return None;+ }+ current.push(cursor.next_point()?);+ }+ CMD_LINE_TO => {+ if current.is_empty() || count == 0 {+ return None;+ }+ for _ in 0..count {+ current.push(cursor.next_point()?);+ }+ }+ CMD_CLOSE_PATH => {+ if count != 1 || current.len() < 3 {+ return None;+ }+ let ring = std::mem::take(&mut current);+ // ClosePath returns the cursor to the ring's start.+ cursor.set(ring[0]);+ let positive = signed_area(&ring) > 0;+ let mut closed = ring;+ closed.push(closed[0]);+ if positive {+ out.push(vec![closed]);+ } else {+ out.last_mut()?.push(closed);+ }+ }+ _ => return None,+ }+ }+ // An unterminated ring means a truncated stream.+ current.is_empty().then_some(out)+}++/// Walks a command stream, carrying the delta cursor.+struct Cursor<'a> {+ geometry: &'a [u32],+ i: usize,+ x: i32,+ y: i32,+}++impl<'a> Cursor<'a> {+ fn new(geometry: &'a [u32]) -> Cursor<'a> {+ Cursor { geometry, i: 0, x: 0, y: 0 }+ }++ fn next_command(&mut self) -> Option<(u32, u32)> {+ let v = *self.geometry.get(self.i)?;+ self.i += 1;+ Some(command_parts(v))+ }++ fn next_point(&mut self) -> Option<(i32, i32)> {+ let dx = *self.geometry.get(self.i)?;+ let dy = *self.geometry.get(self.i + 1)?;+ self.i += 2;+ self.x = self.x.wrapping_add(proto::zigzag_decode(dx as u64) as i32);+ self.y = self.y.wrapping_add(proto::zigzag_decode(dy as u64) as i32);+ Some((self.x, self.y))+ }++ fn set(&mut self, (x, y): (i32, i32)) {+ self.x = x;+ self.y = y;+ }+}+ #[cfg(test)] mod tests { use super::*;@@ -593,4 +860,373 @@ mod tests { // Range requests and partial writes both produce these. assert!(Tile::decode(&REAL_TILE[..REAL_TILE.len() / 2]).is_err()); }++ // --- signed area -------------------------------------------------------++ #[test]+ fn signed_area_is_positive_for_the_specs_exterior_winding() {+ // MVT states the rule as a sign, not a direction: exterior rings are+ // positive under the surveyor's formula. In tile space, where y grows+ // downward, that is clockwise on screen -- top-right, bottom-right,+ // bottom-left, top-left. Quoting the direction instead of the sign is a+ // reliable way to get this backwards, which is why the encoder tests below+ // assert on the sign.+ let clockwise_on_screen = [(10, 0), (10, 10), (0, 10), (0, 0)];+ assert_eq!(signed_area(&clockwise_on_screen), 200);+ let mut other = clockwise_on_screen.to_vec();+ other.reverse();+ assert_eq!(signed_area(&other), -200);+ }++ #[test]+ fn signed_area_ignores_an_explicit_closing_vertex() {+ let open = [(10, 0), (10, 10), (0, 10), (0, 0)];+ let mut closed = open.to_vec();+ closed.push(open[0]);+ assert_eq!(signed_area(&open), signed_area(&closed));+ // Twice the area of a 10x10 square.+ assert_eq!(signed_area(&open).abs(), 200);+ }++ #[test]+ fn signed_area_is_zero_for_anything_that_encloses_nothing() {+ assert_eq!(signed_area(&[]), 0);+ assert_eq!(signed_area(&[(1, 1)]), 0);+ assert_eq!(signed_area(&[(0, 0), (5, 5)]), 0);+ // Collinear.+ assert_eq!(signed_area(&[(0, 0), (5, 0), (10, 0)]), 0);+ // A degenerate out-and-back.+ assert_eq!(signed_area(&[(0, 0), (10, 0), (0, 0)]), 0);+ }++ #[test]+ fn signed_area_does_not_overflow_at_the_coordinate_extremes() {+ // Two i32 spans multiply to 62 bits, so the accumulator must be i64.+ let big = i32::MAX;+ let a = signed_area(&[(0, 0), (big, 0), (big, big), (0, big)]);+ assert!(a != 0 && a.abs() > i32::MAX as i64, "{a}");+ }++ // --- line encoding -----------------------------------------------------++ fn line_roundtrip(lines: Vec<Vec<(i32, i32)>>) {+ let encoded = encode_lines(&lines);+ let decoded = decode_lines(&encoded).expect("our own output must decode");+ assert_eq!(decoded, lines);+ }++ #[test]+ fn a_line_round_trips() {+ line_roundtrip(vec![vec![(0, 0), (100, 0), (100, 100)]]);+ // Negative deltas, and a doubling-back.+ line_roundtrip(vec![vec![(500, 500), (0, 0), (500, 500), (-50, 20)]]);+ // Multiple parts share one cursor, which is where an off-by-one in the+ // delta chain would show up.+ line_roundtrip(vec![+ vec![(0, 0), (10, 10)],+ vec![(4000, 4000), (4090, 4000)],+ vec![(-5, -5), (0, 0), (5, 5)],+ ]);+ }++ #[test]+ fn the_line_command_stream_has_the_shape_the_spec_requires() {+ let g = encode_lines(&[vec![(3, 6), (8, 12), (20, 34)]]);+ // MoveTo(1), one point, LineTo(2), two points.+ assert_eq!(command_parts(g[0]), (CMD_MOVE_TO, 1));+ assert_eq!(command_parts(g[3]), (CMD_LINE_TO, 2));+ assert_eq!(g.len(), 1 + 2 + 1 + 4);+ // First point is an absolute-from-origin delta.+ assert_eq!(proto::zigzag_decode(g[1] as u64), 3);+ assert_eq!(proto::zigzag_decode(g[2] as u64), 6);+ // Second is relative to the first.+ assert_eq!(proto::zigzag_decode(g[4] as u64), 5);+ assert_eq!(proto::zigzag_decode(g[5] as u64), 6);+ }++ #[test]+ fn a_degenerate_line_part_is_skipped_not_emitted() {+ // A lone MoveTo would encode a point inside a line layer, and LineTo(0) is+ // illegal outright.+ assert!(encode_lines(&[vec![]]).is_empty());+ assert!(encode_lines(&[vec![(1, 1)]]).is_empty());+ // The valid parts around it still come through.+ let g = encode_lines(&[vec![(1, 1)], vec![(0, 0), (5, 5)], vec![]]);+ assert_eq!(decode_lines(&g).unwrap(), vec![vec![(0, 0), (5, 5)]]);+ }++ #[test]+ fn decode_lines_rejects_streams_that_are_not_lines() {+ // A multipoint MoveTo(3).+ assert!(decode_lines(&encode_points(&[(1, 1), (2, 2), (3, 3)])).is_none());+ // A LineTo with no preceding MoveTo.+ assert!(decode_lines(&[command(CMD_LINE_TO, 1), 2, 2]).is_none());+ // A ClosePath belongs to a polygon.+ assert!(decode_lines(&[command(CMD_MOVE_TO, 1), 2, 2, command(CMD_CLOSE_PATH, 1)]).is_none());+ // Truncated payload.+ assert!(decode_lines(&[command(CMD_MOVE_TO, 1), 2]).is_none());+ assert!(decode_lines(&[command(CMD_MOVE_TO, 1), 2, 2, command(CMD_LINE_TO, 2), 1, 1]).is_none());+ // Empty is a valid empty geometry, not an error.+ assert_eq!(decode_lines(&[]), Some(vec![]));+ }++ // --- polygon encoding: orientation, closure, holes ---------------------++ /// The unit square as an exterior ring, positive area.+ fn ext() -> Vec<(i32, i32)> {+ vec![(0, 0), (0, 100), (100, 100), (100, 0), (0, 0)]+ }++ /// A smaller square inside it, given in the *same* direction as `ext` -- so the+ /// encoder has to flip it.+ fn hole() -> Vec<(i32, i32)> {+ vec![(20, 20), (20, 80), (80, 80), (80, 20), (20, 20)]+ }++ #[test]+ fn the_encoder_derives_orientation_rather_than_trusting_the_input() {+ // Both rings arrive wound the same way. The clipper and the simplifier+ // upstream do not preserve orientation, so the input's winding means+ // nothing and the encoder must fix both.+ let g = encode_polygons(&[vec![ext(), hole()]]);+ let decoded = decode_polygons(&g).expect("our own output must decode");+ assert_eq!(decoded.len(), 1, "one polygon: {decoded:?}");+ assert_eq!(decoded[0].len(), 2, "exterior plus one hole");+ assert!(signed_area(&decoded[0][0]) > 0, "exterior must be positive");+ assert!(signed_area(&decoded[0][1]) < 0, "interior must be negative");++ // And the same when the input is wound the other way round.+ let mut e = ext();+ e.reverse();+ let mut h = hole();+ h.reverse();+ let decoded = decode_polygons(&encode_polygons(&[vec![e, h]])).unwrap();+ assert!(signed_area(&decoded[0][0]) > 0);+ assert!(signed_area(&decoded[0][1]) < 0);+ }++ #[test]+ fn every_ring_is_terminated_by_close_path_and_holes_follow_their_exterior() {+ let g = encode_polygons(&[vec![ext(), hole()]]);+ let mut commands = Vec::new();+ let mut i = 0;+ while i < g.len() {+ let (cmd, count) = command_parts(g[i]);+ commands.push(cmd);+ i += 1 + if cmd == CMD_CLOSE_PATH { 0 } else { count as usize * 2 };+ }+ assert_eq!(+ commands,+ vec![+ CMD_MOVE_TO, CMD_LINE_TO, CMD_CLOSE_PATH, // exterior+ CMD_MOVE_TO, CMD_LINE_TO, CMD_CLOSE_PATH, // its hole+ ]+ );+ }++ #[test]+ fn the_explicit_closing_vertex_is_stripped_because_close_path_implies_it() {+ // Same square, once closed and once not: the streams must be identical.+ let mut open = ext();+ open.pop();+ assert_eq!(encode_polygons(&[vec![ext()]]), encode_polygons(&[vec![open]]));+ // 4 corners: MoveTo(1) + 2 + LineTo(3) + 6 + ClosePath = 11 integers. A+ // retained closing vertex would make it LineTo(4) and 13.+ assert_eq!(encode_polygons(&[vec![ext()]]).len(), 11);+ // A ring closed several times over is still stripped to its corners.+ let mut twice = ext();+ twice.push((0, 0));+ assert_eq!(encode_polygons(&[vec![twice]]).len(), 11);+ }++ #[test]+ fn a_polygon_round_trips_with_its_rings_closed() {+ let decoded = decode_polygons(&encode_polygons(&[vec![ext(), hole()]])).unwrap();+ for ring in &decoded[0] {+ assert_eq!(ring.first(), ring.last(), "decode re-closes every ring");+ assert!(ring.len() >= 4);+ }+ // Geometry is preserved up to orientation and rotation of the vertex list.+ assert_eq!(signed_area(&decoded[0][0]).abs(), signed_area(&ext()).abs());+ assert_eq!(signed_area(&decoded[0][1]).abs(), signed_area(&hole()).abs());+ }++ #[test]+ fn several_polygons_are_grouped_by_orientation_on_the_way_back() {+ let far = vec![+ vec![(1000, 1000), (1000, 1100), (1100, 1100), (1100, 1000), (1000, 1000)],+ vec![(1020, 1020), (1020, 1080), (1080, 1080), (1080, 1020), (1020, 1020)],+ ];+ let g = encode_polygons(&[vec![ext(), hole()], far]);+ let decoded = decode_polygons(&g).unwrap();+ assert_eq!(decoded.len(), 2, "two polygons: {decoded:?}");+ assert_eq!(decoded[0].len(), 2);+ assert_eq!(decoded[1].len(), 2);+ for poly in &decoded {+ assert!(signed_area(&poly[0]) > 0);+ assert!(signed_area(&poly[1]) < 0);+ }+ }++ #[test]+ fn a_zero_area_or_too_short_ring_is_dropped() {+ // Collinear, so it cannot be oriented.+ assert!(encode_polygons(&[vec![vec![(0, 0), (5, 0), (10, 0), (0, 0)]]]).is_empty());+ assert!(encode_polygons(&[vec![vec![(0, 0), (5, 5)]]]).is_empty());+ assert!(encode_polygons(&[vec![vec![]]]).is_empty());+ // A degenerate hole is dropped, the exterior kept.+ let g = encode_polygons(&[vec![ext(), vec![(5, 5), (6, 5), (7, 5), (5, 5)]]]);+ let decoded = decode_polygons(&g).unwrap();+ assert_eq!(decoded[0].len(), 1, "exterior only");+ }++ #[test]+ fn losing_the_exterior_ring_drops_its_holes_too() {+ // A hole with nothing around it renders as solid fill in the layer's+ // colour, which is worse than the feature being absent.+ let g = encode_polygons(&[vec![vec![(0, 0), (5, 0), (10, 0), (0, 0)], hole()]]);+ assert!(g.is_empty(), "{g:?}");+ // The polygon after it is unaffected.+ let g = encode_polygons(&[+ vec![vec![(0, 0), (5, 0), (10, 0)], hole()],+ vec![ext()],+ ]);+ assert_eq!(decode_polygons(&g).unwrap().len(), 1);+ }++ #[test]+ fn close_path_resets_the_cursor_to_the_rings_start() {+ // The spec says ClosePath returns the cursor to the ring's first vertex, so+ // the next ring's MoveTo delta is measured from there. Getting this wrong+ // puts every ring after the first in the wrong place, which the round trip+ // is the only thing that catches.+ let a = vec![(0, 0), (0, 10), (10, 10), (10, 0), (0, 0)];+ let b = vec![(500, 500), (500, 510), (510, 510), (510, 500), (500, 500)];+ let decoded = decode_polygons(&encode_polygons(&[vec![a.clone()], vec![b.clone()]])).unwrap();+ assert_eq!(decoded.len(), 2);+ let corners = |ring: &[(i32, i32)]| {+ let mut c: Vec<(i32, i32)> = ring[..ring.len() - 1].to_vec();+ c.sort_unstable();+ c+ };+ assert_eq!(corners(&decoded[0][0]), corners(&a));+ assert_eq!(corners(&decoded[1][0]), corners(&b));+ }++ #[test]+ fn decode_polygons_rejects_malformed_streams() {+ // Opens with a hole: there is nothing to attach it to, and guessing would+ // silently turn a hole into a fill.+ let ring = [(20, 80), (80, 80), (80, 20), (20, 20)];+ assert!(signed_area(&ring) < 0, "a hole by area, not by intent");+ let mut g = vec![command(CMD_MOVE_TO, 1)];+ let (mut cx, mut cy) = (0i32, 0i32);+ push_delta(&mut g, ring[0], &mut cx, &mut cy);+ g.push(command(CMD_LINE_TO, 3));+ for p in &ring[1..] {+ push_delta(&mut g, *p, &mut cx, &mut cy);+ }+ g.push(command(CMD_CLOSE_PATH, 1));+ assert!(decode_polygons(&g).is_none(), "a leading hole is rejected");++ // Unterminated ring (no ClosePath).+ assert!(decode_polygons(&[command(CMD_MOVE_TO, 1), 2, 2, command(CMD_LINE_TO, 2), 1, 1, 1, 1]).is_none());+ // ClosePath with too few vertices.+ assert!(decode_polygons(&[command(CMD_MOVE_TO, 1), 2, 2, command(CMD_CLOSE_PATH, 1)]).is_none());+ // A second MoveTo before the ring is closed.+ assert!(decode_polygons(&[command(CMD_MOVE_TO, 1), 2, 2, command(CMD_MOVE_TO, 1), 2, 2]).is_none());+ assert_eq!(decode_polygons(&[]), Some(vec![]));+ }++ #[test]+ fn the_decoders_do_not_confuse_each_others_geometry() {+ let points = encode_points(&[(1, 1), (2, 2)]);+ let lines = encode_lines(&[vec![(0, 0), (10, 10)]]);+ let polys = encode_polygons(&[vec![ext()]]);+ assert!(decode_points(&points).is_some());+ assert!(decode_points(&lines).is_none());+ assert!(decode_points(&polys).is_none());+ assert!(decode_lines(&points).is_none());+ assert!(decode_lines(&lines).is_some());+ assert!(decode_lines(&polys).is_none());+ assert!(decode_polygons(&points).is_none());+ // A line stream has no ClosePath, so it decodes as no polygons at all+ // rather than as a bogus one.+ assert_eq!(decode_polygons(&lines), None);+ assert!(decode_polygons(&polys).is_some());+ }++ // --- golden byte fixture ----------------------------------------------++ #[test]+ fn a_line_and_polygon_tile_encodes_to_exactly_these_bytes() {+ // A golden fixture, computed by hand from the wire layout in the module+ // docs. It pins the whole encode path -- field numbers, field order, packed+ // geometry, the property dictionaries -- so a change anywhere in it has to+ // be deliberate rather than incidental.+ let mut roads = Layer::new("roads");+ roads.features.push(Feature {+ id: None,+ geom_type: GeomType::LineString,+ geometry: encode_lines(&[vec![(0, 0), (2, 4)]]),+ props: vec![("kind".to_string(), Value::String("rail".into()))],+ });+ let body = Tile { layers: vec![roads] }.encode();++ // layer message:+ // 1 name "roads" 0a 05 72 6f 61 64 73+ // 2 feature:+ // 2 tags [0, 0] 12 02 00 00+ // 3 type 2 (LineString) 18 02+ // 4 geom [9, 0, 0, 10, 4, 8] 22 06 09 00 00 0a 04 08+ // 3 keys "kind" 1a 04 6b 69 6e 64+ // 4 values { 1: "rail" } 22 06 0a 04 72 61 69 6c+ // 5 extent 4096 28 80 20+ // 15 version 2 78 02+ #[rustfmt::skip]+ let layer: Vec<u8> = vec![+ 0x0a, 0x05, b'r', b'o', b'a', b'd', b's',+ 0x12, 0x0e,+ 0x12, 0x02, 0x00, 0x00,+ 0x18, 0x02,+ 0x22, 0x06, 0x09, 0x00, 0x00, 0x0a, 0x04, 0x08,+ 0x1a, 0x04, b'k', b'i', b'n', b'd',+ 0x22, 0x06, 0x0a, 0x04, b'r', b'a', b'i', b'l',+ 0x28, 0x80, 0x20,+ 0x78, 0x02,+ ];+ let mut expected: Vec<u8> = vec![0x1a, layer.len() as u8];+ expected.extend_from_slice(&layer);+ assert_eq!(body, expected, "encoded {body:02x?}");++ // And it reads back as what it claims to be.+ let tile = Tile::decode(&body).unwrap();+ let f = &tile.layer("roads").unwrap().features[0];+ assert_eq!(f.geom_type, GeomType::LineString);+ assert_eq!(decode_lines(&f.geometry).unwrap(), vec![vec![(0, 0), (2, 4)]]);+ assert_eq!(f.get("kind"), Some(&Value::String("rail".into())));+ }++ #[test]+ fn a_polygon_features_geometry_survives_a_tile_round_trip() {+ // The encoders feed Feature::geometry, which the tile codec treats as+ // opaque -- so the two halves have to agree on the stream, and this is what+ // proves they do end to end.+ let mut admin = Layer::new("admin_city");+ admin.features.push(Feature {+ id: Some(7),+ geom_type: GeomType::Polygon,+ geometry: encode_polygons(&[vec![ext(), hole()]]),+ props: vec![("name".to_string(), Value::String("Oakland".into()))],+ });+ let tile = Tile::decode(&Tile { layers: vec![admin] }.encode()).unwrap();+ let f = &tile.layer("admin_city").unwrap().features[0];+ assert_eq!(f.id, Some(7));+ assert_eq!(f.geom_type, GeomType::Polygon);+ let rings = decode_polygons(&f.geometry).unwrap();+ assert_eq!(rings.len(), 1);+ assert_eq!(rings[0].len(), 2);+ assert!(signed_area(&rings[0][0]) > 0);+ assert!(signed_area(&rings[0][1]) < 0);+ } }
scripts/maps/tile_build/src/simplify.rs
diff --git a/scripts/maps/tile_build/src/simplify.rs b/scripts/maps/tile_build/src/simplify.rsnew file mode 100644index 0000000000..7fcf89129d--- /dev/null+++ b/scripts/maps/tile_build/src/simplify.rs@@ -0,0 +1,383 @@+//! Douglas-Peucker simplification, in integer tile coordinates.+//!+//! Runs **after** the clip, so it only ever sees vertices already inside a tile's+//! buffered rect. That ordering matters: simplifying first and clipping second+//! would let a removed vertex change where an edge crosses the tile boundary, and+//! two adjacent tiles would disagree about the crossing point.+//!+//! ## Why integers+//!+//! The output is going straight into an MVT command stream, which is integer. Any+//! precision the algorithm preserves below one unit is discarded moments later, so+//! working in floats would only add rounding differences between runs. Distances+//! are compared **squared**, in `i128`, so there is no square root and no overflow:+//! a buffered coordinate fits in `i32`, and the cross product of two such spans+//! needs 64 bits before it is squared.+//!+//! ## Rings have two extra rules+//!+//! * **Closure is preserved.** The first and last vertex of a closed ring are both+//! anchors, so the ring cannot be opened by simplification.+//! * **A ring never drops below four vertices**, i.e. three distinct corners plus+//! the repeated close. Fewer than that encloses no area, and an MVT polygon with+//! a two-vertex ring is a renderer's problem rather than a small one. When+//! simplification would go that far the **ring is dropped instead**, and if that+//! ring was the exterior the whole polygon goes with it. Keeping a collapsed+//! sliver would paint a hairline in the layer's fill colour, which is worse than+//! the feature being absent at that zoom.+//!+//! ## The tolerance policy is ours, not tippecanoe's+//!+//! [`tolerance_for`] is a fixed number of tile-extent units, and it returns zero at+//! the maximum zoom so the deepest tiles keep full detail. Because a tile is always+//! `extent` units across whatever the zoom, a constant tolerance is already+//! zoom-relative: the same 1 unit covers roughly 1000x more ground at z6 than at+//! z16, which is exactly the behaviour a pyramid wants. This is a deliberate,+//! documented policy rather than a reproduction of `--simplification`, and the+//! tests assert the policy's own invariants -- never equality with tippecanoe.++use crate::geom::{IPt, IntGeometry};++/// Simplification tolerance at [`crate::mvt::DEFAULT_EXTENT`], in extent units.+///+/// One unit is 1/4096 of a tile, which at z16 is under a metre. Below that,+/// detail is not representable in the tile anyway.+pub const DEFAULT_TOLERANCE: f64 = 1.0;++/// The least a ring may be reduced to: three distinct corners plus the close.+pub const MIN_RING_VERTICES: usize = 4;++/// The tolerance to use at zoom `z`, given the archive's maximum zoom and a+/// multiplier (1.0 for the default policy).+///+/// Zero at `max_zoom`: the deepest zoom is the one a user sees at full scale, and+/// it is also the only zoom whose geometry cannot be recovered from a deeper one.+pub fn tolerance_for(z: u8, max_zoom: u8, multiplier: f64) -> f64 {+ if z >= max_zoom {+ 0.0+ } else {+ DEFAULT_TOLERANCE * multiplier+ }+}++/// Simplify every part of a geometry.+///+/// Points pass through: there is nothing in a point to remove, and dropping one+/// would silently thin a layer that the drop policy is supposed to own.+pub fn simplify(g: &IntGeometry, tolerance: f64) -> IntGeometry {+ if tolerance <= 0.0 {+ return g.clone();+ }+ match g {+ IntGeometry::Points(_) => g.clone(),+ IntGeometry::Lines(lines) => IntGeometry::Lines(+ lines+ .iter()+ .map(|l| simplify_line(l, tolerance))+ .filter(|l| l.len() >= 2)+ .collect(),+ ),+ IntGeometry::Polygons(polys) => IntGeometry::Polygons(+ polys+ .iter()+ .filter_map(|rings| {+ let mut out: Vec<Vec<IPt>> = Vec::with_capacity(rings.len());+ for (i, ring) in rings.iter().enumerate() {+ match simplify_ring(ring, tolerance) {+ Some(r) => out.push(r),+ // The exterior collapsing takes the holes with it.+ None if i == 0 => return None,+ None => continue,+ }+ }+ (!out.is_empty()).then_some(out)+ })+ .collect(),+ ),+ }+}++/// Douglas-Peucker on an open polyline. The endpoints are always kept.+pub fn simplify_line(line: &[IPt], tolerance: f64) -> Vec<IPt> {+ if line.len() < 3 || tolerance <= 0.0 {+ return line.to_vec();+ }+ let tol_sq = (tolerance * tolerance) as i128;+ let mut keep = vec![false; line.len()];+ keep[0] = true;+ keep[line.len() - 1] = true;+ mark(line, 0, line.len() - 1, tol_sq, &mut keep);+ line.iter()+ .zip(&keep)+ .filter(|(_, k)| **k)+ .map(|(p, _)| *p)+ .collect()+}++/// Douglas-Peucker on a ring, or `None` when the result would enclose no area.+///+/// A closed ring (first == last) stays closed. An unclosed one stays unclosed, and+/// its floor is one lower since it has no repeated vertex.+pub fn simplify_ring(ring: &[IPt], tolerance: f64) -> Option<Vec<IPt>> {+ let closed = ring.len() > 1 && ring.first() == ring.last();+ let floor = if closed { MIN_RING_VERTICES } else { MIN_RING_VERTICES - 1 };+ if ring.len() < floor {+ return None;+ }+ if tolerance <= 0.0 {+ return Some(ring.to_vec());+ }++ // Running Douglas-Peucker over the closed ring works because the chord from+ // the first vertex to the last is degenerate, so `perp_dist_sq` falls back to+ // point-to-point distance and picks the vertex furthest from the start. That+ // splits the ring into two arcs, each of which then simplifies normally.+ let simplified = simplify_line(ring, tolerance);+ if simplified.len() < floor {+ return None;+ }+ // Belt and braces: closure is what `keep[len-1] = true` guarantees, but a+ // polygon that silently opened would be a rendering bug nothing else catches.+ if closed && simplified.first() != simplified.last() {+ return None;+ }+ Some(simplified)+}++/// Mark the vertices Douglas-Peucker keeps between two anchors.+///+/// Iterative rather than recursive: a coastline ring can be hundreds of thousands+/// of vertices, and the recursion depth is only bounded by the data.+fn mark(pts: &[IPt], first: usize, last: usize, tol_sq: i128, keep: &mut [bool]) {+ let mut stack = vec![(first, last)];+ while let Some((a, b)) = stack.pop() {+ if b <= a + 1 {+ continue;+ }+ let mut worst = 0i128;+ let mut worst_i = a;+ for i in (a + 1)..b {+ let d = perp_dist_sq(pts[i], pts[a], pts[b]);+ if d > worst {+ worst = d;+ worst_i = i;+ }+ }+ if worst > tol_sq {+ keep[worst_i] = true;+ stack.push((a, worst_i));+ stack.push((worst_i, b));+ }+ }+}++/// Squared distance from `p` to the segment `a -> b`.+///+/// A zero-length chord degrades to point-to-point distance, which is what makes+/// the closed-ring case work.+fn perp_dist_sq(p: IPt, a: IPt, b: IPt) -> i128 {+ let (dx, dy) = ((b.0 - a.0) as i128, (b.1 - a.1) as i128);+ let (px, py) = ((p.0 - a.0) as i128, (p.1 - a.1) as i128);+ let len_sq = dx * dx + dy * dy;+ if len_sq == 0 {+ return px * px + py * py;+ }+ // Distance from the infinite line, not the segment: Douglas-Peucker measures+ // deviation from the chord, and both endpoints are anchors anyway.+ let cross = px * dy - py * dx;+ // cross^2 / len_sq, kept as an integer division. Truncating biases the+ // comparison very slightly towards dropping a vertex, which is the safe+ // direction: it can never keep a vertex that is genuinely below tolerance.+ (cross * cross) / len_sq+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn a_collinear_run_collapses_to_its_endpoints() {+ let line = vec![(0, 0), (10, 0), (20, 0), (30, 0), (40, 0)];+ assert_eq!(simplify_line(&line, 1.0), vec![(0, 0), (40, 0)]);+ }++ #[test]+ fn a_deviation_above_tolerance_is_kept_and_below_is_dropped() {+ // The middle vertex sits 5 units off the chord.+ let line = vec![(0, 0), (50, 5), (100, 0)];+ assert_eq!(simplify_line(&line, 1.0), line, "5 > 1, so it stays");+ assert_eq!(+ simplify_line(&line, 10.0),+ vec![(0, 0), (100, 0)],+ "5 < 10, so it goes"+ );+ }++ #[test]+ fn endpoints_are_never_removed() {+ // Even a line whose interior is entirely within tolerance keeps its ends.+ let line = vec![(0, 0), (1, 0), (2, 0), (100, 0)];+ let out = simplify_line(&line, 50.0);+ assert_eq!(out.first(), Some(&(0, 0)));+ assert_eq!(out.last(), Some(&(100, 0)));+ assert!(out.len() >= 2);+ }++ #[test]+ fn simplification_is_monotonic_in_the_tolerance() {+ // A zigzag of decreasing amplitude: a larger tolerance must never keep more+ // vertices than a smaller one.+ let line: Vec<IPt> = (0..40)+ .map(|i| (i * 10, if i % 2 == 0 { 40 - i } else { -(40 - i) }))+ .collect();+ let mut prev = usize::MAX;+ for tol in [0.5, 1.0, 2.0, 4.0, 8.0, 16.0, 32.0, 64.0] {+ let n = simplify_line(&line, tol).len();+ assert!(+ n <= prev,+ "tolerance {tol} kept {n} vertices, more than the {prev} before it"+ );+ prev = n;+ }+ // And the extremes behave.+ assert_eq!(simplify_line(&line, 0.0), line, "no tolerance, no change");+ assert_eq!(simplify_line(&line, 1e9).len(), 2, "everything but the ends");+ }++ #[test]+ fn simplification_never_adds_a_vertex_or_reorders_them() {+ let line: Vec<IPt> = (0..50).map(|i| (i * 7, (i * i) % 23)).collect();+ for tol in [1.0, 3.0, 9.0] {+ let out = simplify_line(&line, tol);+ assert!(out.len() <= line.len());+ // The output is a subsequence of the input.+ let mut it = line.iter();+ for p in &out {+ assert!(it.any(|q| q == p), "{p:?} is not in the input, or is out of order");+ }+ }+ }++ #[test]+ fn a_closed_ring_stays_closed() {+ // A square with a redundant midpoint on each side.+ let ring = vec![+ (0, 0),+ (50, 0),+ (100, 0),+ (100, 50),+ (100, 100),+ (50, 100),+ (0, 100),+ (0, 50),+ (0, 0),+ ];+ let out = simplify_ring(&ring, 1.0).expect("a square survives");+ assert_eq!(out.first(), out.last(), "closure preserved");+ assert_eq!(out.len(), 5, "four corners plus the close: {out:?}");+ }++ #[test]+ fn an_unclosed_ring_stays_unclosed() {+ let ring = vec![(0, 0), (50, 0), (100, 0), (100, 100), (0, 100)];+ let out = simplify_ring(&ring, 1.0).unwrap();+ assert_ne!(out.first(), out.last());+ assert_eq!(out.len(), 4, "the collinear midpoint goes: {out:?}");+ }++ #[test]+ fn a_ring_is_dropped_rather_than_collapsed_below_four_vertices() {+ // A very thin sliver: at a large tolerance every interior vertex is within+ // tolerance of the chord, so Douglas-Peucker would leave 2 vertices. That+ // encloses no area, so the ring must be dropped instead.+ let ring = vec![(0, 0), (500, 1), (1000, 0), (500, -1), (0, 0)];+ assert_eq!(simplify_ring(&ring, 1000.0), None, "a collapsed ring is dropped");+ // At a tolerance it can actually survive, it does.+ assert!(simplify_ring(&ring, 0.5).is_some());+ }++ #[test]+ fn a_ring_that_is_already_too_small_is_rejected() {+ assert_eq!(simplify_ring(&[], 1.0), None);+ assert_eq!(simplify_ring(&[(0, 0)], 1.0), None);+ assert_eq!(simplify_ring(&[(0, 0), (1, 1)], 1.0), None);+ // Closed, but only two distinct vertices.+ assert_eq!(simplify_ring(&[(0, 0), (1, 1), (0, 0)], 1.0), None);+ // The minimum viable closed ring, at zero tolerance.+ assert!(simplify_ring(&[(0, 0), (10, 0), (0, 10), (0, 0)], 0.0).is_some());+ }++ #[test]+ fn a_ring_at_the_floor_is_dropped_only_when_it_is_below_tolerance() {+ // Four vertices is the floor, but Douglas-Peucker can still remove the two+ // interior ones -- the ring is a line from ring[0] back to ring[0], so both+ // corners are measured against a degenerate chord. Whether it survives is+ // therefore a question about its size, not its vertex count.+ let ring = vec![(0, 0), (1000, 0), (0, 1000), (0, 0)];+ assert_eq!(simplify_ring(&ring, 1.0), Some(ring.clone()), "1000 units across, 1 unit tolerance");+ assert_eq!(simplify_ring(&ring, 1e9), None, "sub-tolerance, so dropped not collapsed");+ }++ #[test]+ fn the_geometry_entry_point_drops_lines_that_fall_below_two_vertices() {+ // simplify_line always keeps both ends, so a 2-vertex line survives; the+ // filter exists for a degenerate 1-vertex input.+ let g = IntGeometry::Lines(vec![+ vec![(0, 0), (10, 0), (20, 0)],+ vec![(5, 5)],+ ]);+ let IntGeometry::Lines(out) = simplify(&g, 1.0) else { panic!() };+ assert_eq!(out.len(), 1);+ assert_eq!(out[0], vec![(0, 0), (20, 0)]);+ }++ #[test]+ fn losing_the_exterior_ring_drops_the_whole_polygon() {+ // A 1000x2 sliver and a 100000-unit square, at a 1000-unit tolerance: the+ // sliver is entirely sub-tolerance and the square is nowhere near it.+ let sliver = vec![(0, 0), (500, 1), (1000, 0), (500, -1), (0, 0)];+ let fat = vec![(0, 0), (100_000, 0), (100_000, 100_000), (0, 100_000), (0, 0)];+ // Exterior collapses: the polygon goes, hole and all.+ let g = IntGeometry::Polygons(vec![vec![sliver.clone(), fat.clone()]]);+ let IntGeometry::Polygons(out) = simplify(&g, 1000.0) else { panic!() };+ assert!(out.is_empty(), "{out:?}");+ // A hole collapsing leaves the exterior intact.+ let g = IntGeometry::Polygons(vec![vec![fat, sliver]]);+ let IntGeometry::Polygons(out) = simplify(&g, 1000.0) else { panic!() };+ assert_eq!(out.len(), 1);+ assert_eq!(out[0].len(), 1, "the hole was dropped, the exterior kept");+ }++ #[test]+ fn points_pass_through_untouched() {+ // Thinning points is the drop policy's job, not simplification's.+ let g = IntGeometry::Points(vec![(0, 0), (1, 1), (2, 2), (3, 3)]);+ assert_eq!(simplify(&g, 1e9), g);+ }++ #[test]+ fn a_zero_tolerance_is_the_identity() {+ let g = IntGeometry::Lines(vec![vec![(0, 0), (1, 0), (2, 0), (3, 0)]]);+ assert_eq!(simplify(&g, 0.0), g);+ assert_eq!(simplify(&g, -1.0), g, "a negative tolerance is not a licence");+ }++ #[test]+ fn the_tolerance_policy_spares_the_deepest_zoom() {+ assert_eq!(tolerance_for(14, 14, 1.0), 0.0, "max zoom keeps full detail");+ assert_eq!(tolerance_for(15, 14, 1.0), 0.0, "and so does anything past it");+ assert_eq!(tolerance_for(13, 14, 1.0), DEFAULT_TOLERANCE);+ assert_eq!(tolerance_for(6, 14, 4.0), DEFAULT_TOLERANCE * 4.0);+ }++ #[test]+ fn the_distance_maths_does_not_overflow_at_the_coordinate_extremes() {+ // A span of the full i32 range, squared, needs more than 64 bits. If this+ // panics in debug or wraps in release, the comparison is meaningless.+ let big = i32::MAX / 2;+ let d = perp_dist_sq((0, big), (-big, 0), (big, 0));+ assert!(d > 0, "{d}");+ assert_eq!(perp_dist_sq((5, 5), (0, 0), (0, 0)), 50, "degenerate chord");+ assert_eq!(perp_dist_sq((5, 0), (0, 0), (10, 0)), 0, "on the chord");+ }+}
scripts/maps/tile_build/src/tiling.rs
diff --git a/scripts/maps/tile_build/src/tiling.rs b/scripts/maps/tile_build/src/tiling.rsindex 0a29425ef8..d5c904a4d6 100644--- a/scripts/maps/tile_build/src/tiling.rs+++ b/scripts/maps/tile_build/src/tiling.rs@@ -1,11 +1,13 @@ //! Tile a point layer, and merge tilesets — the `tippecanoe` and `tile-join` //! replacements. //!-//! Only points are *generated*: `transit_stops` is the layer we build, and a point-//! needs no clipping, simplification or winding-order handling. Lines and polygons-//! are only ever *carried through* by [`merge_tiles`], which never looks inside a-//! geometry stream.+//! Points need no clipping, simplification or winding-order handling, so this+//! module stays as simple as a point layer allows. The geometry core that lines and+//! polygons need lives in [`crate::geom`], [`crate::clip`] and+//! [`crate::simplify`]; [`merge_tiles`] still never looks inside a geometry stream,+//! which is what makes a composite lossless. +use crate::geom::project; use crate::mvt::{self, Feature, GeomType, Layer, Tile, Value, DEFAULT_EXTENT}; use crate::pmtiles::{self, Archive, Builder}; use crate::proto::Result;@@ -19,20 +21,6 @@ pub struct Point { pub props: Vec<(String, Value)>, } -/// Web-Mercator project a lon/lat to fractional tile coordinates at `z`.-///-/// Latitude is clamped to the Mercator limit: the projection diverges at the-/// poles, and a feed with a `0,0`-style placeholder stop would otherwise produce-/// an infinity.-fn project(lon: f64, lat: f64, z: u8) -> (f64, f64) {- let n = (1u64 << z) as f64;- let lat = lat.clamp(-85.051_128_78, 85.051_128_78);- let x = (lon.clamp(-180.0, 180.0) + 180.0) / 360.0 * n;- let s = lat.to_radians().sin();- let y = (0.5 - (((1.0 + s) / (1.0 - s)).ln()) / (4.0 * std::f64::consts::PI)) * n;- (x, y)-}- /// Bucket points into tiles for one zoom and encode each as an MVT. /// /// Returns `(tile_id, mvt body)`. Points landing outside the tile grid are@@ -203,22 +191,6 @@ mod tests { } } - #[test]- fn projection_anchors_are_right() {- // z0: the whole world is one tile, and 0,0 sits at its centre.- let (x, y) = project(0.0, 0.0, 0);- assert!((x - 0.5).abs() < 1e-9, "lon 0 -> x 0.5, got {x}");- assert!((y - 0.5).abs() < 1e-9, "lat 0 -> y 0.5, got {y}");- // The antimeridian and the Mercator top corner.- let (x, _) = project(-180.0, 0.0, 0);- assert!(x.abs() < 1e-9);- let (_, y) = project(0.0, 85.051_128_78, 0);- assert!(y.abs() < 1e-6, "Mercator top -> y 0, got {y}");- // A pole must clamp rather than diverge.- let (_, y) = project(0.0, 90.0, 4);- assert!(y.is_finite(), "lat 90 must clamp, got {y}");- }- #[test] fn a_point_lands_in_the_expected_tile() { // San Francisco at z11 is a well-known tile: x=327, y=791.