Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / scripts / maps / mamaps_build / src / schema / transit.rs
transit.rs515 lines · 23.4 KiBRaw
| 1 | //! `transit`: coloured rail lines, and the one layer whose data is not in the `.osm.pbf` at all. |
| 2 | //! |
| 3 | //! A transit line is a **GTFS shape**: one polyline out of an agency's own `shapes.txt`, carrying |
| 4 | //! the official `route_color` out of its `routes.txt`. `scripts/maps/gtfs_ingest`'s `transit_shapes` |
| 5 | //! binary turns a set of feeds into a `.geojsonseq` of them, and [`stream_routes`] reads that file |
| 6 | //! the way [`crate::schema::landtype::stream_prepared`] reads a prepared land polygon. The rail track |
| 7 | //! itself stays on the `roads` layer as the grey dashed casing from the reference style's |
| 8 | //! `roads_rail`, so the coloured line draws over neutral track exactly like a metro map. |
| 9 | //! # Why not OSM route relations |
| 10 | //! |
| 11 | //! It used to be exactly that: a `type=route` relation's member ways, coloured by the relation's |
| 12 | //! `colour=` tag or a per-mode guess. Both halves were wrong. A relation's members include its |
| 13 | //! **platforms**, and the member role is not in scope where the colour is assigned, so every |
| 14 | //! platform way came out as a wide coloured band beside the track. And a guessed colour is a guess |
| 15 | //! — GTFS has the agency's answer, so the layer takes it. |
| 16 | //! |
| 17 | //! The trade is coverage: anywhere with no feed in the built region loses lines it had from OSM, |
| 18 | //! and an agency-supplied shape does not sit exactly on OSM's rail casing. |
| 19 | //! |
| 20 | //! # Stations |
| 21 | //! |
| 22 | //! Stations stay on the `poi` layer as kind `station` (task 50), but with a `kind_detail` |
| 23 | //! naming the station mode — which is what makes them identifiable as *transit* stations when |
| 24 | //! the POI toggle is off. That half is still a tag query over the `.osm.pbf`. See |
| 25 | //! [`station_detail`]; its `station` tag reaches the pre-screen through `poi`'s own `FILTERS`. |
| 26 | |
| 27 | use std::path::Path; |
| 28 | |
| 29 | use osm_ingest::proto::{err, Result}; |
| 30 | use tile_build::geom::Geometry; |
| 31 | use tile_build::progress::Progress; |
| 32 | use tilecodec::mamaps::dict::LAYER_TRANSIT; |
| 33 | use tilecodec::mvt::Value; |
| 34 | |
| 35 | use super::{detail, kind, Class, TagSource}; |
| 36 | |
| 37 | /// The modes this layer carries. |
| 38 | /// |
| 39 | /// **A matched pair with `gtfs_ingest`'s `transit_shapes`**, which maps GTFS `route_type` onto |
| 40 | /// these five names and carries the fallback colour for each. The two crates cannot share code, so |
| 41 | /// a name added here has to be added there or nothing will ever be classified into it. |
| 42 | const MODES: &[&str] = &["subway", "light_rail", "tram", "train", "monorail"]; |
| 43 | |
| 44 | /// The zoom every transit line surfaces at, whatever its mode. |
| 45 | /// |
| 46 | /// One floor rather than [`crate::schema::roads`]' per-mode ladder, because a transit layer is a |
| 47 | /// **network** and half a network is worse than none: trunk rail at z8 with the metro withheld |
| 48 | /// until z12 draws a city as though it had no metro. The zoom that matters is the one where the |
| 49 | /// whole network first reads, and that is the trunk's. |
| 50 | const MIN_ZOOM: u8 = 8; |
| 51 | |
| 52 | /// The zoom long-distance rail surfaces at. |
| 53 | /// |
| 54 | /// The one exception to the single floor: an Amtrak or VIA line is the network at country zoom, |
| 55 | /// where nothing else on this layer would read. `transit_shapes` marks these lines `intercity`. |
| 56 | const INTERCITY_MIN_ZOOM: u8 = 3; |
| 57 | |
| 58 | /// A transit line's class: layer `transit`, kind `rail`, detail naming the mode. |
| 59 | /// |
| 60 | /// The kind stays `rail` (what the reference style's `roads_rail` matches) while the detail |
| 61 | /// distinguishes a subway from a tram — which is what lets the renderer vary width by mode |
| 62 | /// while keying colour off `transit_color`. An intercity line's detail is `intercity` rather |
| 63 | /// than its mode, which is what the style's country-zoom `transit-intercity` filters on. |
| 64 | pub fn transit_class(mode: &str, intercity: bool) -> Option<Class> { |
| 65 | if !MODES.contains(&mode) { |
| 66 | return None; |
| 67 | } |
| 68 | Some(Class { |
| 69 | layer: LAYER_TRANSIT, |
| 70 | kind: kind("rail"), |
| 71 | kind_detail: detail(if intercity { "intercity" } else { mode }), |
| 72 | flags: 0, |
| 73 | area: false, |
| 74 | min_zoom: if intercity { INTERCITY_MIN_ZOOM } else { MIN_ZOOM }, |
| 75 | min_area_px: 0.0, |
| 76 | }) |
| 77 | } |
| 78 | |
| 79 | /// Stream a prepared transit-routes file into the feature sink, clipped to `bbox`. |
| 80 | /// |
| 81 | /// The `.geojsonseq` `transit_shapes` writes: one `LineString` per rail route, with `color` |
| 82 | /// (`RRGGBB`), `mode`, `ordinal`, `lanes` and `taper` properties. Modelled on |
| 83 | /// [`crate::schema::landtype::stream_prepared`] down to the streaming read and the "this file yielded |
| 84 | /// nothing, so you passed the wrong one" error at the end. |
| 85 | /// |
| 86 | /// Every malformed line is a hard error rather than a skip. The file is written by a tool in this |
| 87 | /// repo, so anything this cannot read means the wrong file was handed over — and a transit layer |
| 88 | /// that is quietly half a city is the failure mode that took a device pass to notice. The three |
| 89 | /// lane properties are the one exception: **absent** ones default to a route on its own alignment |
| 90 | /// (`ordinal 0, lanes 1, taper 255`), so a file written before corridors existed still reads. One |
| 91 | /// that is present and unreadable is still an error. |
| 92 | /// |
| 93 | /// `bbox` is `(min_lon, min_lat, max_lon, max_lat)` in degrees and is an intersection test, not a |
| 94 | /// clip: a route running out of the extract is drawn to where the tiler cuts it, exactly as an OSM |
| 95 | /// way straddling the same edge is. |
| 96 | /// |
| 97 | /// An empty file (no non-blank lines) yields zero routes rather than an |
| 98 | /// error: that is what a `--notransit` build feeds in, and zero feeds means |
| 99 | /// an empty transit layer, not a wrong file. A non-empty file with no |
| 100 | /// meeting route is still an error below. |
| 101 | pub fn stream_routes( |
| 102 | path: &Path, |
| 103 | bbox: (f64, f64, f64, f64), |
| 104 | sink: &mut crate::store::Sink, |
| 105 | ) -> Result<u64> { |
| 106 | let text = std::fs::read_to_string(path) |
| 107 | .map_err(|e| osm_ingest::proto::Error(format!("cannot read {}: {e}", path.display())))?; |
| 108 | if text.lines().all(|line| line.trim().is_empty()) { |
| 109 | println!(" 0 transit route(s): empty routes file, the transit layer is empty"); |
| 110 | return Ok(0); |
| 111 | } |
| 112 | let mut written = 0u64; |
| 113 | let mut skipped = 0u64; |
| 114 | // File order is feature order and the layer is coalesced, so the push |
| 115 | // stays serial; the bar is what keeps a large feed from reading as a |
| 116 | // hang. Ticked per line read (not per route kept), so it spans the |
| 117 | // whole file even when most of it is outside the extract. |
| 118 | let total_lines = text.lines().filter(|line| !line.trim().is_empty()).count(); |
| 119 | let mut bar = |
| 120 | Progress::new("Transit: routes".to_string(), total_lines, "line(s)", true); |
| 121 | for (line_number, line) in text.lines().enumerate() { |
| 122 | if line.trim().is_empty() { |
| 123 | continue; |
| 124 | } |
| 125 | bar.tick("line(s)"); |
| 126 | let at = |what: &str| { |
| 127 | osm_ingest::proto::Error(format!("{}:{}: {what}", path.display(), line_number + 1)) |
| 128 | }; |
| 129 | let Some(feature) = tile_build::geojson::parse_feature(line) else { |
| 130 | return Err(at("not a GeoJSON feature")); |
| 131 | }; |
| 132 | // Lines only. A prepared transit-routes file has nothing else in it, and a polygon in |
| 133 | // there would be a sign the coastline product was passed by mistake. |
| 134 | let Geometry::Lines(lines) = feature.geometry else { |
| 135 | return Err(at("not a LineString; is this the transit-routes file?")); |
| 136 | }; |
| 137 | let Some(mode) = prop(&feature.props, "mode") else { |
| 138 | return Err(at("no `mode` property")); |
| 139 | }; |
| 140 | // Absent is an ordinary line, like the lane inputs below; present and not 0/1 is an error. |
| 141 | let Some(intercity) = byte_prop(&feature.props, "intercity", 0).filter(|v| *v <= 1) else { |
| 142 | return Err(at("an `intercity` property that is not 0 or 1")); |
| 143 | }; |
| 144 | let Some(class) = transit_class(&mode, intercity == 1) else { |
| 145 | return Err(at(&format!("`{mode}` is not a mode this layer carries"))); |
| 146 | }; |
| 147 | let Some(color) = prop(&feature.props, "color").as_deref().and_then(hex_rrggbb) else { |
| 148 | return Err(at("no usable `color` property; it must be non-zero bare RRGGBB hex")); |
| 149 | }; |
| 150 | let Some(ordinal) = byte_prop(&feature.props, "ordinal", 0) else { |
| 151 | return Err(at("an `ordinal` property that is not a whole number in 0..=255")); |
| 152 | }; |
| 153 | let Some(lanes) = byte_prop(&feature.props, "lanes", 1) else { |
| 154 | return Err(at("a `lanes` property that is not a whole number in 0..=255")); |
| 155 | }; |
| 156 | let Some(taper) = byte_prop(&feature.props, "taper", 255) else { |
| 157 | return Err(at("a `taper` property that is not a whole number in 0..=255")); |
| 158 | }; |
| 159 | for line in lines { |
| 160 | if line.len() < 2 || !meets(&line, bbox) { |
| 161 | skipped += 1; |
| 162 | continue; |
| 163 | } |
| 164 | sink.push_transit(&class, &crate::store::EncodedGeom::live(&Geometry::Lines(vec![line]))?, color, ordinal, lanes, taper)?; |
| 165 | written += 1; |
| 166 | } |
| 167 | } |
| 168 | if written == 0 { |
| 169 | return err(format!( |
| 170 | "{} holds no transit route meeting {bbox:?}; is it the right area?", |
| 171 | path.display(), |
| 172 | )); |
| 173 | } |
| 174 | bar.finish("line(s)"); |
| 175 | println!(" {written} transit route(s) kept, {skipped} outside the extract"); |
| 176 | Ok(written) |
| 177 | } |
| 178 | |
| 179 | /// A string-valued property, by name. |
| 180 | fn prop(props: &[(String, Value)], name: &str) -> Option<String> { |
| 181 | props.iter().find(|(k, _)| k == name).and_then(|(_, v)| match v { |
| 182 | Value::String(s) => Some(s.clone()), |
| 183 | _ => None, |
| 184 | }) |
| 185 | } |
| 186 | |
| 187 | /// One of the lane inputs as a byte. `None` only for a property that is there and unreadable. |
| 188 | /// |
| 189 | /// Absent is `missing` on purpose: everything else in this reader hard-errors, and falling into |
| 190 | /// that path would make a routes file written before corridors existed unreadable rather than |
| 191 | /// simply un-fanned. The GeoJSON reader gives a non-negative literal back as a `Uint` and a |
| 192 | /// negative one as a `Double`, so every arm is the same number. |
| 193 | fn byte_prop(props: &[(String, Value)], name: &str, missing: u8) -> Option<u8> { |
| 194 | match props.iter().find(|(k, _)| k == name) { |
| 195 | None => Some(missing), |
| 196 | Some((_, Value::Uint(v))) => u8::try_from(*v).ok(), |
| 197 | Some((_, Value::Int(v))) | Some((_, Value::SInt(v))) => u8::try_from(*v).ok(), |
| 198 | Some((_, Value::Double(v))) if v.fract() == 0.0 => { |
| 199 | (*v >= 0.0 && *v <= u8::MAX as f64).then_some(*v as u8) |
| 200 | } |
| 201 | Some(_) => None, |
| 202 | } |
| 203 | } |
| 204 | |
| 205 | /// A bare `RRGGBB` hex colour as `0xRRGGBB`, or `None`. |
| 206 | /// |
| 207 | /// Zero is refused: it means "no colour" on the wire and [`crate::store::Sink::push_transit`] |
| 208 | /// rejects it, so catching it here names the offending line instead. |
| 209 | fn hex_rrggbb(raw: &str) -> Option<u32> { |
| 210 | let hex = raw.trim(); |
| 211 | if hex.len() != 6 || !hex.chars().all(|c| c.is_ascii_hexdigit()) { |
| 212 | return None; |
| 213 | } |
| 214 | u32::from_str_radix(hex, 16).ok().filter(|c| *c != 0) |
| 215 | } |
| 216 | |
| 217 | /// Does a polyline meet `bbox`? Intersection, not containment. |
| 218 | fn meets(line: &[(f64, f64)], bbox: (f64, f64, f64, f64)) -> bool { |
| 219 | let (mut min_x, mut min_y) = (f64::MAX, f64::MAX); |
| 220 | let (mut max_x, mut max_y) = (f64::MIN, f64::MIN); |
| 221 | for &(x, y) in line { |
| 222 | min_x = min_x.min(x); |
| 223 | min_y = min_y.min(y); |
| 224 | max_x = max_x.max(x); |
| 225 | max_y = max_y.max(y); |
| 226 | } |
| 227 | !(max_x < bbox.0 || min_x > bbox.2 || max_y < bbox.1 || min_y > bbox.3) |
| 228 | } |
| 229 | |
| 230 | /// The station mode for a `poi` station feature's `kind_detail`. |
| 231 | /// |
| 232 | /// `station=subway/light_rail/tram` name the mode directly; a bare `railway=station` is a |
| 233 | /// `station`; a `railway=halt` is a `halt`. This is the tag the renderer reads to show stations |
| 234 | /// when Transit is ON even with POIs OFF: `poi` layer, kind `station`, detail naming one of |
| 235 | /// these — everything else on the layer is a different kind already. |
| 236 | pub fn station_detail(tags: &(impl TagSource + ?Sized)) -> &'static str { |
| 237 | match tags.get("station") { |
| 238 | Some("subway") => "subway", |
| 239 | Some("light_rail") => "light_rail", |
| 240 | Some("tram") => "tram", |
| 241 | Some("monorail") => "monorail", |
| 242 | _ => match tags.get("railway") { |
| 243 | Some("halt") => "halt", |
| 244 | _ => "station", |
| 245 | }, |
| 246 | } |
| 247 | } |
| 248 | |
| 249 | #[cfg(test)] |
| 250 | mod tests { |
| 251 | use super::*; |
| 252 | use tilecodec::mamaps::dict; |
| 253 | |
| 254 | fn station_mode(pairs: &[(&str, &str)]) -> &'static str { |
| 255 | super::station_detail(pairs) |
| 256 | } |
| 257 | |
| 258 | /// One `LineString` per line, written by `transit_shapes`. |
| 259 | fn feature(color: &str, mode: &str, coords: &str) -> String { |
| 260 | format!( |
| 261 | "{{\"type\":\"Feature\",\"geometry\":{{\"type\":\"LineString\",\ |
| 262 | \"coordinates\":[{coords}]}},\"properties\":{{\"color\":\"{color}\",\ |
| 263 | \"mode\":\"{mode}\"}}}}" |
| 264 | ) |
| 265 | } |
| 266 | |
| 267 | /// The same, carrying the corridor lane inputs. |
| 268 | fn slotted(color: &str, mode: &str, ordinal: u8, lanes: u8, taper: u8, coords: &str) -> String { |
| 269 | format!( |
| 270 | "{{\"type\":\"Feature\",\"geometry\":{{\"type\":\"LineString\",\ |
| 271 | \"coordinates\":[{coords}]}},\"properties\":{{\"color\":\"{color}\",\ |
| 272 | \"mode\":\"{mode}\",\"ordinal\":{ordinal},\"lanes\":{lanes},\ |
| 273 | \"taper\":{taper}}}}}" |
| 274 | ) |
| 275 | } |
| 276 | |
| 277 | fn scratch(tag: &str) -> std::path::PathBuf { |
| 278 | std::env::temp_dir().join(format!("mamaps_transit_{tag}_{}", std::process::id())) |
| 279 | } |
| 280 | |
| 281 | #[test] |
| 282 | fn every_mode_has_a_class_and_they_all_share_one_floor() { |
| 283 | for mode in MODES { |
| 284 | let class = transit_class(mode, false).expect("a class"); |
| 285 | assert_eq!(class.layer, dict::LAYER_TRANSIT); |
| 286 | assert_eq!(dict::KINDS[class.kind as usize - 1], "rail"); |
| 287 | assert_eq!(dict::DETAILS[class.kind_detail as usize - 1], *mode); |
| 288 | assert!(!class.area, "a line, even looped"); |
| 289 | // The whole network appears at once; see [`MIN_ZOOM`]. The style's `transit-rail` |
| 290 | // carries the same 8, and a floor deeper than that here would leave it asking for |
| 291 | // features the archive does not hold. |
| 292 | assert_eq!(class.min_zoom, 8, "{mode}"); |
| 293 | } |
| 294 | assert!(transit_class("bus", false).is_none()); |
| 295 | } |
| 296 | |
| 297 | #[test] |
| 298 | fn an_intercity_line_surfaces_at_country_zoom() { |
| 299 | let class = transit_class("train", true).expect("a class"); |
| 300 | assert_eq!(dict::DETAILS[class.kind_detail as usize - 1], "intercity"); |
| 301 | assert_eq!(class.min_zoom, 3); |
| 302 | assert_eq!(dict::KINDS[class.kind as usize - 1], "rail", "still drawn by transit-rail"); |
| 303 | assert!(transit_class("bus", true).is_none(), "still only the rail modes"); |
| 304 | |
| 305 | let path = scratch("intercity.geojsonseq"); |
| 306 | let coords = "[-122.4,37.7],[-118.2,34.0]"; |
| 307 | std::fs::write( |
| 308 | &path, |
| 309 | format!( |
| 310 | "{}\n{}\n", |
| 311 | feature("0057A8", "train", coords).replace("\"mode\":\"train\"", "\"mode\":\"train\",\"intercity\":1"), |
| 312 | feature("0057A8", "train", coords), |
| 313 | ), |
| 314 | ) |
| 315 | .expect("write"); |
| 316 | let spill = scratch("intercity.features"); |
| 317 | let mut sink = crate::store::Sink::create(&spill).expect("sink"); |
| 318 | assert_eq!(stream_routes(&path, (-180.0, -90.0, 180.0, 90.0), &mut sink).expect("read"), 2); |
| 319 | let store = sink.finish(&spill).expect("finish"); |
| 320 | let mut reader = store.reader().expect("reader"); |
| 321 | let floors: Vec<u8> = std::iter::from_fn(|| reader.next().expect("read")).map(|f| f.class.min_zoom).collect(); |
| 322 | assert_eq!(floors, vec![3, 8], "flagged, then an ordinary line"); |
| 323 | |
| 324 | std::fs::write(&path, feature("0057A8", "train", coords).replace("\"mode\":\"train\"", "\"mode\":\"train\",\"intercity\":2") + "\n") |
| 325 | .expect("write"); |
| 326 | let mut sink = crate::store::Sink::create(&spill).expect("sink"); |
| 327 | assert!(stream_routes(&path, (-180.0, -90.0, 180.0, 90.0), &mut sink).is_err(), "2 is not a flag"); |
| 328 | let _ = std::fs::remove_file(&path); |
| 329 | let _ = std::fs::remove_file(&spill); |
| 330 | } |
| 331 | |
| 332 | #[test] |
| 333 | fn colours_are_nonzero_bare_hex() { |
| 334 | assert_eq!(hex_rrggbb("E4002B"), Some(0xE4002B)); |
| 335 | assert_eq!(hex_rrggbb(" e4002b "), Some(0xE4002B)); |
| 336 | assert_eq!(hex_rrggbb("#E4002B"), None, "the exporter writes bare hex"); |
| 337 | assert_eq!(hex_rrggbb("F00"), None, "no short form"); |
| 338 | assert_eq!(hex_rrggbb("GGGGGG"), None); |
| 339 | // Zero means "no colour" on the wire, so it must never reach `push_transit`. |
| 340 | assert_eq!(hex_rrggbb("000000"), None); |
| 341 | } |
| 342 | |
| 343 | #[test] |
| 344 | fn a_prepared_route_streams_in_as_a_coloured_transit_line() { |
| 345 | let path = scratch("routes.geojsonseq"); |
| 346 | std::fs::write( |
| 347 | &path, |
| 348 | format!( |
| 349 | "{}\n{}\n", |
| 350 | feature("0054A5", "subway", "[-122.4,37.7],[-122.39,37.71]"), |
| 351 | feature("E31E24", "light_rail", "[-122.4,37.7],[-122.41,37.72]"), |
| 352 | ), |
| 353 | ) |
| 354 | .expect("write"); |
| 355 | let spill = scratch("routes.features"); |
| 356 | let mut sink = crate::store::Sink::create(&spill).expect("sink"); |
| 357 | assert_eq!( |
| 358 | stream_routes(&path, (-180.0, -90.0, 180.0, 90.0), &mut sink).expect("read"), |
| 359 | 2, |
| 360 | ); |
| 361 | let store = sink.finish(&spill).expect("finish"); |
| 362 | |
| 363 | let mut reader = store.reader().expect("reader"); |
| 364 | let first = reader.next().expect("read").expect("a feature"); |
| 365 | assert_eq!(first.class.layer, dict::LAYER_TRANSIT); |
| 366 | assert_eq!(dict::KINDS[first.class.kind as usize - 1], "rail"); |
| 367 | assert_eq!(dict::DETAILS[first.class.kind_detail as usize - 1], "subway"); |
| 368 | assert_eq!(first.transit_color, 0x00_54_A5, "the agency's own colour, verbatim"); |
| 369 | assert_eq!( |
| 370 | (first.transit_ordinal, first.transit_lanes, first.transit_taper), |
| 371 | (0, 1, 255), |
| 372 | "absent lane inputs are a route on its own alignment", |
| 373 | ); |
| 374 | let second = reader.next().expect("read").expect("a feature"); |
| 375 | assert_eq!(second.transit_color, 0xE3_1E_24); |
| 376 | assert_eq!(second.class.min_zoom, 8, "the network's single floor"); |
| 377 | |
| 378 | let _ = std::fs::remove_file(&path); |
| 379 | let _ = std::fs::remove_file(&spill); |
| 380 | } |
| 381 | |
| 382 | /// The lane inputs ride through to the feature untouched — the renderer, not the exporter, |
| 383 | /// decides how many lanes to use, so nothing here clamps the count. |
| 384 | #[test] |
| 385 | fn the_corridor_lane_inputs_stream_through_to_the_feature() { |
| 386 | let path = scratch("slots.geojsonseq"); |
| 387 | std::fs::write( |
| 388 | &path, |
| 389 | format!( |
| 390 | "{}\n{}\n{}\n", |
| 391 | slotted("0054A5", "subway", 0, 10, 255, "[-122.4,37.7],[-122.39,37.71]"), |
| 392 | slotted("0054A5", "subway", 9, 10, 128, "[-122.4,37.7],[-122.39,37.71]"), |
| 393 | slotted("0054A5", "subway", 0, 1, 255, "[-122.4,37.7],[-122.39,37.71]"), |
| 394 | ), |
| 395 | ) |
| 396 | .expect("write"); |
| 397 | let spill = scratch("slots.features"); |
| 398 | let mut sink = crate::store::Sink::create(&spill).expect("sink"); |
| 399 | assert_eq!(stream_routes(&path, (-180.0, -90.0, 180.0, 90.0), &mut sink).expect("read"), 3); |
| 400 | let store = sink.finish(&spill).expect("finish"); |
| 401 | |
| 402 | let mut reader = store.reader().expect("reader"); |
| 403 | let mut read = Vec::new(); |
| 404 | while let Some(feature) = reader.next().expect("read") { |
| 405 | read.push((feature.transit_ordinal, feature.transit_lanes, feature.transit_taper)); |
| 406 | } |
| 407 | assert_eq!(read, vec![(0, 10, 255), (9, 10, 128), (0, 1, 255)]); |
| 408 | |
| 409 | let _ = std::fs::remove_file(&path); |
| 410 | let _ = std::fs::remove_file(&spill); |
| 411 | } |
| 412 | |
| 413 | #[test] |
| 414 | fn a_lane_input_that_is_not_a_byte_is_an_error() { |
| 415 | let spill = scratch("badslot.features"); |
| 416 | let path = scratch("badslot.geojsonseq"); |
| 417 | for body in [ |
| 418 | "\"ordinal\":\"left\"", |
| 419 | "\"ordinal\":1.5", |
| 420 | "\"lanes\":99999", |
| 421 | "\"taper\":-1", |
| 422 | ] { |
| 423 | std::fs::write( |
| 424 | &path, |
| 425 | format!( |
| 426 | "{{\"type\":\"Feature\",\"geometry\":{{\"type\":\"LineString\",\ |
| 427 | \"coordinates\":[[-122.4,37.7],[-122.39,37.71]]}},\"properties\":\ |
| 428 | {{\"color\":\"0054A5\",\"mode\":\"subway\",{body}}}}}\n" |
| 429 | ), |
| 430 | ) |
| 431 | .expect("write"); |
| 432 | let mut sink = crate::store::Sink::create(&spill).expect("sink"); |
| 433 | assert!( |
| 434 | stream_routes(&path, (-180.0, -90.0, 180.0, 90.0), &mut sink).is_err(), |
| 435 | "{body} was accepted", |
| 436 | ); |
| 437 | } |
| 438 | let _ = std::fs::remove_file(&path); |
| 439 | let _ = std::fs::remove_file(&spill); |
| 440 | } |
| 441 | |
| 442 | /// The same clip `earth` does, for the same reason: the file covers whatever regions were |
| 443 | /// exported, and a corridor build must not carry lines from outside it. |
| 444 | #[test] |
| 445 | fn a_route_outside_the_build_area_is_not_carried() { |
| 446 | let path = scratch("clip.geojsonseq"); |
| 447 | std::fs::write( |
| 448 | &path, |
| 449 | format!( |
| 450 | "{}\n{}\n", |
| 451 | feature("0054A5", "subway", "[-122.4,37.7],[-122.39,37.71]"), |
| 452 | feature("0054A5", "train", "[-9.0,38.0],[-8.9,38.1]"), |
| 453 | ), |
| 454 | ) |
| 455 | .expect("write"); |
| 456 | let spill = scratch("clip.features"); |
| 457 | let mut sink = crate::store::Sink::create(&spill).expect("sink"); |
| 458 | let california = (-125.0, 32.0, -114.0, 42.0); |
| 459 | assert_eq!(stream_routes(&path, california, &mut sink).expect("read"), 1); |
| 460 | |
| 461 | // And an area with no route in it is an error, not an empty layer. |
| 462 | let mut sink = crate::store::Sink::create(&spill).expect("sink"); |
| 463 | assert!(stream_routes(&path, (-160.0, 0.0, -150.0, 10.0), &mut sink).is_err()); |
| 464 | |
| 465 | let _ = std::fs::remove_file(&path); |
| 466 | let _ = std::fs::remove_file(&spill); |
| 467 | } |
| 468 | |
| 469 | /// Every way this file can be the wrong file. Each is an error naming the line, because a |
| 470 | /// transit layer that is quietly half a city is what this change exists to stop shipping. |
| 471 | #[test] |
| 472 | fn a_line_this_cannot_read_is_an_error_rather_than_a_skip() { |
| 473 | let spill = scratch("bad.features"); |
| 474 | let world = (-180.0, -90.0, 180.0, 90.0); |
| 475 | for (tag, body) in [ |
| 476 | ("nonsense", "not json at all".to_string()), |
| 477 | ( |
| 478 | "polygon", |
| 479 | "{\"type\":\"Feature\",\"properties\":{\"color\":\"0054A5\",\"mode\":\"subway\"},\ |
| 480 | \"geometry\":{\"type\":\"Polygon\",\"coordinates\":[[[0.0,0.0],[1.0,0.0],\ |
| 481 | [1.0,1.0],[0.0,0.0]]]}}" |
| 482 | .to_string(), |
| 483 | ), |
| 484 | ("no_mode", feature("0054A5", "", "[-122.4,37.7],[-122.39,37.71]")), |
| 485 | ("bus", feature("0054A5", "bus", "[-122.4,37.7],[-122.39,37.71]")), |
| 486 | ("black", feature("000000", "subway", "[-122.4,37.7],[-122.39,37.71]")), |
| 487 | ("no_colour", feature("nope", "subway", "[-122.4,37.7],[-122.39,37.71]")), |
| 488 | ] { |
| 489 | let path = scratch(&format!("bad_{tag}.geojsonseq")); |
| 490 | std::fs::write(&path, format!("{body}\n")).expect("write"); |
| 491 | let mut sink = crate::store::Sink::create(&spill).expect("sink"); |
| 492 | assert!(stream_routes(&path, world, &mut sink).is_err(), "{tag} was accepted"); |
| 493 | let _ = std::fs::remove_file(&path); |
| 494 | } |
| 495 | // A missing file too, rather than an empty layer. |
| 496 | let mut sink = crate::store::Sink::create(&spill).expect("sink"); |
| 497 | assert!(stream_routes(Path::new("no_such_routes.geojsonseq"), world, &mut sink).is_err()); |
| 498 | let _ = std::fs::remove_file(&spill); |
| 499 | } |
| 500 | |
| 501 | #[test] |
| 502 | fn stations_name_their_mode() { |
| 503 | assert_eq!(station_mode(&[("railway", "station")]), "station"); |
| 504 | assert_eq!(station_mode(&[("railway", "halt")]), "halt"); |
| 505 | assert_eq!( |
| 506 | station_mode(&[("railway", "station"), ("station", "subway")]), |
| 507 | "subway" |
| 508 | ); |
| 509 | assert_eq!( |
| 510 | station_mode(&[("station", "light_rail")]), |
| 511 | "light_rail", |
| 512 | "a station tag alone counts" |
| 513 | ); |
| 514 | } |
| 515 | } |