Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / scripts / maps / osm_ingest / src / extract_part1.rs
extract_part1.rs396 lines · 13.1 KiBRaw
| 1 | impl RoadRow { |
| 2 | fn tags(&self) -> RoadTags<'_> { |
| 3 | RoadTags { |
| 4 | // `highway` is not re-read: `class` already holds what it classified to. |
| 5 | highway: None, |
| 6 | maxspeed: self.maxspeed.as_deref(), |
| 7 | lanes: self.lanes.as_deref(), |
| 8 | lanes_forward: self.lanes_forward.as_deref(), |
| 9 | lanes_backward: self.lanes_backward.as_deref(), |
| 10 | turn_lanes: self.turn_lanes.as_deref(), |
| 11 | turn_lanes_forward: self.turn_lanes_forward.as_deref(), |
| 12 | turn_lanes_backward: self.turn_lanes_backward.as_deref(), |
| 13 | oneway: self.oneway.as_deref(), |
| 14 | width: self.width.as_deref(), |
| 15 | bridge: self.bridge.as_deref(), |
| 16 | tunnel: self.tunnel.as_deref(), |
| 17 | layer: self.layer.as_deref(), |
| 18 | } |
| 19 | } |
| 20 | } |
| 21 | |
| 22 | fn build_roads( |
| 23 | input: &Path, |
| 24 | blobs: &[pbf::BlobLoc], |
| 25 | out: &Path, |
| 26 | opts: &Options, |
| 27 | ) -> Result<Stats> { |
| 28 | let select = Select::parse(&roads::FILTERS)?; |
| 29 | |
| 30 | // Same two passes as `maxspeed`: ways, then the node coordinates they need. |
| 31 | let (chunks, blob_kinds) = pbf::run_pass( |
| 32 | input, |
| 33 | blobs, |
| 34 | None, |
| 35 | KIND_WAYS, |
| 36 | "Pass 1: ways", |
| 37 | Vec::<RoadRow>::new, |
| 38 | |state: &mut Vec<RoadRow>, block| roads_blob(state, block, &select), |
| 39 | )?; |
| 40 | let mut rows: Vec<RoadRow> = Vec::new(); |
| 41 | for chunk in chunks { |
| 42 | rows.extend(chunk); |
| 43 | } |
| 44 | println!("{} road way(s)", rows.len()); |
| 45 | |
| 46 | let table = NodeLocations::new(rows.iter().flat_map(|r| r.refs.iter().copied()).collect())?; |
| 47 | println!("{} node location(s) needed", table.len()); |
| 48 | let table = resolve_nodes(input, blobs, &blob_kinds, "Pass 2: nodes", table)?; |
| 49 | |
| 50 | let mut lines: Vec<LineFeature> = Vec::with_capacity(rows.len()); |
| 51 | let mut outside_bbox = 0usize; |
| 52 | // `drain` rather than a borrow: at planet scale the rows and the rendered output |
| 53 | // would otherwise both be resident, and the rows are the larger half. |
| 54 | for row in rows.drain(..) { |
| 55 | let coords = table.line(&row.refs); |
| 56 | if coords.len() < 2 { |
| 57 | continue; |
| 58 | } |
| 59 | if !parts_touch_bbox(std::slice::from_ref(&coords), opts.bbox.as_ref()) { |
| 60 | outside_bbox += 1; |
| 61 | continue; |
| 62 | } |
| 63 | let f = roads::feature(row.class, &row.tags(), Geometry::LineString(coords), row.id); |
| 64 | lines.push(LineFeature { sort: ("way", row.id), rendered: render(&f) }); |
| 65 | } |
| 66 | |
| 67 | let written = write_lines(out, lines)?; |
| 68 | println!("Wrote {} roads feature(s) to {}", written, out.display()); |
| 69 | if outside_bbox > 0 { |
| 70 | println!("{outside_bbox} feature(s) dropped by --bbox"); |
| 71 | } |
| 72 | Ok(Stats { |
| 73 | features: written, |
| 74 | from_nodes: 0, |
| 75 | from_ways: written, |
| 76 | from_relations: 0, |
| 77 | outside_bbox, |
| 78 | }) |
| 79 | } |
| 80 | |
| 81 | fn roads_blob( |
| 82 | state: &mut Vec<RoadRow>, |
| 83 | block: &pbf::PrimitiveBlock, |
| 84 | select: &Select, |
| 85 | ) -> Result<u8> { |
| 86 | let mut kinds = 0u8; |
| 87 | visit_block(block, KIND_WAYS, &mut kinds, &mut |el: Element| { |
| 88 | if let Element::Way(w) = el { |
| 89 | if w.refs.len() < 2 || w.tags.is_empty() { |
| 90 | return Ok(()); |
| 91 | } |
| 92 | if !select.matches(|k| w.tags.get_str(k)) { |
| 93 | return Ok(()); |
| 94 | } |
| 95 | let t = RoadTags { highway: w.tags.get_str("highway"), ..Default::default() }; |
| 96 | let Some(class) = roads::classify(&t) else { |
| 97 | return Ok(()); |
| 98 | }; |
| 99 | let own = |k: &str| w.tags.get_str(k).map(str::to_string); |
| 100 | state.push(RoadRow { |
| 101 | id: w.id, |
| 102 | refs: w.refs.to_vec(), |
| 103 | class, |
| 104 | maxspeed: own("maxspeed"), |
| 105 | lanes: own("lanes"), |
| 106 | lanes_forward: own("lanes:forward"), |
| 107 | lanes_backward: own("lanes:backward"), |
| 108 | turn_lanes: own("turn:lanes"), |
| 109 | turn_lanes_forward: own("turn:lanes:forward"), |
| 110 | turn_lanes_backward: own("turn:lanes:backward"), |
| 111 | oneway: own("oneway"), |
| 112 | width: own("width"), |
| 113 | bridge: own("bridge"), |
| 114 | tunnel: own("tunnel"), |
| 115 | layer: own("layer"), |
| 116 | }); |
| 117 | } |
| 118 | Ok(()) |
| 119 | })?; |
| 120 | Ok(kinds) |
| 121 | } |
| 122 | |
| 123 | // --- transit_lines -------------------------------------------------------- |
| 124 | |
| 125 | /// One classified way or relation, with its tag values copied out of the block. |
| 126 | struct TransitRow { |
| 127 | /// `"way"` or `"relation"`, for the `osm_id` and for the sort. |
| 128 | element: &'static str, |
| 129 | id: i64, |
| 130 | kind: &'static str, |
| 131 | name: Option<String>, |
| 132 | reference: Option<String>, |
| 133 | colour: Option<String>, |
| 134 | /// A way has one part. A relation has one per member way, in member order. |
| 135 | /// Empty until the way pass fills a relation's in. |
| 136 | parts: Vec<Vec<i64>>, |
| 137 | /// A relation's member way ids, in member order. |
| 138 | member_ways: Vec<i64>, |
| 139 | } |
| 140 | |
| 141 | #[derive(Default)] |
| 142 | struct TransitWayPass { |
| 143 | rows: Vec<TransitRow>, |
| 144 | /// `(way id, its refs)` for ways a relation claimed. A per-chunk assoc list |
| 145 | /// rather than a map: cheap to push, and the merge is single-threaded anyway. |
| 146 | wanted: Vec<(i64, Vec<i64>)>, |
| 147 | } |
| 148 | |
| 149 | fn build_transit_lines( |
| 150 | input: &Path, |
| 151 | blobs: &[pbf::BlobLoc], |
| 152 | out: &Path, |
| 153 | opts: &Options, |
| 154 | ) -> Result<Stats> { |
| 155 | let way_select = Select::parse(&transit_lines::WAY_FILTERS)?; |
| 156 | let rel_select = Select::parse(&transit_lines::RELATION_FILTERS)?; |
| 157 | |
| 158 | // Pass 1: relations, which decide which ways matter. |
| 159 | let (chunks, blob_kinds) = pbf::run_pass( |
| 160 | input, |
| 161 | blobs, |
| 162 | None, |
| 163 | KIND_RELATIONS, |
| 164 | "Pass 1: relations", |
| 165 | Vec::<TransitRow>::new, |
| 166 | |state: &mut Vec<TransitRow>, block| transit_relation_blob(state, block, &rel_select), |
| 167 | )?; |
| 168 | let mut rel_rows: Vec<TransitRow> = Vec::new(); |
| 169 | for chunk in chunks { |
| 170 | rel_rows.extend(chunk); |
| 171 | } |
| 172 | let mut wanted_ways: Vec<i64> = rel_rows |
| 173 | .iter() |
| 174 | .flat_map(|r| r.member_ways.iter().copied()) |
| 175 | .collect(); |
| 176 | wanted_ways.sort_unstable(); |
| 177 | wanted_ways.dedup(); |
| 178 | println!( |
| 179 | "{} route relation(s), {} member way(s)", |
| 180 | rel_rows.len(), |
| 181 | wanted_ways.len() |
| 182 | ); |
| 183 | |
| 184 | // Pass 2: ways, which are both features in their own right and the geometry |
| 185 | // the relations need. |
| 186 | let (chunks, _) = pbf::run_pass( |
| 187 | input, |
| 188 | blobs, |
| 189 | Some(&blob_kinds), |
| 190 | KIND_WAYS, |
| 191 | "Pass 2: ways", |
| 192 | TransitWayPass::default, |
| 193 | |state, block| transit_way_blob(state, block, &way_select, &wanted_ways), |
| 194 | )?; |
| 195 | let mut way_rows: Vec<TransitRow> = Vec::new(); |
| 196 | let mut member_refs: HashMap<i64, Vec<i64>> = HashMap::new(); |
| 197 | for chunk in chunks { |
| 198 | way_rows.extend(chunk.rows); |
| 199 | member_refs.extend(chunk.wanted); |
| 200 | } |
| 201 | println!("{} railway way(s)", way_rows.len()); |
| 202 | |
| 203 | // A relation's parts, in member order. Members whose way is missing from the |
| 204 | // extract are simply absent, which is the same thing GDAL produced. |
| 205 | for row in &mut rel_rows { |
| 206 | row.parts = row |
| 207 | .member_ways |
| 208 | .iter() |
| 209 | .filter_map(|w| member_refs.get(w).cloned()) |
| 210 | .collect(); |
| 211 | } |
| 212 | |
| 213 | // Pass 3: node coordinates for everything both earlier passes collected. |
| 214 | let table = NodeLocations::new( |
| 215 | way_rows |
| 216 | .iter() |
| 217 | .chain(rel_rows.iter()) |
| 218 | .flat_map(|r| r.parts.iter().flat_map(|p| p.iter().copied())) |
| 219 | .collect(), |
| 220 | )?; |
| 221 | println!("{} node location(s) needed", table.len()); |
| 222 | let table = resolve_nodes(input, blobs, &blob_kinds, "Pass 3: nodes", table)?; |
| 223 | |
| 224 | let mut lines: Vec<LineFeature> = Vec::new(); |
| 225 | let mut outside_bbox = 0usize; |
| 226 | let mut from_ways = 0usize; |
| 227 | let mut from_relations = 0usize; |
| 228 | for row in way_rows.iter().chain(rel_rows.iter()) { |
| 229 | let parts: Vec<Vec<Coord>> = row |
| 230 | .parts |
| 231 | .iter() |
| 232 | .map(|refs| table.line(refs)) |
| 233 | .filter(|p| p.len() >= 2) |
| 234 | .collect(); |
| 235 | if parts.is_empty() { |
| 236 | continue; |
| 237 | } |
| 238 | if !parts_touch_bbox(&parts, opts.bbox.as_ref()) { |
| 239 | outside_bbox += 1; |
| 240 | continue; |
| 241 | } |
| 242 | // A way is one line; a relation is a MultiLineString of its member ways, |
| 243 | // deliberately unstitched. See the module docs in `transit_lines`. |
| 244 | let geometry = if row.element == "way" { |
| 245 | Geometry::LineString(parts.into_iter().next().expect("non-empty")) |
| 246 | } else { |
| 247 | Geometry::MultiLineString(parts) |
| 248 | }; |
| 249 | let t = TransitTags { |
| 250 | name: row.name.as_deref(), |
| 251 | reference: row.reference.as_deref(), |
| 252 | colour: row.colour.as_deref(), |
| 253 | ..Default::default() |
| 254 | }; |
| 255 | let f = transit_lines::feature(row.kind, &t, geometry, row.element, row.id); |
| 256 | lines.push(LineFeature { |
| 257 | sort: (row.element, row.id), |
| 258 | rendered: render(&f), |
| 259 | }); |
| 260 | if row.element == "way" { |
| 261 | from_ways += 1; |
| 262 | } else { |
| 263 | from_relations += 1; |
| 264 | } |
| 265 | } |
| 266 | |
| 267 | let written = write_lines(out, lines)?; |
| 268 | println!( |
| 269 | "Wrote {written} transit_lines feature(s) to {} ({from_ways} way, {from_relations} relation)", |
| 270 | out.display() |
| 271 | ); |
| 272 | if outside_bbox > 0 { |
| 273 | println!("{outside_bbox} feature(s) dropped by --bbox"); |
| 274 | } |
| 275 | Ok(Stats { |
| 276 | features: written, |
| 277 | from_nodes: 0, |
| 278 | from_ways, |
| 279 | from_relations, |
| 280 | outside_bbox, |
| 281 | }) |
| 282 | } |
| 283 | |
| 284 | fn transit_relation_blob( |
| 285 | state: &mut Vec<TransitRow>, |
| 286 | block: &pbf::PrimitiveBlock, |
| 287 | select: &Select, |
| 288 | ) -> Result<u8> { |
| 289 | let mut kinds = 0u8; |
| 290 | visit_block(block, KIND_RELATIONS, &mut kinds, &mut |el: Element| { |
| 291 | if let Element::Relation(r) = el { |
| 292 | if !select.matches(|k| r.tags.get_str(k)) { |
| 293 | return Ok(()); |
| 294 | } |
| 295 | let t = TransitTags { |
| 296 | railway: r.tags.get_str("railway"), |
| 297 | type_: r.tags.get_str("type"), |
| 298 | route: r.tags.get_str("route"), |
| 299 | name: r.tags.get_str("name"), |
| 300 | reference: r.tags.get_str("ref"), |
| 301 | colour: r.tags.get_str("colour"), |
| 302 | color: r.tags.get_str("color"), |
| 303 | }; |
| 304 | let Some(kind) = transit_lines::classify(&t) else { |
| 305 | return Ok(()); |
| 306 | }; |
| 307 | // Way members that are the route's path. `forward`/`backward` count; |
| 308 | // `platform*` and `stop*` do not - see [`transit_lines::member_is_path`]. |
| 309 | let member_ways: Vec<i64> = r |
| 310 | .members |
| 311 | .iter() |
| 312 | .filter(|m: &&Member| { |
| 313 | m.kind == MEMBER_WAY && transit_lines::member_is_path(m.role) |
| 314 | }) |
| 315 | .map(|m| m.id) |
| 316 | .collect(); |
| 317 | if member_ways.is_empty() { |
| 318 | return Ok(()); |
| 319 | } |
| 320 | state.push(TransitRow { |
| 321 | element: "relation", |
| 322 | id: r.id, |
| 323 | kind, |
| 324 | name: t.name.map(str::to_string), |
| 325 | reference: t.reference.map(str::to_string), |
| 326 | colour: transit_lines::colour(&t).map(str::to_string), |
| 327 | parts: Vec::new(), |
| 328 | member_ways, |
| 329 | }); |
| 330 | } |
| 331 | Ok(()) |
| 332 | })?; |
| 333 | Ok(kinds) |
| 334 | } |
| 335 | |
| 336 | fn transit_way_blob( |
| 337 | state: &mut TransitWayPass, |
| 338 | block: &pbf::PrimitiveBlock, |
| 339 | select: &Select, |
| 340 | wanted: &[i64], |
| 341 | ) -> Result<u8> { |
| 342 | let mut kinds = 0u8; |
| 343 | visit_block(block, KIND_WAYS, &mut kinds, &mut |el: Element| { |
| 344 | if let Element::Way(w) = el { |
| 345 | if w.refs.len() < 2 { |
| 346 | return Ok(()); |
| 347 | } |
| 348 | if wanted.binary_search(&w.id).is_ok() { |
| 349 | state.wanted.push((w.id, w.refs.to_vec())); |
| 350 | } |
| 351 | if w.tags.is_empty() || !select.matches(|k| w.tags.get_str(k)) { |
| 352 | return Ok(()); |
| 353 | } |
| 354 | let t = TransitTags { |
| 355 | railway: w.tags.get_str("railway"), |
| 356 | type_: w.tags.get_str("type"), |
| 357 | route: w.tags.get_str("route"), |
| 358 | name: w.tags.get_str("name"), |
| 359 | reference: w.tags.get_str("ref"), |
| 360 | colour: w.tags.get_str("colour"), |
| 361 | color: w.tags.get_str("color"), |
| 362 | }; |
| 363 | if let Some(kind) = transit_lines::classify(&t) { |
| 364 | state.rows.push(TransitRow { |
| 365 | element: "way", |
| 366 | id: w.id, |
| 367 | kind, |
| 368 | name: t.name.map(str::to_string), |
| 369 | reference: t.reference.map(str::to_string), |
| 370 | colour: transit_lines::colour(&t).map(str::to_string), |
| 371 | parts: vec![w.refs.to_vec()], |
| 372 | member_ways: Vec::new(), |
| 373 | }); |
| 374 | } |
| 375 | } |
| 376 | Ok(()) |
| 377 | })?; |
| 378 | Ok(kinds) |
| 379 | } |
| 380 | |
| 381 | // --- admin_city ----------------------------------------------------------- |
| 382 | |
| 383 | /// One `admin_level=8` boundary relation, with its member ways and tags copied out. |
| 384 | struct AdminRow { |
| 385 | id: i64, |
| 386 | name: Option<String>, |
| 387 | name_en: Option<String>, |
| 388 | /// `(way id, is_outer)` in member order. |
| 389 | members: Vec<(i64, bool)>, |
| 390 | } |
| 391 | |
| 392 | #[derive(Default)] |
| 393 | struct AdminWayPass { |
| 394 | /// `(way id, its refs)` for ways a boundary relation claimed. |
| 395 | wanted: Vec<(i64, Vec<i64>)>, |
| 396 | } |