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

Modern-Apps.git / scripts / maps / osm_ingest / src / roads.rs

roads.rs442 lines · 17.6 KiBRaw
1//! The `roads` layer: road geometry with the speed, lane and width attributes the
2//! app needs to draw and label roads itself.
3//!
4//! This is the layer that retires [`crate::maxspeed`]. That one existed to answer
5//! exactly one question -- what is the posted limit under the puck -- and carried a
6//! way's geometry only as the thing the answer was attached to. Owning road
7//! rendering in-app needs the same geometry plus lanes and width, and a second
8//! near-identical layer of every road in the world is not worth a property.
9//!
10//! ## Speed is carried BOTH ways, deliberately
11//!
12//! `maxspeed` is the OSM tag verbatim and `maxspeed_kmh` is
13//! [`crate::tags::parse_maxspeed`]'s km/h number. Neither is redundant:
14//!
15//! * The **number** is what a data-driven style expression can compare against,
16//! because MVT gives the app an int and not a string it has to parse per feature.
17//! * The **raw string** is the only thing that survives `maxspeed=DE:urban`,
18//! `GB:nsl_single` and friends -- `parse_maxspeed` returns 0 for every implicit
19//! country scheme -- and the only thing that records whether a limit was authored
20//! in mph, which is what decides the unit the app's speed badge renders in.
21//! `OsmMaxspeed.kt::parseMaxspeed` resolves both and stays the consumer of record.
22//!
23//! `maxspeed_kmh` is **omitted, not zeroed**, when there is no numeric limit, so
24//! `none`, `walk`, `signals` and `DE:urban` are absent rather than claiming a limit
25//! of nought. `crate::maxspeed`'s guard test spells out what each of them becomes.
26//!
27//! ## Lane masks are the graph's, unchanged
28//!
29//! `turn_lanes_forward` / `turn_lanes_backward` are `|`-separated decimal
30//! [`crate::tags`] `LANE_*` masks, one token per lane, left to right -- the same
31//! bits, in the same order, that the routing graph writes and
32//! `maps/src/main/rust/src/graph.rs` reads. Which tag feeds which direction follows
33//! `graph_build::way_attrs` exactly, so a road cannot describe its lanes one way to
34//! the router and another to the renderer.
35
36use crate::geojson::{osm_ref, Feature, Geometry, Value};
37use crate::tags;
38
39/// The `highway=*` values this layer carries: the set [`crate::tags::get_hw_id`] gives
40/// a non-zero id, since that id *is* the emitted `class`, plus the `*_link` ramps it
41/// has no id for (see [`base_highway`]).
42pub const CLASSES: [&str; 15] = [
43 "motorway",
44 "trunk",
45 "primary",
46 "secondary",
47 "tertiary",
48 "unclassified",
49 "residential",
50 "service",
51 "living_street",
52 "pedestrian",
53 "track",
54 "footway",
55 "cycleway",
56 "path",
57 "steps",
58];
59
60/// The `*_link` values, which are slip roads of a [`CLASSES`] parent.
61pub const LINK_CLASSES: [&str; 5] = [
62 "motorway_link",
63 "trunk_link",
64 "primary_link",
65 "secondary_link",
66 "tertiary_link",
67];
68
69/// The `osmium tags-filter` expression, kept in step with [`CLASSES`] and
70/// [`LINK_CLASSES`] by a test.
71pub const FILTERS: [&str; 1] = ["highway=motorway,trunk,primary,secondary,tertiary,\
72unclassified,residential,service,living_street,pedestrian,track,footway,cycleway,\
73path,steps,motorway_link,trunk_link,primary_link,secondary_link,tertiary_link"];
74
75#[derive(Debug, Default, Clone, Copy)]
76pub struct RoadTags<'a> {
77 pub highway: Option<&'a str>,
78 pub maxspeed: Option<&'a str>,
79 pub lanes: Option<&'a str>,
80 pub lanes_forward: Option<&'a str>,
81 pub lanes_backward: Option<&'a str>,
82 pub turn_lanes: Option<&'a str>,
83 pub turn_lanes_forward: Option<&'a str>,
84 pub turn_lanes_backward: Option<&'a str>,
85 pub oneway: Option<&'a str>,
86 pub width: Option<&'a str>,
87 pub bridge: Option<&'a str>,
88 pub tunnel: Option<&'a str>,
89 pub layer: Option<&'a str>,
90}
91
92/// The parent class of a `highway` value: `motorway_link` -> `motorway`.
93///
94/// A slip road IS its parent class as far as drawing goes -- it is the same asphalt at
95/// the same width, and a map that omits interchange ramps has holes in every
96/// motorway junction. [`crate::tags::get_hw_id`] maps the five real `*_link` values
97/// itself; stripping here as well keeps the parent check for any other suffix.
98pub fn base_highway(value: Option<&str>) -> Option<&str> {
99 let v = value?;
100 Some(v.strip_suffix("_link").unwrap_or(v))
101}
102
103/// The road class number, or `None` for a `highway` value that is not a road.
104pub fn classify(t: &RoadTags) -> Option<u8> {
105 match tags::get_hw_id(base_highway(t.highway)) {
106 0 => None,
107 id => Some(id),
108 }
109}
110
111/// An OSM flag tag that is set. Absent, empty and `no` are all unset; anything
112/// else counts, because `bridge=viaduct` and `tunnel=building_passage` are as much
113/// a bridge and a tunnel as `yes` is.
114fn flag(v: Option<&str>) -> bool {
115 matches!(v, Some(s) if !s.is_empty() && s != "no")
116}
117
118/// `layer=*` as a signed number for draw order. Absent or unparseable is 0, the
119/// same as ground level; the `1;2` and `0.5` forms real data contains are not
120/// orderings this layer can express, so they get ground level rather than a guess.
121pub fn parse_layer(v: Option<&str>) -> i32 {
122 v.and_then(|s| s.trim().parse::<i32>().ok()).unwrap_or(0)
123}
124
125/// Per-lane `LANE_*` masks for each direction, `(forward, backward)`.
126///
127/// A verbatim copy of `graph_build::way_attrs`'s derivation: forward lanes come
128/// from `turn:lanes:forward`, or from a plain `turn:lanes` when the way is a
129/// oneway; backward from `turn:lanes:backward`, and a oneway has none. The plain
130/// `lanes*` counts only pad or truncate a real `turn:lanes` list.
131pub fn lane_masks(t: &RoadTags) -> (Vec<u16>, Vec<u16>) {
132 let oneway = is_oneway(t);
133 let count_all = tags::parse_int_tag(t.lanes);
134 let count_fwd = tags::parse_int_tag(t.lanes_forward);
135 let count_bwd = tags::parse_int_tag(t.lanes_backward);
136
137 let fwd_spec = t.turn_lanes_forward.or(if oneway { t.turn_lanes } else { None });
138 let fwd_hint = if count_fwd > 0 {
139 count_fwd
140 } else if oneway {
141 count_all
142 } else {
143 0
144 };
145 let bwd_spec = if oneway { None } else { t.turn_lanes_backward };
146 (
147 tags::build_dir_lanes(fwd_spec, fwd_hint),
148 tags::build_dir_lanes(bwd_spec, count_bwd),
149 )
150}
151
152/// `oneway=yes`, and only that -- the same test the routing graph applies, so the
153/// two cannot disagree about a road. `oneway=-1` is a direction rather than a
154/// flag and neither models it.
155pub fn is_oneway(t: &RoadTags) -> bool {
156 t.oneway == Some("yes")
157}
158
159/// One direction's masks as the `|`-separated decimal tokens the property holds.
160pub fn pack_lanes(masks: &[u16]) -> String {
161 let mut out = String::new();
162 for (i, m) in masks.iter().enumerate() {
163 if i > 0 {
164 out.push('|');
165 }
166 out.push_str(&m.to_string());
167 }
168 out
169}
170
171/// Build the emitted feature.
172///
173/// Every attribute past `class` and `osm_id` is **omitted when it has nothing to
174/// say**, rather than written as a zero or an empty string. At planet scale this is
175/// most of the layer's size: the great majority of roads carry no `turn:lanes`, no
176/// `width` and no `layer`, and a property present on every feature is a property
177/// paid for on every feature.
178pub fn feature<'a>(
179 class: u8,
180 t: &RoadTags<'a>,
181 geometry: Geometry,
182 way_id: i64,
183) -> Feature<'a> {
184 let mut props: Vec<(&'a str, Value)> = vec![("class", Value::num(class))];
185
186 if let Some(v) = t.maxspeed.filter(|v| !v.is_empty()) {
187 props.push(("maxspeed", Value::str(v)));
188 }
189 let kmh = tags::parse_maxspeed(t.maxspeed);
190 if kmh > 0 {
191 props.push(("maxspeed_kmh", Value::num(kmh)));
192 }
193
194 let lanes = tags::parse_int_tag(t.lanes);
195 if lanes > 0 {
196 props.push(("lanes", Value::num(lanes.min(tags::MAX_LANES))));
197 }
198 let (fwd, bwd) = lane_masks(t);
199 if !fwd.is_empty() {
200 props.push(("turn_lanes_forward", Value::str(pack_lanes(&fwd))));
201 }
202 if !bwd.is_empty() {
203 props.push(("turn_lanes_backward", Value::str(pack_lanes(&bwd))));
204 }
205
206 if is_oneway(t) {
207 props.push(("oneway", Value::num(1u8)));
208 }
209 let width = tags::parse_width_m(t.width);
210 if width > 0.0 {
211 // Two decimals: centimetre resolution is already finer than the tag is
212 // ever surveyed to, and a fixed form keeps two runs byte-identical.
213 props.push(("width", Value::Raw(format!("{width:.2}"))));
214 }
215 if flag(t.bridge) {
216 props.push(("bridge", Value::num(1u8)));
217 }
218 if flag(t.tunnel) {
219 props.push(("tunnel", Value::num(1u8)));
220 }
221 let layer = parse_layer(t.layer);
222 if layer != 0 {
223 props.push(("layer", Value::num(layer)));
224 }
225
226 props.push(("osm_id", osm_ref("way", way_id)));
227 Feature { geometry, props }
228}
229
230#[cfg(test)]
231mod tests {
232 use super::*;
233 use crate::tags::{LANE_LEFT, LANE_NONE, LANE_RIGHT, LANE_THROUGH};
234
235 fn road(highway: &str) -> RoadTags<'_> {
236 RoadTags { highway: Some(highway), ..Default::default() }
237 }
238
239 fn keys<'a>(f: &Feature<'a>) -> Vec<&'a str> {
240 f.props.iter().map(|(k, _)| *k).collect()
241 }
242
243 fn rendered(f: &Feature) -> String {
244 let mut line = Vec::new();
245 crate::geojson::render_feature(f, &mut line);
246 String::from_utf8(line).unwrap()
247 }
248
249 #[test]
250 fn the_class_is_the_graphs_own_road_type_number() {
251 // Sharing `get_hw_id` is what keeps the rendered class and the routed
252 // class the same fact about a road.
253 assert_eq!(classify(&road("motorway")), Some(1));
254 assert_eq!(classify(&road("residential")), Some(7));
255 assert_eq!(classify(&road("steps")), Some(15));
256 // Not a road: no feature at all.
257 assert_eq!(classify(&road("proposed")), None);
258 assert_eq!(classify(&road("")), None);
259 assert_eq!(classify(&RoadTags::default()), None);
260 }
261
262 #[test]
263 fn a_slip_road_takes_its_parent_class() {
264 // `get_hw_id` has no id for a `*_link` and cannot be given one without
265 // renumbering the graph's on-disk road types, so the suffix is dropped.
266 assert_eq!(classify(&road("motorway_link")), classify(&road("motorway")));
267 assert_eq!(classify(&road("tertiary_link")), Some(5));
268 assert_eq!(base_highway(Some("primary_link")), Some("primary"));
269 assert_eq!(base_highway(Some("primary")), Some("primary"));
270 // Not every `_link` suffix is a road: the parent still has to classify.
271 assert_eq!(classify(&road("raceway_link")), None);
272 }
273
274 #[test]
275 fn the_pbf_filter_and_the_class_set_agree() {
276 let select = crate::select::Select::parse(&FILTERS).unwrap();
277 for value in CLASSES {
278 assert_ne!(
279 tags::get_hw_id(Some(value)),
280 0,
281 "highway={value} is filtered in but has no class"
282 );
283 assert!(
284 select.matches(|k| if k == "highway" { Some(value) } else { None }),
285 "highway={value} classifies but is pre-filtered out"
286 );
287 }
288 // Every ramp is let through and lands on its parent's class.
289 for value in LINK_CLASSES {
290 assert!(
291 select.matches(|k| if k == "highway" { Some(value) } else { None }),
292 "highway={value} classifies but is pre-filtered out"
293 );
294 let parent = value.strip_suffix("_link").unwrap();
295 assert_eq!(classify(&road(value)), classify(&road(parent)), "{value}");
296 }
297 // And nothing outside the set gets through.
298 for value in ["proposed", "construction", "raceway", "bus_guideway"] {
299 assert_eq!(tags::get_hw_id(Some(value)), 0, "{value}");
300 assert!(!select.matches(|k| if k == "highway" { Some(value) } else { None }));
301 }
302 }
303
304 #[test]
305 fn speed_is_carried_as_both_the_raw_tag_and_a_number() {
306 let t = RoadTags { highway: Some("residential"), maxspeed: Some("25 mph"), ..Default::default() };
307 let f = feature(7, &t, Geometry::LineString(vec![]), 3001);
308 assert_eq!(keys(&f), ["class", "maxspeed", "maxspeed_kmh", "osm_id"]);
309 let s = rendered(&f);
310 assert!(s.contains("\"maxspeed\":\"25 mph\""), "{s}");
311 assert!(s.contains("\"maxspeed_kmh\":40"), "{s}");
312 }
313
314 #[test]
315 fn a_speed_the_number_cannot_hold_keeps_its_string_and_omits_the_number() {
316 // The whole reason both are emitted. `parse_maxspeed` answers 0 for every
317 // one of these, and 0 is not a speed limit, so the property is absent and
318 // the app falls back to parsing the raw value.
319 for raw in ["none", "walk", "signals", "DE:urban", "GB:nsl_single"] {
320 let t = RoadTags { highway: Some("motorway"), maxspeed: Some(raw), ..Default::default() };
321 let f = feature(1, &t, Geometry::LineString(vec![]), 1);
322 assert_eq!(keys(&f), ["class", "maxspeed", "osm_id"], "{raw}");
323 assert!(rendered(&f).contains(&format!("\"maxspeed\":\"{raw}\"")), "{raw}");
324 }
325 // And a way with no maxspeed tag at all carries neither.
326 let f = feature(7, &road("residential"), Geometry::LineString(vec![]), 1);
327 assert_eq!(keys(&f), ["class", "osm_id"]);
328 }
329
330 #[test]
331 fn turn_lanes_pack_to_the_graphs_masks_in_lane_order() {
332 let t = RoadTags {
333 highway: Some("primary"),
334 turn_lanes_forward: Some("left|through|through;right"),
335 ..Default::default()
336 };
337 let (fwd, bwd) = lane_masks(&t);
338 assert_eq!(fwd, vec![LANE_LEFT, LANE_THROUGH, LANE_THROUGH | LANE_RIGHT]);
339 assert!(bwd.is_empty());
340 assert_eq!(
341 pack_lanes(&fwd),
342 format!("{LANE_LEFT}|{LANE_THROUGH}|{}", LANE_THROUGH | LANE_RIGHT)
343 );
344 let f = feature(3, &t, Geometry::LineString(vec![]), 1);
345 assert_eq!(keys(&f), ["class", "turn_lanes_forward", "osm_id"]);
346 }
347
348 #[test]
349 fn lane_direction_derivation_matches_the_routing_graph() {
350 // A plain `turn:lanes` belongs to the forward direction only on a oneway;
351 // on a two-way street it is ambiguous and the graph takes neither side.
352 let two_way = RoadTags {
353 highway: Some("residential"),
354 turn_lanes: Some("left|through"),
355 ..Default::default()
356 };
357 assert_eq!(lane_masks(&two_way), (Vec::new(), Vec::new()));
358
359 let one_way = RoadTags { oneway: Some("yes"), ..two_way };
360 assert_eq!(lane_masks(&one_way).0, vec![LANE_LEFT, LANE_THROUGH]);
361 assert!(lane_masks(&one_way).1.is_empty());
362
363 // A oneway never carries backward lanes, whatever the tag says.
364 let contradictory = RoadTags {
365 oneway: Some("yes"),
366 turn_lanes_backward: Some("through"),
367 ..two_way
368 };
369 assert!(lane_masks(&contradictory).1.is_empty());
370
371 // `lanes:forward` pads a short list; on a oneway plain `lanes` does.
372 let padded = RoadTags {
373 highway: Some("primary"),
374 turn_lanes_forward: Some("left"),
375 lanes_forward: Some("3"),
376 ..Default::default()
377 };
378 assert_eq!(lane_masks(&padded).0, vec![LANE_LEFT, LANE_NONE, LANE_NONE]);
379 }
380
381 #[test]
382 fn a_mistagged_lane_count_cannot_become_an_allocation() {
383 // `MAX_LANES` guards both the padding and the emitted count.
384 let t = RoadTags {
385 highway: Some("motorway"),
386 turn_lanes_forward: Some("through"),
387 lanes: Some("999999999"),
388 lanes_forward: Some("999999999"),
389 ..Default::default()
390 };
391 assert_eq!(lane_masks(&t).0.len(), tags::MAX_LANES as usize);
392 let s = rendered(&feature(1, &t, Geometry::LineString(vec![]), 1));
393 assert!(s.contains(&format!("\"lanes\":{}", tags::MAX_LANES)), "{s}");
394 }
395
396 #[test]
397 fn width_converts_feet_and_rejects_nonsense() {
398 assert!((tags::parse_width_m(Some("3.5")) - 3.5).abs() < 1e-9);
399 assert!((tags::parse_width_m(Some("3.5 m")) - 3.5).abs() < 1e-9);
400 assert_eq!(tags::parse_width_m(Some("wide")), 0.0);
401 assert_eq!(tags::parse_width_m(Some("-2")), 0.0);
402 assert_eq!(tags::parse_width_m(None), 0.0);
403 // Every form of feet, however it is spaced or cased. Reading one of these as
404 // metres would make a residential street wider than a motorway.
405 for v in ["10 ft", "10ft", "10 FT ", "10 Feet", "10'"] {
406 assert!((tags::parse_width_m(Some(v)) - 3.048).abs() < 1e-9, "{v}");
407 }
408
409 // Emitted with two decimals, so two runs are byte-identical.
410 let t = RoadTags { highway: Some("residential"), width: Some("10 ft"), ..Default::default() };
411 assert!(rendered(&feature(7, &t, Geometry::LineString(vec![]), 1)).contains("\"width\":3.05"));
412 }
413
414 #[test]
415 fn draw_order_flags_survive_their_real_tag_values() {
416 // `bridge=viaduct` is a bridge; `tunnel=no` is not a tunnel.
417 let t = RoadTags {
418 highway: Some("motorway"),
419 bridge: Some("viaduct"),
420 tunnel: Some("no"),
421 layer: Some("-1"),
422 ..Default::default()
423 };
424 let f = feature(1, &t, Geometry::LineString(vec![]), 1);
425 assert_eq!(keys(&f), ["class", "bridge", "layer", "osm_id"]);
426 assert!(rendered(&f).contains("\"layer\":-1"));
427
428 // Ground level is the default, so it is never written.
429 for v in [None, Some("0"), Some(""), Some("1;2"), Some("half")] {
430 assert_eq!(parse_layer(v), 0, "{v:?}");
431 }
432 }
433
434 #[test]
435 fn a_bare_road_is_class_plus_osm_id_and_nothing_else() {
436 // The common case at planet scale, and the reason every other property is
437 // conditional.
438 let f = feature(7, &road("residential"), Geometry::LineString(vec![(0.0, 0.0), (1.0, 1.0)]), 42);
439 assert_eq!(keys(&f), ["class", "osm_id"]);
440 assert!(rendered(&f).contains("\"osm_id\":\"way/42\""));
441 }
442}