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

Modern-Apps.git / scripts / maps / mamaps_build / src / main.rs

main.rs247 lines · 10.4 KiBRaw
1//! `mamaps_build` — one `.osm.pbf` in, one `.mamaps` archive out.
2//!
3//! The generator this project exists to build. It produces all 9 layers (`landtype`, `roads`,
4//! `boundaries`, `buildings`, `places`, `poi`, `transit`, `traffic`, `junction`), and the shape
5//! does not change when a rule does because every layer is one module under [`schema`].
6//!
7//! ```text
8//! mamaps_build --input california.osm.pbf --out california.mamaps
9//! --coastline LAND.shp --graph GRAPH_DIR
10//! --transit-routes ROUTES.geojsonseq --dem HEIGHTMAPS.mdem
11//! [--region california|world]
12//! [--build-graph-to DIR] [--build-poi-to DIR]
13//!
14//! All six flags are required. Every build carries all 9 layers at z0-14 as
15//! FORMAT_VERSION 8: there is no layer selection, no zoom selection and no
16//! store reuse, so a build is a pure function of its six inputs.
17//!
18//! `--region` filters the built layers (`roads`, `poi`, `buildings`) to the
19//! region's bbox. Everything else is always included regardless. `world` (the
20//! default) disables the filter.
21//!
22//! `--build-graph-to` / `--build-poi-to` fold the routing graph and POI
23//! sidecars into this process instead of running `road_graph` / `poi_extract`
24//! as separate binaries first. Same thread pool, one shared blob scan, and the
25//! graph coverage is validated against the region before stage A runs — which
26//! is what stops a 43-minute tile build dying on a missing `metadata.bin`.
27//! ```
28//!
29//! # Why not through the existing tiler
30//!
31//! `tile_build` already turns GeoJSON-seq into PMTiles, and routing through it would have been less
32//! new code. But it would also mean encoding to MVT and decoding again, which loses exactly the
33//! attributes this format was built to carry: a road's `is_bridge`, a boundary's numeric admin
34//! level, a ring's stated winding. So the geometry is reused — projection, significance,
35//! simplification, tile bisection, clipping, all of `tile_build` — and only the last step, turning a
36//! clipped shape into bytes, is this crate's.
37
38use std::path::PathBuf;
39use std::process::ExitCode;
40
41mod coalesce;
42mod coalesce_extra;
43mod corridor;
44mod dem;
45mod extract;
46mod extract_fallback;
47mod lanefill;
48mod rings;
49mod shapefile;
50mod schema;
51mod store;
52mod tiler;
53mod tilespill;
54mod timing;
55
56/// The allocator, replaced because the default one was three quarters of the build.
57///
58/// A build tool has no business caring which allocator it gets, and this one did not until the
59/// encode pass was measured against the machine it runs on: **1358 s of worker CPU against 180 s of
60/// wall on a 32-core, 64-thread box** — a speed-up of 7.5 where the pool can give 64. Nothing in
61/// that pass is shared. [`rings::normalise`], `body::serialize_into` and DEFLATE each read one tile
62/// and write one tile, there is no lock and no atomic in the path, and the
63/// memory traffic works out at a few hundred MB/s against eight channels of DDR5. The only thing
64/// all sixty-four threads still contend on is the heap.
65///
66/// And they hit it hard. `normalise` allocates a `Vec` per polygon group, another for its exterior
67/// and one per hole it keeps, on the way to rebuilding a layer's arenas; z14 of a us-west build is
68/// 44.4 M features across 943,401 tiles, which is tens of millions of allocate/free pairs on
69/// Windows' process heap in about two and a half minutes.
70///
71/// Swapping it out took the tiling stage from **351 s to 110 s** on the same spill, for a
72/// byte-identical archive:
73///
74/// | phase | default heap | mimalloc |
75/// |---|---|---|
76/// | map | 125.1 s | 72.9 s |
77/// | merge | 33.2 s | 9.6 s |
78/// | encode | 180.3 s | 21.6 s |
79/// | append | 12.4 s | 3.3 s |
80/// | *encode CPU: stage C* | *452.6 s* | *54.4 s* |
81/// | *encode CPU: serialise* | *355.9 s* | *5.4 s* |
82/// | *encode CPU: deflate* | *550.0 s* | *181.1 s* |
83///
84/// Serialisation is the one that says what this really was. It is a memcpy into a reused
85/// [`tilecodec::mamaps::body::Scratch`] and it cost 356 s of CPU; it now costs 5.4 s. That was never
86/// encoding, it was the handful of buffer growths per tile going to `HeapAlloc` under sixty-four
87/// threads of contention.
88///
89/// Two things this is not. It is not a substitute for allocating less — `normalise` should be
90/// threading scratch buffers through rather than building a `Vec` per ring, and a cheaper allocator
91/// only makes that less urgent. And it is not free: mimalloc holds freed pages back rather than
92/// returning them promptly, which took peak RSS from 6.86 GB to 10.14 GB on the same build. That
93/// trade is worth revisiting if memory becomes the binding constraint again.
94///
95/// No `mi_collect` purge is wired after stage A's phase drops for the same reason: `mi_collect`
96/// lives behind the `extended` feature (plus its `cty` dependency), which is not in the offline
97/// registry cache, and the drops that matter for the planet peak are not heap frees at all --
98/// unmapping an anon segment releases pagefile commit immediately, and a file mapping never
99/// charged it. A purge would only return heap slack (relations, members, rayon buffers), which
100/// is measured in hundreds of MB against the multi-GB anon/mmap peaks above.
101///
102/// It cannot change a byte of the output — an allocator decides *where*, never *what* — so it needed
103/// no argument about ordering, only a measurement. The us-west archive hashes the same either way.
104#[global_allocator]
105static ALLOCATOR: mimalloc::MiMalloc = mimalloc::MiMalloc;
106
107/// The deepest zoom an archive is built to. Fixed: every build is z0-14.
108///
109/// Named rather than inlined because layer code is bounded by it: a layer's tiler-side `min_zoom`
110/// past this lands its features in no tile at all, so [`schema::junction`] pins itself against
111/// this constant and lowering it fails that test instead of silently emptying a layer.
112pub const DEFAULT_MAX_ZOOM: u8 = 14;
113
114fn main() -> ExitCode {
115 let args: Vec<String> = std::env::args().collect();
116 let mut input: Option<PathBuf> = None;
117 let mut out: Option<PathBuf> = None;
118 let mut coastline: Option<PathBuf> = None;
119 let mut transit_routes: Option<PathBuf> = None;
120 let mut graph: Option<PathBuf> = None;
121 let mut dem: Option<PathBuf> = None;
122 let mut region: Option<String> = None;
123 let mut build_graph_to: Option<PathBuf> = None;
124 let mut build_poi_to: Option<PathBuf> = None;
125
126 let mut i = 1;
127 while i < args.len() {
128 let value = |name: &str| -> Result<String, String> {
129 args.get(i + 1).cloned().ok_or_else(|| format!("{name} needs a value"))
130 };
131 let taken = match args[i].as_str() {
132 "--input" => value("--input").map(|v| {
133 input = Some(PathBuf::from(v));
134 2
135 }),
136 "--out" => value("--out").map(|v| {
137 out = Some(PathBuf::from(v));
138 2
139 }),
140 "--coastline" => value("--coastline").map(|v| {
141 coastline = Some(PathBuf::from(v));
142 2
143 }),
144 "--transit-routes" => value("--transit-routes").map(|v| {
145 transit_routes = Some(PathBuf::from(v));
146 2
147 }),
148 "--graph" => value("--graph").map(|v| {
149 graph = Some(PathBuf::from(v));
150 2
151 }),
152 "--dem" => value("--dem").map(|v| {
153 dem = Some(PathBuf::from(v));
154 2
155 }),
156 "--region" => value("--region").map(|v| {
157 region = Some(v);
158 2
159 }),
160 "--build-graph-to" => value("--build-graph-to").map(|v| {
161 build_graph_to = Some(PathBuf::from(v));
162 2
163 }),
164 "--build-poi-to" => value("--build-poi-to").map(|v| {
165 build_poi_to = Some(PathBuf::from(v));
166 2
167 }),
168 "-h" | "--help" => {
169 usage();
170 return ExitCode::SUCCESS;
171 }
172 other => Err(format!("unexpected argument '{other}'")),
173 };
174 match taken {
175 Ok(step) => i += step,
176 Err(e) => {
177 eprintln!("mamaps_build: {e}");
178 usage();
179 return ExitCode::from(2);
180 }
181 }
182 }
183
184 let (Some(input), Some(out), Some(coastline), Some(transit_routes), Some(graph), Some(dem)) =
185 (input, out, coastline, transit_routes, graph, dem)
186 else {
187 usage();
188 return ExitCode::from(2);
189 };
190
191 // `--region` defaults to world (no filtering). Parsed here so a bad value
192 // fails in seconds, not after stage A.
193 let region = match region.as_deref().unwrap_or("world") {
194 s => match osm_ingest::region::Region::parse(s) {
195 Ok(r) => r,
196 Err(e) => {
197 eprintln!("mamaps_build: {}", e.0);
198 usage();
199 return ExitCode::from(2);
200 }
201 },
202 };
203
204 let settings = RunSettings {
205 coastline,
206 transit_routes,
207 graph,
208 dem,
209 region,
210 build_graph_to,
211 build_poi_to,
212 };
213 match run(&input, &out, &settings) {
214 Ok(()) => ExitCode::SUCCESS,
215 Err(e) => {
216 eprintln!("mamaps_build: {e}");
217 ExitCode::FAILURE
218 }
219 }
220}
221
222/// Everything a run needs beyond its input and output paths.
223///
224/// All four side inputs are required: every build carries all 9 layers.
225struct RunSettings {
226 /// A prepared land polygon for `landtype`'s mainland — see [`check_required`].
227 coastline: PathBuf,
228 /// A prepared GTFS export for `transit`'s coloured rail lines.
229 transit_routes: PathBuf,
230 /// The v6 routing graph directory (`nodes.bin`/`edges.bin`/`intermediate.bin`/`metadata.bin`)
231 /// for `traffic`'s per-component lines and `junction`'s lane connectors.
232 graph: PathBuf,
233 /// The `.mdem` heightmap dataset `dem_ingest` produced.
234 /// Every tile carries the DEM grid sampled to its own z/x/y.
235 dem: PathBuf,
236 /// Which region's bbox filters roads/pois/buildings. `world` = no filter.
237 region: osm_ingest::region::Region,
238 /// When set, build the routing graph in-process into this dir (shared pool,
239 /// shared blob scan) instead of reading `--graph`.
240 build_graph_to: Option<PathBuf>,
241 /// When set, build the POI sidecars in-process into this dir instead of
242 /// expecting them from a prior `poi_extract` run.
243 build_poi_to: Option<PathBuf>,
244}
245
246include!("main_part1.rs");
247include!("main_part2.rs");