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

Modern-Apps.git / scripts / maps / mamaps_build / src / schema / mod.rs

mod.rs440 lines · 16.8 KiBRaw
1//! The tag → kind mapping: OSM tags in, `.mamaps` layer and interned ids out.
2//!
3//! **The main body of work and the main risk of this whole project.** Planetiler's Protomaps
4//! profile is thousands of lines of accumulated judgement, and reproducing it is the thing that
5//! takes weeks rather than days. So it lives here, alone, behind one function, with no I/O and no
6//! geometry: [`classify`] takes tags and returns a [`Class`] or nothing, which makes every rule in
7//! it a unit test rather than a screenshot.
8//!
9//! # The rules
10//!
11//! Ordered and **first match wins**, like the `osmium tags-filter` expressions this replaces and
12//! like Planetiler's own dispatch. Order is therefore load-bearing: a `natural=water` way that also
13//! carries `building=yes` is water, because water is asked first.
14//!
15//! Every layer is pre-screened by [`osm_ingest::select::Select`] before any rule runs. Tag lookup
16//! is a linear scan over a block's string table, so at planet scale it matters a great deal whether
17//! the common case reads three tags or thirty.
18//!
19//! # What a `Class` is not
20//!
21//! It carries no geometry and no name. Names are the largest thing this format drops — an upstream
22//! `water` feature carries forty `name:*` localisations — and nothing in the style reads one.
23
24use tilecodec::mamaps::dict;
25
26pub mod boundaries;
27pub mod buildings;
28pub mod buildings_extra;
29pub mod junction;
30pub mod landtype;
31pub mod places;
32pub mod poi;
33pub mod roads;
34pub mod roads_extra;
35pub mod safety;
36pub mod traffic;
37pub mod traffic_extra;
38pub mod transit;
39
40/// Tag lookup, so a rule is a pure function of its tags.
41///
42/// [`osm_ingest::osm::Tags`] borrows from the PBF block it was decoded out of, which would make
43/// every test here a synthetic protobuf. Behind this trait a test is a list of pairs, which is what
44/// makes the mapping — the risky part — cheap enough to cover properly.
45pub trait TagSource {
46 fn get(&self, key: &str) -> Option<&str>;
47
48 fn has(&self, key: &str) -> bool {
49 self.get(key).is_some()
50 }
51
52 /// Is this tag one of OSM's affirmatives?
53 ///
54 /// `yes`, `true` and `1` all mean yes, and a bridge tagged `viaduct` is still a bridge. Only
55 /// `no` and absence mean no.
56 fn truthy(&self, key: &str) -> bool {
57 !matches!(self.get(key), None | Some("no") | Some("false") | Some("0"))
58 }
59}
60
61impl TagSource for osm_ingest::osm::Tags<'_, '_> {
62 fn get(&self, key: &str) -> Option<&str> {
63 self.get_str(key)
64 }
65}
66
67/// Tags as a plain list, for tests.
68impl TagSource for [(&str, &str)] {
69 fn get(&self, key: &str) -> Option<&str> {
70 self.iter().find(|(k, _)| *k == key).map(|(_, v)| *v)
71 }
72}
73
74/// Where a feature goes and what it is, once classified.
75#[derive(Debug, Clone, Copy, PartialEq)]
76pub struct Class {
77 /// An index into [`dict::LAYERS`].
78 pub layer: u8,
79 /// An index into [`dict::KINDS`], or [`dict::NONE`].
80 pub kind: u16,
81 /// An index into [`dict::DETAILS`], a number under [`FLAG_DETAIL_NUMERIC`], or
82 /// [`dict::NONE`].
83 ///
84 /// [`FLAG_DETAIL_NUMERIC`]: tilecodec::mamaps::body::FLAG_DETAIL_NUMERIC
85 pub kind_detail: u16,
86 pub flags: u8,
87 /// Is this an area? Decides whether a closed way becomes a polygon or a line.
88 ///
89 /// Not derivable from the geometry: a closed way is a ring for a lake and a loop road for a
90 /// cul-de-sac, and only the tags say which.
91 pub area: bool,
92 /// The shallowest zoom this feature is worth carrying at.
93 ///
94 /// Where most of the upstream profile's judgement lives, and the reason a world tile is not
95 /// every pond in California. Compared against the tile's zoom, so a feature simply is not
96 /// written above it.
97 pub min_zoom: u8,
98 /// The smallest drawn area worth carrying, in square pixels of a 256-unit tile.
99 ///
100 /// Zero for a line and for anything a zoom gate alone separates. What it is for is the case a
101 /// zoom cannot fix: a national park and a back garden are both `leisure=park`, and only a size
102 /// Converted to the tile's own units by [`landtype::min_area_units`].
103 pub min_area_px: f64,
104}
105
106impl Class {
107 /// A polygon feature with no detail and no flags.
108 pub const fn area(layer: u8, kind: u16, min_zoom: u8) -> Class {
109 Class {
110 layer,
111 kind,
112 kind_detail: dict::NONE,
113 flags: 0,
114 area: true,
115 min_zoom,
116 min_area_px: 0.0,
117 }
118 }
119
120 /// A line feature with no detail and no flags.
121 pub const fn line(layer: u8, kind: u16, min_zoom: u8) -> Class {
122 Class {
123 layer,
124 kind,
125 kind_detail: dict::NONE,
126 flags: 0,
127 area: false,
128 min_zoom,
129 min_area_px: 0.0,
130 }
131 }
132}
133
134/// Look up a `kind` name's id at compile-time-ish cost.
135///
136/// A linear scan over 79 short strings, called once per classified feature. Interning at
137/// classification time rather than at encode time is what keeps the encoder free of names entirely.
138///
139/// Panics on a name the table does not carry, because every name here is a literal in this crate
140/// and `every_kind_this_schema_names_is_in_the_dictionary` proves them all.
141pub fn kind(name: &str) -> u16 {
142 match dict::KINDS.iter().position(|k| *k == name) {
143 Some(index) => index as u16 + 1,
144 None => panic!("the schema names kind `{name}`, which the dictionary has no id for"),
145 }
146}
147
148/// Look up a `kind_detail` name's id.
149pub fn detail(name: &str) -> u16 {
150 match dict::DETAILS.iter().position(|d| *d == name) {
151 Some(index) => index as u16 + 1,
152 None => panic!("the schema names detail `{name}`, which the dictionary has no id for"),
153 }
154}
155
156/// The deepest zoom a layer is worth carrying at, by layer id.
157///
158/// The `landtype` wash is no longer a low-zoom backdrop: it tiles to z14 at 1.0x sharpness, so
159/// parks, shorelines and desert stay crisp under z14 roads and buildings. Boundaries stop at
160/// z12 (z13 overzooms from z12 exactly as z14 overzoomed z13 — admin lines soften one level,
161/// nothing else moves). Traffic stops at z13: congestion ribbons overzoom legibly (the ids still
162/// match 1:1, only the geometry stretches 2x — sub-pixel for a congestion overlay), and
163/// z14 traffic was the layer's dominant cost. Every other layer tiles to the archive
164/// max (14). Enforced in the spill lane filter beside `min_zoom`, so no spill format
165/// change: a per-layer table, not a per-feature field.
166pub const MAX_ZOOM_PER_LAYER: [u8; 10] = [
167 14, // landtype
168 14, // roads
169 12, // boundaries (overzoomed at z13+)
170 14, // buildings
171 14, // places
172 14, // poi
173 14, // transit
174 13, // traffic (overzoomed at z14; ids unaffected)
175 14, // junction
176 14, // safety
177];
178
179/// The cap for `layer`, or 14 (no cap) for an id outside the table.
180pub fn max_zoom_for_layer(layer: u8) -> u8 {
181 MAX_ZOOM_PER_LAYER.get(layer as usize).copied().unwrap_or(14)
182}
183
184/// Which layers a build is producing.
185#[derive(Debug, Clone, Copy, PartialEq, Eq)]
186pub struct Layers {
187 pub landtype: bool,
188 pub buildings: bool,
189 pub roads: bool,
190 pub boundaries: bool,
191 pub places: bool,
192 pub poi: bool,
193 pub transit: bool,
194 pub traffic: bool,
195 pub junction: bool,
196}
197
198impl Layers {
199 pub fn all() -> Layers {
200 Layers {
201 landtype: true,
202 buildings: true,
203 roads: true,
204 boundaries: true,
205 places: true,
206 poi: true,
207 transit: true,
208 traffic: true,
209 junction: true,
210 }
211 }
212}
213
214/// Classify one element's tags, or `None` for the overwhelming majority that are not drawn.
215///
216/// Ordered and first-match-wins. `is_way` distinguishes a way from a relation, which matters
217/// because a closed way's area-ness is a tag question while a multipolygon relation is always an
218/// area.
219///
220/// Every build carries all 9 layers, so there is no layer selection to gate on.
221pub fn classify(tags: &(impl TagSource + ?Sized), is_way: bool, layers: Layers) -> Option<Class> {
222 debug_assert_eq!(layers, Layers::all(), "every build carries all 9 layers");
223 // The early half of `landtype` (islands, cliffs, water) at the old earth+water position:
224 // a `natural=water` way that also carries `building=yes` is water, because water is
225 // asked first.
226 if let Some(class) = landtype::classify_early(tags, is_way) {
227 return Some(class);
228 }
229 // Before buildings, because a road bridge over a building passage is a road.
230 if let Some(class) = roads::classify(tags) {
231 return Some(class);
232 }
233 if let Some(class) = buildings::classify(tags) {
234 return Some(class);
235 }
236 if let Some(class) = boundaries::classify(tags) {
237 return Some(class);
238 }
239 // The late half of `landtype` (surfaces, human use) at the old land position: last among
240 // geometry, because it is the layer everything else is drawn on top of.
241 if let Some(class) = landtype::classify_late(tags) {
242 return Some(class);
243 }
244 // Labels last of all: an area-mapped feature keeps its fill (a park stays a `landuse`
245 // polygon, a museum its `buildings` footprint) and only what no geometry layer claimed —
246 // overwhelmingly nodes — becomes a point label. Ways that reach here are centroided by
247 // extract; see `places` for why points.
248 if let Some(class) = places::classify(tags) {
249 return Some(class);
250 }
251 if let Some(class) = poi::classify(tags) {
252 return Some(class);
253 }
254 None
255}
256
257/// A label's display name for a classified feature, or `None` when the layer carries none.
258///
259/// `places` and `poi` name points; `roads` and `water` name their lines (a street or a river) so
260/// the renderer can curve a label along the centreline. All four coalesce `name:en` then `name`,
261/// the same order the reference style does. Called by extract at each classify site; the name
262/// travels beside the class into the spill and is interned per tile with no format cost — the name
263/// table already exists.
264pub fn display_name(tags: &(impl TagSource + ?Sized), layer: u8) -> Option<String> {
265 match layer {
266 dict::LAYER_PLACES => places::display_name(tags),
267 dict::LAYER_POI => poi::display_name(tags),
268 dict::LAYER_ROADS | dict::LAYER_LANDTYPE => line_name(tags),
269 _ => None,
270 }
271}
272
273/// The coalesced `name:en`/`name` of a line feature, trimmed, or `None` when it has neither.
274///
275/// The same rule [`places::display_name`] applies, spelled out here because a road or a river is
276/// not a `places` label and reusing that function would read as one.
277fn line_name(tags: &(impl TagSource + ?Sized)) -> Option<String> {
278 tags.get("name:en")
279 .or_else(|| tags.get("name"))
280 .map(str::trim)
281 .filter(|name| !name.is_empty())
282 .map(str::to_string)
283}
284
285/// The `osmium tags-filter` expressions that pre-screen each layer, as one list.
286///
287/// Reading three tags to reject a feature instead of the thirty the rules would read between them.
288/// A superset of what the rules accept, so a screen that lets something through is harmless and one
289/// that rejects something is a bug.
290///
291/// Every build carries all 9 layers, so the screen is unconditional.
292pub fn filters() -> Vec<&'static str> {
293 let mut out = Vec::new();
294 out.extend_from_slice(landtype::FILTERS);
295 out.extend_from_slice(roads::FILTERS);
296 out.extend_from_slice(buildings::FILTERS);
297 out.extend_from_slice(boundaries::FILTERS);
298 out.extend_from_slice(places::FILTERS);
299 out.extend_from_slice(poi::FILTERS);
300 out.extend_from_slice(safety::FILTERS);
301 // No `transit` entry: the layer's geometry comes from a GTFS export rather than the `.osm.pbf`,
302 // and the one tag it still reads — `station`, for a station POI's `kind_detail` — is screened by
303 // `poi::FILTERS`.
304 out
305}
306
307#[cfg(test)]
308mod tests {
309 use super::*;
310
311 /// Every name this crate writes has to be in the dictionary, or [`kind`] and [`detail`] panic
312 /// at runtime on whichever feature happens to hit that rule first.
313 #[test]
314 fn every_name_this_schema_uses_is_in_the_dictionary() {
315 for name in landtype::KINDS
316 .iter()
317 .chain(buildings::KINDS)
318 .chain(roads::KINDS)
319 .chain(boundaries::KINDS)
320 .chain(places::KINDS)
321 .chain(poi::KINDS)
322 .chain(safety::KINDS)
323 {
324 assert!(
325 dict::KINDS.contains(name),
326 "the schema names kind `{name}`, which the dictionary has no id for",
327 );
328 assert_eq!(dict::KINDS[kind(name) as usize - 1], *name);
329 }
330 for name in roads::DETAILS {
331 assert!(
332 dict::DETAILS.contains(name),
333 "the schema names detail `{name}`, which the dictionary has no id for",
334 );
335 assert_eq!(dict::DETAILS[detail(name) as usize - 1], *name);
336 }
337 }
338
339 #[test]
340 fn every_build_carries_all_nine_layers() {
341 let all = Layers::all();
342 for layer in [
343 all.landtype,
344 all.buildings,
345 all.roads,
346 all.boundaries,
347 all.places,
348 all.poi,
349 all.transit,
350 all.traffic,
351 all.junction,
352 ] {
353 assert!(layer, "every build carries all 9 layers");
354 }
355 }
356
357 /// Order is load-bearing and first match wins. A way tagged as both a road and a building is a
358 /// road, because a building passage is something you drive through.
359 #[test]
360 fn the_rules_are_ordered_and_the_first_match_wins() {
361 let both: &[(&str, &str)] = &[("highway", "residential"), ("building", "yes")];
362 let class = classify(both, true, Layers::all()).expect("classified");
363 assert_eq!(class.layer, dict::LAYER_ROADS);
364 // And water is asked before either.
365 let water: &[(&str, &str)] =
366 &[("natural", "water"), ("highway", "residential"), ("building", "yes")];
367 assert_eq!(
368 classify(water, true, Layers::all()).expect("water").layer,
369 dict::LAYER_LANDTYPE
370 );
371 }
372
373 #[test]
374 fn the_pre_screen_is_a_superset_of_what_the_rules_accept() {
375 // Not provable in general, so this pins the shape: the screen is a list of tag *keys* the
376 // rules actually read, in osmium's `tags-filter` spelling, and no layer has an empty one —
377 // an empty screen would let every element in the file through to the rules.
378 let all = filters();
379 assert!(!all.is_empty());
380 for filter in &all {
381 assert!(!filter.is_empty(), "an empty screen matches everything");
382 assert!(!filter.contains(' '), "`{filter}` is not a bare tag key");
383 }
384 // Every key a rule reads for a *decision* has to be in the screen, or the rule never runs.
385 // `water` is what `landtype`'s reservoir rule reads alongside `landuse`; `man_made` is
386 // the pier rule; `public_transport` the platform rule.
387 for key in [
388 "natural",
389 "waterway",
390 "landuse",
391 "water",
392 "building",
393 "highway",
394 "railway",
395 "boundary",
396 "place",
397 "leisure",
398 "amenity",
399 "shop",
400 "tourism",
401 "aeroway",
402 "man_made",
403 "public_transport",
404 "name",
405 "route",
406 "station",
407 "enforcement",
408 ] {
409 assert!(all.contains(&key), "the screen omits `{key}`");
410 }
411 // `station` is what `transit::station_detail` reads, and it is screened by
412 // `poi::FILTERS` — otherwise every station silently loses its mode.
413 assert!(all.contains(&"station"), "the screen omits `station`");
414 }
415
416 #[test]
417 fn the_landtype_wash_tiles_to_z14_and_boundaries_keep_z13() {
418 use tilecodec::mamaps::dict;
419 // The merged wash tiles to the archive max (crisp parks and shorelines under z14
420 // streets); boundaries keep z13 (lines carry sub-10m wiggles a 2x stretch could
421 // straighten).
422 assert_eq!(max_zoom_for_layer(dict::LAYER_LANDTYPE), 14, "the wash is street detail");
423 assert_eq!(max_zoom_for_layer(dict::LAYER_BOUNDARIES), 12, "lines overzoom past z12");
424 // Traffic stops at z13 and overzooms at z14: congestion ribbons stretch 2x
425 // (sub-pixel for an overlay) while the ids still match 1:1.
426 assert_eq!(max_zoom_for_layer(dict::LAYER_TRAFFIC), 13, "traffic overzooms at z14");
427 for layer in [
428 dict::LAYER_ROADS,
429 dict::LAYER_BUILDINGS,
430 dict::LAYER_PLACES,
431 dict::LAYER_POI,
432 dict::LAYER_TRANSIT,
433 dict::LAYER_JUNCTION,
434 dict::LAYER_SAFETY,
435 ] {
436 assert_eq!(max_zoom_for_layer(layer), 14, "layer {layer} is street detail");
437 }
438 assert_eq!(max_zoom_for_layer(99), 14, "unknown layer is uncapped");
439 }
440}