git clone https://garage44.eu/jeroen/cartopolis.git.. /crates/geo/src/traffic.rs
//! The drivable network, read off the `streets` layer the cell already parsed.
//!
//! This is the pure half of ambient traffic: it turns a tile into a list of
//! centrelines a car may drive along, with the direction it may drive them in and
//! how fast. The ECS half — the car pool, the steering and the meshes — is
//! `cartopolis`'s `systems::traffic`.
//!
//! Like the street furniture and the parked vehicles, it costs **no request and
//! no extra decode**: `map_geometry` fetches one MVT body per cell and this reads
//! a layer that body already contains and that `tessellate_roads` has already
//! walked. Unlike them it is not a fill — every line here is a surveyed road, and
//! the only invented thing is the traffic on it.
//!
//! Four things shape it:
//!
//! * **Direction is a three-way answer, not a flag.** Shortbread carries
//! `oneway` *and* `oneway_reverse` — the second meaning the way is one-way
//! against its own digitisation order. `street_style` ORs them together because
//! a painted road is the same width either way; traffic cannot, because the two
//! send a car in opposite directions. Getting this wrong is not subtle: half
//! the one-way streets in the city would run backwards.
//! * **A tunnel is a road here, and its depth travels with the line.** The
//! geometry, the raster and the street labels all refuse a tunnel-flagged way
//! (`drawn_street`), because they draw the ground and a tunnel is not on it.
//! This is a *network*, and inheriting that refusal cut the graph at every
//! portal: a car reaching Groningen's ring ran to the end of its line and was
//! recycled, so 863 m of carriageway under the park carried nothing. Each line
//! now carries [`DriveLine::deck`], the height of its own carriageway, which
//! `cartopolis::systems::tunnels` resolved per feature.
//! * **Lines are simplified and short ones dropped.** A z14 street carries
//! junction-accurate detail no car needs, and every vertex is a step in the
//! steering loop. [`DRIVE_SIMPLIFY_M`] is the same idea as the labels'
//! `LABEL_SIMPLIFY_M` and for the same reason.
//! * **Ownership is half-open on the first vertex**, as everywhere else here, so
//! a road crossing a cell boundary is emitted once. The geometry is taken
//! **unclipped** — a car that drives off the edge of its own cell is on the
//! same road, and clipping would put a junction there that the map does not
//! have.
use mvt_reader::feature::Feature;
use crate::vector_tiles::{flag_of, kind_of, street_shape, TileData};
/// Vertices closer together than this are merged. A z14 street line has
/// junction-accurate detail; a car following it needs a driving line.
const DRIVE_SIMPLIFY_M: f32 = 8.0;
/// Lines shorter than this are dropped. A stub that takes under two seconds to
/// drive is a place to hand a car off, not a road to spawn one on.
const MIN_DRIVE_LEN_M: f32 = 25.0;
/// Which way traffic may run along a [`DriveLine`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Flow {
/// Both ways — the usual case.
Both,
/// Only in the polyline's own order.
Forward,
/// Only against it (`oneway_reverse`).
Backward,
}
/// Who may travel along a line.
///
/// Not an enum, because the common case is **both**: a residential street carries
/// cars on the carriageway and people on the pavement beside it, and modelling
/// that as one-or-the-other would either empty the pavements or put pedestrians
/// in the road.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Uses {
pub drive: bool,
pub walk: bool,
/// Bicycles: a cycleway, and the ordinary streets they share with cars
/// ([`cycle_ok`]).
pub cycle: bool,
}
/// One travelable centreline, in the tessellator's tile-local metre frame (origin
/// at the cell's north-west corner, +x east, +z south).
#[derive(Debug, Clone)]
pub struct DriveLine {
pub points: Vec<[f32; 2]>,
pub flow: Flow,
/// Free-flow speed in m/s **for a car**. Zero on a line no car may use;
/// walkers carry their own pace and do not read this.
pub speed: f32,
/// Half the carriageway, so a car can sit in its own lane rather than on the
/// centre line — and so a walker can be put on the pavement *outside* it.
pub half_width: f32,
pub uses: Uses,
/// Height of the carriageway at each point where the line runs through a
/// structure below the ground — a tunnel, its ramps, the cuttings between —
/// in the frame the structure is drawn in (`tunnels::SunkenWay::road_y`), and
/// `NaN` everywhere else, where a car stands on the ground. Parallel to
/// [`points`](Self::points).
///
/// **Parallel arrays, and every operation on one must keep them so** — the
/// same contract, and the same failure, as `Route::points` and
/// `Route::levels`: thinned independently they drift apart at the first
/// collapsed pair, and the symptom is a car descending a few metres before
/// the portal.
///
/// It is on the line rather than sampled from the world because *position is
/// not enough*. A street crossing over Groningen's ring is at the same XZ as
/// the carriageway seven metres under it, so a depth read off the map would
/// drop that street's traffic into the tunnel — the identical mistake
/// `DeckPlates::lift_at` made in the other direction, hoisting an underpass
/// onto the viaduct above it.
pub deck: Vec<f32>,
/// Whether this way is flagged `bridge`.
///
/// A deck's height is a *measurement* — `map_geometry::resolve_bridge_decks`
/// reads it out of the survey some frames after the cell lands — so unlike
/// [`deck`](Self::deck) it cannot be baked here. What can be recorded here is
/// the half that is a fact about the road rather than about the world, and
/// it is the half that matters: `DeckPlates::lift_at` answers by position,
/// and a viaduct and the street beneath it are at the same position. The
/// route line settled this the same way (`Route::levels`), and the first
/// attempt there hoisted every underpass onto the structure above it.
pub on_deck: bool,
/// Which sides of a street have somewhere to walk. Both until
/// [`keep_walkers_off`] has looked at the ground beside it.
pub pavements: Pavements,
}
/// Whether a street has a pavement on each side, relative to the line's own
/// order: `right` is the side a car driving it forward keeps to.
///
/// The tile models no pavements, so a walker on a street stands where one would
/// be — [`PAVEMENT_CLEARANCE_M`] outside the kerb — and on a road with a grass
/// verge instead that is the middle of the lawn. This is the answer to "is there
/// a pavement there at all", taken from the same grass map the blades grow on.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Pavements {
pub right: bool,
pub left: bool,
}
impl Pavements {
pub const BOTH: Self = Self {
right: true,
left: true,
};
/// The pavement on `side`: `+1` right of the line's order, `-1` left.
#[must_use]
pub fn on(self, side: f32) -> bool {
if side > 0.0 {
self.right
} else {
self.left
}
}
}
/// How far beyond the kerb a walker on a street stands — the middle of a
/// pavement that the tile does not draw.
pub const PAVEMENT_CLEARANCE_M: f32 = 1.6;
/// How often along a street its pavements are checked, metres.
const PAVEMENT_SAMPLE_M: f32 = 6.0;
/// The share of a side's samples that may land on grass with the side still
/// counting as a pavement. Not zero: the grass polygons and the road ribbon are
/// separate generalisations, and a lawn reaching to the kerb at every corner
/// would otherwise strip the pavements off half the streets in a town.
const PAVEMENT_GRASS_SHARE: f32 = 0.3;
/// Take the walkers off the grass and out of the water.
///
/// For every street people share with cars, sample where its pavements would be
/// on each side; a side that is mostly `green` (the client passes the grass
/// layer's own `GrassArea::plantable`, or `GrassArea::wet` — a quay street's
/// canal side, where walkers were seen strolling along the water's edge, in the
/// same tile-local frame) has no pavement, and a
/// street with neither loses its walkers outright — a verge-lined arterial is a
/// road nobody strolls along. A path, a footway or a pedestrian street is not
/// sampled: people walk *on* those, and a path across a park is meant to be
/// across the grass.
pub fn keep_walkers_off(lines: &mut [DriveLine], green: &dyn Fn(f32, f32) -> bool) {
for line in lines.iter_mut() {
if !(line.uses.walk && line.uses.drive) {
continue;
}
let reach = line.half_width + PAVEMENT_CLEARANCE_M;
let (mut n, mut right, mut left) = (0u32, 0u32, 0u32);
for w in line.points.windows(2) {
let (a, b) = (w[0], w[1]);
let (dx, dz) = (b[0] - a[0], b[1] - a[1]);
let len = (dx * dx + dz * dz).sqrt();
if len < 1e-3 {
continue;
}
// Right of travel in a +x east, +z south frame, as the client's
// `traffic::right_of` has it.
let (rx, rz) = (-dz / len, dx / len);
let steps = (len / PAVEMENT_SAMPLE_M).ceil().max(1.0) as u32;
for k in 0..steps {
let t = (k as f32 + 0.5) / steps as f32;
let (px, pz) = (a[0] + dx * t, a[1] + dz * t);
n += 1;
right += u32::from(green(px + rx * reach, pz + rz * reach));
left += u32::from(green(px - rx * reach, pz - rz * reach));
}
}
if n == 0 {
continue;
}
let paved = |g: u32| (g as f32) <= n as f32 * PAVEMENT_GRASS_SHARE;
line.pavements = Pavements {
right: paved(right),
left: paved(left),
};
if !line.pavements.right && !line.pavements.left {
line.uses.walk = false;
}
}
}
impl DriveLine {
/// Total length in metres.
#[must_use]
pub fn length(&self) -> f32 {
self.points
.windows(2)
.map(|w| {
let (dx, dz) = (w[1][0] - w[0][0], w[1][1] - w[0][1]);
(dx * dx + dz * dz).sqrt()
})
.sum()
}
}
/// Free-flow speed in m/s for a Shortbread `streets` kind, or `None` for the
/// kinds a car may not drive on.
///
/// Deliberately below the legal limits. These are *ambient* cars on a city map:
/// what has to read correctly is that a motorway moves much faster than a
/// residential street, not that either matches a speedometer. A car doing a true
/// 100 km/h past a stationary camera is a streak.
#[must_use]
pub fn drive_speed(kind: &str) -> Option<f32> {
Some(match kind {
"motorway" => 26.0,
"trunk" => 22.0,
"primary" => 15.0,
"secondary" => 13.0,
"tertiary" => 11.0,
"residential" | "unclassified" => 7.5,
"living_street" => 4.5,
"service" => 4.5,
// Everything else is a path, a railway or something we do not recognise.
// The tree scatter's rule applies: no traffic beats invented traffic.
_ => return None,
})
}
/// Whether people may walk along a Shortbread `streets` kind.
///
/// Broader than [`drive_speed`] in one direction and narrower in the other. A
/// footway, a path, a pedestrian street or a cycleway carries people and no cars;
/// an ordinary street carries both, because it has pavements the tile does not
/// model separately and putting nobody on them empties the city. A motorway, a
/// trunk road and every railway carry nobody — a pedestrian strolling up the A28
/// is worse than an empty verge.
///
/// `steps` is deliberately included even though nothing here climbs: a flight of
/// steps between two streets is a route people are on, and a walker traversing it
/// at pavement level reads as a person on a staircase from any distance this is
/// seen at. It is listed rather than falling out of a default so that the choice
/// is visible.
#[must_use]
pub fn walk_ok(kind: &str) -> bool {
matches!(
kind,
"footway"
| "path"
| "pedestrian"
| "steps"
| "cycleway"
| "living_street"
| "residential"
| "unclassified"
| "service"
| "tertiary"
| "secondary"
)
}
/// Whether bicycles ride along a Shortbread `streets` kind, given the way's
/// `bicycle` tag as the tile carries it.
///
/// A cycleway, and the streets a cyclist shares with cars, from a living street
/// up to a secondary road. **Not a primary road**: in the Netherlands one has a
/// cycle track of its own beside it, mapped as its own `cycleway`, so cyclists
/// on the carriageway as well would ride beside the people the map already has
/// on the track. A footway, a path or a pedestrian street only where the way
/// says bikes are welcome (`designated` or `yes`) — a cyclist weaving through a
/// shopping street's walkers is worse than an empty one. `bicycle=no` closes
/// any of them, as the router reads it (`routing::bike_denied`).
#[must_use]
pub fn cycle_ok(kind: &str, bicycle: Option<&str>) -> bool {
if matches!(bicycle, Some("no" | "dismount")) {
return false;
}
match kind {
"cycleway" | "living_street" | "residential" | "unclassified" | "service" | "tertiary"
| "secondary" => true,
"path" | "footway" | "pedestrian" => matches!(bicycle, Some("designated" | "yes")),
_ => false,
}
}
/// Whether OSM's access tags on a highway way keep cars off it.
///
/// **The tile cannot answer this.** Shortbread's `streets` layer carries no
/// access tags, so a street closed to cars arrives as an ordinary `residential`
/// one — Groningen's Vismarkt and most of the shopping streets round it are
/// `motor_vehicle=no`, and ambient cars drove through the market stalls. The
/// tags come from the street-detail Overpass query instead
/// (`systems::street_detail`), which is why this takes a lookup rather than a
/// feature.
///
/// The most specific key present decides: `motorcar`, then `motor_vehicle`,
/// then `vehicle`, then `access` — so `motor_vehicle=no` + `vehicle=yes` (bikes
/// welcome, cars not) is closed, and `access=no` + `motor_vehicle=destination`
/// is open. `destination` stays open: residents and visitors do drive it.
#[must_use]
pub fn cars_barred<'a>(tag: impl Fn(&str) -> Option<&'a str>) -> bool {
["motorcar", "motor_vehicle", "vehicle", "access"]
.iter()
.find_map(|k| tag(k))
.is_some_and(|v| {
matches!(
v,
"no" | "private" | "delivery" | "agricultural" | "forestry" | "emergency"
)
})
}
/// How near a closed way a drive line's samples must lie to be on it, metres.
/// Wider than the z14 quantisation and [`DRIVE_SIMPLIFY_M`]'s chord error,
/// narrower than the gap between two parallel streets.
const CLOSED_MATCH_M: f32 = 4.0;
/// Whether most of `line` runs along one of `closed` — the barred ways of
/// [`cars_barred`], in the same frame.
///
/// A drive line and an OSM way are the same road drawn twice — the tile's
/// generalised, Overpass's exact — with no id in common, so they are matched by
/// position: the line is sampled every few metres, and it is closed when more
/// than half its samples lie within [`CLOSED_MATCH_M`] of a closed way. Half,
/// not any: a line crossing the end of a closed street touches it at the
/// junction and stays open.
#[must_use]
pub fn runs_along_closed(line: &[[f32; 2]], closed: &[&[[f32; 2]]]) -> bool {
let samples = densify(line, CLOSED_MATCH_M);
if samples.is_empty() || closed.is_empty() {
return false;
}
let r2 = CLOSED_MATCH_M * CLOSED_MATCH_M;
let near = |p: [f32; 2]| {
closed.iter().any(|way| {
way.windows(2)
.any(|s| segment_distance2(p, s[0], s[1]) <= r2)
})
};
let hits = samples.iter().filter(|p| near(**p)).count();
hits * 2 > samples.len()
}
/// Squared distance from `p` to the segment `a`–`b`.
fn segment_distance2(p: [f32; 2], a: [f32; 2], b: [f32; 2]) -> f32 {
let (dx, dz) = (b[0] - a[0], b[1] - a[1]);
let len2 = dx * dx + dz * dz;
let t = if len2 > 0.0 {
(((p[0] - a[0]) * dx + (p[1] - a[1]) * dz) / len2).clamp(0.0, 1.0)
} else {
0.0
};
let (ex, ez) = (a[0] + dx * t - p[0], a[1] + dz * t - p[1]);
ex * ex + ez * ez
}
/// Read a tile's `streets` layer as a travelable network.
///
/// Takes the cell's already-parsed [`TileData`] rather than the tile body, for
/// the reason every other consumer on this worker does: they each read a
/// different layer out of the same bytes.
pub fn extract_drive_lines(
tile: &TileData,
tile_m: f32,
sunken: &[crate::tunnels::SunkenWay],
) -> Result<Vec<DriveLine>, String> {
use geo_types::Geometry;
let Some(meta) = tile.layer("streets") else {
return Ok(Vec::new());
};
let features = tile.features(meta);
let extent = TileData::extent(meta);
let scale = tile_m / extent;
let mut out = Vec::new();
for (fi, feature) in features.iter().enumerate() {
let Some(kind) = kind_of(feature) else {
continue;
};
// This feature's own sunken corridors, if `tunnels` decided it has any.
let mine: Vec<&crate::tunnels::SunkenWay> =
sunken.iter().filter(|s| s.feature == fi).collect();
let drive = drive_speed(kind);
let walk = walk_ok(kind);
let cycle = cycle_ok(kind, bicycle_of(feature));
if drive.is_none() && !walk && !cycle {
continue;
}
let speed = drive.unwrap_or(0.0);
// **A tunnel is a road, and refusing it put a hole in the network.**
//
// This was `drawn_street`, which takes every tunnel-flagged way off the
// ground sheet because the geometry draws it somewhere else. That is the
// right answer for a *ribbon* and the wrong one for a network: it left
// the drive graph cut at every portal, so a car reaching Groningen's ring
// tunnel ran to the end of its line and was recycled, and the 863 m of
// carriageway under the park carried no traffic at all. Where the road
// goes is `street_shape`'s business; how deep it goes is the corridor's,
// and a flagged way with no corridor is an arcade at ground level.
let Some((_, half_width)) = street_shape(feature) else {
continue;
};
let flow = flow_of(feature);
let on_deck = flag_of(feature, "bridge");
let lines: Vec<&geo_types::LineString<f32>> = match &feature.geometry {
Geometry::LineString(ls) => vec![ls],
Geometry::MultiLineString(ml) => ml.iter().collect(),
_ => continue,
};
for line in lines {
let Some(first) = line.0.first() else {
continue;
};
// Half-open ownership on the first vertex: a road crossing a cell
// boundary belongs to exactly one cell and is emitted once, with no
// tolerance to tune. The rest of the line is kept **unclipped** — a
// car driving off the edge is still on the same road.
if first.x < 0.0 || first.y < 0.0 || first.x >= extent || first.y >= extent {
continue;
}
let raw: Vec<[f32; 2]> = line
.0
.iter()
// `mvt-reader` clips its cursor at `i32::MAX` rather than at the
// extent, so a wild coordinate is a real possibility here — see
// `TILE_BUFFER_FRAC`. Written as a positive test so a NaN is
// rejected rather than admitted.
.filter(|c| c.x.abs() < extent * 8.0 && c.y.abs() < extent * 8.0)
.map(|c| [c.x * scale, c.y * scale])
.collect();
let mut points = simplify(&raw, DRIVE_SIMPLIFY_M);
if points.len() < 2 {
continue;
}
// **A sunken road bends in the vertical where its line does not.** A
// portal's ramp now runs down an ordinary way beyond the tag, which is
// routinely one straight segment hundreds of metres long; sampled at
// its two ends the car's depth would fall from -7 m to 0 over the whole
// way while the drawn ramp reaches the surface after 117 m, and the car
// would drive through the ground under it.
if !mine.is_empty() {
points = densify(&points, DRIVE_DECK_STEP_M);
}
// **After the simplify, never before it.** The two arrays have to be
// parallel, and the cheap way to guarantee that is to derive one from
// the other's surviving points rather than to thin both and hope.
let deck: Vec<f32> = points
.iter()
.map(|p| {
mine.iter()
.filter_map(|s| s.road_under(*p))
.reduce(f32::min)
.unwrap_or(f32::NAN)
})
.collect();
let candidate = DriveLine {
points,
flow,
speed,
half_width,
uses: Uses {
drive: drive.is_some(),
walk,
cycle,
},
deck,
on_deck,
pavements: Pavements::BOTH,
};
if candidate.length() < MIN_DRIVE_LEN_M {
continue;
}
out.push(candidate);
}
}
Ok(out)
}
/// Which way traffic runs, from the two flags Shortbread carries.
///
/// **`oneway` and `oneway_reverse` are different answers and must not be ORed.**
/// `vector_tiles::street_style` does OR them, correctly, because a painted road
/// is the same width whichever way it runs; a car is not, and treating the two
/// as one sends every `oneway_reverse` street's traffic backwards.
///
/// Split from the feature so the rule is a pure function with a test on it — the
/// MVT plumbing around it is not what can be got wrong here.
#[must_use]
pub fn flow_from(oneway: bool, oneway_reverse: bool) -> Flow {
if oneway_reverse {
Flow::Backward
} else if oneway {
Flow::Forward
} else {
Flow::Both
}
}
/// The way's `bicycle` tag, which Shortbread passes through as a string.
fn bicycle_of(feature: &Feature) -> Option<&str> {
match feature.properties.as_ref()?.get("bicycle")? {
mvt_reader::feature::Value::String(s) => Some(s.as_str()),
_ => None,
}
}
fn flow_of(feature: &Feature) -> Flow {
flow_from(
crate::vector_tiles::flag_of(feature, "oneway"),
crate::vector_tiles::flag_of(feature, "oneway_reverse"),
)
}
/// Longest step along a line with a sunken corridor on it, metres — short enough
/// that a linearly interpolated deck follows a ramp's two bends to within a few
/// centimetres, and never shorter than [`DRIVE_SIMPLIFY_M`].
const DRIVE_DECK_STEP_M: f32 = 12.0;
/// Split every segment longer than `max_m` into equal steps no longer than it.
fn densify(points: &[[f32; 2]], max_m: f32) -> Vec<[f32; 2]> {
let mut out = Vec::with_capacity(points.len());
for w in points.windows(2) {
let (a, b) = (w[0], w[1]);
let len = (b[0] - a[0]).hypot(b[1] - a[1]);
#[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
let steps = (len / max_m).ceil().max(1.0) as usize;
for k in 0..steps {
#[allow(clippy::cast_precision_loss)]
let t = k as f32 / steps as f32;
out.push([a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t]);
}
}
if let Some(&end) = points.last() {
out.push(end);
}
out
}
/// Drop vertices closer together than `min_m`, keeping both ends.
///
/// A cheap running filter rather than Douglas–Peucker: the input is already a
/// generalised z14 line, the output is a driving line and not a drawn one, and
/// the only thing that matters is that no step is so short the steering loop
/// spends a frame on it.
fn simplify(points: &[[f32; 2]], min_m: f32) -> Vec<[f32; 2]> {
if points.len() < 2 {
return points.to_vec();
}
let min2 = min_m * min_m;
let mut out = vec![points[0]];
for p in &points[1..] {
let last = *out.last().expect("seeded above");
let (dx, dz) = (p[0] - last[0], p[1] - last[1]);
if dx * dx + dz * dz >= min2 {
out.push(*p);
}
}
// The end always survives, or a line loses its last stretch and every car on
// it hands off early — but never as a duplicate of the point before it.
let end = *points.last().expect("checked above");
let last = *out.last().expect("seeded above");
if (end[0] - last[0]).abs() > 1e-3 || (end[1] - last[1]).abs() > 1e-3 {
out.push(end);
}
out
}
#[cfg(test)]
mod tests {
use super::*;
use crate::testdata::groningen as fixture;
const TILE_M: f32 = 1472.0;
fn street(points: &[[f32; 2]], drive: bool) -> DriveLine {
DriveLine {
points: points.to_vec(),
flow: Flow::Both,
speed: 7.5,
half_width: 3.0,
uses: Uses {
drive,
walk: true,
cycle: true,
},
deck: vec![f32::NAN; points.len()],
on_deck: false,
pavements: Pavements::BOTH,
}
}
/// A street along +x, a lawn south of it (+z, which is its right) and a
/// pavement north: only the north side keeps its walkers. Lawn both sides
/// and nobody walks it; a path over the same lawn keeps them, on it.
#[test]
fn walkers_keep_off_the_verges() {
let south_lawn = |_x: f32, z: f32| z > 0.0;
let mut lines = vec![
street(&[[0.0, 0.0], [120.0, 0.0]], true),
street(&[[0.0, 0.0], [120.0, 0.0]], false),
];
keep_walkers_off(&mut lines, &south_lawn);
assert_eq!(
lines[0].pavements,
Pavements {
right: false,
left: true
}
);
assert!(lines[0].uses.walk);
assert!(lines[1].uses.walk, "a path is walked on, not beside");
assert_eq!(lines[1].pavements, Pavements::BOTH);
let mut verged = vec![street(&[[0.0, 0.0], [120.0, 0.0]], true)];
keep_walkers_off(&mut verged, &|_, _| true);
assert!(!verged[0].uses.walk, "grass both sides: nobody walks it");
assert!(verged[0].uses.drive, "the cars still do");
// A lawn reaching the kerb at one corner does not strip a pavement.
let mut corner = vec![street(&[[0.0, 0.0], [120.0, 0.0]], true)];
keep_walkers_off(&mut corner, &|x, _| x < 12.0);
assert_eq!(corner[0].pavements, Pavements::BOTH);
}
#[test]
fn the_fixture_yields_a_drivable_network() {
let lines = extract_drive_lines(&fixture(), TILE_M, &[]).expect("extract");
assert!(
lines.len() > 10,
"a city tile should be drivable: {}",
lines.len()
);
for l in &lines {
assert!(l.points.len() >= 2);
assert!(l.length() >= MIN_DRIVE_LEN_M);
assert!(l.uses.drive || l.uses.walk, "a line nobody may use");
if l.uses.drive {
assert!(l.speed > 0.0 && l.speed <= 30.0);
}
assert!(l.half_width > 0.0);
}
assert!(
lines.iter().any(|l| l.uses.walk && !l.uses.drive),
"a city tile has footways cars may not use"
);
assert!(
lines.iter().any(|l| l.uses.drive && l.uses.walk),
"an ordinary street carries both"
);
}
/// Nobody walks up a motorway or along a railway, and the two lists are not
/// the same list — a footway carries people and no cars, a motorway the
/// reverse.
#[test]
fn the_two_networks_differ_in_both_directions() {
for kind in ["footway", "path", "pedestrian", "cycleway", "steps"] {
assert!(walk_ok(kind), "{kind} carries people");
assert!(drive_speed(kind).is_none(), "{kind} carries no cars");
}
for kind in ["motorway", "trunk"] {
assert!(!walk_ok(kind), "{kind} carries nobody on foot");
assert!(drive_speed(kind).is_some(), "{kind} carries cars");
}
for kind in ["rail", "tram", "subway"] {
assert!(!walk_ok(kind) && drive_speed(kind).is_none(), "{kind}");
}
for kind in ["residential", "living_street", "service"] {
assert!(
walk_ok(kind) && drive_speed(kind).is_some(),
"{kind} carries both"
);
}
}
/// Cyclists ride the cycleways and the streets they share with cars, never a
/// motorway or a primary road (which has its own track), and a footpath only
/// where the way invites them.
#[test]
fn cyclists_keep_to_where_bikes_ride() {
for kind in [
"cycleway",
"residential",
"living_street",
"tertiary",
"secondary",
] {
assert!(cycle_ok(kind, None), "{kind} carries bikes");
}
for kind in ["motorway", "trunk", "primary", "steps", "rail", "track"] {
assert!(!cycle_ok(kind, None), "{kind} carries no bikes");
}
assert!(!cycle_ok("footway", None));
assert!(!cycle_ok("pedestrian", Some("permissive")));
assert!(cycle_ok("path", Some("designated")));
assert!(cycle_ok("footway", Some("yes")));
assert!(
!cycle_ok("cycleway", Some("no")),
"bicycle=no closes any way"
);
assert!(!cycle_ok("residential", Some("dismount")));
}
#[test]
fn the_fixture_has_cycleways() {
let lines = extract_drive_lines(&fixture(), TILE_M, &[]).expect("extract");
let only_bikes = lines
.iter()
.filter(|l| l.uses.cycle && !l.uses.drive)
.count();
let shared = lines
.iter()
.filter(|l| l.uses.cycle && l.uses.drive)
.count();
assert!(only_bikes > 0, "Groningen has cycle tracks");
assert!(shared > 0, "and streets bikes share with cars");
}
/// The one thing in this module a picture cannot show and a drive can: a
/// `oneway_reverse` street must send its traffic the *other* way. The raster
/// path ORs the two flags because a road's width does not care; traffic does.
#[test]
fn oneway_and_oneway_reverse_are_opposite_answers() {
assert_eq!(flow_from(true, false), Flow::Forward);
assert_eq!(flow_from(false, true), Flow::Backward);
assert_eq!(flow_from(false, false), Flow::Both);
// A way tagged both ways round is nonsense in the source; `reverse` wins
// rather than the pair silently collapsing to "forward", which is the
// answer ORing them would give.
assert_eq!(flow_from(true, true), Flow::Backward);
}
/// Nothing may drive on a footpath, a cycleway or a railway. An invented car
/// on a towpath is worse than an empty one.
#[test]
fn only_roads_are_drivable() {
for kind in [
"footway",
"path",
"cycleway",
"steps",
"pedestrian",
"rail",
"tram",
"subway",
"light_rail",
] {
assert!(drive_speed(kind).is_none(), "{kind} must not be drivable");
}
for kind in ["motorway", "primary", "residential", "service"] {
assert!(drive_speed(kind).is_some(), "{kind} must be drivable");
}
}
/// A motorway has to be clearly faster than a residential street, or the
/// whole speed table is decoration.
#[test]
fn the_speed_table_is_ordered() {
let motorway = drive_speed("motorway").expect("drivable");
let primary = drive_speed("primary").expect("drivable");
let residential = drive_speed("residential").expect("drivable");
let living = drive_speed("living_street").expect("drivable");
assert!(motorway > primary && primary > residential && residential > living);
}
/// The most specific access key decides, both ways round — the Vismarkt's
/// own tags are the first case.
#[test]
fn the_most_specific_access_key_decides() {
let tags = |pairs: &'static [(&'static str, &'static str)]| {
move |k: &str| pairs.iter().find(|(key, _)| *key == k).map(|(_, v)| *v)
};
assert!(cars_barred(tags(&[
("motor_vehicle", "no"),
("vehicle", "yes")
])));
assert!(!cars_barred(tags(&[
("access", "no"),
("motor_vehicle", "destination")
])));
assert!(cars_barred(tags(&[("vehicle", "no")])));
assert!(cars_barred(tags(&[("access", "private")])));
assert!(!cars_barred(tags(&[("motorcar", "yes"), ("access", "no")])));
assert!(!cars_barred(tags(&[])));
}
/// A line on a closed way is closed; one that only crosses its end, or runs
/// beside it a street's width away, is not.
#[test]
fn a_line_is_closed_only_along_a_closed_way() {
let way: &[[f32; 2]] = &[[0.0, 0.0], [100.0, 0.0]];
let closed = [way];
assert!(runs_along_closed(
&[[0.0, 1.5], [60.0, 2.0], [100.0, 1.0]],
&closed
));
assert!(!runs_along_closed(
&[[100.0, -50.0], [100.0, 50.0]],
&closed
));
assert!(!runs_along_closed(&[[0.0, 12.0], [100.0, 12.0]], &closed));
// Mostly closed, then on into an open street: still closed.
assert!(runs_along_closed(
&[[0.0, 0.0], [100.0, 0.0], [140.0, 0.0]],
&closed
));
assert!(!runs_along_closed(&[[0.0, 0.0], [100.0, 0.0]], &[]));
}
/// Simplification keeps both ends and never emits a zero-length step — a
/// zero step is a frame the steering loop spends going nowhere.
#[test]
fn simplify_keeps_both_ends_and_drops_the_crowd() {
let dense: Vec<[f32; 2]> = (0..=40).map(|i| [i as f32, 0.0]).collect();
let out = simplify(&dense, 8.0);
assert_eq!(out.first(), Some(&[0.0, 0.0]));
assert_eq!(out.last(), Some(&[40.0, 0.0]));
assert!(out.len() < dense.len(), "nothing was dropped");
for w in out.windows(2) {
let (dx, dz) = (w[1][0] - w[0][0], w[1][1] - w[0][1]);
assert!(dx * dx + dz * dz > 1e-6, "a zero-length step survived");
}
}
}