use std::sync::Arc;
use geo::{Coord, Euclidean, Length, LineString};
use geolith::names::push_names;
use crate::layers::Layer;
use crate::source::input::{DataSource, InputFeature};
use crate::tile::feature::PropValue;
use super::buildings::ProcessedFeature;
const MAX_SHIELDS: usize = 6;
const NETWORK_PRIORITY: [&[&str]; 3] = [
&["US:I", "NL:A", "BAB"],
&["US:US", "NL:N"],
&["US:", "NL:S-road"],
];
const INTERNATIONAL_NETWORKS: [&str; 2] = ["e-road", "AsianHighway"];
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct Shield {
pub(crate) text: String,
pub(crate) network: String,
}
fn normalize_network(network: &str) -> String {
if network.starts_with("NL:S:") {
return "NL:S-road".into();
}
if network.starts_with("US:") {
for suffix in [":Local", ":Express"] {
if let Some(base) = network.strip_suffix(suffix) {
return base.into();
}
}
}
network.into()
}
fn network_rank(network: &str) -> usize {
if INTERNATIONAL_NETWORKS.contains(&network) {
return NETWORK_PRIORITY.len() + 1;
}
NETWORK_PRIORITY
.iter()
.position(|tier| tier.iter().any(|p| network.starts_with(p)))
.unwrap_or(NETWORK_PRIORITY.len())
}
pub(crate) fn route_shields(relations: &[crate::source::input::RelationInfo]) -> Vec<Shield> {
let mut shields: Vec<Shield> = relations
.iter()
.filter(|r| {
r.tags.get("type").is_some_and(|t| t == "route")
&& r.tags.get("route").is_some_and(|t| t == "road")
})
.filter_map(|r| {
let network = normalize_network(r.tags.get("network")?);
let text: String = r
.tags
.get("ref")?
.chars()
.filter(|c| !c.is_whitespace())
.collect();
(!text.is_empty()).then_some(Shield { text, network })
})
.collect();
shields.sort_by(|a, b| {
(network_rank(&a.network), &a.text, &a.network).cmp(&(
network_rank(&b.network),
&b.text,
&b.network,
))
});
shields.dedup();
shields.truncate(MAX_SHIELDS);
shields
}
const SHIELD_KEYS: [(&str, &str); MAX_SHIELDS] = [
("network_1", "shield_text_1"),
("network_2", "shield_text_2"),
("network_3", "shield_text_3"),
("network_4", "shield_text_4"),
("network_5", "shield_text_5"),
("network_6", "shield_text_6"),
];
fn push_shields(properties: &mut Vec<(String, PropValue)>, shields: &[Shield]) {
for (s, (network_key, text_key)) in shields.iter().zip(SHIELD_KEYS) {
properties.push((network_key.into(), PropValue::Str(s.network.clone())));
properties.push((text_key.into(), PropValue::Str(s.text.clone())));
}
if let Some(primary) = shields.first() {
properties.push(("network".into(), PropValue::Str(primary.network.clone())));
properties.push(("shield_text".into(), PropValue::Str(primary.text.clone())));
}
}
const SEGMENT_FLAGS: [&str; 3] = ["is_bridge", "is_tunnel", "is_link"];
const SEGMENT_FLAG_KEYS: [[&str; 2]; 3] = [
["road_flags.is_bridge", "rail_flags.is_bridge"],
["road_flags.is_tunnel", "rail_flags.is_tunnel"],
["road_flags.is_link", "rail_flags.is_link"],
];
pub fn process(feature: &InputFeature) -> Option<ProcessedFeature> {
match &feature.source {
DataSource::Overture { .. } => {
let class = classify_overture(feature)?;
let whole = segment_flags(feature, 0.0, 1.0, true);
Some(overture_feature(
feature,
&class,
feature.geometry.clone(),
whole,
))
}
DataSource::Osm { .. } => process_osm(feature),
_ => None,
}
}
#[must_use]
pub fn process_all(feature: &InputFeature) -> Vec<ProcessedFeature> {
if !matches!(feature.source, DataSource::Overture { .. }) {
return process(feature).into_iter().collect();
}
let Some(class) = classify_overture(feature) else {
return Vec::new();
};
let cuts = flag_cuts(feature);
let line = match feature.geometry.as_ref() {
geo::Geometry::LineString(line) if !cuts.is_empty() => line,
_ => return process(feature).into_iter().collect(),
};
let mut bounds = Vec::with_capacity(cuts.len() + 2);
bounds.push(0.0);
bounds.extend_from_slice(&cuts);
bounds.push(1.0);
let mut out = Vec::with_capacity(bounds.len() - 1);
for pair in bounds.windows(2) {
let (start, end) = (pair[0], pair[1]);
let Some(piece) = sub_line(line, start, end) else {
continue;
};
let flags = segment_flags(feature, start, end, false);
let geometry = Arc::new(geo::Geometry::LineString(piece));
out.push(overture_feature(feature, &class, geometry, flags));
}
out
}
struct OvertureClass {
kind: &'static str,
kind_detail: Option<String>,
min_zoom: u8,
}
fn classify_overture(feature: &InputFeature) -> Option<OvertureClass> {
match feature.get_str("subtype") {
Some("rail") => {
let class = feature.get_str("class").unwrap_or("unknown");
let min_zoom = if class == "standard_gauge" { 11 } else { 14 };
Some(OvertureClass {
kind: "rail",
kind_detail: Some(class.to_string()),
min_zoom,
})
}
Some("water") => Some(OvertureClass {
kind: "ferry",
kind_detail: None,
min_zoom: 11,
}),
Some("road") | None => {
let class = feature.get_str("class").unwrap_or("unknown");
let (kind, min_zoom) = classify_highway(class);
let detail = feature.get_str("subclass").unwrap_or(class);
Some(OvertureClass {
kind,
kind_detail: Some(detail.to_string()),
min_zoom,
})
}
Some(_) => None,
}
}
fn flag_ranges(feature: &InputFeature, keys: [&str; 2]) -> Vec<(f64, f64)> {
keys.into_iter()
.filter_map(|key| feature.get_str(key))
.flat_map(|s| s.split(';'))
.filter_map(|r| {
let (a, b) = r.split_once(':')?;
Some((a.parse().ok()?, b.parse().ok()?))
})
.collect()
}
fn flag_cuts(feature: &InputFeature) -> Vec<f64> {
let mut cuts: Vec<f64> = SEGMENT_FLAG_KEYS
.into_iter()
.flat_map(|keys| flag_ranges(feature, keys))
.flat_map(|(a, b)| [a, b])
.filter(|v| *v > 1e-9 && *v < 1.0 - 1e-9)
.collect();
cuts.sort_by(f64::total_cmp);
cuts.dedup_by(|a, b| (*a - *b).abs() < 1e-9);
cuts
}
fn segment_flags(feature: &InputFeature, start: f64, end: f64, whole_only: bool) -> [bool; 3] {
let mut out = [false; 3];
for (slot, keys) in out.iter_mut().zip(SEGMENT_FLAG_KEYS) {
*slot = flag_ranges(feature, keys).iter().any(|&(a, b)| {
if whole_only {
a <= start + 1e-9 && b >= end - 1e-9
} else {
a < end - 1e-9 && b > start + 1e-9
}
});
}
if feature.get_str("subclass") == Some("link") {
out[2] = true;
}
out
}
fn sub_line(line: &LineString<f64>, start: f64, end: f64) -> Option<LineString<f64>> {
let total = Euclidean.length(line);
if total <= 0.0 || end - start <= 1e-12 {
return None;
}
let (from, to) = (start * total, end * total);
let mut coords: Vec<Coord<f64>> = Vec::with_capacity(line.0.len());
let mut walked = 0.0;
for seg in line.lines() {
let len = (seg.dx().powi(2) + seg.dy().powi(2)).sqrt();
let (seg_from, seg_to) = (walked, walked + len);
if len > 0.0 && seg_to > from && seg_from < to {
let at = |d: f64| {
let t = ((d - seg_from) / len).clamp(0.0, 1.0);
Coord {
x: seg.start.x + seg.dx() * t,
y: seg.start.y + seg.dy() * t,
}
};
if coords.is_empty() {
coords.push(at(from.max(seg_from)));
}
coords.push(at(to.min(seg_to)));
}
walked = seg_to;
}
(coords.len() >= 2).then(|| LineString::new(coords))
}
fn overture_feature(
feature: &InputFeature,
class: &OvertureClass,
geometry: Arc<geo::Geometry<f64>>,
flags: [bool; 3],
) -> ProcessedFeature {
let mut properties = Vec::with_capacity(8);
properties.push(("kind".into(), PropValue::Str(class.kind.into())));
if let Some(detail) = &class.kind_detail {
properties.push(("kind_detail".into(), PropValue::Str(detail.clone())));
}
for (on, flag) in flags.into_iter().zip(SEGMENT_FLAGS) {
if on {
properties.push((flag.into(), PropValue::Bool(true)));
}
}
if let Some(r) = feature.get_str("road_ref").or(feature.get_str("ref")) {
properties.push(("ref".into(), PropValue::Str(r.to_string())));
}
push_names(feature, &mut properties);
properties.push(("sort_rank".into(), PropValue::I64(400)));
properties.push((
"min_zoom".into(),
PropValue::I64((class.min_zoom + 1) as i64),
));
ProcessedFeature {
id: feature.id,
geometry,
layer: Layer::Roads,
min_zoom: class.min_zoom,
max_zoom: 15,
sort_rank: 400,
properties,
}
}
fn process_osm(feature: &InputFeature) -> Option<ProcessedFeature> {
let highway = feature.get_str("highway")?;
if !feature.can_be_line() {
return None;
}
let (kind, min_zoom) = classify_highway(highway);
let is_link = highway.ends_with("_link");
let adjusted_zoom = if is_link {
min_zoom.saturating_add(2)
} else {
min_zoom
};
let service_zoom = if highway == "service" {
match feature.get_str("service") {
Some("parking_aisle") | Some("driveway") => adjusted_zoom.saturating_add(1),
_ => adjusted_zoom,
}
} else {
adjusted_zoom
};
let mut properties = Vec::with_capacity(12);
properties.push(("kind".into(), PropValue::Str(kind.into())));
properties.push(("kind_detail".into(), PropValue::Str(highway.to_string())));
if feature.get_str("bridge").is_some_and(|v| v != "no") {
properties.push(("is_bridge".into(), PropValue::Bool(true)));
} else if feature.get_str("tunnel").is_some_and(|v| v != "no") {
properties.push(("is_tunnel".into(), PropValue::Bool(true)));
}
if feature.get_str("oneway").is_some_and(|v| v == "yes") {
properties.push(("oneway".into(), PropValue::Str("yes".into())));
}
if let Some(r) = feature.get_str("ref") {
properties.push(("ref".into(), PropValue::Str(r.to_string())));
}
push_shields(&mut properties, &route_shields(feature.osm_relations()));
push_names(feature, &mut properties);
if is_link {
properties.push(("is_link".into(), PropValue::Bool(true)));
}
properties.push(("sort_rank".into(), PropValue::I64(400)));
properties.push(("min_zoom".into(), PropValue::I64((service_zoom + 1) as i64)));
Some(ProcessedFeature {
id: feature.id,
geometry: feature.geometry.clone(),
layer: Layer::Roads,
min_zoom: service_zoom,
max_zoom: 15,
sort_rank: 400,
properties,
})
}
fn classify_highway(highway: &str) -> (&'static str, u8) {
let base = highway.trim_end_matches("_link");
match base {
"motorway" => ("highway", 3),
"trunk" => ("major_road", 6),
"primary" => ("major_road", 7),
"secondary" => ("major_road", 9),
"tertiary" => ("major_road", 9),
"residential" | "unclassified" | "road" | "raceway" => ("minor_road", 12),
"service" => ("minor_road", 13),
"pedestrian" | "track" | "corridor" => ("path", 12),
"path" | "cycleway" | "bridleway" | "footway" | "steps" => ("path", 13),
"living_street" => ("minor_road", 12),
_ => ("minor_road", 14),
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::source::input::{DataSource, OsmElementType, RelationInfo};
use std::collections::HashMap;
use std::sync::Arc;
fn make_feature(props: &[(&str, PropValue)]) -> InputFeature {
let mut properties = HashMap::new();
for (k, v) in props {
properties.insert(k.to_string(), v.clone());
}
InputFeature {
id: 1,
geometry: Arc::new(geo::Geometry::LineString(geo::LineString::from(vec![
(0.0, 0.0),
(1.0, 1.0),
]))),
properties,
bbox: None,
source: DataSource::Overture {
theme: String::new(),
otype: String::new(),
},
}
}
fn make_osm_line(tags: &[(&str, &str)]) -> InputFeature {
let mut properties = HashMap::new();
for (k, v) in tags {
properties.insert(k.to_string(), PropValue::Str(v.to_string()));
}
InputFeature {
id: 100,
geometry: Arc::new(geo::Geometry::LineString(geo::LineString::from(vec![
(0.0, 0.0),
(1.0, 1.0),
]))),
properties,
bbox: None,
source: DataSource::Osm {
element_type: OsmElementType::Way,
relations: vec![],
},
}
}
fn make_osm_line_with_relations(
tags: &[(&str, &str)],
relations: Vec<RelationInfo>,
) -> InputFeature {
let mut properties = HashMap::new();
for (k, v) in tags {
properties.insert(k.to_string(), PropValue::Str(v.to_string()));
}
InputFeature {
id: 100,
geometry: Arc::new(geo::Geometry::LineString(geo::LineString::from(vec![
(0.0, 0.0),
(1.0, 1.0),
]))),
properties,
bbox: None,
source: DataSource::Osm {
element_type: OsmElementType::Way,
relations,
},
}
}
#[test]
fn motorway_is_highway() {
let feat = make_feature(&[("class", PropValue::Str("motorway".into()))]);
let result = process(&feat).unwrap();
assert_eq!(result.layer, Layer::Roads);
assert_eq!(result.min_zoom, 3);
assert_eq!(result.sort_rank, 400);
assert!(
result
.properties
.iter()
.any(|(k, v)| k == "kind" && *v == PropValue::Str("highway".into()))
);
}
#[test]
fn primary_is_major_road() {
let feat = make_feature(&[("class", PropValue::Str("primary".into()))]);
let result = process(&feat).unwrap();
assert_eq!(result.min_zoom, 7);
assert!(
result
.properties
.iter()
.any(|(k, v)| k == "kind" && *v == PropValue::Str("major_road".into()))
);
}
#[test]
fn service_is_minor_road() {
let feat = make_feature(&[("class", PropValue::Str("service".into()))]);
let result = process(&feat).unwrap();
assert_eq!(result.min_zoom, 13);
assert!(
result
.properties
.iter()
.any(|(k, v)| k == "kind" && *v == PropValue::Str("minor_road".into()))
);
}
#[test]
fn footway_is_path() {
for class in ["path", "cycleway", "bridleway", "footway", "steps"] {
let feat = make_feature(&[("class", PropValue::Str(class.into()))]);
let result = process(&feat).expect(class);
assert_eq!(result.min_zoom, 13, "{class}");
assert!(
result
.properties
.iter()
.any(|(k, v)| k == "kind" && *v == PropValue::Str("path".into())),
"{class}"
);
}
}
#[test]
fn bridge_property_extracted() {
let feat = make_feature(&[
("class", PropValue::Str("motorway".into())),
("road_flags.is_bridge", PropValue::Str("0:1".into())),
]);
let result = process(&feat).unwrap();
assert!(
result
.properties
.iter()
.any(|(k, v)| k == "is_bridge" && *v == PropValue::Bool(true))
);
}
#[test]
fn overture_trunk_min_zoom_6() {
let feat = make_feature(&[("class", PropValue::Str("trunk".into()))]);
let result = process(&feat).unwrap();
assert_eq!(result.min_zoom, 6);
}
#[test]
fn overture_secondary_tertiary_min_zoom_9() {
for class in ["secondary", "tertiary"] {
let feat = make_feature(&[("class", PropValue::Str(class.into()))]);
let result = process(&feat).unwrap();
assert_eq!(result.min_zoom, 9, "class={class}");
}
}
#[test]
fn overture_residential_min_zoom_12() {
for class in ["residential", "unclassified", "road", "raceway"] {
let feat = make_feature(&[("class", PropValue::Str(class.into()))]);
let result = process(&feat).unwrap();
assert_eq!(result.min_zoom, 12, "class={class}");
assert!(
result
.properties
.iter()
.any(|(k, v)| k == "kind" && *v == PropValue::Str("minor_road".into()))
);
}
}
#[test]
fn overture_living_street_min_zoom_12() {
let feat = make_feature(&[("class", PropValue::Str("living_street".into()))]);
let result = process(&feat).unwrap();
assert_eq!(result.min_zoom, 12);
}
#[test]
fn overture_pedestrian_track_corridor_path_min_zoom_12() {
for class in ["pedestrian", "track", "corridor"] {
let feat = make_feature(&[("class", PropValue::Str(class.into()))]);
let result = process(&feat).unwrap();
assert_eq!(result.min_zoom, 12, "class={class}");
assert!(
result
.properties
.iter()
.any(|(k, v)| k == "kind" && *v == PropValue::Str("path".into()))
);
}
}
#[test]
fn overture_unknown_class_falls_through() {
let weird = [("class", PropValue::Str("weird_class".into()))];
for props in [&weird[..], &[]] {
let result = process(&make_feature(props)).expect("a road");
assert_eq!(result.min_zoom, 14, "{props:?}");
assert!(
result
.properties
.iter()
.any(|(k, v)| k == "kind" && *v == PropValue::Str("minor_road".into())),
"{props:?}"
);
}
}
fn prop<'a>(result: &'a ProcessedFeature, key: &str) -> Option<&'a PropValue> {
result
.properties
.iter()
.find(|(k, _)| k == key)
.map(|(_, v)| v)
}
fn s(v: &str) -> PropValue {
PropValue::Str(v.into())
}
fn make_long_feature(props: &[(&str, PropValue)]) -> InputFeature {
let mut feat = make_feature(props);
feat.geometry = Arc::new(geo::Geometry::LineString(geo::LineString::from(vec![
(0.0, 0.0),
(4.0, 0.0),
(10.0, 0.0),
])));
feat
}
fn x_span(result: &ProcessedFeature) -> (f64, f64) {
match result.geometry.as_ref() {
geo::Geometry::LineString(l) => (l.0[0].x, l.0[l.0.len() - 1].x),
other => panic!("expected a LineString, got {other:?}"),
}
}
#[test]
fn overture_standard_gauge_rail_is_rail_from_z11() {
let feat = make_feature(&[("subtype", s("rail")), ("class", s("standard_gauge"))]);
let result = process(&feat).unwrap();
assert_eq!(prop(&result, "kind"), Some(&s("rail")));
assert_eq!(prop(&result, "kind_detail"), Some(&s("standard_gauge")));
assert_eq!(result.min_zoom, 11);
}
#[test]
fn overture_minor_rail_classes_are_rail_from_z14() {
for class in [
"subway",
"light_rail",
"tram",
"monorail",
"narrow_gauge",
"funicular",
"unknown",
] {
let feat = make_feature(&[("subtype", s("rail")), ("class", s(class))]);
let result = process(&feat).unwrap();
assert_eq!(prop(&result, "kind"), Some(&s("rail")), "{class}");
assert_eq!(prop(&result, "kind_detail"), Some(&s(class)), "{class}");
assert_eq!(result.min_zoom, 14, "{class}");
}
}
#[test]
fn overture_water_segment_is_ferry_from_z11() {
let feat = make_feature(&[("subtype", s("water"))]);
let result = process(&feat).unwrap();
assert_eq!(prop(&result, "kind"), Some(&s("ferry")));
assert!(prop(&result, "kind_detail").is_none());
assert_eq!(result.min_zoom, 11);
}
#[test]
fn overture_unknown_subtype_is_dropped() {
let feat = make_feature(&[("subtype", s("hyperloop")), ("class", s("motorway"))]);
assert!(process(&feat).is_none());
assert!(process_all(&feat).is_empty());
}
#[test]
fn overture_subclass_becomes_kind_detail() {
let feat = make_feature(&[
("subtype", s("road")),
("class", s("footway")),
("subclass", s("sidewalk")),
]);
let result = process(&feat).unwrap();
assert_eq!(prop(&result, "kind"), Some(&s("path")));
assert_eq!(prop(&result, "kind_detail"), Some(&s("sidewalk")));
}
#[test]
fn overture_link_subclass_sets_is_link() {
let feat = make_feature(&[
("subtype", s("road")),
("class", s("primary")),
("subclass", s("link")),
]);
let result = process(&feat).unwrap();
assert_eq!(prop(&result, "is_link"), Some(&PropValue::Bool(true)));
}
#[test]
fn overture_whole_segment_flags_are_emitted() {
let feat = make_feature(&[
("class", s("motorway")),
("road_flags.is_bridge", s("0:1")),
("road_flags.is_tunnel", s("0:1")),
("road_flags.is_link", s("0:1")),
]);
let result = process(&feat).unwrap();
for flag in ["is_bridge", "is_tunnel", "is_link"] {
assert_eq!(prop(&result, flag), Some(&PropValue::Bool(true)), "{flag}");
}
assert_eq!(process_all(&feat).len(), 1);
}
#[test]
fn overture_rail_flags_are_read() {
let feat = make_feature(&[
("subtype", s("rail")),
("class", s("subway")),
("rail_flags.is_tunnel", s("0:1")),
]);
let result = process(&feat).unwrap();
assert_eq!(prop(&result, "is_tunnel"), Some(&PropValue::Bool(true)));
}
#[test]
fn segment_flags_are_read_from_both_overture_columns() {
for (key, property) in [
("road_flags.is_bridge", "is_bridge"),
("rail_flags.is_bridge", "is_bridge"),
("road_flags.is_tunnel", "is_tunnel"),
("rail_flags.is_tunnel", "is_tunnel"),
("road_flags.is_link", "is_link"),
("rail_flags.is_link", "is_link"),
] {
let feat = make_feature(&[
("subtype", s("road")),
("class", s("primary")),
(key, s("0:1")),
]);
let result = process(&feat).unwrap();
assert_eq!(
prop(&result, property),
Some(&PropValue::Bool(true)),
"{key}"
);
}
}
#[test]
fn overture_partial_bridge_is_not_on_the_whole_segment() {
let feat = make_long_feature(&[
("class", s("primary")),
("road_flags.is_bridge", s("0.2:0.5")),
]);
let whole = process(&feat).unwrap();
assert!(prop(&whole, "is_bridge").is_none());
}
#[test]
fn overture_partial_bridge_splits_the_segment() {
let feat = make_long_feature(&[
("class", s("primary")),
("road_flags.is_bridge", s("0.2:0.5")),
]);
let pieces = process_all(&feat);
assert_eq!(pieces.len(), 3);
let bridge: Vec<_> = pieces
.iter()
.filter(|p| prop(p, "is_bridge").is_some())
.collect();
assert_eq!(bridge.len(), 1);
let (x0, x1) = x_span(bridge[0]);
assert!(
(x0 - 2.0).abs() < 1e-9 && (x1 - 5.0).abs() < 1e-9,
"{x0}..{x1}"
);
let total: f64 = pieces
.iter()
.map(|p| {
let (a, b) = x_span(p);
b - a
})
.sum();
assert!((total - 10.0).abs() < 1e-9, "pieces cover {total}");
for p in &pieces {
assert_eq!(prop(p, "kind"), Some(&s("major_road")));
}
}
#[test]
fn overture_split_piece_keeps_interior_vertices() {
let feat = make_long_feature(&[
("class", s("primary")),
("road_flags.is_tunnel", s("0.3:0.6")),
]);
let tunnel = process_all(&feat)
.into_iter()
.find(|p| prop(p, "is_tunnel").is_some())
.unwrap();
match tunnel.geometry.as_ref() {
geo::Geometry::LineString(l) => {
let xs: Vec<f64> = l.0.iter().map(|c| c.x).collect();
assert_eq!(xs.len(), 3);
assert!((xs[1] - 4.0).abs() < 1e-9, "{xs:?}");
}
other => panic!("expected a LineString, got {other:?}"),
}
}
#[test]
fn overture_malformed_flag_ranges_are_ignored() {
let feat = make_long_feature(&[
("class", s("primary")),
("road_flags.is_bridge", s("nonsense;0.4")),
]);
let pieces = process_all(&feat);
assert_eq!(pieces.len(), 1);
assert!(prop(&pieces[0], "is_bridge").is_none());
}
#[test]
fn overture_partial_flag_on_a_multilinestring_is_not_split() {
let mut feat = make_feature(&[
("class", s("primary")),
("road_flags.is_bridge", s("0.2:0.5")),
]);
feat.geometry = Arc::new(geo::Geometry::MultiLineString(geo::MultiLineString::new(
vec![geo::LineString::from(vec![(0.0, 0.0), (1.0, 0.0)])],
)));
let pieces = process_all(&feat);
assert_eq!(pieces.len(), 1);
assert!(prop(&pieces[0], "is_bridge").is_none());
}
#[test]
fn overture_zero_length_segment_with_partial_flag_yields_nothing() {
let mut feat = make_feature(&[
("class", s("primary")),
("road_flags.is_bridge", s("0.2:0.5")),
]);
feat.geometry = Arc::new(geo::Geometry::LineString(geo::LineString::from(vec![
(3.0, 3.0),
(3.0, 3.0),
])));
assert!(process_all(&feat).is_empty());
}
#[test]
fn sub_line_of_zero_length_line_is_none() {
let line = geo::LineString::from(vec![(1.0, 1.0), (1.0, 1.0)]);
assert!(sub_line(&line, 0.0, 1.0).is_none());
}
#[test]
fn osm_process_all_matches_process() {
let feat = make_osm_line(&[("highway", "primary")]);
let all = process_all(&feat);
assert_eq!(all.len(), 1);
assert_eq!(prop(&all[0], "kind"), Some(&s("major_road")));
}
#[test]
fn overture_road_ref_extracted() {
let feat = make_feature(&[
("class", PropValue::Str("motorway".into())),
("road_ref", PropValue::Str("I-95".into())),
]);
let result = process(&feat).unwrap();
assert!(
result
.properties
.iter()
.any(|(k, v)| k == "ref" && *v == PropValue::Str("I-95".into()))
);
}
#[test]
fn overture_falls_back_to_ref_field() {
let feat = make_feature(&[
("class", PropValue::Str("motorway".into())),
("ref", PropValue::Str("A1".into())),
]);
let result = process(&feat).unwrap();
assert!(
result
.properties
.iter()
.any(|(k, v)| k == "ref" && *v == PropValue::Str("A1".into()))
);
}
#[test]
fn overture_names_primary_extracted() {
let feat = make_feature(&[
("class", PropValue::Str("motorway".into())),
("names.primary", PropValue::Str("Autobahn 5".into())),
]);
let result = process(&feat).unwrap();
assert!(
result
.properties
.iter()
.any(|(k, v)| k == "name" && *v == PropValue::Str("Autobahn 5".into()))
);
}
fn has(r: &ProcessedFeature, key: &str, value: &str) -> bool {
r.properties
.iter()
.any(|(k, v)| k == key && *v == PropValue::Str(value.into()))
}
#[test]
fn osm_road_with_a_two_script_name_splits_it_and_keeps_name_en() {
let r = process(&make_osm_line(&[
("highway", "primary"),
("name", "Rue Principale / شارع رئيسي"),
("name:en", "Main Street"),
]))
.unwrap();
assert!(has(&r, "name", "Rue Principale"));
assert!(has(&r, "name2", "شارع رئيسي"));
assert!(has(&r, "script2", "Arabic"));
assert!(has(&r, "name:en", "Main Street"));
assert!(r.properties.iter().all(|(k, _)| k != "script"));
}
#[test]
fn overture_road_takes_name_en_from_the_common_names() {
let r = process(&make_feature(&[
("class", PropValue::Str("motorway".into())),
("names.primary", PropValue::Str("شارع النيل".into())),
("names.common.en", PropValue::Str("Nile Street".into())),
]))
.unwrap();
assert!(has(&r, "name", "شارع النيل"));
assert!(has(&r, "script", "Arabic"));
assert!(has(&r, "name:en", "Nile Street"));
}
#[test]
fn overture_falls_back_to_name_field() {
let feat = make_feature(&[
("class", PropValue::Str("motorway".into())),
("name", PropValue::Str("Main St".into())),
]);
let result = process(&feat).unwrap();
assert!(
result
.properties
.iter()
.any(|(k, v)| k == "name" && *v == PropValue::Str("Main St".into()))
);
}
#[test]
fn overture_min_zoom_property_set() {
let feat = make_feature(&[("class", PropValue::Str("motorway".into()))]);
let result = process(&feat).unwrap();
assert!(
result
.properties
.iter()
.any(|(k, v)| k == "min_zoom" && *v == PropValue::I64(4))
);
}
#[test]
fn osm_motorway_basic() {
let feat = make_osm_line(&[("highway", "motorway")]);
let result = process(&feat).unwrap();
assert_eq!(result.layer, Layer::Roads);
assert_eq!(result.min_zoom, 3);
assert!(
result
.properties
.iter()
.any(|(k, v)| k == "kind" && *v == PropValue::Str("highway".into()))
);
}
#[test]
fn osm_no_highway_returns_none() {
let feat = make_osm_line(&[("name", "Foo")]);
assert!(process(&feat).is_none());
}
#[test]
fn osm_non_line_geometry_returns_none() {
let mut props = HashMap::new();
props.insert("highway".to_string(), PropValue::Str("motorway".into()));
let feat = InputFeature {
id: 1,
geometry: Arc::new(geo::Geometry::Point(geo::Point::new(0.0, 0.0))),
properties: props,
bbox: None,
source: DataSource::Osm {
element_type: OsmElementType::Node,
relations: vec![],
},
};
assert!(process(&feat).is_none());
}
#[test]
fn osm_motorway_link_zoom_offset_plus_2() {
let feat = make_osm_line(&[("highway", "motorway_link")]);
let result = process(&feat).unwrap();
assert_eq!(result.min_zoom, 5);
assert!(
result
.properties
.iter()
.any(|(k, v)| k == "is_link" && *v == PropValue::Bool(true))
);
}
#[test]
fn osm_service_driveway_zoom_plus_1() {
for service in ["driveway", "parking_aisle"] {
let feat = make_osm_line(&[("highway", "service"), ("service", service)]);
assert_eq!(process(&feat).expect(service).min_zoom, 14, "{service}");
}
}
#[test]
fn osm_service_other_no_offset() {
let alley = [("highway", "service"), ("service", "alley")];
for tags in [&alley[..], &[("highway", "service")]] {
assert_eq!(
process(&make_osm_line(tags)).expect("a road").min_zoom,
13,
"{tags:?}"
);
}
}
#[test]
fn osm_bridge_no_skipped() {
let feat = make_osm_line(&[("highway", "primary"), ("bridge", "no")]);
let result = process(&feat).unwrap();
assert!(!result.properties.iter().any(|(k, _)| k == "is_bridge"));
}
#[test]
fn osm_tunnel_extracted_when_no_bridge() {
let feat = make_osm_line(&[("highway", "primary"), ("tunnel", "yes")]);
let result = process(&feat).unwrap();
assert!(
result
.properties
.iter()
.any(|(k, v)| k == "is_tunnel" && *v == PropValue::Bool(true))
);
}
#[test]
fn osm_tunnel_no_skipped() {
let feat = make_osm_line(&[("highway", "primary"), ("tunnel", "no")]);
let result = process(&feat).unwrap();
assert!(!result.properties.iter().any(|(k, _)| k == "is_tunnel"));
}
#[test]
fn osm_bridge_takes_priority_over_tunnel() {
let bridge = [("highway", "primary"), ("bridge", "yes")];
let both = [("highway", "primary"), ("bridge", "yes"), ("tunnel", "yes")];
for tags in [&bridge[..], &both] {
let result = process(&make_osm_line(tags)).expect("a road");
assert!(
result
.properties
.iter()
.any(|(k, v)| k == "is_bridge" && *v == PropValue::Bool(true)),
"{tags:?}"
);
assert!(
!result.properties.iter().any(|(k, _)| k == "is_tunnel"),
"{tags:?}"
);
}
}
#[test]
fn osm_oneway_yes_extracted() {
let feat = make_osm_line(&[("highway", "primary"), ("oneway", "yes")]);
let result = process(&feat).unwrap();
assert!(
result
.properties
.iter()
.any(|(k, v)| k == "oneway" && *v == PropValue::Str("yes".into()))
);
}
#[test]
fn osm_oneway_no_skipped() {
let feat = make_osm_line(&[("highway", "primary"), ("oneway", "no")]);
let result = process(&feat).unwrap();
assert!(!result.properties.iter().any(|(k, _)| k == "oneway"));
}
#[test]
fn osm_ref_from_direct_tag() {
let feat = make_osm_line(&[("highway", "primary"), ("ref", "B12")]);
let result = process(&feat).unwrap();
assert!(
result
.properties
.iter()
.any(|(k, v)| k == "ref" && *v == PropValue::Str("B12".into()))
);
}
fn relation(id: i64, tags: &[(&str, &str)]) -> RelationInfo {
RelationInfo {
id,
admin_level: None,
disputed: false,
role: String::new(),
tags: tags
.iter()
.map(|(k, v)| ((*k).to_string(), (*v).to_string()))
.collect(),
}
}
fn route(id: i64, route: &str, network: &str, reference: &str) -> RelationInfo {
relation(
id,
&[
("type", "route"),
("route", route),
("network", network),
("ref", reference),
],
)
}
fn text(value: &str) -> Option<PropValue> {
Some(PropValue::Str(value.into()))
}
#[test]
fn osm_ref_is_the_way_tag_and_the_route_gives_the_shield() {
let feat = make_osm_line_with_relations(
&[("highway", "motorway"), ("ref", "I 90")],
vec![route(1, "road", "US:I", "90")],
);
let result = process(&feat).unwrap();
assert_eq!(prop(&result, "ref").cloned(), text("I 90"));
assert_eq!(prop(&result, "network").cloned(), text("US:I"));
assert_eq!(prop(&result, "shield_text").cloned(), text("90"));
assert_eq!(prop(&result, "network_1").cloned(), text("US:I"));
assert_eq!(prop(&result, "shield_text_1").cloned(), text("90"));
assert!(prop(&result, "network_2").is_none());
}
#[test]
fn the_autobahn_number_is_the_primary_shield_over_e_road_and_bus_routes() {
let relations = vec![
route(80053, "road", "e-road", "E 51"),
relation(1_516_377, &[("type", "route"), ("route", "road")]),
route(3_046_906, "bus", "Flixbus", "009"),
relation(
3_144_678,
&[
("type", "route"),
("disused:route", "bus"),
("network", "Flixbus"),
("ref", "038"),
],
),
route(5_485_765, "road", "BAB", "A 115"),
route(9_581_031, "bus", "Eurolines", "EU0328"),
];
let expected = vec![
Shield {
text: "A115".into(),
network: "BAB".into(),
},
Shield {
text: "E51".into(),
network: "e-road".into(),
},
];
let mut reversed = relations.clone();
reversed.reverse();
assert_eq!(route_shields(&relations), expected);
assert_eq!(route_shields(&reversed), expected);
let feat =
make_osm_line_with_relations(&[("highway", "motorway"), ("ref", "A 115")], relations);
let result = process(&feat).unwrap();
assert_eq!(prop(&result, "ref").cloned(), text("A 115"));
assert_eq!(prop(&result, "network").cloned(), text("BAB"));
assert_eq!(prop(&result, "shield_text").cloned(), text("A115"));
assert_eq!(prop(&result, "network_2").cloned(), text("e-road"));
assert_eq!(prop(&result, "shield_text_2").cloned(), text("E51"));
assert!(prop(&result, "network_3").is_none());
}
#[test]
fn us_shields_follow_the_protomaps_us_priority() {
let shields = route_shields(&[
route(1, "road", "US:CA", "1"),
route(2, "road", "US:US", "101"),
route(3, "road", "US:I:Express", "5"),
route(4, "road", "US:I", "5"),
]);
let got: Vec<(&str, &str)> = shields
.iter()
.map(|s| (s.network.as_str(), s.text.as_str()))
.collect();
assert_eq!(got, [("US:I", "5"), ("US:US", "101"), ("US:CA", "1")]);
}
#[test]
fn nl_shields_and_the_six_shield_cap() {
let shields = route_shields(&[
route(1, "road", "NL:S:Amsterdam", "S 100"),
route(2, "road", "NL:N", "N 200"),
route(3, "road", "NL:A", "A 10"),
route(4, "road", "other", "Z9"),
route(5, "road", "other", "B2"),
route(6, "road", "e-road", "E 22"),
route(7, "road", "other", "C3"),
]);
let got: Vec<(&str, &str)> = shields
.iter()
.map(|s| (s.network.as_str(), s.text.as_str()))
.collect();
assert_eq!(
got,
[
("NL:A", "A10"),
("NL:N", "N200"),
("NL:S-road", "S100"),
("other", "B2"),
("other", "C3"),
("other", "Z9"),
]
);
}
#[test]
fn routes_without_network_or_ref_and_bus_routes_give_no_shield() {
let feat = make_osm_line_with_relations(
&[("highway", "motorway"), ("ref", "E5")],
vec![
relation(1, &[("type", "route"), ("route", "road"), ("ref", "1")]),
relation(2, &[("type", "route"), ("route", "road"), ("network", "x")]),
route(3, "road", "x", " "),
route(4, "bus", "Flixbus", "042"),
],
);
let result = process(&feat).unwrap();
assert_eq!(prop(&result, "ref").cloned(), text("E5"));
assert!(prop(&result, "network").is_none());
assert!(prop(&result, "shield_text").is_none());
}
#[test]
fn osm_no_ref_or_network() {
let feat = make_osm_line(&[("highway", "primary")]);
let result = process(&feat).unwrap();
assert!(!result.properties.iter().any(|(k, _)| k == "ref"));
assert!(!result.properties.iter().any(|(k, _)| k == "network"));
}
#[test]
fn osm_name_extracted() {
let feat = make_osm_line(&[("highway", "primary"), ("name", "Main Street")]);
let result = process(&feat).unwrap();
assert!(
result
.properties
.iter()
.any(|(k, v)| k == "name" && *v == PropValue::Str("Main Street".into()))
);
}
#[test]
fn osm_residential_min_zoom_12() {
let feat = make_osm_line(&[("highway", "residential")]);
let result = process(&feat).unwrap();
assert_eq!(result.min_zoom, 12);
}
#[test]
fn osm_link_strips_link_for_classify() {
let feat = make_osm_line(&[("highway", "primary_link")]);
let result = process(&feat).unwrap();
assert_eq!(result.min_zoom, 9);
assert!(
result
.properties
.iter()
.any(|(k, v)| k == "is_link" && *v == PropValue::Bool(true))
);
}
#[test]
fn osm_unknown_highway_min_zoom_14() {
let feat = make_osm_line(&[("highway", "weird_class")]);
let result = process(&feat).unwrap();
assert_eq!(result.min_zoom, 14);
}
#[test]
fn osm_min_zoom_property_set() {
let feat = make_osm_line(&[("highway", "motorway")]);
let result = process(&feat).unwrap();
assert!(
result
.properties
.iter()
.any(|(k, v)| k == "min_zoom" && *v == PropValue::I64(4))
);
}
#[test]
fn other_data_source_returns_none() {
let feat = InputFeature {
id: 1,
geometry: Arc::new(geo::Geometry::LineString(geo::LineString::from(vec![
(0.0, 0.0),
(1.0, 1.0),
]))),
properties: HashMap::new(),
bbox: None,
source: DataSource::LandPolygons,
};
assert!(process(&feat).is_none());
}
}