Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / scripts / maps / gtfs_ingest / src / bundle_part2.rs
bundle_part2.rs411 lines · 18.2 KiBRaw
| 1 | /// One candidate's spans, in its own order of travel. |
| 2 | fn spans_of( |
| 3 | candidate: &Candidate, |
| 4 | runs: &[Run], |
| 5 | samples: &[Sample], |
| 6 | probe_cum: &[f64], |
| 7 | own_cum: &[f64], |
| 8 | corridors: &BTreeMap<u32, Corridor>, |
| 9 | ) -> Vec<Span> { |
| 10 | let whole = || { |
| 11 | vec![Span { points: candidate.points.to_vec(), ordinal: 0, lanes: 1, taper: 255 }] |
| 12 | }; |
| 13 | if runs.is_empty() || (runs.len() == 1 && !corridors.contains_key(&runs[0].set)) { |
| 14 | return whole(); |
| 15 | } |
| 16 | |
| 17 | let placements: Vec<Option<Placement>> = runs |
| 18 | .iter() |
| 19 | .map(|run| { |
| 20 | let corridor = corridors.get(&run.set)?; |
| 21 | let a = distance_along(corridor, samples[run.from].point); |
| 22 | let b = distance_along(corridor, samples[run.to].point); |
| 23 | let (forward, lo, hi) = if a <= b { (true, a, b) } else { (false, b, a) }; |
| 24 | // A run with no usable extent on the reference — the two ends project to one |
| 25 | // place — has nothing to snap to, so the candidate keeps its own geometry there. |
| 26 | if hi - lo < SAMPLE_M { |
| 27 | return None; |
| 28 | } |
| 29 | let near = |at: usize| nearest(corridor, samples[at].point).0 <= SNAP_M; |
| 30 | let snap = (run.from..=run.to).find(|&at| near(at)).map(|first| { |
| 31 | (first, (first..=run.to).rev().find(|&at| near(at)).unwrap_or(first)) |
| 32 | }); |
| 33 | Some(Placement { corridor, forward, lo, hi, snap }) |
| 34 | }) |
| 35 | .collect(); |
| 36 | |
| 37 | // Per run: its pieces and the points it begins and ends at, both in the candidate's order |
| 38 | // of travel, and whether that order runs against the reference's. |
| 39 | let mut pieces: Vec<Vec<Span>> = Vec::with_capacity(runs.len()); |
| 40 | let mut ends: Vec<Option<Bounds>> = Vec::with_capacity(runs.len()); |
| 41 | let mut against: Vec<bool> = Vec::with_capacity(runs.len()); |
| 42 | |
| 43 | for (at, run) in runs.iter().enumerate() { |
| 44 | let (own_from, own_to) = (probe_cum[run.from], probe_cum[run.to]); |
| 45 | let own_piece = |from: f64, to: f64, ordinal: u8, lanes: u8, taper: u8| -> Option<Span> { |
| 46 | let points = slice_between(candidate.points, own_cum, from, to); |
| 47 | (points.len() >= 2).then_some(Span { points, ordinal, lanes, taper }) |
| 48 | }; |
| 49 | |
| 50 | let Some(place) = &placements[at] else { |
| 51 | let out: Vec<Span> = own_piece(own_from, own_to, 0, 1, 255).into_iter().collect(); |
| 52 | ends.push(bounds_of(&out)); |
| 53 | pieces.push(out); |
| 54 | against.push(false); |
| 55 | continue; |
| 56 | }; |
| 57 | let corridor = place.corridor; |
| 58 | let lanes = u8::try_from(corridor.colours.len()).unwrap_or(u8::MAX); |
| 59 | let ordinal = corridor |
| 60 | .colours |
| 61 | .iter() |
| 62 | .position(|c| *c == candidate.color) |
| 63 | .and_then(|at| u8::try_from(at).ok()) |
| 64 | .unwrap_or(0); |
| 65 | |
| 66 | let Some((first, last)) = place.snap else { |
| 67 | let out: Vec<Span> = |
| 68 | own_piece(own_from, own_to, ordinal, lanes, 255).into_iter().collect(); |
| 69 | ends.push(bounds_of(&out)); |
| 70 | pieces.push(out); |
| 71 | against.push(!place.forward); |
| 72 | continue; |
| 73 | }; |
| 74 | |
| 75 | // A taper means one thing: opening the fan off the member's own alignment. A corridor |
| 76 | // of one colour has no fan to open, and where the neighbouring run is on a corridor |
| 77 | // too there is no own alignment to leave — the line is in a lane on both sides and |
| 78 | // steps from one to the other, which is a fraction of the fan rather than the whole |
| 79 | // of it dipping through zero. |
| 80 | let fanned = lanes > 1; |
| 81 | let eases = |other: Option<usize>| { |
| 82 | fanned && matches!(other, Some(i) if placements[i].is_none()) |
| 83 | }; |
| 84 | let at_start = eases(at.checked_sub(1)); |
| 85 | let at_end = eases((at + 1 < runs.len()).then_some(at + 1)); |
| 86 | |
| 87 | // The ease runs from the run's start to where the member's own survey first comes |
| 88 | // within `SNAP_M`, which makes it adaptive: a shallow convergence gets a long ease |
| 89 | // and a sharp junction a short one. At least `TAPER_M` so the offset has somewhere to |
| 90 | // ramp when the member converges at once, and never more than a quarter of the run so |
| 91 | // the body keeps a usable share of it. |
| 92 | let extent = own_to - own_from; |
| 93 | let ease = |to_snap: f64| to_snap.max(TAPER_M).min(extent / 4.0); |
| 94 | let lead = if at_start { ease(probe_cum[first] - own_from) } else { 0.0 }; |
| 95 | let trail = if at_end { ease(own_to - probe_cum[last]) } else { 0.0 }; |
| 96 | |
| 97 | // Where the body meets the reference: the handover point where there is an ease, and |
| 98 | // the run boundary where there is not. |
| 99 | let ref_at = |
| 100 | |own: f64| distance_along(corridor, point_at(candidate.points, own_cum, own)); |
| 101 | let (from_end, to_end) = |
| 102 | if place.forward { (place.lo, place.hi) } else { (place.hi, place.lo) }; |
| 103 | let body_from = if lead > 0.0 { ref_at(own_from + lead) } else { from_end }; |
| 104 | let body_to = if trail > 0.0 { ref_at(own_to - trail) } else { to_end }; |
| 105 | |
| 106 | let mut out: Vec<Span> = Vec::new(); |
| 107 | if lead > 0.0 { |
| 108 | let step = lead / TAPER_STEPS as f64; |
| 109 | for k in 0..TAPER_STEPS { |
| 110 | let base = own_from + k as f64 * step; |
| 111 | out.extend(own_piece(base, base + step, ordinal, lanes, taper_fraction(k + 1))); |
| 112 | } |
| 113 | } |
| 114 | let mut body = slice_between(&corridor.points, &corridor.cum, body_from, body_to); |
| 115 | if !place.forward { |
| 116 | body.reverse(); |
| 117 | } |
| 118 | let mut body_exit = None; |
| 119 | if body.len() >= 2 { |
| 120 | let (head, tail) = (body[0], body[body.len() - 1]); |
| 121 | // The ease is on the member's own survey and the body is on the reference, up to |
| 122 | // `SNAP_M` apart. Carry one vertex across so the two meet, the same trick the |
| 123 | // inter-run weld below uses. The ease pieces themselves are adjoining slices of |
| 124 | // one polyline and already share their boundary vertex exactly. |
| 125 | if let Some(lead_end) = out.last_mut() { |
| 126 | if lead_end.points.last() != Some(&head) { |
| 127 | lead_end.points.push(head); |
| 128 | } |
| 129 | } |
| 130 | out.push(Span { points: body, ordinal, lanes, taper: 255 }); |
| 131 | body_exit = Some(tail); |
| 132 | } |
| 133 | if trail > 0.0 { |
| 134 | let step = trail / TAPER_STEPS as f64; |
| 135 | let starts_at = out.len(); |
| 136 | for k in 0..TAPER_STEPS { |
| 137 | let base = own_to - trail + k as f64 * step; |
| 138 | out.extend(own_piece( |
| 139 | base, |
| 140 | base + step, |
| 141 | ordinal, |
| 142 | lanes, |
| 143 | taper_fraction(TAPER_STEPS - k), |
| 144 | )); |
| 145 | } |
| 146 | if let (Some(tail), Some(trail_start)) = (body_exit, out.get_mut(starts_at)) { |
| 147 | if trail_start.points.first() != Some(&tail) { |
| 148 | trail_start.points.insert(0, tail); |
| 149 | } |
| 150 | } |
| 151 | } |
| 152 | |
| 153 | ends.push(bounds_of(&out)); |
| 154 | pieces.push(out); |
| 155 | against.push(!place.forward); |
| 156 | } |
| 157 | |
| 158 | // Two runs meet at a point each of them located only to a sample step, and on two |
| 159 | // different polylines: a member's own survey and a reference, or two references where a |
| 160 | // route steps straight from one corridor into the next. Carry one across to the other so |
| 161 | // the pieces meet rather than leaving a gap at the seam — the corridor's own geometry |
| 162 | // where there is one to preserve, and the run that follows otherwise. |
| 163 | for at in 1..pieces.len() { |
| 164 | let (Some(before), Some(after)) = (ends[at - 1], ends[at]) else { continue }; |
| 165 | if placements[at - 1].is_some() && placements[at].is_none() { |
| 166 | let head = pieces[at].first_mut().expect("bounds imply a piece"); |
| 167 | if head.points.first() != Some(&before.1) { |
| 168 | head.points.insert(0, before.1); |
| 169 | } |
| 170 | } else { |
| 171 | let tail = pieces[at - 1].last_mut().expect("bounds imply a piece"); |
| 172 | if tail.points.last() != Some(&after.0) { |
| 173 | tail.points.push(after.0); |
| 174 | } |
| 175 | } |
| 176 | } |
| 177 | |
| 178 | // Every piece of a corridor run is stored in the reference's direction, so all its |
| 179 | // members share one left-hand normal and ordinal `i` is the same physical side for all of |
| 180 | // them. An ease piece is cut from the member's own survey and inherits that survey's |
| 181 | // direction, so for a member travelling against the reference it has to be turned round |
| 182 | // here or the fan mirrors across the ease. Only the order the pieces are listed in |
| 183 | // follows the candidate. |
| 184 | for (run_pieces, against) in pieces.iter_mut().zip(&against) { |
| 185 | if *against { |
| 186 | for span in run_pieces.iter_mut() { |
| 187 | span.points.reverse(); |
| 188 | } |
| 189 | } |
| 190 | } |
| 191 | |
| 192 | let flat: Vec<Span> = pieces.into_iter().flatten().collect(); |
| 193 | if flat.is_empty() { |
| 194 | whole() |
| 195 | } else { |
| 196 | flat |
| 197 | } |
| 198 | } |
| 199 | |
| 200 | /// Cumulative ground distance to each vertex of a polyline. |
| 201 | fn cumulative(points: &[(i32, i32)]) -> Vec<f64> { |
| 202 | let mut out = Vec::with_capacity(points.len()); |
| 203 | let mut total = 0.0; |
| 204 | for (at, point) in points.iter().enumerate() { |
| 205 | if at > 0 { |
| 206 | total += distance_m(points[at - 1], *point); |
| 207 | } |
| 208 | out.push(total); |
| 209 | } |
| 210 | out |
| 211 | } |
| 212 | |
| 213 | /// The point `at` metres along a polyline, interpolated within its segment. |
| 214 | fn point_at(points: &[(i32, i32)], cum: &[f64], at: f64) -> (i32, i32) { |
| 215 | if points.len() < 2 { |
| 216 | return points.first().copied().unwrap_or((0, 0)); |
| 217 | } |
| 218 | let last = points.len() - 1; |
| 219 | if at <= 0.0 { |
| 220 | return points[0]; |
| 221 | } |
| 222 | if at >= cum[last] { |
| 223 | return points[last]; |
| 224 | } |
| 225 | let seg = cum.partition_point(|d| *d <= at).max(1) - 1; |
| 226 | let span = cum[seg + 1] - cum[seg]; |
| 227 | let t = if span > 0.0 { (at - cum[seg]) / span } else { 0.0 }; |
| 228 | let (a, b) = (points[seg], points[seg + 1]); |
| 229 | ( |
| 230 | (a.0 as f64 + (b.0 - a.0) as f64 * t).round() as i32, |
| 231 | (a.1 as f64 + (b.1 - a.1) as f64 * t).round() as i32, |
| 232 | ) |
| 233 | } |
| 234 | |
| 235 | /// The part of a polyline between two distances along it, with both ends interpolated. |
| 236 | /// |
| 237 | /// Both ends land exactly on the polyline, so two adjacent slices share their boundary |
| 238 | /// vertex and the pieces of one route meet. Empty when the two distances leave nothing |
| 239 | /// between them. |
| 240 | fn slice_between(points: &[(i32, i32)], cum: &[f64], from: f64, to: f64) -> Vec<(i32, i32)> { |
| 241 | if points.len() < 2 { |
| 242 | return Vec::new(); |
| 243 | } |
| 244 | let total = cum[cum.len() - 1]; |
| 245 | let (from, to) = (from.clamp(0.0, total), to.clamp(0.0, total)); |
| 246 | let (from, to) = if from <= to { (from, to) } else { (to, from) }; |
| 247 | let mut out = vec![point_at(points, cum, from)]; |
| 248 | for (at, along) in cum.iter().enumerate() { |
| 249 | if *along > from && *along < to && out[out.len() - 1] != points[at] { |
| 250 | out.push(points[at]); |
| 251 | } |
| 252 | } |
| 253 | let end = point_at(points, cum, to); |
| 254 | if out[out.len() - 1] != end { |
| 255 | out.push(end); |
| 256 | } |
| 257 | if out.len() < 2 { |
| 258 | Vec::new() |
| 259 | } else { |
| 260 | out |
| 261 | } |
| 262 | } |
| 263 | |
| 264 | /// How far along a corridor's reference the nearest point to `p` lies. |
| 265 | fn distance_along(corridor: &Corridor, p: (i32, i32)) -> f64 { |
| 266 | nearest(corridor, p).1 |
| 267 | } |
| 268 | |
| 269 | /// The nearest point on a corridor's reference to `p`, as `(distance to it, distance along)`. |
| 270 | fn nearest(corridor: &Corridor, p: (i32, i32)) -> (f64, f64) { |
| 271 | let (points, cum) = (&corridor.points, &corridor.cum); |
| 272 | let mut best = (f64::INFINITY, 0.0f64); |
| 273 | for at in 0..points.len().saturating_sub(1) { |
| 274 | let (t, offset) = project(p, points[at], points[at + 1], 0.0); |
| 275 | if offset < best.0 { |
| 276 | best = (offset, cum[at] + t * (cum[at + 1] - cum[at])); |
| 277 | } |
| 278 | } |
| 279 | best |
| 280 | } |
| 281 | |
| 282 | /// How far to the side of a corridor's reference `p` lies, in metres, signed positive to the |
| 283 | /// right of the reference's direction of travel. |
| 284 | /// |
| 285 | /// The same nearest-segment walk [`distance_along`] does, because [`project`] returns an |
| 286 | /// unsigned distance and no side. Against the nearest segment's unit tangent `(ux, uy)` in an |
| 287 | /// (east, north) frame — the frame [`directed`] already produces — the side of the offset `d` |
| 288 | /// is `d.east * uy - d.north * ux`. Positive is the right-hand side because `tess::stroke` |
| 289 | /// emits `(0, +1)` as the normal of an eastward segment and `line.vert` shifts along it, so |
| 290 | /// ascending offset is ascending ordinal: `lane_offset_px` gives ordinal zero the most |
| 291 | /// negative offset, which is the left of the reference's travel. |
| 292 | /// |
| 293 | /// Only the reference's own stretch of the corridor, `extent`, is searched. Past the mouth the |
| 294 | /// reference has left the corridor too, and the segment nearest an approaching member is then |
| 295 | /// as likely to be the reference's departure as the corridor — which reads a member leaving |
| 296 | /// west as having no side at all. Clamped, the approach is measured against the reference's |
| 297 | /// tangent at the mouth, which is the axis the lanes are laid out across. |
| 298 | fn signed_offset(corridor: &Corridor, extent: (f64, f64), p: (i32, i32)) -> f64 { |
| 299 | let (points, cum) = (&corridor.points, &corridor.cum); |
| 300 | let mut best = (f64::INFINITY, 0.0f64); |
| 301 | for at in 0..points.len().saturating_sub(1) { |
| 302 | if cum[at + 1] < extent.0 || cum[at] > extent.1 { |
| 303 | continue; |
| 304 | } |
| 305 | let (a, b) = (points[at], points[at + 1]); |
| 306 | let (_, distance) = project(p, a, b, 0.0); |
| 307 | if distance >= best.0 { |
| 308 | continue; |
| 309 | } |
| 310 | let cos_lat = ((a.0 as f64 + b.0 as f64) * 0.5 * 1e-7).to_radians().cos(); |
| 311 | let (east, north) = ((b.1 - a.1) as f64 * cos_lat, (b.0 - a.0) as f64); |
| 312 | let length = (east * east + north * north).sqrt(); |
| 313 | if length <= 0.0 { |
| 314 | continue; |
| 315 | } |
| 316 | let (ux, uy) = (east / length, north / length); |
| 317 | let d_east = (p.1 - a.1) as f64 * 1e-7 * 111_320.0 * cos_lat; |
| 318 | let d_north = (p.0 - a.0) as f64 * 1e-7 * 111_320.0; |
| 319 | best = (distance, d_east * uy - d_north * ux); |
| 320 | } |
| 321 | best.1 |
| 322 | } |
| 323 | |
| 324 | /// One probe point along a candidate, with the unit direction of travel there. |
| 325 | struct Sample { |
| 326 | route: u32, |
| 327 | point: (i32, i32), |
| 328 | ux: f64, |
| 329 | uy: f64, |
| 330 | } |
| 331 | |
| 332 | /// One walked sample of a line: its point and the unit direction of travel there. |
| 333 | /// |
| 334 | /// Exposed so a caller that runs several of [`Covered`]'s gates over one line can walk it |
| 335 | /// once and hand the samples to each, rather than every gate re-walking the same points. |
| 336 | pub type Walked = ((i32, i32), f64, f64); |
| 337 | |
| 338 | /// Walk a polyline at [`SAMPLE_M`], returning each sample with its unit direction of travel. |
| 339 | pub fn walk(points: &[(i32, i32)]) -> Vec<Walked> { |
| 340 | let walked = resample(points, SAMPLE_M); |
| 341 | if walked.len() < 2 { |
| 342 | return Vec::new(); |
| 343 | } |
| 344 | directed(&walked) |
| 345 | } |
| 346 | |
| 347 | /// Each point of `line` with the unit direction of travel there. One entry per input point: |
| 348 | /// a degenerate segment carries the previous direction forward rather than dropping the |
| 349 | /// point, so the result stays index-aligned with its input. |
| 350 | fn directed(line: &[(i32, i32)]) -> Vec<((i32, i32), f64, f64)> { |
| 351 | let mut out = Vec::with_capacity(line.len()); |
| 352 | let (mut ux, mut uy) = (1.0f64, 0.0f64); |
| 353 | for i in 0..line.len() { |
| 354 | let (a, b) = if i + 1 < line.len() { (line[i], line[i + 1]) } else { (line[i.max(1) - 1], line[i]) }; |
| 355 | let cos_lat = ((a.0 as f64 + b.0 as f64) * 0.5 * 1e-7).to_radians().cos(); |
| 356 | let dy = (b.0 - a.0) as f64; |
| 357 | let dx = (b.1 - a.1) as f64 * cos_lat; |
| 358 | let length = (dx * dx + dy * dy).sqrt(); |
| 359 | if length > 0.0 { |
| 360 | (ux, uy) = (dx / length, dy / length); |
| 361 | } |
| 362 | out.push((line[i], ux, uy)); |
| 363 | } |
| 364 | out |
| 365 | } |
| 366 | |
| 367 | /// The nine cells a corridor-radius match can live in, centre first. |
| 368 | /// |
| 369 | /// Returning on the first match means visit order decides how much of the neighbourhood is |
| 370 | /// scanned. The point's own cell is by far the likeliest to hold it — a corridor of 30 m inside a |
| 371 | /// cell of 40 m — so it goes first, then the four edge neighbours, then the corners, which can |
| 372 | /// only match across a cell join. Visiting them in `-1..=1` order put a corner first and scanned |
| 373 | /// most of the neighbourhood before reaching the answer. |
| 374 | /// |
| 375 | /// A pure reordering: the set of samples examined is unchanged, so every result is too. |
| 376 | const NEIGHBOURHOOD: [(i32, i32); 9] = |
| 377 | [(0, 0), (1, 0), (-1, 0), (0, 1), (0, -1), (1, 1), (1, -1), (-1, 1), (-1, -1)]; |
| 378 | |
| 379 | /// Track already drawn, for suppressing a line that adds nothing. |
| 380 | /// |
| 381 | /// Two services of one colour must never draw as parallel lines: nothing distinguishes them, |
| 382 | /// so the second is pure over-draw. What stops that is the lane, which is assigned per |
| 383 | /// **colour** — two lines of one colour in one corridor take the same offset over the same |
| 384 | /// reference geometry and coincide exactly, reading as the one line they are. |
| 385 | /// |
| 386 | /// This is the other half: a line wholly on top of track already drawn in its colour is not |
| 387 | /// worth carrying at all. A route publishes its two directions, its short-turns and its |
| 388 | /// branch variants as separate shapes, and every other feed covering the city republishes |
| 389 | /// the lot re-surveyed a few metres off. |
| 390 | /// |
| 391 | /// **Whole lines only.** Subtracting the covered *parts* of a line was tried and is wrong: it |
| 392 | /// cut every route into fragments, and a stretch too short to be worth emitting left a hole |
| 393 | /// that nothing else drew. A line either adds something or it does not. |
| 394 | /// |
| 395 | /// The lookup is a `HashMap` of cells rather than the sorted vector the rest of this module |
| 396 | /// uses. Nothing iterates it — the answer is a boolean about one point — so it cannot leak an |
| 397 | /// order into the output. |
| 398 | #[derive(Default)] |
| 399 | pub struct Covered { |
| 400 | points: Vec<((i32, i32), f64, f64)>, |
| 401 | cells: std::collections::HashMap<Cell, Vec<u32>>, |
| 402 | /// Which service drew each sample, parallel to `points`. See [`Covered::crowd`]. |
| 403 | tags: Vec<u32>, |
| 404 | /// The `(cell, tag)` pairs already holding a representative. One sample per cell per |
| 405 | /// service is enough for [`covers`](Covered::covers) and [`tags_over`](Covered::tags_over): |
| 406 | /// both ask whether *any* sample of a service is within a corridor of a point, and every |
| 407 | /// sample of one service in one cell answers that identically. Keeping only the first turns |
| 408 | /// a cell's occupancy from overlap depth — a trunk republished by a dozen feeds is a dozen |
| 409 | /// sample runs in the same cells — into distinct services, which is what those gates read. |
| 410 | filled: std::collections::HashSet<(Cell, u32)>, |
| 411 | } |