Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
translate ▾

Modern-Apps.git / scripts / maps / osm_ingest / src / compact.rs

compact.rs440 lines · 14.9 KiBRaw
1//! Degree-2 chain collapsing: the step that turns one graph edge per OSM
2//! geometry vertex into one graph edge per road between junctions.
3//!
4//! Before this stage, `graph_build` emitted an edge for every consecutive pair
5//! of way nodes, so every geometry vertex was a routing node with two
6//! neighbours. California came out at 35.8 M nodes / 74.3 M directed edges — a
7//! ratio of 2.07, the signature of a graph where almost every node is a
8//! pass-through. Those nodes cost 16 bytes each in `nodes.bin`, 14 bytes per
9//! direction in `edges.bin` and 8 bytes per direction in `lanes.bin`, and they
10//! buy nothing: no route ever chooses anything at them.
11//!
12//! Collapsing them moves the vertices into `intermediate.bin` at 4 bytes each
13//! (see [`crate::geom`]) and leaves the road network's shape untouched.
14//!
15//! # What may be collapsed
16//!
17//! A node is interior to a chain only when removing it cannot change a routing
18//! decision or lose data:
19//!
20//! * exactly two incident segments, leading to two *distinct* neighbours that
21//! are both distinct from the node itself;
22//! * both segments agree on road type, speed limit, name and one-way-ness, so
23//! the merged edge can carry a single set of attributes;
24//! * their lane masks agree *in each traversed direction* — checked on mask
25//! contents, not on pool offsets, since two ways with identical lanes intern
26//! them at different offsets;
27//! * one-way segments must actually flow through the node, one in and one out;
28//! * the node carries no transit stop code, because `graph_build`'s isolated
29//! stop reconnection addresses stop nodes directly.
30//!
31//! # Chains that close on themselves
32//!
33//! A ring road whose every node is interior has no anchor to start from. The
34//! lowest-numbered node on such a cycle is promoted back to a real node so the
35//! ring becomes one edge from it to itself. A self-loop is inert for routing —
36//! no shortest path traverses one — but it keeps the ring snappable and drawable,
37//! which is all its interior nodes were doing anyway.
38
39use crate::geom;
40
41/// Sentinel for "this node was collapsed away".
42pub const REMOVED: u32 = u32::MAX;
43
44/// An undirected road segment between two adjacent way nodes: what pass 3
45/// produces before it is split into one or two directed edges.
46///
47/// Road type, speed limit and name come from the way and so are shared by both
48/// directions; only lane masks differ, which is why they are stored per
49/// direction.
50#[derive(Clone, Copy)]
51pub struct Seg {
52 pub u: u32,
53 pub v: u32,
54 pub dist_mm: u32,
55 pub name_offset: u32,
56 pub type_: u8,
57 pub speed_limit: u8,
58 /// True when the way is only traversable `u` -> `v`.
59 pub oneway: bool,
60 pub fwd_lane_off: u32,
61 pub fwd_lane_count: u16,
62 pub bwd_lane_off: u32,
63 pub bwd_lane_count: u16,
64}
65
66impl Seg {
67 /// The endpoint that is not `n`. For a self-loop this is `n` again.
68 #[inline]
69 fn other(&self, n: u32) -> u32 {
70 if self.u == n {
71 self.v
72 } else {
73 self.u
74 }
75 }
76
77 /// Lane pool range for traversal starting at `from`.
78 #[inline]
79 fn lanes_from(&self, from: u32) -> (u32, u16) {
80 if self.u == from {
81 (self.fwd_lane_off, self.fwd_lane_count)
82 } else {
83 (self.bwd_lane_off, self.bwd_lane_count)
84 }
85 }
86}
87
88/// One collapsed run of segments, to be emitted as one directed edge per
89/// permitted direction.
90///
91/// `pts_start`/`pts_len` index [`Compacted::pts`], which holds *original* node
92/// ids: the caller needs their coordinates for the geometry blob, and only its
93/// two endpoints survive into `nodes.bin`.
94pub struct Chain {
95 pub pts_start: u64,
96 pub pts_len: u32,
97 /// Sum of the merged segments' distances, saturating.
98 pub dist_mm: u32,
99 pub name_offset: u32,
100 pub type_: u8,
101 pub speed_limit: u8,
102 pub oneway: bool,
103 /// Lanes for `pts[0]` -> `pts[last]`.
104 pub fwd_lane_off: u32,
105 pub fwd_lane_count: u16,
106 /// Lanes for `pts[last]` -> `pts[0]`. Meaningless when `oneway`.
107 pub bwd_lane_off: u32,
108 pub bwd_lane_count: u16,
109}
110
111impl Chain {
112 /// Original node ids from tail to head.
113 pub fn pts<'a>(&self, all: &'a [u32]) -> &'a [u32] {
114 let s = self.pts_start as usize;
115 &all[s..s + self.pts_len as usize]
116 }
117}
118
119pub struct Compacted {
120 /// Original node id -> surviving node id, or [`REMOVED`].
121 pub new_id: Vec<u32>,
122 /// How many nodes survived.
123 pub kept: u32,
124 pub chains: Vec<Chain>,
125 pub pts: Vec<u32>,
126 /// Chains that had to be cut because their geometry would not fit one edge.
127 pub splits: usize,
128}
129
130/// Collapse every eligible degree-2 chain in `segs`.
131///
132/// `point` supplies a node's coordinates (needed to budget the geometry blob),
133/// `is_stop` reports whether it carries a transit stop code, and `lane_pool` is
134/// the interned lane-mask pool the segments' offsets point into.
135pub fn compact(
136 node_count: u32,
137 segs: &[Seg],
138 lane_pool: &[u16],
139 point: impl Fn(u32) -> geom::Pt,
140 is_stop: impl Fn(u32) -> bool,
141) -> Compacted {
142 let n = node_count as usize;
143 let inc = Incidence::build(n, segs);
144 let mut interior = classify(n, segs, lane_pool, &inc, &is_stop);
145
146 let mut out =
147 Compacted { new_id: Vec::new(), kept: 0, chains: Vec::new(), pts: Vec::new(), splits: 0 };
148 let mut seg_used = vec![false; segs.len()];
149
150 // Walk every chain that has at least one real endpoint.
151 for a in 0..n as u32 {
152 if interior[a as usize] {
153 continue;
154 }
155 for si in inc.at(a) {
156 walk_chain(a, si, segs, &inc, &mut interior, &mut seg_used, &point, &mut out);
157 }
158 }
159
160 // Anything still unused is a cycle of interior nodes with no anchor. Break
161 // it at its lowest-numbered node and walk again. Each pass consumes at
162 // least one cycle, so this terminates.
163 for si in 0..segs.len() {
164 if seg_used[si] {
165 continue;
166 }
167 let anchor = cycle_anchor(si, segs, &inc);
168 interior[anchor as usize] = false;
169 for sj in inc.at(anchor) {
170 walk_chain(anchor, sj, segs, &inc, &mut interior, &mut seg_used, &point, &mut out);
171 }
172 }
173
174 // Renumber. Survivors keep their relative order, so the Morton sort the
175 // device binary-searches is preserved for free.
176 out.new_id = vec![REMOVED; n];
177 let mut next = 0u32;
178 for (i, &is_interior) in interior.iter().enumerate().take(n) {
179 if !is_interior {
180 out.new_id[i] = next;
181 next += 1;
182 }
183 }
184 out.kept = next;
185 out
186}
187
188/// Segment ids incident to each node, as a CSR.
189struct Incidence {
190 start: Vec<u64>,
191 seg: Vec<u32>,
192}
193
194impl Incidence {
195 fn build(n: usize, segs: &[Seg]) -> Incidence {
196 let mut start = vec![0u64; n + 2];
197 for s in segs {
198 start[s.u as usize + 1] += 1;
199 start[s.v as usize + 1] += 1;
200 }
201 for i in 0..=n {
202 start[i + 1] += start[i];
203 }
204 let mut seg = vec![0u32; start[n] as usize];
205 let mut cursor: Vec<u64> = start[..=n].to_vec();
206 for (i, s) in segs.iter().enumerate() {
207 for endpoint in [s.u, s.v] {
208 let c = &mut cursor[endpoint as usize];
209 seg[*c as usize] = i as u32;
210 *c += 1;
211 }
212 }
213 start.truncate(n + 1);
214 Incidence { start, seg }
215 }
216
217 #[inline]
218 fn at(&self, n: u32) -> impl Iterator<Item = u32> + '_ {
219 let (a, b) = (self.start[n as usize] as usize, self.start[n as usize + 1] as usize);
220 self.seg[a..b].iter().copied()
221 }
222
223 #[inline]
224 fn degree(&self, n: u32) -> u64 {
225 self.start[n as usize + 1] - self.start[n as usize]
226 }
227}
228
229/// Decide, for every node, whether it is a pass-through vertex that can be
230/// folded into an edge's geometry.
231fn classify(
232 n: usize,
233 segs: &[Seg],
234 lane_pool: &[u16],
235 inc: &Incidence,
236 is_stop: &impl Fn(u32) -> bool,
237) -> Vec<bool> {
238 let lanes = |off: u32, count: u16| -> &[u16] {
239 if count == 0 || off == u32::MAX {
240 return &[];
241 }
242 let s = off as usize;
243 &lane_pool[s..s + count as usize]
244 };
245
246 let mut interior = vec![false; n];
247 for w in 0..n as u32 {
248 if is_stop(w) {
249 continue;
250 }
251 // Degree 0 is dropped rather than kept: a node with no incident segment
252 // is a way the region filter removed, dead weight in `nodes.bin` with no
253 // edge ever addressing it. Marked interior so the renumber below hands
254 // it REMOVED; no walk can reach a node with no segments, so the mark is
255 // unreachable by construction.
256 if inc.degree(w) == 0 {
257 interior[w as usize] = true;
258 continue;
259 }
260 if inc.degree(w) != 2 {
261 continue;
262 }
263 let mut it = inc.at(w);
264 let (i1, i2) = match (it.next(), it.next()) {
265 (Some(a), Some(b)) => (a, b),
266 _ => continue,
267 };
268 let (s1, s2) = (&segs[i1 as usize], &segs[i2 as usize]);
269 let (a, b) = (s1.other(w), s2.other(w));
270 // Distinct neighbours, neither of them w. `a == b` means two parallel
271 // segments between the same pair of nodes; collapsing that would fuse
272 // two genuinely different roads into one polyline.
273 if a == w || b == w || a == b {
274 continue;
275 }
276 if s1.type_ != s2.type_
277 || s1.speed_limit != s2.speed_limit
278 || s1.name_offset != s2.name_offset
279 || s1.oneway != s2.oneway
280 {
281 continue;
282 }
283 if s1.oneway {
284 // Traffic has to pass through: one segment must end at w and the
285 // other start there. Two one-ways both pointing at w make it a
286 // sink, which is a real feature of the network, not a pass-through.
287 let flows = (s1.v == w && s2.u == w) || (s2.v == w && s1.u == w);
288 if !flows {
289 continue;
290 }
291 }
292 // Lane masks must agree along each direction actually traversed.
293 let (o1, c1) = s1.lanes_from(a);
294 let (o2, c2) = s2.lanes_from(w);
295 if lanes(o1, c1) != lanes(o2, c2) {
296 continue;
297 }
298 if !s1.oneway {
299 let (o3, c3) = s2.lanes_from(b);
300 let (o4, c4) = s1.lanes_from(w);
301 if lanes(o3, c3) != lanes(o4, c4) {
302 continue;
303 }
304 }
305 interior[w as usize] = true;
306 }
307 interior
308}
309
310/// Follow the chain that leaves anchor `a` through segment `si`, emitting one or
311/// more [`Chain`]s. Does nothing if the segment was already consumed from the
312/// other end.
313#[allow(clippy::too_many_arguments)]
314fn walk_chain(
315 a: u32,
316 si: u32,
317 segs: &[Seg],
318 inc: &Incidence,
319 interior: &mut [bool],
320 seg_used: &mut [bool],
321 point: &impl Fn(u32) -> geom::Pt,
322 out: &mut Compacted,
323) {
324 if seg_used[si as usize] {
325 return;
326 }
327 let mut path = vec![a];
328 // One entry per hop in `path`, so a split run can take its own distances
329 // rather than look them up again. The lookup would have to match a segment by
330 // its endpoints, which is ambiguous for a two-node run between two junctions
331 // joined by more than one way.
332 let mut hops: Vec<u32> = Vec::new();
333 let mut prev_seg = si;
334 let mut cur = segs[si as usize].other(a);
335 seg_used[si as usize] = true;
336 hops.push(segs[si as usize].dist_mm);
337 path.push(cur);
338
339 while interior[cur as usize] {
340 // Interior nodes have exactly two incident segments by construction, so
341 // "the one we did not arrive on" is well defined.
342 let next_seg = match inc.at(cur).find(|s| *s != prev_seg) {
343 Some(s) => s,
344 None => break,
345 };
346 if seg_used[next_seg as usize] {
347 break;
348 }
349 seg_used[next_seg as usize] = true;
350 hops.push(segs[next_seg as usize].dist_mm);
351 cur = segs[next_seg as usize].other(cur);
352 path.push(cur);
353 prev_seg = next_seg;
354 }
355
356 // A one-way chain must be emitted along its traffic flow, not along whichever
357 // end the walk happened to start from. `classify` guarantees every segment in
358 // it is consistently oriented, so the first segment decides: if the walk came
359 // in against the flow, turn the whole path around.
360 let mut first_seg = si;
361 let mut last_seg = prev_seg;
362 if segs[si as usize].oneway && segs[si as usize].u != path[0] {
363 path.reverse();
364 hops.reverse();
365 std::mem::swap(&mut first_seg, &mut last_seg);
366 }
367
368 // The chain's attributes are those of its first segment; every segment in it
369 // was required to agree.
370 let head = &segs[first_seg as usize];
371 let (fwd_lane_off, fwd_lane_count) = head.lanes_from(path[0]);
372 let last = path[path.len() - 1];
373 let (bwd_lane_off, bwd_lane_count) = segs[last_seg as usize].lanes_from(last);
374
375 let runs = split_runs(&path, point);
376 if runs.len() > 1 {
377 out.splits += runs.len() - 1;
378 }
379 for (lo, hi) in runs {
380 // A cut point becomes a real node again.
381 if lo != 0 {
382 interior[path[lo] as usize] = false;
383 }
384 let pts_start = out.pts.len() as u64;
385 out.pts.extend_from_slice(&path[lo..=hi]);
386 out.chains.push(Chain {
387 pts_start,
388 pts_len: (hi - lo + 1) as u32,
389 dist_mm: hops[lo..hi].iter().fold(0u32, |a, d| a.saturating_add(*d)),
390 name_offset: head.name_offset,
391 type_: head.type_,
392 speed_limit: head.speed_limit,
393 oneway: head.oneway,
394 fwd_lane_off,
395 fwd_lane_count,
396 bwd_lane_off,
397 bwd_lane_count,
398 });
399 }
400}
401
402/// Cut `path` into runs that each fit one edge's geometry.
403///
404/// Returns inclusive index ranges. A run of two nodes is always allowed even if
405/// its single segment is too long to delta-encode: the caller stores no geometry
406/// for it, and the reader's straight-chord fallback is then exactly right,
407/// because a two-node run *is* a straight chord.
408fn split_runs(path: &[u32], point: &impl Fn(u32) -> geom::Pt) -> Vec<(usize, usize)> {
409 let mut runs = Vec::new();
410 let mut start = 0usize;
411 let mut cost = 1u64;
412 let mut i = 1usize;
413 while i < path.len() {
414 let step = geom::segment_points(point(path[i - 1]), point(path[i]));
415 if cost + step <= u64::from(geom::MAX_POINTS) {
416 cost += step;
417 i += 1;
418 continue;
419 }
420 if i - 1 > start {
421 // Close the run before this segment and retry it with a fresh
422 // budget starting at the shared node.
423 runs.push((start, i - 1));
424 start = i - 1;
425 cost = 1;
426 } else {
427 // One segment that cannot be encoded at all, even alone.
428 runs.push((start, i));
429 start = i;
430 cost = 1;
431 i += 1;
432 }
433 }
434 if start < path.len() - 1 {
435 runs.push((start, path.len() - 1));
436 }
437 runs
438}
439
440include!("compact_part1.rs");