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

Modern-Apps.git / scripts / maps / mamaps_build / src / tiler_part2_s1.rs

tiler_part2_s1.rs218 lines · 9.8 KiBRaw
1/// The tolerance to simplify a layer at: the per-zoom policy, with a floor for buildings
2/// and a multiplier for the boundary wash.
3///
4/// Buildings live only at z14 and up, where [`simplify::tolerance_for`] returns 0.0 — full
5/// detail. Half an extent unit there is ~0.3 m on the ground, sub-pixel on any screen the style
6/// draws at, and only drops what is invisible anyway: exactly-collinear midpoints, whose
7/// significance is 0 and which any non-zero threshold already removes, plus sub-pixel jaggies.
8/// Every other layer keeps the policy tolerance untouched. A coarser global tolerance still wins
9/// (`max`, not replace), and a zero/negative policy for a non-building layer is unchanged.
10///
11/// `boundaries` alone keeps the [`WASH_SIMPLIFICATION`] multiplier: a low-zoom line backdrop.
12/// `landtype` simplifies at 1.5x: natural boundaries (forest edges, shorelines,
13/// farmland) are washes, not navigation geometry — same reasoning as
14/// boundaries, smaller factor because parks and lakes are looked at closer.
15/// Roads and transit curves take the wash below z14: at z13 a 1.5x tolerance
16/// drops sub-10m wiggles (a 2x grid stretch could straighten them) while z14
17/// stays at policy 0.0 — full detail where carriageway/lane alignment lives.
18/// Buildings and the point layers keep 1.0 — navigation geometry and
19/// labels, not a wash.
20///
21/// The prototype at `analysis/mamaps_building_savings.py` estimates this plus the snap below at
22/// ~2% + ~4% of building-tile bytes; buildings are z14-only, 9.76M features, ~20% of the archive.
23fn tolerance_for_layer(layer: u8, z: u8, tolerance: f64) -> f64 {
24 use tilecodec::mamaps::dict;
25 if layer == dict::LAYER_BUILDINGS
26 && z >= crate::schema::buildings::MIN_ZOOM
27 {
28 tolerance.max(BUILDING_TOLERANCE)
29 } else if layer == dict::LAYER_BOUNDARIES {
30 tolerance * WASH_SIMPLIFICATION
31 } else if layer == dict::LAYER_LANDTYPE {
32 // z13 tiles span ~5 km: triple the wash there, keep 1.5x at z14
33 // where parks sit under streets.
34 if z == 13 {
35 let o = size_opts();
36 if o.keep_z13_wash && o.simplify_scale > 0.0 {
37 tolerance / o.simplify_scale * LANDTYPE_Z13_SIMPLIFICATION
38 } else {
39 tolerance * LANDTYPE_Z13_SIMPLIFICATION
40 }
41 } else {
42 tolerance * LANDTYPE_SIMPLIFICATION
43 }
44 } else if z < crate::DEFAULT_MAX_ZOOM
45 && (layer == dict::LAYER_ROADS || layer == dict::LAYER_TRANSIT)
46 {
47 // Below the archive max the policy tolerance is non-zero, so the wash
48 // bites; at z14 policy is 0.0 and 1.5x of zero is zero — crisp.
49 tolerance * WASH_SIMPLIFICATION
50 } else {
51 tolerance
52 }
53}
54
55/// The tolerance for one feature: the layer policy, plus the z14 roads
56/// floor. Washable roads (not arterial, no lanes/split — see `needs_crisp`)
57/// take [`ROAD_DETAIL_FLOOR`] at the archive max, where the layer policy is
58/// 0.0; everything else keeps the layer value untouched.
59fn tolerance_for_feature(feature: &crate::extract::Feature, z: u8, tolerance: f64) -> f64 {
60 use tilecodec::mamaps::dict;
61 let base = tolerance_for_layer(feature.class.layer, z, tolerance);
62 let base = if z == crate::DEFAULT_MAX_ZOOM
63 && feature.class.layer == dict::LAYER_ROADS
64 && !needs_crisp(feature)
65 {
66 base.max(ROAD_DETAIL_FLOOR)
67 } else {
68 base
69 };
70 // `--z14-tolerance`: a z14 floor for the washable layers (crisp roads keep full detail).
71 let floor = size_opts().z14_tolerance;
72 if floor > 0.0 && z == crate::DEFAULT_MAX_ZOOM {
73 let l = feature.class.layer;
74 let washable = l == dict::LAYER_LANDTYPE
75 || l == dict::LAYER_BOUNDARIES
76 || l == dict::LAYER_BUILDINGS
77 || (l == dict::LAYER_ROADS && !needs_crisp(feature));
78 if washable {
79 return base.max(floor);
80 }
81 }
82 base
83}
84
85/// Snap a building geometry's near-axis-aligned edges to exactly axis-aligned.
86///
87/// Hand-digitised footprints are near-rectangles: edges within [`BUILDING_SNAP`] of horizontal
88/// or vertical snap flat, turning an 8-delta wobble into a repeated constant the varint arena
89/// encodes cheaply. Runs on `SigPt` survivors **after** [`simplify::filter`], via
90/// [`Vertex::moved`] so significance rides along untouched — nothing downstream re-measures.
91/// Only ever called for the buildings layer (the caller gates it); strictly per-edge — never
92/// a corner merge, never a vertex invented or removed — so winding, closure and hole
93/// containment are exactly what the filter left.
94///
95/// Deterministic by construction: a pure function of the ring's coordinates, so two runs tile
96/// identically however features are chunked or threaded — the property
97/// `the_archive_is_identical_however_the_features_are_chunked` defends.
98fn snap_building_rings(geometry: &Geometry<SigPt>, layer: u8) -> Geometry<SigPt> {
99 debug_assert_eq!(layer, tilecodec::mamaps::dict::LAYER_BUILDINGS);
100 match geometry {
101 Geometry::Points(_) | Geometry::Lines(_) => geometry.clone(),
102 Geometry::Polygons(polygons) => Geometry::Polygons(
103 polygons
104 .iter()
105 .map(|rings| rings.iter().map(|ring| snap_building_ring(ring)).collect())
106 .collect(),
107 ),
108 }
109}
110
111/// Snap one ring's near-axis-aligned edges flat, preserving length, order, closure and winding.
112fn snap_building_ring(ring: &[SigPt]) -> Vec<SigPt> {
113 if ring.len() < 2 {
114 return ring.to_vec();
115 }
116 // The explicit close duplicates the first vertex; snapping the closing edge in the same
117 // pass as the rest would compare the duplicate against its twin and average the corner
118 // away. Snap the distinct vertices, then re-close with the surviving first.
119 let closed = ring.len() > 1 && ring.first().map(|v| v.xy()) == ring.last().map(|v| v.xy());
120 let open_len = ring.len() - usize::from(closed);
121 if open_len < 2 {
122 return ring.to_vec();
123 }
124 let open = &ring[..open_len];
125 let mut snapped: Vec<(f64, f64)> = open.iter().map(|v| v.xy()).collect();
126 // Forward pass: each edge votes its dominant direction; a near-horizontal edge levels both
127 // endpoints to their mean y, a near-vertical one to their mean x. Means, not first-wins, so
128 // a shared corner snapped from either side lands identically — the seam property the
129 // annotate-then-filter design exists for.
130 for i in 0..open_len {
131 let j = (i + 1) % open_len;
132 let ((x0, y0), (x1, y1)) = (snapped[i], snapped[j]);
133 let (dx, dy) = ((x1 - x0).abs(), (y1 - y0).abs());
134 if dx <= BUILDING_SNAP && dy > BUILDING_SNAP {
135 // Near-vertical: level x.
136 let x = (x0 + x1) / 2.0;
137 snapped[i].0 = x;
138 snapped[j].0 = x;
139 } else if dy <= BUILDING_SNAP && dx > BUILDING_SNAP {
140 // Near-horizontal: level y.
141 let y = (y0 + y1) / 2.0;
142 snapped[i].1 = y;
143 snapped[j].1 = y;
144 }
145 }
146 let mut out: Vec<SigPt> = open
147 .iter()
148 .zip(snapped)
149 .map(|(v, (x, y))| {
150 // Round onto the building grid: hand jitter (±1 unit) collapses
151 // into repeated constants. Runs here — after the filter, on
152 // survivors only — so measured significance is never stale.
153 let gx = (x / crate::tiler::BUILDING_GRID).round() * crate::tiler::BUILDING_GRID;
154 let gy = (y / crate::tiler::BUILDING_GRID).round() * crate::tiler::BUILDING_GRID;
155 v.moved((gx, gy))
156 })
157 .collect();
158 if closed {
159 out.push(out[0]);
160 }
161 out
162}
163
164
165/// `--coord-quant`: snap tile-local coordinates to a `q`-unit grid, dropping consecutive
166/// duplicates. Max displacement per vertex is `q/2` per axis (`q/sqrt(2)` units). A line that
167/// collapses below 2 vertices or a ring below 4 is dropped (a ring that was the exterior takes
168/// its polygon with it) — the same floors `simplify::filter` applies. Points are untouched.
169/// Rings are re-normalised by stage C afterwards, so `rings_validated` stays true.
170fn snap_grid(g: tile_build::geom::IntGeometry, q: i32) -> tile_build::geom::IntGeometry {
171 use tile_build::geom::IntGeometry;
172 let s = |v: i32| (v + q / 2).div_euclid(q) * q;
173 let snap = |pts: &[(i32, i32)]| -> Vec<(i32, i32)> {
174 let mut out: Vec<(i32, i32)> = Vec::with_capacity(pts.len());
175 for &(x, y) in pts {
176 let p = (s(x), s(y));
177 if out.last() != Some(&p) {
178 out.push(p);
179 }
180 }
181 out
182 };
183 match g {
184 IntGeometry::Points(p) => IntGeometry::Points(p),
185 IntGeometry::Lines(lines) => {
186 IntGeometry::Lines(lines.iter().map(|l| snap(l)).filter(|l| l.len() >= 2).collect())
187 }
188 IntGeometry::Polygons(polys) => IntGeometry::Polygons(
189 polys
190 .iter()
191 .filter_map(|rings| {
192 let mut out = Vec::with_capacity(rings.len());
193 for (i, r) in rings.iter().enumerate() {
194 let sr = snap(r);
195 // Distinct corners: a closed ring repeats its first vertex.
196 let closed = sr.len() > 1 && sr.first() == sr.last();
197 let distinct = sr.len() - usize::from(closed);
198 if distinct >= 3 {
199 out.push(sr);
200 } else if i == 0 {
201 return None;
202 }
203 }
204 (!out.is_empty()).then_some(out)
205 })
206 .collect(),
207 ),
208 }
209}
210
211fn is_empty_int(g: &tile_build::geom::IntGeometry) -> bool {
212 use tile_build::geom::IntGeometry;
213 match g {
214 IntGeometry::Points(p) => p.is_empty(),
215 IntGeometry::Lines(l) => l.is_empty(),
216 IntGeometry::Polygons(p) => p.is_empty(),
217 }
218}