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

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

tiler_part6.rs285 lines · 13.2 KiBRaw
1/// Append one feature's tile-local geometry to a layer. Returns `(features, points)` added.
2///
3/// A polygon becomes **one feature per ring group**, so a feature's parts are exactly one exterior
4/// and its holes — which is what the tessellator wants and what makes "one outer per feature" an
5/// invariant worth stating.
6///
7/// A point becomes **one feature per point**, each with its own part and its own name: labels are
8/// independent features that happen to share a tile, not a multi-point geometry, because the
9/// renderer draws (and collides) them one at a time.
10fn push(entry: &mut ChunkEntry, feature: &Feature, geometry: &IntGeometry) -> (u64, u64) {
11 let layer = &mut entry.layer;
12 let class = &feature.class;
13 // `places`, `poi` and `boundaries` have an id table. Pushed in every branch rather than only
14 // in the point one so the two vectors cannot drift apart - the table is indexed by feature
15 // position, so a feature with no id of its own still needs its `ID_NONE` entry.
16 let track_ids = crate::extract::layer_tracks_ids(class.layer);
17 // The `buildings` layer carries an S3DB attribute side table, dense-parallel to its features
18 // exactly as the id table is — so every building feature pushes an entry (a default one when
19 // the building had no S3DB tags), in every branch, so the two vectors cannot drift.
20 let track_buildings = class.layer == tilecodec::mamaps::dict::LAYER_BUILDINGS;
21 // `roads` and `landtype` line features carry a display name for curved labels; it is
22 // interned into the tile's name table like a point label's, at no format cost.
23 let name_line_layer = matches!(
24 class.layer,
25 tilecodec::mamaps::dict::LAYER_ROADS | tilecodec::mamaps::dict::LAYER_LANDTYPE
26 );
27 let mut added = (0u64, 0u64);
28 match geometry {
29 IntGeometry::Polygons(polygons) => {
30 // Below a few square pixels a polygon is a speck rather than detail, and there are
31 // millions of them. Measured **after** clipping, on the shape that would actually be
32 // drawn, so a large park clipped to a sliver of one tile is kept where it is big and
33 // dropped where it is not.
34 let floor = crate::schema::landtype::min_area_units(class.min_area_px, EXTENT);
35 for rings in polygons {
36 // A ring needs three distinct points plus the closing one; anything less bounds no
37 // area. Filtered *before* anything is appended, because a part and its points have
38 // to be committed together — the encoder requires the parts to tile the arena
39 // exactly, so half-appending a group and rolling it back would leave orphaned
40 // coordinates.
41 let keep: Vec<(usize, &Vec<(i32, i32)>)> =
42 rings.iter().enumerate().filter(|(_, ring)| ring.len() >= 4).collect();
43 // If the exterior did not survive, what is left is a hole with nothing to be a hole
44 // in, which would paint as the inverse of the shape.
45 if !keep.first().is_some_and(|(index, _)| *index == 0) {
46 continue;
47 }
48 if floor > 0.0 && ring_area(keep[0].1) < floor {
49 continue;
50 }
51 let parts_offset = layer.parts.len() as u32;
52 for (index, ring) in &keep {
53 added.1 += push_part(
54 layer,
55 ring,
56 if *index == 0 { WINDING_OUTER } else { WINDING_HOLE },
57 );
58 }
59 layer.features.push(BodyFeature {
60 kind: class.kind,
61 kind_detail: class.kind_detail,
62 geom_type: GEOM_POLYGON,
63 flags: class.flags,
64 name_idx: tilecodec::mamaps::body::NAME_NONE,
65 parts_offset,
66 part_count: keep.len() as u32,
67 transit_color: feature.transit_color,
68 transit_ordinal: feature.transit_ordinal,
69 transit_lanes: feature.transit_lanes,
70 transit_taper: feature.transit_taper,
71 lane_count: feature.lane_count,
72 });
73 if track_ids {
74 entry.ids.push(feature.id);
75 }
76 if track_buildings {
77 entry.buildings.push(feature.building.unwrap_or_default());
78 }
79 added.0 += 1;
80 }
81 }
82 IntGeometry::Lines(lines) => {
83 let parts_offset = layer.parts.len() as u32;
84 for line in lines {
85 if line.len() < 2 {
86 continue;
87 }
88 added.1 += push_part(layer, line, WINDING_OUTER);
89 }
90 let part_count = layer.parts.len() as u32 - parts_offset;
91 if part_count > 0 {
92 // A road or river's name, interned for a curved label; NAME_NONE otherwise.
93 let name_idx = if name_line_layer {
94 intern_name(&mut entry.names, feature.name.as_deref())
95 } else {
96 tilecodec::mamaps::body::NAME_NONE
97 };
98 layer.features.push(BodyFeature {
99 kind: class.kind,
100 kind_detail: class.kind_detail,
101 geom_type: GEOM_LINE,
102 flags: class.flags,
103 name_idx,
104 parts_offset,
105 part_count,
106 transit_color: feature.transit_color,
107 transit_ordinal: feature.transit_ordinal,
108 transit_lanes: feature.transit_lanes,
109 transit_taper: feature.transit_taper,
110 lane_count: feature.lane_count,
111 });
112 if track_ids {
113 entry.ids.push(feature.id);
114 }
115 if track_buildings {
116 entry.buildings.push(feature.building.unwrap_or_default());
117 }
118 // Roads carry a per-feature turn-lane record, dense-parallel to the layer's
119 // features like the id table is for its layers. Pushed here — the one branch a road
120 // ever reaches (a road is a line) — inside the `part_count > 0` guard so it stays
121 // aligned with the feature that was actually added.
122 if class.layer == tilecodec::mamaps::dict::LAYER_ROADS {
123 entry.turn_lanes.push(tilecodec::mamaps::body::LaneTurns {
124 forward: feature.turn_fwd.clone(),
125 backward: feature.turn_bwd.clone(),
126 });
127 entry.carriageways.push(feature.carriageway);
128 }
129 added.0 += 1;
130 }
131 }
132 IntGeometry::Points(points) => {
133 // One feature per point, each naming its own label. Points carry no simplification
134 // survivors to filter: a label is either in the tile or it is not.
135 for point in points {
136 // Interned before the layer is borrowed: the name table lives on the entry, the
137 // geometry on the layer, and the two borrows must not overlap.
138 let name_idx = intern_name(&mut entry.names, feature.name.as_deref());
139 let parts_offset = layer.parts.len() as u32;
140 added.1 += push_part(layer, &[*point], WINDING_OUTER);
141 layer.features.push(BodyFeature {
142 kind: class.kind,
143 kind_detail: class.kind_detail,
144 geom_type: GEOM_POINT,
145 flags: class.flags,
146 name_idx,
147 parts_offset,
148 part_count: 1,
149 transit_color: feature.transit_color,
150 transit_ordinal: feature.transit_ordinal,
151 transit_lanes: feature.transit_lanes,
152 transit_taper: feature.transit_taper,
153 lane_count: feature.lane_count,
154 });
155 if track_ids {
156 entry.ids.push(feature.id);
157 }
158 if track_buildings {
159 entry.buildings.push(feature.building.unwrap_or_default());
160 }
161 added.0 += 1;
162 }
163 }
164 }
165 added
166}
167
168/// Append one path's points to a layer's arena, clamped to what an `i16` holds.
169///
170/// The clip buffer keeps a coordinate within a few percent of the extent, so `i16` has eight times
171/// the headroom needed and this never bites. Clamping rather than asserting because a single stray
172/// vertex should not fail a whole build.
173fn push_part(layer: &mut BodyLayer, points: &[(i32, i32)], winding: u16) -> u64 {
174 let coord_start = layer.coords.len() as u32;
175 for &(x, y) in points {
176 layer.coords.push((
177 x.clamp(i16::MIN as i32, i16::MAX as i32) as i16,
178 y.clamp(i16::MIN as i32, i16::MAX as i32) as i16,
179 ));
180 }
181 layer.parts.push(Part { coord_start, point_count: points.len() as u32, winding });
182 points.len() as u64
183}
184
185/// A ring's absolute area, by the shoelace formula.
186///
187/// `i64` throughout: a 4096-unit tile's coordinates cross-multiply to about 2^24 per term, and a
188/// long ring accumulates thousands of them, which overflows an `i32` and would silently report a
189/// huge shape as a tiny one.
190fn ring_area(ring: &[(i32, i32)]) -> f64 {
191 let mut twice = 0i64;
192 for pair in ring.windows(2) {
193 let ((x0, y0), (x1, y1)) = (pair[0], pair[1]);
194 twice += x0 as i64 * y1 as i64 - x1 as i64 * y0 as i64;
195 }
196 (twice.abs() as f64) / 2.0
197}
198
199fn is_empty(g: &Geometry<SigPt>) -> bool {
200 match g {
201 Geometry::Points(points) => points.is_empty(),
202 Geometry::Lines(lines) => lines.iter().all(|l| l.len() < 2),
203 Geometry::Polygons(polygons) => polygons.iter().all(|rings| {
204 rings.first().map(|ring| ring.len() < 4).unwrap_or(true)
205 }),
206 }
207}
208
209/// Whether a merged tile is pure water background: one `landtype` layer, one polygon
210/// feature of a water kind, one exterior ring covering the whole tile, no holes.
211///
212/// Such a tile draws exactly what the style's water background already paints, so
213/// [`encode_tile`](super::tiler_part5::encode_tile) drops it (`None`, not stored) and the
214/// reader overzooms the parent. The checks are deliberately narrow — one layer, one
215/// feature, one part, water kind, full bleed, no holes — so a tile carrying anything
216/// drawable (an island hole, a named water label, a second layer) keeps its body.
217///
218/// `extent` is the tile grid ([`super::EXTENT`]); the full-bleed bar is half a unit, the
219/// same sub-pixel magnitude as [`super::BUILDING_TOLERANCE`]. Clipped water rings run along
220/// the tile edge but rarely exactly on it, so exact equality would never fire.
221fn is_water_background(layers: &[ChunkEntry]) -> bool {
222 use tilecodec::mamaps::dict;
223 let [entry] = layers else { return false };
224 if entry.layer.layer_id != dict::LAYER_LANDTYPE || entry.layer.features.len() != 1 {
225 return false;
226 }
227 let feature = &entry.layer.features[0];
228 if feature.geom_type != GEOM_POLYGON || feature.part_count != 1 {
229 return false;
230 }
231 if !is_water_kind_id(feature.kind) {
232 return false;
233 }
234 // No holes: a holed polygon is an island (or a lake ring), which is drawable land.
235 let part = &entry.layer.parts[feature.parts_offset as usize];
236 if part.winding != WINDING_OUTER {
237 return false;
238 }
239 let start = part.coord_start as usize;
240 let points = &entry.layer.coords[start..start + part.point_count as usize];
241 if points.len() < 4 {
242 return false;
243 }
244 let extent = EXTENT as f64;
245 let (mut min_x, mut min_y) = (f64::MAX, f64::MAX);
246 let (mut max_x, mut max_y) = (f64::MIN, f64::MIN);
247 for &(x, y) in points {
248 min_x = min_x.min(x as f64);
249 min_y = min_y.min(y as f64);
250 max_x = max_x.max(x as f64);
251 max_y = max_y.max(y as f64);
252 }
253 const BLEED: f64 = 0.5;
254 min_x <= BLEED && min_y <= BLEED && max_x >= extent - BLEED && max_y >= extent - BLEED
255}
256
257/// Whether an interned `landtype` kind id is one the style paints as water.
258///
259/// Name-resolved (not hard-coded ids) so the check cannot drift when the dictionary
260/// grows. Mirrors the renderer's own water list (`tile::geometry::terrain::WATER_KINDS`)
261/// minus `fountain`/`swimming_pool`: those are street furniture, never full-bleed tiles.
262fn is_water_kind_id(kind: u16) -> bool {
263 use tilecodec::mamaps::dict;
264 if kind == dict::NONE {
265 return false;
266 }
267 matches!(
268 dict::KINDS.get(kind as usize - 1).copied(),
269 Some(
270 "ocean" | "sea" | "lake" | "water" | "river" | "stream" | "bay" | "strait"
271 | "fjord" | "reef" | "canal" | "dock",
272 ),
273 )
274}
275
276
277
278/// A build that produced nothing is a build whose schema matched nothing, which is worth failing on
279/// rather than publishing an empty archive.
280pub fn check_not_empty(stats: &[ZoomStats]) -> Result<()> {
281 if stats.iter().all(|s| s.tiles == 0) {
282 return err("the build produced no tiles: nothing in the input matched the schema");
283 }
284 Ok(())
285}