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

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

junction_part2.rs287 lines · 12.7 KiBRaw
1/// Spread `lanes` across `exits`, both already in left→right order, as `(lane, exit)` pairs.
2///
3/// Whichever side is larger drives the pairing, so every lane gets a connector and every exit gets
4/// fed. Two left-turn lanes onto one road give two connectors into the same exit, which is right —
5/// a dual left turn is two ribbons. One lane onto a two-lane exit gives two connectors out of the
6/// same lane, which is also right: the lane fans.
7fn distribute(lanes: &[usize], exits: &[usize]) -> Vec<(usize, usize)> {
8 if lanes.is_empty() || exits.is_empty() {
9 return Vec::new();
10 }
11 if lanes.len() >= exits.len() {
12 lanes
13 .iter()
14 .enumerate()
15 .map(|(i, &lane)| (lane, exits[i * exits.len() / lanes.len()]))
16 .collect()
17 } else {
18 exits
19 .iter()
20 .enumerate()
21 .map(|(j, &exit)| (lanes[j * lanes.len() / exits.len()], exit))
22 .collect()
23 }
24}
25
26/// The lane connectors through the junction at node `n`, in emission order.
27///
28/// The whole of [`stream_junctions`]'s loop body except the `sink.push` /
29/// `emitted` counting: pure per-node work over shared-read-only tables
30/// (`Graph`/`LaneTable` are file mappings with `&self` accessors,
31/// `InEdges::of` is a pure slice, `Conventions::at_tile` is a
32/// `HashMap::get`), so a batch of node ids fans out across the pool exactly
33/// as `materialise_ways` does and the serial drain pushes the results in `n`
34/// order — which is what keeps the spill, and therefore the archive,
35/// byte-identical at every thread count.
36///
37/// Within a node the order is exactly the serial loop's: `incoming` order,
38/// `legal.sort_by(angle)`, `pairs.sort_unstable(); dedup()`.
39fn junctions_for_node(
40 n: u64,
41 graph: &Graph,
42 lanes: Option<&LaneTable>,
43 incoming: &InEdges,
44 conventions: &Conventions,
45) -> Vec<Vec<(f64, f64)>> {
46 let mut out: Vec<Vec<(f64, f64)>> = Vec::new();
47 let node = graph.node(n);
48 let in_arms: Vec<Arm> = incoming
49 .of(n)
50 .iter()
51 .filter_map(|&idx| {
52 arm(graph, lanes, idx, source_of(graph, idx) as u32, n as u32, false)
53 })
54 .collect();
55 let out_arms: Vec<Arm> = (graph.edge_ptr(n)..graph.edge_ptr(n + 1))
56 .filter(|&idx| is_drivable(graph.edge_type(idx)))
57 .filter_map(|idx| {
58 let target = graph.edge_target(idx, n as u32).ok()?;
59 arm(graph, lanes, idx, n as u32, target, true)
60 })
61 .collect();
62 if in_arms.is_empty() || out_arms.len() < 2 {
63 return out;
64 }
65 // A junction is a node three or more distinct roads meet at. Degree-2 chains are collapsed
66 // by the generator, so the survivors below this bar are dead ends, attribute breaks and
67 // transit stops — none of which anything turns at.
68 let degree: BTreeSet<u32> =
69 in_arms.iter().chain(&out_arms).map(|a| a.neighbour).collect();
70 if degree.len() < 3 {
71 return out;
72 }
73 // Thinning rule: a junction with no arterial arm emits nothing. Quiet
74 // residential crossings keep their carriageways; they lose only the lane
75 // markings, which is where the layer's bytes concentrate.
76 if !in_arms
77 .iter()
78 .chain(&out_arms)
79 .any(|a| a.road_class <= super::junction::ARTERIAL_MAX_CLASS)
80 {
81 return out;
82 }
83
84 let (tx, ty) = tile_build::geom::project(
85 f64::from(node.1) * 1e-7,
86 f64::from(node.0) * 1e-7,
87 super::boundaries::COARSE_ZOOM,
88 );
89 let left_hand = conventions
90 .at_tile(
91 super::boundaries::COARSE_ZOOM,
92 tx.max(0.0) as u64,
93 ty.max(0.0) as u64,
94 )
95 .left_hand;
96
97 for approach in &in_arms {
98 // Every exit but the one back the way you came. The graph carries no turn restrictions,
99 // so this is the whole legality model: inference, and generous.
100 let mut legal: Vec<(usize, f64, Turn)> = out_arms
101 .iter()
102 .enumerate()
103 .filter(|(_, exit)| exit.neighbour != approach.neighbour)
104 .map(|(i, exit)| {
105 let delta = normalise_degrees(exit.heading - approach.heading);
106 (i, delta, classify_turn(delta))
107 })
108 // A reversal is not a movement this layer draws, and the neighbour test above does
109 // not catch it. On a divided highway the median slot reverses onto the *opposing
110 // carriageway*, which is a different node, so it survives that filter and arrives
111 // here as a legal 180-degree movement. The curve it produces never enters the
112 // junction at all: with `f_out = -f_in` all four bezier control points sit behind
113 // the node, so it draws as a flat hook doubling back along the approach.
114 .filter(|(_, _, turn)| *turn != Turn::Reverse)
115 .collect();
116 if legal.is_empty() {
117 continue;
118 }
119 // Left→right as the driver sees them, which is the order lane masks are stored in.
120 legal.sort_by(|a, b| a.1.total_cmp(&b.1));
121
122 // Both ends read the same function of their own arm, so neither can drift from the
123 // other and neither depends on who is looking. No count is derived from the junction's
124 // shape: `legal.len()` counts exits, not lanes, and using it as a width fanned the
125 // endpoints across phantom lanes and off the carriageway.
126 let approach_lanes = effective_lanes(approach);
127
128 // `turn:lanes` where it exists, the arm's own lane count where it does not.
129 let mut pairs: Vec<(usize, usize)> = match &approach.masks {
130 Some(masks) => {
131 let mut pairs = Vec::new();
132 for turn in Turn::ALL {
133 let bit = turn.bit();
134 let claimants: Vec<usize> = masks
135 .iter()
136 .enumerate()
137 .filter(|(_, m)| {
138 // A lane whose only marking is "none" is treated as a through lane,
139 // which is what an unmarked lane at a junction means in practice.
140 **m & bit != 0
141 || (turn == Turn::Through
142 && (**m == 0 || **m == LANE_NONE))
143 })
144 .map(|(k, _)| k)
145 .collect();
146 if claimants.is_empty() {
147 continue;
148 }
149 pairs.extend(distribute(&claimants, &exits_for(turn, &legal)));
150 }
151 pairs
152 }
153 // Untagged, which is the overwhelming majority of roads. The arm's real lanes are
154 // spread over its legal exits — and since an untagged arm has exactly one, every
155 // movement leaves from lane 0 and the connectors share the arm's mouth. Assigning
156 // a lane *index* per exit here was the other half of the fabricated width: it put
157 // the third movement 1.5 lane widths out on a road with one lane.
158 None => {
159 let lanes: Vec<usize> = (0..approach_lanes).collect();
160 let exits: Vec<usize> = legal.iter().map(|(i, _, _)| *i).collect();
161 distribute(&lanes, &exits)
162 }
163 };
164
165 // Ordered so a movement's lanes rank left→right, and deduplicated because two tagged
166 // indications can fall back to the same exit and would otherwise draw one connector
167 // twice on top of itself.
168 pairs.sort_unstable();
169 pairs.dedup();
170
171 for &(in_lane, exit_index) in &pairs {
172 let exit = &out_arms[exit_index];
173 let Some((_, _, turn)) = legal.iter().find(|(i, _, _)| *i == exit_index) else {
174 continue;
175 };
176 // Through movements need no connector: the approach lane's own
177 // carriageway ribbon already paints the straight path, and the
178 // connector draws as an exact identity over it (same style entry,
179 // same colour — see the module docs on reading a screenshot).
180 // Dropping them keeps only turns, which is where the markings
181 // actually differ from the road beneath.
182 if *turn == Turn::Through {
183 continue;
184 };
185 // Thinning rule: a slight (20–45°) movement at a three-way node is
186 // a road bend, not a turn — the carriageway already shows the path.
187 // Kept at degree 4+, where a slight exit is a real choice.
188 if degree.len() == 3
189 && matches!(*turn, Turn::SlightLeft | Turn::SlightRight)
190 {
191 continue;
192 }
193 let out_lanes = effective_lanes(exit);
194 // This lane's place among the lanes making the same movement into the same exit.
195 let siblings: Vec<usize> =
196 pairs.iter().filter(|(_, e)| *e == exit_index).map(|&(l, _)| l).collect();
197 let rank = siblings.iter().position(|&l| l == in_lane).unwrap_or(0);
198 let out_lane =
199 exit_lane(*turn, in_lane, approach_lanes, out_lanes, rank, siblings.len());
200 let Some(points) = connector(ConnectorArgs {
201 node,
202 approach,
203 in_lane,
204 approach_lanes,
205 exit,
206 out_lane,
207 exit_lanes: out_lanes,
208 turn: *turn,
209 left_hand,
210 }) else {
211 continue;
212 };
213 out.push(points);
214 }
215 }
216 out
217}
218
219/// Read the v6 graph at `dir` and push one line feature per lane connector into `sink`. Returns the
220/// number of connectors emitted.
221///
222/// `conventions` decides which side of a road's centreline the direction of travel sits on, so a
223/// left-hand-traffic country's connectors are not mirrored. It is resolved from each junction's own
224/// coordinate at [`super::boundaries::COARSE_ZOOM`], which is the granularity the grid holds.
225///
226/// Not clipped to a bounding box, for the same reason [`crate::schema::traffic::stream_graph`] is
227/// not: the graph is already the built region and the tiler clips each connector per tile.
228pub fn stream_junctions(dir: &Path, conventions: &Conventions, sink: &mut Sink) -> Result<u64> {
229 let graph = Graph::load(dir)?;
230 let lanes = LaneTable::load(dir)?;
231 let incoming = InEdges::build(&graph)?;
232 let class = junction_class();
233 let mut emitted = 0u64;
234
235 // Pipelined, the `materialise_ways` pattern: `junctions_for_node` is pure per-node work over
236 // shared-read-only tables, and so is building each connector's spill record, so both run on
237 // the pool while the drain only appends **in `n` order** -- which is what keeps the spill, and
238 // therefore the archive, byte-identical at every thread count. The bar ticks in the drain, per
239 // node, so it spans the whole graph and this phase is never silent.
240 //
241 // Was batches of 32 Ki nodes with the records encoded in the drain: on the planet (440 M
242 // nodes, 177 M connectors) that ran 4m40s at ~28 cores, the drain and the per-batch barrier
243 // being the limit.
244 const JUNCTION_GROUP: usize = 256 * 1024;
245 let mut bar = Progress::new(
246 "Junctions".to_string(),
247 graph.node_count as usize,
248 "node(s)",
249 true,
250 );
251 // One task per run of `JUNCTION_NODES` consecutive nodes, each producing one `RecordRun`, so
252 // the serial drain appends a run at a time rather than a record at a time (~177 M connectors
253 // on the planet).
254 const JUNCTION_NODES: usize = 1024;
255 let node_count = graph.node_count as usize;
256 let units = node_count.div_ceil(JUNCTION_NODES);
257 crate::extract::pipeline_ordered(
258 units,
259 JUNCTION_GROUP / JUNCTION_NODES,
260 |u| -> Result<crate::store::RecordRun> {
261 let mut run = crate::store::RecordRun::default();
262 let lo = u * JUNCTION_NODES;
263 for n in lo..(lo + JUNCTION_NODES).min(node_count) {
264 for points in junctions_for_node(n as u64, &graph, lanes.as_ref(), &incoming, conventions) {
265 let encoded = crate::store::EncodedGeom::live(&Geometry::Lines(vec![points]))?;
266 run.add(crate::store::PreRecord::named(
267 &class,
268 &encoded,
269 None,
270 tilecodec::mamaps::body::ID_NONE,
271 )?);
272 }
273 }
274 Ok(run)
275 },
276 |u, run| {
277 let run = run?;
278 emitted += run.len() as u64;
279 sink.push_run(run)?;
280 let lo = u * JUNCTION_NODES;
281 bar.tick_n((lo + JUNCTION_NODES).min(node_count) - lo, "node(s)");
282 Ok(())
283 },
284 )?;
285 bar.finish("node(s)");
286 Ok(emitted)
287}