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

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

traffic_s1.rs390 lines · 16.7 KiBRaw
1impl Graph {
2 pub(crate) fn load(dir: &Path) -> Result<Graph> {
3 let meta = std::fs::read(dir.join("metadata.bin")).map_err(|e| {
4 osm_ingest::proto::Error(format!(
5 "cannot read {}: {e}",
6 dir.join("metadata.bin").display()
7 ))
8 })?;
9 if meta.len() < 40 {
10 return err(format!("metadata.bin is {} bytes, a v6 MARG header is 40", meta.len()));
11 }
12 if u32_at(&meta, 0) != MARG_MAGIC {
13 return err("metadata.bin is not a MARG graph header".to_string());
14 }
15 let version = u32_at(&meta, 4);
16 if !(GRAPH_VERSION_MIN..=GRAPH_VERSION_MAX).contains(&version) {
17 return err(format!(
18 "the graph is version {version}; the traffic layer reads v{GRAPH_VERSION_MIN}..=v{GRAPH_VERSION_MAX}"
19 ));
20 }
21 let varint_v8 = version >= 8;
22 let zsec_v9 = version >= 9;
23 let inter_block = if varint_v8 { INTERMEDIATE_BLOCK_V8 } else { INTERMEDIATE_BLOCK };
24 let blocked_v7 = version >= GRAPH_VERSION;
25 let node_count = u64_at(&meta, 8);
26 let edge_count = u64_at(&meta, 16);
27 let escape_count = u64_at(&meta, 24);
28 if edge_count > u32::MAX as u64 {
29 return err(format!("edge_count {edge_count} does not fit u32"));
30 }
31 if escape_count > edge_count {
32 return err(format!("escape_count {escape_count} exceeds edge_count {edge_count}"));
33 }
34
35 // The three tables open concurrently: three page-cache faults on
36 // three files, no dependency between them. Metadata validation above
37 // stays serial — it sizes everything below. Small win, almost free.
38 let (nodes, edges, inter) = std::thread::scope(|scope| {
39 let open = |name: &'static str| {
40 scope.spawn(move || {
41 osm_ingest::mem::Mapped::open(&dir.join(name)).map_err(osm_ingest::proto::Error)
42 })
43 };
44 let (a, b, c) = (open("nodes.bin"), open("edges.bin"), open("intermediate.bin"));
45 let nodes = a.join().expect("the nodes.bin opener");
46 let edges = b.join().expect("the edges.bin opener");
47 let inter = c.join().expect("the intermediate.bin opener");
48 nodes
49 .and_then(|nodes| edges.map(|edges| (nodes, edges)))
50 .and_then(|(nodes, edges)| inter.map(|inter| (nodes, edges, inter)))
51 })?;
52 let want_nodes = (node_count + 1)
53 .checked_mul(12)
54 .ok_or_else(|| osm_ingest::proto::Error("node table size overflows".to_string()))?;
55 // v7 nodes are a ZBLK section: parse, check the unpacked length, and
56 // inflate eagerly (batch tool — the whole table is walked).
57 let nodes_owned = if blocked_v7 {
58 let view = tilecodec::blocked::Blocked::parse(&nodes).map_err(|e| {
59 osm_ingest::proto::Error(format!("nodes.bin is not a blocked section: {e}"))
60 })?;
61 if view.unpacked_len() != want_nodes || view.record_len() != 12 {
62 return err(format!(
63 "nodes.bin unpacks to {} byte(s), expected {want_nodes}",
64 view.unpacked_len()
65 ));
66 }
67 inflate_all(&view)?
68 } else {
69 if nodes.len() as u64 != want_nodes {
70 return err(format!(
71 "nodes.bin is {} bytes, expected {} for {node_count}+1 records",
72 nodes.len(),
73 want_nodes,
74 ));
75 }
76 Vec::new()
77 };
78
79 // v7 edge records are a ZBLK section at the file head; escapes and
80 // names follow it exactly as before. The records' end comes from the
81 // section, not from `edge_count * 7`.
82 let (escape_first_off, rec_owned) = if blocked_v7 {
83 let view = tilecodec::blocked::Blocked::parse(&edges).map_err(|e| {
84 osm_ingest::proto::Error(format!("edges.bin is not a blocked section: {e}"))
85 })?;
86 if view.unpacked_len() != edge_count * 7 || view.record_len() != 7 {
87 return err(format!(
88 "edges.bin unpacks to {} byte(s), expected {} 7-byte records",
89 view.unpacked_len(),
90 edge_count
91 ));
92 }
93 let rec_end = view.block_offset(view.block_count()).ok_or_else(|| {
94 osm_ingest::proto::Error("edges.bin block table has no end".to_string())
95 })? as usize;
96 (align_up8(rec_end), inflate_all(&view)?)
97 } else {
98 (align_up8((edge_count as usize) * 7), Vec::new())
99 };
100 let escape_blocks = edge_count.div_ceil(ESCAPE_BLOCK) + 1;
101 let escapes_off = escape_first_off + (escape_blocks as usize) * 4;
102 let want_edges_min = escapes_off + (escape_count as usize) * 12;
103 if edges.len() < want_edges_min {
104 return err(format!(
105 "edges.bin is {} bytes, too short for {edge_count} edges and {escape_count} escapes",
106 edges.len(),
107 ));
108 }
109
110 if inter.len() < 8 {
111 return err("intermediate.bin is too short to hold its geometry-edge count".to_string());
112 }
113 let g_edges = u64_at(&inter, inter.len() - 8);
114 if g_edges > edge_count {
115 return err(format!(
116 "intermediate.bin claims {g_edges} geometry edges, past the {edge_count} in the graph"
117 ));
118 }
119 let bitmap_bytes = edge_bitmap_bytes(edge_count);
120 let coarse_bytes = ((g_edges.div_ceil(inter_block) + 1) * 8) as usize;
121 let within_bytes = ((g_edges + 1) * 2) as usize;
122 let trailer = bitmap_bytes + coarse_bytes + within_bytes + 8;
123 if inter.len() < trailer {
124 return err(format!(
125 "intermediate.bin is {} bytes, too short for its {trailer}-byte trailer",
126 inter.len(),
127 ));
128 }
129 let blob_bytes = inter.len() - trailer;
130 // v9: the blob is a ZSEC section; inflate it whole (a batch tool walks it all).
131 let blob_owned = if zsec_v9 {
132 let z = tilecodec::zsec::ZSec::parse(&inter[..blob_bytes]).map_err(|e| {
133 osm_ingest::proto::Error(format!("intermediate.bin v9 blob: {e:?}"))
134 })?;
135 let mut raw = Vec::with_capacity(z.raw_len() as usize);
136 for b in 0..z.block_count() {
137 raw.extend_from_slice(
138 &z.block(b).map_err(|e| osm_ingest::proto::Error(format!("{e:?}")))?,
139 );
140 }
141 raw
142 } else {
143 Vec::new()
144 };
145 let geom_rank_off = blob_bytes;
146 let geom_present_off = blob_bytes + present_offset(edge_count);
147 let coarse_off = blob_bytes + bitmap_bytes;
148 let within_off = coarse_off + coarse_bytes;
149
150 Ok(Graph {
151 nodes,
152 edges,
153 inter,
154 nodes_owned,
155 rec_owned,
156 node_count,
157 escape_first_off,
158 escapes_off,
159 geom_rank_off,
160 geom_present_off,
161 coarse_off,
162 within_off,
163 inter_block,
164 varint_v8,
165 blob_owned,
166 })
167 }
168
169 /// A node's `(lat_e7, lon_e7)`.
170 pub(crate) fn node(&self, n: u64) -> (i32, i32) {
171 let base = (n as usize) * 12;
172 (i32_at(self.nb(), base), i32_at(self.nb(), base + 4))
173 }
174
175 /// A node's first outgoing edge index. The sentinel record (index `node_count`) holds
176 /// `edge_count`, so `edge_ptr(n+1)` is always defined for a real node `n`.
177 pub(crate) fn edge_ptr(&self, n: u64) -> u32 {
178 u32_at(self.nb(), (n as usize) * 12 + 8)
179 }
180
181 pub(crate) fn edge_type(&self, idx: u32) -> u8 {
182 self.rb()[(idx as usize) * 7 + 5]
183 }
184
185 /// The target node of edge `idx` whose source is `s`, decoding the escape table when the
186 /// delta or distance is sentinelled.
187 pub(crate) fn edge_target(&self, idx: u32, s: u32) -> Result<u32> {
188 let base = (idx as usize) * 7;
189 let rb = self.rb();
190 let delta = i16_at(rb, base);
191 let dist =
192 (rb[base + 2] as u32) | ((rb[base + 3] as u32) << 8) | ((rb[base + 4] as u32) << 16);
193 if delta == TARGET_DELTA_ESCAPE || dist == DIST_MM_ESCAPE {
194 self.escape_target(idx)
195 } else {
196 Ok(s.wrapping_add_signed(delta as i32))
197 }
198 }
199
200 fn escape_target(&self, idx: u32) -> Result<u32> {
201 let block = (idx as u64 / ESCAPE_BLOCK) as usize;
202 let lo = u32_at(&self.edges, self.escape_first_off + block * 4);
203 let hi = u32_at(&self.edges, self.escape_first_off + (block + 1) * 4);
204 for r in lo..hi {
205 let rb = self.escapes_off + (r as usize) * 12;
206 if u32_at(&self.edges, rb) == idx {
207 return Ok(u32_at(&self.edges, rb + 4));
208 }
209 }
210 err(format!("edge {idx} is escaped but has no escape row"))
211 }
212
213 /// Does edge `idx` store an interior-point blob?
214 pub(crate) fn geom_contains(&self, idx: u32) -> bool {
215 let byte = self.geom_present_off + (idx as usize) / 8;
216 self.inter[byte] & (1u8 << (idx % 8)) != 0
217 }
218
219 /// The rank of edge `idx` among the geometry-carrying edges: the number of set bits strictly
220 /// below it in the presence bitmap.
221 fn geom_rank(&self, idx: u32) -> u64 {
222 let byte = (idx as usize) / 8;
223 let block = byte / RANK_BLOCK_BYTES;
224 let mut n = u64_at(&self.inter, self.geom_rank_off + block * 8);
225 for b in (block * RANK_BLOCK_BYTES)..byte {
226 n += self.inter[self.geom_present_off + b].count_ones() as u64;
227 }
228 let mask = ((1u16 << (idx % 8)) - 1) as u8;
229 n += (self.inter[self.geom_present_off + byte] & mask).count_ones() as u64;
230 n
231 }
232
233 /// The blob byte offset of the `g`th geometry edge: `coarse[g/32] + within[g]`.
234 fn geom_offset(&self, g: u64) -> u64 {
235 let coarse = u64_at(&self.inter, self.coarse_off + (g / self.inter_block) as usize * 8);
236 let within = u16_at(&self.inter, self.within_off + (g as usize) * 2) as u64;
237 coarse + within
238 }
239
240 /// The `(start, end)` byte range of edge `idx`'s interior-point blob, or `None` when it stores
241 /// no geometry (a straight chord).
242 fn intermediate_range(&self, idx: u32) -> Option<(usize, usize)> {
243 if !self.geom_contains(idx) {
244 return None;
245 }
246 let g = self.geom_rank(idx);
247 Some((self.geom_offset(g) as usize, self.geom_offset(g + 1) as usize))
248 }
249
250 /// The full polyline of edge `idx` in canonical `source -> target` order, as `(lat_e7, lon_e7)`
251 /// vertices: the source node, any stored interior points, then the target node.
252 pub(crate) fn polyline(&self, idx: u32, s: u32, t: u32) -> Vec<(i32, i32)> {
253 let (slat, slon) = self.node(s as u64);
254 let (tlat, tlon) = self.node(t as u64);
255 let mut out = Vec::with_capacity(4);
256 out.push((slat, slon));
257 if let Some((start, end)) = self.intermediate_range(idx) {
258 if self.varint_v8 {
259 // Mirrors graph.rs decode_edge_coords (v8/v9).
260 let blob: &[u8] =
261 if self.blob_owned.is_empty() { &self.inter } else { &self.blob_owned };
262 let b = &blob[start..end.min(blob.len())];
263 let q =
264 |v: i32| (v as i64).div_euclid(10) + i64::from((v as i64).rem_euclid(10) >= 5);
265 let (mut qlat, mut qlon) = (q(slat), q(slon));
266 let mut at = 0usize;
267 let uvar = |at: &mut usize| -> Option<u64> {
268 let (mut r, mut sh) = (0u64, 0u32);
269 while *at < b.len() {
270 let x = b[*at];
271 *at += 1;
272 r |= u64::from(x & 0x7f) << sh;
273 if x & 0x80 == 0 {
274 return Some(r);
275 }
276 sh += 7;
277 }
278 None
279 };
280 let mut count = 1usize;
281 while at < b.len() && count + 1 < MAX_POINTS {
282 let (Some(a), Some(c)) = (uvar(&mut at), uvar(&mut at)) else { break };
283 qlat += ((a >> 1) as i64) ^ -((a & 1) as i64);
284 qlon += ((c >> 1) as i64) ^ -((c & 1) as i64);
285 out.push(((qlat * 10) as i32, (qlon * 10) as i32));
286 count += 1;
287 }
288 out.push((tlat, tlon));
289 return out;
290 }
291 let (mut lat, mut lon) = (slat, slon);
292 let mut off = start;
293 // count starts at 1 for the source; the reader stops at MAX_POINTS total, matching
294 // `graph.rs::decode_edge_coords`.
295 let mut count = 1usize;
296 while off + 4 <= end && count + 1 < MAX_POINTS {
297 let d_lat = i16_at(&self.inter, off) as i32;
298 let d_lon = i16_at(&self.inter, off + 2) as i32;
299 lat = lat.wrapping_add(d_lat);
300 lon = lon.wrapping_add(d_lon);
301 out.push((lat, lon));
302 count += 1;
303 off += 4;
304 }
305 }
306 out.push((tlat, tlon));
307 out
308 }
309
310 /// Is there a drivable edge running `from -> to`? Used to tell a straight two-way chord (which
311 /// has such a twin and is emitted only in the canonical direction) from a one-way (which has
312 /// none and is always emitted).
313 pub(crate) fn has_drivable_twin(&self, from: u32, to: u32) -> Result<bool> {
314 let lo = self.edge_ptr(from as u64);
315 let hi = self.edge_ptr(from as u64 + 1);
316 for e in lo..hi {
317 let rc = self.edge_type(e) & ROAD_TYPE_MASK;
318 if (1..=9).contains(&rc) && self.edge_target(e, from)? == to {
319 return Ok(true);
320 }
321 }
322 Ok(false)
323 }
324}
325
326/// Read the v6 graph at `dir` and push one line feature per drivable component segment into `sink`,
327/// each carrying its packed `component_id`. Returns the number of segments emitted.
328///
329/// Modelled on [`crate::schema::landtype::stream_prepared`] and
330/// [`crate::schema::transit::stream_routes`]: a source of geometry outside the `.osm.pbf`, read
331/// after the OSM passes and streamed straight into the feature sink. Unlike those two it is not
332/// clipped to a bbox here — the graph is already the built region, and the tiler clips each segment
333/// per tile like any other line.
334#[cfg(test)]
335pub fn stream_graph(dir: &Path, sink: &mut Sink) -> Result<u64> {
336 let graph = Graph::load(dir)?;
337 let class = traffic_class();
338 let mut emitted = 0u64;
339 for n in 0..graph.node_count {
340 let s = n as u32;
341 let lo = graph.edge_ptr(n);
342 let hi = graph.edge_ptr(n + 1);
343 for idx in lo..hi {
344 let ty = graph.edge_type(idx);
345 // Step 1: the reverse twin of a curved two-way owns no geometry; its forward twin does.
346 if ty & REVERSE_GEOMETRY_FLAG != 0 {
347 continue;
348 }
349 // A driving overlay: motorway..living_street only.
350 let rc = ty & ROAD_TYPE_MASK;
351 if !(1..=9).contains(&rc) {
352 continue;
353 }
354 let target = graph.edge_target(idx, s)?;
355 if target as u64 >= graph.node_count {
356 return err(format!(
357 "edge {idx} targets node {target}, past the {} in the graph",
358 graph.node_count,
359 ));
360 }
361 // Step 2: a straight two-way chord is emitted only in the canonical direction; a
362 // one-way (no drivable twin back) is always emitted.
363 if !graph.geom_contains(idx) && graph.has_drivable_twin(target, s)? && s >= target {
364 continue;
365 }
366 let verts = graph.polyline(idx, s, target);
367 for seg in 0..verts.len().saturating_sub(1) {
368 let (a_lat, a_lon) = verts[seg];
369 let (b_lat, b_lon) = verts[seg + 1];
370 // A zero-length segment draws nothing and would only cost a feature and an id.
371 if a_lat == b_lat && a_lon == b_lon {
372 continue;
373 }
374 let component_id = pack_component_id(idx as u64, seg as u32);
375 let line = vec![vec![
376 (a_lon as f64 * 1e-7, a_lat as f64 * 1e-7),
377 (b_lon as f64 * 1e-7, b_lat as f64 * 1e-7),
378 ]];
379 sink.push_named(
380 &class,
381 &crate::store::EncodedGeom::live(&Geometry::Lines(line))?,
382 None,
383 component_id,
384 )?;
385 emitted += 1;
386 }
387 }
388 }
389 Ok(emitted)
390}