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

Modern-Apps.git / scripts / maps / mamaps_build / src / schema / junction_part1.rs

junction_part1.rs413 lines · 18.6 KiBRaw
1/// Bucket a signed turn angle (degrees, positive clockwise/right) into a [`Turn`].
2///
3/// The thresholds are OSM's own reading of the `turn` vocabulary: `slight` up to 45°, the plain
4/// direction out to 135°, `sharp` beyond that, and a reversal past 170°.
5fn classify_turn(delta_degrees: f64) -> Turn {
6 let magnitude = delta_degrees.abs();
7 let right = delta_degrees > 0.0;
8 if magnitude <= 20.0 {
9 Turn::Through
10 } else if magnitude > 170.0 {
11 Turn::Reverse
12 } else if magnitude <= 45.0 {
13 if right {
14 Turn::SlightRight
15 } else {
16 Turn::SlightLeft
17 }
18 } else if magnitude <= 135.0 {
19 if right {
20 Turn::Right
21 } else {
22 Turn::Left
23 }
24 } else if right {
25 Turn::SharpRight
26 } else {
27 Turn::SharpLeft
28 }
29}
30
31/// Wrap an angle difference into `(-180, 180]`, so a turn's sign is its direction.
32fn normalise_degrees(mut d: f64) -> f64 {
33 while d > 180.0 {
34 d -= 360.0;
35 }
36 while d <= -180.0 {
37 d += 360.0;
38 }
39 d
40}
41
42// --- local geometry -------------------------------------------------------------------------
43
44/// Bearing from `a` to `b` in degrees clockwise from north, on the local tangent plane.
45///
46/// The `e7` units cancel in the ratio; only the `cos(lat)` correction on the east component
47/// matters, and without it every heading north of the tropics comes out rotated.
48fn bearing_degrees(a: (i32, i32), b: (i32, i32)) -> f64 {
49 let mid_lat = (f64::from(a.0) + f64::from(b.0)) * 0.5 * 1e-7;
50 let north = f64::from(b.0) - f64::from(a.0);
51 let east = (f64::from(b.1) - f64::from(a.1)) * mid_lat.to_radians().cos();
52 east.atan2(north).to_degrees()
53}
54
55/// Ground distance between two `e7` points, in metres.
56fn distance_m(a: (i32, i32), b: (i32, i32)) -> f64 {
57 let mid_lat = (f64::from(a.0) + f64::from(b.0)) * 0.5 * 1e-7;
58 let north = (f64::from(b.0) - f64::from(a.0)) * 1e-7 * METRES_PER_DEGREE;
59 let east =
60 (f64::from(b.1) - f64::from(a.1)) * 1e-7 * METRES_PER_DEGREE * mid_lat.to_radians().cos();
61 (north * north + east * east).sqrt()
62}
63
64/// The length of a polyline, in metres.
65fn polyline_length_m(verts: &[(i32, i32)]) -> f64 {
66 verts.windows(2).map(|w| distance_m(w[0], w[1])).sum()
67}
68
69/// A point offset from `origin` by `(east, north)` metres, as `(lon, lat)` degrees.
70fn offset_degrees(origin: (i32, i32), east_m: f64, north_m: f64) -> (f64, f64) {
71 let lat = f64::from(origin.0) * 1e-7;
72 let lon = f64::from(origin.1) * 1e-7;
73 let d_lat = north_m / METRES_PER_DEGREE;
74 // At the poles this divisor collapses; the Mercator clamp means no tile is drawn there anyway,
75 // and a floor keeps a degenerate coordinate from becoming an infinity in the output.
76 let d_lon = east_m / (METRES_PER_DEGREE * lat.to_radians().cos().abs().max(1e-6));
77 (lon + d_lon, lat + d_lat)
78}
79
80/// The unit vector pointing along `heading` (degrees clockwise from north), as `(east, north)`.
81fn forward(heading_degrees: f64) -> (f64, f64) {
82 let r = heading_degrees.to_radians();
83 (r.sin(), r.cos())
84}
85
86/// The unit vector 90° clockwise of `heading` — "right of the direction of travel".
87fn rightward(heading_degrees: f64) -> (f64, f64) {
88 let r = heading_degrees.to_radians();
89 (r.cos(), -r.sin())
90}
91
92// --- the graph, one junction at a time --------------------------------------------------------
93
94/// Is this road class one a car drives on? The same `1..=9` (motorway..living_street) the traffic
95/// layer uses, masked so the reverse-geometry flag cannot trip the range test.
96fn is_drivable(type_: u8) -> bool {
97 (1..=9).contains(&(type_ & ROAD_TYPE_MASK))
98}
99
100/// Incoming drivable edges per node, as a CSR built in one pass over the graph.
101///
102/// `nodes.bin` is out-edges only and there is no reverse index on disk, so this is the whole reason
103/// approaches can be found at all. [`Graph::has_drivable_twin`] is the existing primitive and would
104/// do for a two-way street, but it can only find an approach from a node the junction also has an
105/// out-edge *to* — which misses every one-way approach, and a one-way approach is exactly the
106/// motorway slip road this layer is meant to get right.
107///
108/// Costs `4 * (node_count + 1)` bytes plus 4 per drivable edge, and stores only the edge index: an
109/// in-edge's source node is recovered by [`source_of`], which is a binary search over the same
110/// `edge_ptr` array rather than another 4 bytes an edge.
111struct InEdges {
112 start: Vec<u32>,
113 edges: Vec<u32>,
114}
115
116impl InEdges {
117 fn build(graph: &Graph) -> Result<InEdges> {
118 let node_count = graph.node_count;
119 // Parallel counting sort, not a naive `par_iter`: the serial
120 // `start[target + 1] += 1` is a cross-iteration hazard, so the count
121 // goes through one shared atomic slot per target instead — spread
122 // over `node_count + 1` slots, so the updates are essentially
123 // uncontended — and the fill through the same slots as cursors.
124 //
125 // Memory is the serial shape, not per-shard histograms (shards x
126 // nodes would be tens of GB at planet scale): one atomic slot per
127 // node plus the edge table itself, the same peak as the serial
128 // `start` + `fill` pair this replaces.
129 //
130 // Order is the serial order: sources are visited `n` ascending,
131 // `edge_ptr` ascending, and each node's slice is restored to
132 // ascending `edge_idx` after the fill, so `incoming.of(n)` holds
133 // exactly what the serial loop built and downstream pairing is
134 // unchanged at every thread count.
135 use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
136 use std::sync::Mutex;
137 let slots = node_count as usize + 2;
138 let counts: Vec<AtomicU32> = (0..slots).map(|_| AtomicU32::new(0)).collect();
139 // The first corrupt edge met, serialised: a bounds failure and an
140 // escape-row failure are both fatal, and the message keeps the
141 // serial wording. Checked between phases, so a corrupt graph never
142 // fills (or sorts) a partial index.
143 let first_err: Mutex<Option<osm_ingest::proto::Error>> = Mutex::new(None);
144 let failed = AtomicBool::new(false);
145 // Shards partition the *source* nodes: every edge is visited exactly
146 // once however the ranges fall, so each target's total is exact.
147 let threads = par::threads().max(1);
148 let want_tasks = threads.saturating_mul(4).max(1);
149 let shard_len = ((node_count as usize) / want_tasks).max(1);
150 let mut shards: Vec<std::ops::Range<u64>> = Vec::new();
151 let mut lo = 0u64;
152 while lo < node_count {
153 let hi = (lo + shard_len as u64).min(node_count);
154 shards.push(lo..hi);
155 lo = hi;
156 }
157 // Phase 1: count one slot high, so the prefix sum below leaves
158 // `start[t]` pointing at node `t`'s first slot.
159 par::install(|| {
160 shards.par_iter().for_each(|range| {
161 for n in range.clone() {
162 // Another shard already found corruption: stop feeding
163 // counts nobody will read. Checked per node, not per
164 // edge, so the fast path pays one relaxed load.
165 if failed.load(Ordering::Relaxed) {
166 break;
167 }
168 for idx in graph.edge_ptr(n)..graph.edge_ptr(n + 1) {
169 if !is_drivable(graph.edge_type(idx)) {
170 continue;
171 }
172 let target = match graph.edge_target(idx, n as u32) {
173 Ok(t) => t,
174 Err(e) => {
175 failed.store(true, Ordering::Relaxed);
176 let mut guard = first_err
177 .lock()
178 .unwrap_or_else(|p| p.into_inner());
179 if guard.is_none() {
180 *guard = Some(e);
181 }
182 break;
183 }
184 };
185 if u64::from(target) >= node_count {
186 failed.store(true, Ordering::Relaxed);
187 let mut guard =
188 first_err.lock().unwrap_or_else(|p| p.into_inner());
189 if guard.is_none() {
190 *guard = Some(osm_ingest::proto::Error(format!(
191 "edge {idx} targets node {target}, past the {node_count} in the graph"
192 )));
193 }
194 break;
195 }
196 counts[target as usize + 1].fetch_add(1, Ordering::Relaxed);
197 }
198 }
199 });
200 });
201 if let Some(e) = first_err.lock().unwrap_or_else(|p| p.into_inner()).take() {
202 return Err(e);
203 }
204 // Serial prefix sum, in place: the same array then serves as the
205 // phase-2 fill cursors with no second allocation. The add comes
206 // *before* the snapshot — slot i counts edges targeting node i-1,
207 // so the running total *with* this slot folded in is node i's
208 // block start (slot 0 targets no node and is always empty, pinning
209 // start[0] at 0). Snapshotting before the add shifts every block
210 // one slot down and empties node 0, which is exactly the failure
211 // mode to watch for here.
212 let mut total = 0u32;
213 let mut start = vec![0u32; slots];
214 for (i, slot) in counts.iter().enumerate() {
215 let c = slot.load(Ordering::Relaxed);
216 total = total.checked_add(c).expect(
217 "drivable edges fit u32: Graph::load refuses an edge_count past u32::MAX",
218 );
219 slot.store(total, Ordering::Relaxed);
220 start[i] = total;
221 }
222 // Phase 2: disjoint-slice fill. Every slot written is claimed by
223 // exactly one `fetch_add`, so no two threads share one; phase 1
224 // validated every edge, so the defensive skips below are unreachable
225 // and only guard against filling a corrupt index silently.
226 //
227 // `Vec<AtomicU32>` rather than `&mut Vec<u32>`: the table is shared
228 // across workers, and atomics are `Sync` where a unique borrow is
229 // not. Same 4 bytes a slot, converted back after the join.
230 let edges: Vec<AtomicU32> =
231 std::iter::repeat_with(|| AtomicU32::new(0)).take(total as usize).collect();
232 failed.store(false, Ordering::Relaxed);
233 par::install(|| {
234 shards.par_iter().for_each(|range| {
235 for n in range.clone() {
236 if failed.load(Ordering::Relaxed) {
237 break;
238 }
239 for idx in graph.edge_ptr(n)..graph.edge_ptr(n + 1) {
240 if !is_drivable(graph.edge_type(idx)) {
241 continue;
242 }
243 let Ok(target) = graph.edge_target(idx, n as u32) else {
244 failed.store(true, Ordering::Relaxed);
245 continue;
246 };
247 if u64::from(target) >= node_count {
248 failed.store(true, Ordering::Relaxed);
249 continue;
250 }
251 let at =
252 counts[target as usize].fetch_add(1, Ordering::Relaxed) as usize;
253 // `at` is in-bounds by construction (cursor < start
254 // + count); the check keeps a logic bug a panic
255 // rather than memory unsafety.
256 if let Some(slot) = edges.get(at) {
257 slot.store(idx, Ordering::Relaxed);
258 }
259 }
260 }
261 });
262 });
263 if failed.load(Ordering::Relaxed) {
264 return err(
265 "the graph changed between the junction count and fill passes".to_string(),
266 );
267 }
268 let mut edges: Vec<u32> =
269 edges.into_iter().map(AtomicU32::into_inner).collect();
270 // Restore ascending `edge_idx` within each node: the serial visit
271 // order, and what `incoming.of(n)` has always held. Slices average a
272 // couple of edges, so this pass is a linear walk, not a sort cost.
273 for n in 0..node_count as usize {
274 let (lo, hi) = (start[n] as usize, start[n + 1] as usize);
275 edges[lo..hi].sort_unstable();
276 }
277 start.truncate(node_count as usize + 1);
278 Ok(InEdges { start, edges })
279 }
280
281 fn of(&self, n: u64) -> &[u32] {
282 let lo = self.start[n as usize] as usize;
283 let hi = self.start[n as usize + 1] as usize;
284 &self.edges[lo..hi]
285 }
286}
287
288/// The node edge `idx` leaves from: the last node whose `edge_ptr` is at or below it.
289///
290/// `edge_ptr` ascends across `nodes.bin` and the sentinel record holds `edge_count`, so the answer
291/// is always in `0..node_count` for a valid edge index.
292fn source_of(graph: &Graph, idx: u32) -> u64 {
293 let (mut lo, mut hi) = (1u64, graph.node_count + 1);
294 while lo < hi {
295 let mid = lo + (hi - lo) / 2;
296 if graph.edge_ptr(mid) > idx {
297 hi = mid;
298 } else {
299 lo = mid + 1;
300 }
301 }
302 lo - 1
303}
304
305/// An edge's polyline in the order it is travelled, `from -> to`.
306///
307/// A reverse-geometry edge stores no shape of its own — its twin running the other way owns it — so
308/// the twin's polyline is found and reversed. Without this every curved two-way approach would get
309/// its heading from the straight chord instead of the road, which at a bend is a wrong turn angle
310/// and therefore a wrong lane pairing.
311fn travel_polyline(graph: &Graph, idx: u32, from: u32, to: u32) -> Vec<(i32, i32)> {
312 if graph.geom_contains(idx) {
313 return graph.polyline(idx, from, to);
314 }
315 for twin in graph.edge_ptr(u64::from(to))..graph.edge_ptr(u64::from(to) + 1) {
316 if !graph.geom_contains(twin) || !is_drivable(graph.edge_type(twin)) {
317 continue;
318 }
319 if graph.edge_target(twin, to).is_ok_and(|t| t == from) {
320 let mut verts = graph.polyline(twin, to, from);
321 verts.reverse();
322 return verts;
323 }
324 }
325 // A genuine straight chord: source and target, and nothing between them.
326 graph.polyline(idx, from, to)
327}
328
329/// One movement into or out of a junction, resolved into everything a connector needs.
330struct Arm {
331 /// The node at the far end.
332 neighbour: u32,
333 /// Degrees clockwise from north, always in the direction of travel — so for an approach this is
334 /// the heading traffic *arrives* on, and for an exit the heading it *departs* on.
335 heading: f64,
336 /// The edge's own length in metres, which caps how far the connector may reach along it.
337 length_m: f64,
338 /// Whether the road carries traffic the other way too, which decides whether this direction's
339 /// lanes sit on the centreline or a half-carriageway to one side of it.
340 two_way: bool,
341 /// Per-lane `turn:lanes` masks, left→right, when `lanes.bin` has them. `None` is the common
342 /// case. This is also the arm's only lane-count source — see [`effective_lanes`], which is
343 /// deliberately the one way to ask, so a count can never be fabricated from something that
344 /// merely happened to be in scope.
345 masks: Option<Vec<u16>>,
346 /// The edge's road class (`graph.edge_type & ROAD_TYPE_MASK`: motorway=1 …
347 /// tertiary=5, unclassified=6, …). Read off the edge, never inferred, so the
348 /// arterial gate in `junctions_for_node` is data rather than a second guess.
349 road_class: u8,
350}
351
352/// Resolve one incident edge, or `None` when it is not usable as an arm of this junction.
353fn arm(
354 graph: &Graph,
355 lanes: Option<&LaneTable>,
356 idx: u32,
357 from: u32,
358 to: u32,
359 outgoing: bool,
360) -> Option<Arm> {
361 let verts = travel_polyline(graph, idx, from, to);
362 // The heading is the first geometry step leaving the junction, or the last arriving at it. A
363 // repeated vertex has no direction, so the scan walks past duplicates rather than dividing by
364 // zero — the graph does contain them at edges that were split at a coincident point.
365 let node = if outgoing { verts.first().copied()? } else { verts.last().copied()? };
366 let (heading, ok) = if outgoing {
367 match verts.iter().skip(1).find(|v| **v != node) {
368 Some(next) => (bearing_degrees(node, *next), true),
369 None => (0.0, false),
370 }
371 } else {
372 match verts.iter().rev().skip(1).find(|v| **v != node) {
373 Some(prev) => (bearing_degrees(*prev, node), true),
374 None => (0.0, false),
375 }
376 };
377 if !ok {
378 return None;
379 }
380 let length_m = polyline_length_m(&verts);
381 if length_m < MIN_SETBACK_M {
382 return None;
383 }
384 let masks = lanes.and_then(|table| table.masks(idx)).filter(|m| !m.is_empty());
385 let two_way = graph.has_drivable_twin(to, from).unwrap_or(false);
386 let road_class = graph.edge_type(idx) & ROAD_TYPE_MASK;
387 Some(Arm { neighbour: if outgoing { to } else { from }, heading, length_m, two_way, masks, road_class })
388}
389
390/// A lane's centre, in metres right of the road's centreline as seen by traffic travelling this
391/// arm's direction.
392///
393/// Two offsets stacked. A two-way road's centreline runs between the two directions, so the
394/// carriageway a driver is on sits a half-carriageway to their own side of it — right in a
395/// right-hand-traffic country, left in a left-hand one. Within that carriageway lane `k` of `count`
396/// sits at the usual centred spacing, counted left→right in the direction of travel, which is the
397/// order `lanes.bin` stores masks in.
398///
399/// `width` is the lane width in ground metres at this junction's latitude — see
400/// [`lane_width_ground_m`], and the module docs for why it is not simply [`LANE_WIDTH_MERCATOR_M`].
401///
402/// The opposite direction is assumed to have the same lane count, because the graph gives no way to
403/// ask. An asymmetric road — three lanes one way and one the other — puts its connectors half a
404/// carriageway off.
405fn lane_offset_m(k: usize, count: usize, two_way: bool, left_hand: bool, width: f64) -> f64 {
406 let count = count.max(1);
407 let side = if left_hand { -1.0 } else { 1.0 };
408 let carriageway = if two_way { side * count as f64 * 0.5 * width } else { 0.0 };
409 let within = (k as f64 - (count as f64 - 1.0) * 0.5) * width;
410 carriageway + within
411}
412
413include!("junction_part1_s1.rs");