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

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

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