Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / scripts / maps / mamaps_build / src / extract_part4.rs
extract_part4.rs297 lines · 12.7 KiBRaw
| 1 | /// A node's location in lon/lat, which is the order [`rings::assemble`] and GeoJSON both want. |
| 2 | /// |
| 3 | /// [`NodeLocations::get`] returns lat/lon, matching the PBF's own field order. |
| 4 | fn locate(table: &NodeLocations, id: i64) -> Option<(f64, f64)> { |
| 5 | let (lat_e7, lon_e7) = table.get(id)?; |
| 6 | Some((lon_e7 as f64 * 1e-7, lat_e7 as f64 * 1e-7)) |
| 7 | } |
| 8 | |
| 9 | /// Is this a label layer (`places`/`poi`)? Labels are points with names: ways mapped as areas |
| 10 | /// are centroided to one, relations likewise, and nodes spill directly. |
| 11 | pub(crate) fn is_label(layer: u8) -> bool { |
| 12 | use tilecodec::mamaps::dict::{LAYER_PLACES, LAYER_POI}; |
| 13 | layer == LAYER_PLACES || layer == LAYER_POI |
| 14 | } |
| 15 | |
| 16 | /// Does this layer have an id side table at all? |
| 17 | /// |
| 18 | /// Layer-level, and separate from [`tracks_ids`], because the table is indexed by feature |
| 19 | /// position: every feature in such a layer needs an entry, `ID_NONE` included, or the table stops |
| 20 | /// lining up with the features it describes. |
| 21 | pub(crate) fn layer_tracks_ids(layer: u8) -> bool { |
| 22 | is_label(layer) |
| 23 | || layer == tilecodec::mamaps::dict::LAYER_BOUNDARIES |
| 24 | || layer == tilecodec::mamaps::dict::LAYER_TRAFFIC |
| 25 | } |
| 26 | |
| 27 | /// May this feature carry a non-zero id? |
| 28 | /// |
| 29 | /// Wider than [`is_label`], and deliberately a separate predicate: `is_label` also means |
| 30 | /// "centroid this to a point", which a region's shape must not be. `boundaries` needs ids for |
| 31 | /// a different reason — a region is stored as one clipped polygon per tile, so without an id |
| 32 | /// there is nothing to say which pieces are the same region, and the mask can only punch out |
| 33 | /// the piece under the finger. |
| 34 | /// |
| 35 | /// Keyed on the whole class rather than the layer because `boundaries` holds both kinds of |
| 36 | /// geometry: the region's shape, which is an area and keeps its id, and the border, which is a |
| 37 | /// line and must not. `coalesce` merges adjacent border lines, and the survivor's id would be |
| 38 | /// whichever member happened to come first. |
| 39 | pub(crate) fn tracks_ids(class: &crate::schema::Class) -> bool { |
| 40 | use tilecodec::mamaps::dict::{LAYER_BOUNDARIES, LAYER_TRAFFIC}; |
| 41 | is_label(class.layer) |
| 42 | || (class.layer == LAYER_BOUNDARIES && class.area) |
| 43 | || class.layer == LAYER_TRAFFIC |
| 44 | } |
| 45 | |
| 46 | /// Is this one of the region-filtered layers (`roads`, `poi`, `buildings`)? |
| 47 | /// |
| 48 | /// Only these three are filtered by `--region`. Every other layer is always |
| 49 | /// included regardless of the region setting. |
| 50 | pub(crate) fn is_region_filtered(layer: u8) -> bool { |
| 51 | use tilecodec::mamaps::dict::{LAYER_BUILDINGS, LAYER_POI, LAYER_ROADS}; |
| 52 | layer == LAYER_ROADS || layer == LAYER_POI || layer == LAYER_BUILDINGS |
| 53 | } |
| 54 | |
| 55 | /// Does a materialised geometry touch the region bbox? |
| 56 | /// |
| 57 | /// Touches-box, never containment: a way straddling the border is kept whole |
| 58 | /// (the `complete_ways` rule — truncating would invent a vertex). `None` |
| 59 | /// (world) keeps everything. |
| 60 | pub(crate) fn geometry_touches( |
| 61 | geometry: &Geometry, |
| 62 | region: Option<&osm_ingest::bbox::BBox>, |
| 63 | ) -> bool { |
| 64 | let Some(b) = region else { |
| 65 | return true; |
| 66 | }; |
| 67 | let mut touches = false; |
| 68 | let mut visit = |&(lon, lat): &(f64, f64)| { |
| 69 | // e7 integers, matching `BBox::contains_e7`'s exactness: a float |
| 70 | // comparison would drop a coordinate sitting exactly on the edge. |
| 71 | let (lon_e7, lat_e7) = ((lon * 1e7).round() as i32, (lat * 1e7).round() as i32); |
| 72 | touches |= b.contains_e7(lat_e7, lon_e7); |
| 73 | }; |
| 74 | match geometry { |
| 75 | Geometry::Points(points) => points.iter().for_each(&mut visit), |
| 76 | Geometry::Lines(lines) => lines.iter().flatten().for_each(&mut visit), |
| 77 | Geometry::Polygons(polygons) => polygons.iter().flatten().flatten().for_each(&mut visit), |
| 78 | } |
| 79 | touches |
| 80 | } |
| 81 | |
| 82 | /// Does a lon/lat point touch the region bbox? `None` (world) is always true. |
| 83 | pub(crate) fn point_touches(point: &(f64, f64), region: Option<&osm_ingest::bbox::BBox>) -> bool { |
| 84 | let Some(b) = region else { |
| 85 | return true; |
| 86 | }; |
| 87 | let (lon_e7, lat_e7) = |
| 88 | ((point.0 * 1e7).round() as i32, (point.1 * 1e7).round() as i32); |
| 89 | b.contains_e7(lat_e7, lon_e7) |
| 90 | } |
| 91 | |
| 92 | /// Do stitched polygons touch the region bbox? One touching ring keeps the |
| 93 | /// whole relation — clipping happens per tile in the tiler, not here. |
| 94 | pub(crate) fn polygons_touch( |
| 95 | polygons: &[rings::Polygon], |
| 96 | region: Option<&osm_ingest::bbox::BBox>, |
| 97 | ) -> bool { |
| 98 | let Some(b) = region else { |
| 99 | return true; |
| 100 | }; |
| 101 | polygons.iter().flatten().flatten().any(|&(lon, lat)| { |
| 102 | let (lon_e7, lat_e7) = ((lon * 1e7).round() as i32, (lat * 1e7).round() as i32); |
| 103 | b.contains_e7(lat_e7, lon_e7) |
| 104 | }) |
| 105 | } |
| 106 | |
| 107 | /// The centroid of a coordinate list: the arithmetic mean, or `None` when there is nothing. |
| 108 | /// |
| 109 | /// A label anchor, not a geometric centroid — cheap and exactly what a basemap needs. Area |
| 110 | /// weighting would move the point toward the largest lobe; the mean keeps it among the parts. |
| 111 | fn centroid(line: &[(f64, f64)]) -> Option<(f64, f64)> { |
| 112 | if line.is_empty() { |
| 113 | return None; |
| 114 | } |
| 115 | let (sx, sy) = line.iter().fold((0.0f64, 0.0f64), |(x, y), &(px, py)| (x + px, y + py)); |
| 116 | let n = line.len() as f64; |
| 117 | Some((sx / n, sy / n)) |
| 118 | } |
| 119 | |
| 120 | /// A way's coordinates as the geometry its class says it is. |
| 121 | /// |
| 122 | /// A closed way is a ring only if the tags call it an area; the same shape is a cul-de-sac |
| 123 | /// otherwise. A ring that does not close is closed here rather than dropped, which is what |
| 124 | /// `osmium`'s own export does — an extract cut through the way is the usual reason. |
| 125 | fn way_geometry(line: &[(f64, f64)], area: bool) -> Option<Geometry> { |
| 126 | if !area { |
| 127 | return (line.len() >= 2).then(|| Geometry::Lines(vec![line.to_vec()])); |
| 128 | } |
| 129 | // Three distinct points at minimum, plus the closing one. |
| 130 | if line.len() < 3 { |
| 131 | return None; |
| 132 | } |
| 133 | let mut ring = line.to_vec(); |
| 134 | if ring.first() != ring.last() { |
| 135 | ring.push(ring[0]); |
| 136 | } |
| 137 | if ring.len() < 4 { |
| 138 | return None; |
| 139 | } |
| 140 | Some(Geometry::Polygons(vec![vec![ring]])) |
| 141 | } |
| 142 | |
| 143 | #[cfg(test)] |
| 144 | mod tests { |
| 145 | use super::*; |
| 146 | |
| 147 | /// The claim the bitset path rests on: it yields exactly the sequence the vector path's sort and |
| 148 | /// dedup would, for the same input. Everything downstream -- the id index, the positions the node |
| 149 | /// pass writes coordinates at -- follows from that one equality. |
| 150 | #[test] |
| 151 | fn the_bitset_yields_what_a_sort_and_dedup_would() { |
| 152 | // Deliberately awkward: duplicates, a run of consecutive ids inside one word, gaps that skip |
| 153 | // whole words, both ends of the space, and ids past `u32::MAX`. |
| 154 | let refs: Vec<i64> = vec![ |
| 155 | 0, 63, 64, 65, 1, 1, 1, 4_294_967_295, 4_294_967_296, 12_345_678_901, 128, 127, 2, 63, |
| 156 | 12_345_678_901, 500_000, 499_999, 0, |
| 157 | ]; |
| 158 | let mut want = refs.clone(); |
| 159 | want.sort_unstable(); |
| 160 | want.dedup(); |
| 161 | |
| 162 | let max = *refs.iter().max().expect("refs"); |
| 163 | let mut bits = NeededBits::new(max).expect("size the bitset"); |
| 164 | for &id in &refs { |
| 165 | bits.set(id).expect("set a bit"); |
| 166 | } |
| 167 | assert_eq!(bits.ids().collect::<Vec<i64>>(), want); |
| 168 | assert_eq!(bits.len(), want.len(), "the count must match what `from_sorted` is sized with"); |
| 169 | } |
| 170 | |
| 171 | /// The empty and single-id cases, which the word-at-a-time walk makes easy to get wrong. |
| 172 | #[test] |
| 173 | fn an_empty_or_single_id_bitset_is_not_a_special_case() { |
| 174 | let empty = NeededBits::new(0).expect("size"); |
| 175 | assert_eq!(empty.len(), 0); |
| 176 | assert!(empty.ids().next().is_none()); |
| 177 | |
| 178 | let mut one = NeededBits::new(0).expect("size"); |
| 179 | one.set(0).expect("set"); |
| 180 | assert_eq!(one.ids().collect::<Vec<i64>>(), vec![0]); |
| 181 | assert_eq!(one.len(), 1); |
| 182 | |
| 183 | // The maximum is inclusive, so a bitset sized for it must hold it. |
| 184 | let mut edge = NeededBits::new(64).expect("size"); |
| 185 | edge.set(64).expect("the maximum is in range"); |
| 186 | assert_eq!(edge.ids().collect::<Vec<i64>>(), vec![64]); |
| 187 | } |
| 188 | |
| 189 | /// The bound that makes the bitset affordable is a property of OSM's ids, so an input that |
| 190 | /// breaks it has to say so rather than ask for an allocation the size of one id. |
| 191 | #[test] |
| 192 | fn an_id_outside_osms_own_range_is_refused_rather_than_sized_for() { |
| 193 | assert!(NeededBits::new(MAX_NODE_ID + 1).is_err(), "a wild maximum was sized for"); |
| 194 | assert!(NeededBits::new(i64::MAX).is_err(), "`i64::MAX` was sized for"); |
| 195 | |
| 196 | let mut bits = NeededBits::new(100).expect("size"); |
| 197 | assert!(bits.set(-1).is_err(), "a negative ref was accepted"); |
| 198 | assert!(bits.set(101).is_err(), "a ref past the maximum was accepted"); |
| 199 | assert!(bits.set(100).is_ok()); |
| 200 | } |
| 201 | |
| 202 | /// End to end over a real ways spill: the fused growable bitset must hand |
| 203 | /// pass 3 the same set the old re-scan collectors did — every asked-for id |
| 204 | /// and nothing between them that was never asked for. |
| 205 | #[test] |
| 206 | fn the_fused_bitset_collects_what_the_spill_holds() { |
| 207 | let path = std::env::temp_dir().join(format!( |
| 208 | "mamaps_refcollect_{}_{:?}.ways.tmp", |
| 209 | std::process::id(), |
| 210 | std::thread::current().id(), |
| 211 | )); |
| 212 | let class = schema::Class::area( |
| 213 | tilecodec::mamaps::dict::LAYER_LANDTYPE, |
| 214 | schema::kind("lake"), |
| 215 | 0, |
| 216 | ); |
| 217 | let mut sink = WaySink::create_anon(&path).expect("create the ways spill"); |
| 218 | // Ascending way ids, as pass 1 produces; overlapping refs, as real ways have. |
| 219 | // Bits are set as each way pushes, the way the pass-1 drain does it. |
| 220 | let mut bits = NeededBits::new_growable(); |
| 221 | for way in 0..64i64 { |
| 222 | let refs: Vec<i64> = (0..8).map(|i| way * 5 + i).collect(); |
| 223 | for &id in &refs { |
| 224 | bits.set_growable(id).expect("set a bit"); |
| 225 | } |
| 226 | sink.push(way + 1, &class, &refs, None, 0, &[], &[], Carriageway::default(), None) |
| 227 | .expect("push"); |
| 228 | } |
| 229 | let (counts, store) = sink.finish_anon().expect("finish"); |
| 230 | let _ = store; |
| 231 | |
| 232 | let mut member_map: HashMap<i64, Vec<i64>> = HashMap::new(); |
| 233 | // One member whose refs overlap the spill's, and one that is entirely new. |
| 234 | member_map.insert(7, vec![30, 31, 32, 30]); |
| 235 | member_map.insert(9, vec![10_000, 9_999, 10_000]); |
| 236 | let members = MemberWays::from_map(member_map); |
| 237 | for refs in members.values() { |
| 238 | for &id in refs { |
| 239 | bits.set_growable(id).expect("set a member bit"); |
| 240 | } |
| 241 | } |
| 242 | |
| 243 | // The same ids, not merely the same count: the table must answer for |
| 244 | // every ref and for nothing between them that was never asked for. |
| 245 | let count = bits.len(); |
| 246 | let (words, _) = bits.into_words(); |
| 247 | let table = NodeLocations::from_bitset(words, count).expect("build the table"); |
| 248 | let _ = counts; |
| 249 | for id in [0i64, 1, 30, 31, 32, 319, 9_999, 10_000] { |
| 250 | assert!(table.contains(id), "node {id} is missing"); |
| 251 | } |
| 252 | assert!(table.contains(10_000), "a member-only ref is missing"); |
| 253 | assert!(!table.contains(5_000), "an id nothing asked for is present"); |
| 254 | |
| 255 | let _ = std::fs::remove_file(&path); |
| 256 | } |
| 257 | |
| 258 | #[test] |
| 259 | fn an_open_way_is_a_line_and_a_closed_one_an_area_only_if_tagged() { |
| 260 | let square = [(0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 1.0), (0.0, 0.0)]; |
| 261 | // Tagged an area: a ring. |
| 262 | match way_geometry(&square, true).expect("area") { |
| 263 | Geometry::Polygons(polygons) => { |
| 264 | assert_eq!(polygons.len(), 1); |
| 265 | assert_eq!(polygons[0][0].len(), 5, "already closed, so nothing is added"); |
| 266 | } |
| 267 | other => panic!("{other:?}"), |
| 268 | } |
| 269 | // The same shape untagged: a loop road, which is a line. |
| 270 | assert!(matches!(way_geometry(&square, false), Some(Geometry::Lines(_)))); |
| 271 | } |
| 272 | |
| 273 | /// An extract that cuts through a way leaves it unclosed. Closing it is what `osmium export` |
| 274 | /// does; dropping it would punch a hole in the coastline at every extract boundary. |
| 275 | #[test] |
| 276 | fn an_unclosed_area_is_closed_rather_than_dropped() { |
| 277 | let open = [(0.0, 0.0), (1.0, 0.0), (1.0, 1.0)]; |
| 278 | match way_geometry(&open, true).expect("closed") { |
| 279 | Geometry::Polygons(polygons) => { |
| 280 | let ring = &polygons[0][0]; |
| 281 | assert_eq!(ring.len(), 4); |
| 282 | assert_eq!(ring.first(), ring.last(), "the ring closes"); |
| 283 | } |
| 284 | other => panic!("{other:?}"), |
| 285 | } |
| 286 | } |
| 287 | |
| 288 | #[test] |
| 289 | fn a_degenerate_way_produces_nothing() { |
| 290 | assert!(way_geometry(&[], true).is_none()); |
| 291 | assert!(way_geometry(&[(0.0, 0.0)], true).is_none()); |
| 292 | assert!(way_geometry(&[(0.0, 0.0), (1.0, 1.0)], true).is_none(), "two points bound no area"); |
| 293 | assert!(way_geometry(&[(0.0, 0.0)], false).is_none(), "one point is not a line"); |
| 294 | // But two points are a line. |
| 295 | assert!(way_geometry(&[(0.0, 0.0), (1.0, 1.0)], false).is_some()); |
| 296 | } |
| 297 | } |