Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / scripts / maps / mamaps_build / src / schema / mod.rs
mod.rs424 lines · 16.5 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 | |
| 24 | use tilecodec::mamaps::dict; |
| 25 | |
| 26 | pub mod boundaries; |
| 27 | pub mod buildings; |
| 28 | pub mod buildings_extra; |
| 29 | pub mod junction; |
| 30 | pub mod landtype; |
| 31 | pub mod places; |
| 32 | pub mod poi; |
| 33 | pub mod roads; |
| 34 | pub mod roads_extra; |
| 35 | pub mod safety; |
| 36 | pub mod traffic; |
| 37 | pub mod traffic_extra; |
| 38 | pub 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. |
| 45 | pub 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 | |
| 61 | impl 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. |
| 68 | impl 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)] |
| 76 | pub 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 | |
| 106 | impl 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. |
| 141 | pub 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. |
| 149 | pub 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. |
| 166 | pub 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. |
| 180 | pub 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)] |
| 186 | pub 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 | |
| 198 | impl 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. |
| 221 | pub fn classify( |
| 222 | tags: &(impl TagSource + ?Sized), |
| 223 | is_way: bool, |
| 224 | layers: Layers, |
| 225 | ) -> Option<Class> { |
| 226 | debug_assert_eq!(layers, Layers::all(), "every build carries all 9 layers"); |
| 227 | // The early half of `landtype` (islands, cliffs, water) at the old earth+water position: |
| 228 | // a `natural=water` way that also carries `building=yes` is water, because water is |
| 229 | // asked first. |
| 230 | if let Some(class) = landtype::classify_early(tags, is_way) { |
| 231 | return Some(class); |
| 232 | } |
| 233 | // Before buildings, because a road bridge over a building passage is a road. |
| 234 | if let Some(class) = roads::classify(tags) { |
| 235 | return Some(class); |
| 236 | } |
| 237 | if let Some(class) = buildings::classify(tags) { |
| 238 | return Some(class); |
| 239 | } |
| 240 | if let Some(class) = boundaries::classify(tags) { |
| 241 | return Some(class); |
| 242 | } |
| 243 | // The late half of `landtype` (surfaces, human use) at the old land position: last among |
| 244 | // geometry, because it is the layer everything else is drawn on top of. |
| 245 | if let Some(class) = landtype::classify_late(tags) { |
| 246 | return Some(class); |
| 247 | } |
| 248 | // Labels last of all: an area-mapped feature keeps its fill (a park stays a `landuse` |
| 249 | // polygon, a museum its `buildings` footprint) and only what no geometry layer claimed — |
| 250 | // overwhelmingly nodes — becomes a point label. Ways that reach here are centroided by |
| 251 | // extract; see `places` for why points. |
| 252 | if let Some(class) = places::classify(tags) { |
| 253 | return Some(class); |
| 254 | } |
| 255 | if let Some(class) = poi::classify(tags) { |
| 256 | return Some(class); |
| 257 | } |
| 258 | None |
| 259 | } |
| 260 | |
| 261 | /// A label's display name for a classified feature, or `None` when the layer carries none. |
| 262 | /// |
| 263 | /// `places` and `poi` name points; `roads` and `water` name their lines (a street or a river) so |
| 264 | /// the renderer can curve a label along the centreline. All four coalesce `name:en` then `name`, |
| 265 | /// the same order the reference style does. Called by extract at each classify site; the name |
| 266 | /// travels beside the class into the spill and is interned per tile with no format cost — the name |
| 267 | /// table already exists. |
| 268 | pub fn display_name(tags: &(impl TagSource + ?Sized), layer: u8) -> Option<String> { |
| 269 | match layer { |
| 270 | dict::LAYER_PLACES => places::display_name(tags), |
| 271 | dict::LAYER_POI => poi::display_name(tags), |
| 272 | dict::LAYER_ROADS | dict::LAYER_LANDTYPE => line_name(tags), |
| 273 | _ => None, |
| 274 | } |
| 275 | } |
| 276 | |
| 277 | /// The coalesced `name:en`/`name` of a line feature, trimmed, or `None` when it has neither. |
| 278 | /// |
| 279 | /// The same rule [`places::display_name`] applies, spelled out here because a road or a river is |
| 280 | /// not a `places` label and reusing that function would read as one. |
| 281 | fn line_name(tags: &(impl TagSource + ?Sized)) -> Option<String> { |
| 282 | tags.get("name:en") |
| 283 | .or_else(|| tags.get("name")) |
| 284 | .map(str::trim) |
| 285 | .filter(|name| !name.is_empty()) |
| 286 | .map(str::to_string) |
| 287 | } |
| 288 | |
| 289 | /// The `osmium tags-filter` expressions that pre-screen each layer, as one list. |
| 290 | /// |
| 291 | /// Reading three tags to reject a feature instead of the thirty the rules would read between them. |
| 292 | /// A superset of what the rules accept, so a screen that lets something through is harmless and one |
| 293 | /// that rejects something is a bug. |
| 294 | /// |
| 295 | /// Every build carries all 9 layers, so the screen is unconditional. |
| 296 | pub fn filters() -> Vec<&'static str> { |
| 297 | let mut out = Vec::new(); |
| 298 | out.extend_from_slice(landtype::FILTERS); |
| 299 | out.extend_from_slice(roads::FILTERS); |
| 300 | out.extend_from_slice(buildings::FILTERS); |
| 301 | out.extend_from_slice(boundaries::FILTERS); |
| 302 | out.extend_from_slice(places::FILTERS); |
| 303 | out.extend_from_slice(poi::FILTERS); |
| 304 | out.extend_from_slice(safety::FILTERS); |
| 305 | // No `transit` entry: the layer's geometry comes from a GTFS export rather than the `.osm.pbf`, |
| 306 | // and the one tag it still reads — `station`, for a station POI's `kind_detail` — is screened by |
| 307 | // `poi::FILTERS`. |
| 308 | out |
| 309 | } |
| 310 | |
| 311 | #[cfg(test)] |
| 312 | mod tests { |
| 313 | use super::*; |
| 314 | |
| 315 | /// Every name this crate writes has to be in the dictionary, or [`kind`] and [`detail`] panic |
| 316 | /// at runtime on whichever feature happens to hit that rule first. |
| 317 | #[test] |
| 318 | fn every_name_this_schema_uses_is_in_the_dictionary() { |
| 319 | for name in landtype::KINDS |
| 320 | .iter() |
| 321 | .chain(buildings::KINDS) |
| 322 | .chain(roads::KINDS) |
| 323 | .chain(boundaries::KINDS) |
| 324 | .chain(places::KINDS) |
| 325 | .chain(poi::KINDS) |
| 326 | .chain(safety::KINDS) |
| 327 | { |
| 328 | assert!( |
| 329 | dict::KINDS.contains(name), |
| 330 | "the schema names kind `{name}`, which the dictionary has no id for", |
| 331 | ); |
| 332 | assert_eq!(dict::KINDS[kind(name) as usize - 1], *name); |
| 333 | } |
| 334 | for name in roads::DETAILS { |
| 335 | assert!( |
| 336 | dict::DETAILS.contains(name), |
| 337 | "the schema names detail `{name}`, which the dictionary has no id for", |
| 338 | ); |
| 339 | assert_eq!(dict::DETAILS[detail(name) as usize - 1], *name); |
| 340 | } |
| 341 | } |
| 342 | |
| 343 | #[test] |
| 344 | fn every_build_carries_all_nine_layers() { |
| 345 | let all = Layers::all(); |
| 346 | for layer in [ |
| 347 | all.landtype, |
| 348 | all.buildings, |
| 349 | all.roads, |
| 350 | all.boundaries, |
| 351 | all.places, |
| 352 | all.poi, |
| 353 | all.transit, |
| 354 | all.traffic, |
| 355 | all.junction, |
| 356 | ] { |
| 357 | assert!(layer, "every build carries all 9 layers"); |
| 358 | } |
| 359 | } |
| 360 | |
| 361 | /// Order is load-bearing and first match wins. A way tagged as both a road and a building is a |
| 362 | /// road, because a building passage is something you drive through. |
| 363 | #[test] |
| 364 | fn the_rules_are_ordered_and_the_first_match_wins() { |
| 365 | let both: &[(&str, &str)] = &[("highway", "residential"), ("building", "yes")]; |
| 366 | let class = classify(both, true, Layers::all()).expect("classified"); |
| 367 | assert_eq!(class.layer, dict::LAYER_ROADS); |
| 368 | // And water is asked before either. |
| 369 | let water: &[(&str, &str)] = |
| 370 | &[("natural", "water"), ("highway", "residential"), ("building", "yes")]; |
| 371 | assert_eq!(classify(water, true, Layers::all()).expect("water").layer, dict::LAYER_LANDTYPE); |
| 372 | } |
| 373 | |
| 374 | #[test] |
| 375 | fn the_pre_screen_is_a_superset_of_what_the_rules_accept() { |
| 376 | // Not provable in general, so this pins the shape: the screen is a list of tag *keys* the |
| 377 | // rules actually read, in osmium's `tags-filter` spelling, and no layer has an empty one — |
| 378 | // an empty screen would let every element in the file through to the rules. |
| 379 | let all = filters(); |
| 380 | assert!(!all.is_empty()); |
| 381 | for filter in &all { |
| 382 | assert!(!filter.is_empty(), "an empty screen matches everything"); |
| 383 | assert!(!filter.contains(' '), "`{filter}` is not a bare tag key"); |
| 384 | } |
| 385 | // Every key a rule reads for a *decision* has to be in the screen, or the rule never runs. |
| 386 | // `water` is what `landtype`'s reservoir rule reads alongside `landuse`; `man_made` is |
| 387 | // the pier rule; `public_transport` the platform rule. |
| 388 | for key in [ |
| 389 | "natural", "waterway", "landuse", "water", "building", "highway", "railway", |
| 390 | "boundary", "place", "leisure", "amenity", "shop", "tourism", "aeroway", "man_made", |
| 391 | "public_transport", "name", "route", "station", "enforcement", |
| 392 | ] { |
| 393 | assert!(all.contains(&key), "the screen omits `{key}`"); |
| 394 | } |
| 395 | // `station` is what `transit::station_detail` reads, and it is screened by |
| 396 | // `poi::FILTERS` — otherwise every station silently loses its mode. |
| 397 | assert!(all.contains(&"station"), "the screen omits `station`"); |
| 398 | } |
| 399 | |
| 400 | #[test] |
| 401 | fn the_landtype_wash_tiles_to_z14_and_boundaries_keep_z13() { |
| 402 | use tilecodec::mamaps::dict; |
| 403 | // The merged wash tiles to the archive max (crisp parks and shorelines under z14 |
| 404 | // streets); boundaries keep z13 (lines carry sub-10m wiggles a 2x stretch could |
| 405 | // straighten). |
| 406 | assert_eq!(max_zoom_for_layer(dict::LAYER_LANDTYPE), 14, "the wash is street detail"); |
| 407 | assert_eq!(max_zoom_for_layer(dict::LAYER_BOUNDARIES), 12, "lines overzoom past z12"); |
| 408 | // Traffic stops at z13 and overzooms at z14: congestion ribbons stretch 2x |
| 409 | // (sub-pixel for an overlay) while the ids still match 1:1. |
| 410 | assert_eq!(max_zoom_for_layer(dict::LAYER_TRAFFIC), 13, "traffic overzooms at z14"); |
| 411 | for layer in [ |
| 412 | dict::LAYER_ROADS, |
| 413 | dict::LAYER_BUILDINGS, |
| 414 | dict::LAYER_PLACES, |
| 415 | dict::LAYER_POI, |
| 416 | dict::LAYER_TRANSIT, |
| 417 | dict::LAYER_JUNCTION, |
| 418 | dict::LAYER_SAFETY, |
| 419 | ] { |
| 420 | assert_eq!(max_zoom_for_layer(layer), 14, "layer {layer} is street detail"); |
| 421 | } |
| 422 | assert_eq!(max_zoom_for_layer(99), 14, "unknown layer is uncapped"); |
| 423 | } |
| 424 | } |