1#![warn(missing_docs)]
2
3pub mod cli;
17pub mod config;
18pub use geolith::error;
19pub use geolith::output;
20pub use geolith::{conflation, progress, source};
21pub use geolith_dataset_builder as dataset;
22pub use geolith_search_builder as geocoding;
23pub use geolith_tiles_builder::{
24 geometry, layers, raster, reconstruct, sort, splat, terrain, tile, timing,
25};
26
27#[non_exhaustive]
29#[derive(Debug, Clone, PartialEq, Eq)]
30pub enum PipelineAction {
31 Geocoding,
33 Routing(std::path::PathBuf),
35 Tiles,
37 UnsupportedFormat(String),
39}
40
41#[must_use]
47pub fn select_action(config: &config::Config) -> PipelineAction {
48 match config.output_format.as_str() {
49 "geocoding" => PipelineAction::Geocoding,
50 "routing" => {
51 let out = config
52 .routing_output
53 .clone()
54 .unwrap_or_else(|| std::path::PathBuf::from("planet-routing.glx"));
55 PipelineAction::Routing(out)
56 }
57 "tiles" => PipelineAction::Tiles,
58 other => PipelineAction::UnsupportedFormat(other.to_owned()),
59 }
60}
61
62fn init_tracing() {
67 timing::init();
68 tracing_subscriber::fmt()
72 .with_timer(timing::ElapsedTimer)
73 .with_env_filter(
74 tracing_subscriber::EnvFilter::try_from_default_env()
75 .unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("info")),
76 )
77 .with_writer(std::io::stderr)
78 .init();
79}
80
81pub fn run() -> anyhow::Result<()> {
87 let command = cli::parse_args();
88 init_tracing();
89 run_command(command)
90}
91
92pub fn run_command(command: cli::Command) -> anyhow::Result<()> {
101 tracing::info!("geolith v{}", env!("CARGO_PKG_VERSION"));
102
103 match command {
104 cli::Command::Terrain(args) => run_terrain(&args),
105 cli::Command::SplatTiles(args) => run_splat_tiles(&args),
106 cli::Command::Raster(args) => run_raster(&args),
107 cli::Command::Reconstruct(args) => run_reconstruct(&args),
108 cli::Command::Dataset(args) => dataset::run(&args),
109 cli::Command::Notices => {
110 print!("{}", cli::NOTICE);
111 Ok(())
112 }
113 cli::Command::Tiles(config) => {
114 tracing::info!("config: {:?}", config);
115 run_with_config(&config)
116 }
117 }
118}
119
120#[must_use]
123pub fn exit_code(error: &anyhow::Error) -> i32 {
124 error
125 .downcast_ref::<dataset::exit::Exit>()
126 .map_or(1, |exit| exit.0)
127}
128
129pub fn run_raster(args: &cli::RasterArgs) -> anyhow::Result<()> {
136 let options = args.build_options()?;
137 raster::run(&options, &args.output)
138}
139
140pub fn run_terrain(args: &cli::TerrainArgs) -> anyhow::Result<()> {
146 let options = args.tiler_options()?;
147 terrain::run(&args.dem, args.dem_crs, &args.output, &args.name, &options)
148}
149
150pub fn run_splat_tiles(args: &cli::SplatTilesArgs) -> anyhow::Result<()> {
156 splat::run(&args.job())
157}
158
159pub fn run_reconstruct(args: &cli::ReconstructArgs) -> anyhow::Result<()> {
167 reconstruct::run_reconstruct(&args.video, &args.output, &args.options())
168 .map_err(anyhow::Error::from)
169}
170
171pub fn run_with_config(config: &config::Config) -> anyhow::Result<()> {
181 match select_action(config) {
182 PipelineAction::Geocoding => run_search(config),
183 PipelineAction::Routing(out) => run_routing(config, &out),
184 PipelineAction::UnsupportedFormat(format) => anyhow::bail!(
185 "unsupported --output-format '{format}': expected tiles, geocoding or routing"
186 ),
187 PipelineAction::Tiles => geolith_tiles_builder::run(&config.tiles()?),
188 }
189}
190
191fn run_search(config: &config::Config) -> anyhow::Result<()> {
197 let data = config.required_path(config::PathFlag::Data)?;
198 let output = match config.geocoding_output.clone() {
199 Some(path) => path,
200 None => geocoding::pipeline::default_geocoding_output(
201 config.required_path(config::PathFlag::Output)?,
202 &config.geocoding_format,
203 ),
204 };
205 let mut options = geolith_search_builder::SearchOptions::new(data, output);
206 options.format.clone_from(&config.geocoding_format);
207 options.osm_pbf.clone_from(&config.osm_pbf);
208 options.india_outline.clone_from(&config.india_outline);
209 options.bbox.clone_from(&config.bbox);
210 options.tmpdir.clone_from(&config.tmpdir);
211 options.node_store.clone_from(&config.node_store);
212 options.reuse_node_cache = config.reuse.node_cache;
213 options
214 .wikimedia_importance
215 .clone_from(&config.wikimedia_importance);
216 options.pg_index_flavor = config.pg_index_flavor;
217 geolith_search_builder::run(&options)
218}
219
220fn run_routing(config: &config::Config, out: &std::path::Path) -> anyhow::Result<()> {
227 let Some(pbf) = config.osm_pbf.as_deref() else {
228 anyhow::bail!("--output-format routing needs --osm-pbf: the graph is built from OSM");
229 };
230 let mut options = geolith_routing_builder::RoutingOptions::new(pbf, out);
231 options.tmpdir.clone_from(&config.tmpdir);
232 options
233 .default_speeds
234 .clone_from(&config.routing_default_speeds);
235 options.admins.clone_from(&config.routing_admins);
236 options.timezones.clone_from(&config.routing_timezones);
237 options
238 .predicted_speeds
239 .clone_from(&config.routing_predicted_speeds);
240 options.metric_out.clone_from(&config.routing_metric_out);
241 options.cch.clone_from(&config.routing_cch);
242 if let (Some(_), Some(path)) = (
245 config.routing_admins.as_deref(),
246 config.india_outline.as_deref(),
247 ) {
248 options.india = Some(
249 geocoding::india::IndiaOutline::load(path)?
250 .polygons()
251 .clone(),
252 );
253 }
254 geolith_routing_builder::run(&options)
255}
256
257#[cfg(test)]
258mod tests {
259 use super::*;
260 use crate::config::Config;
261
262 fn make_config(output_format: &str) -> Config {
263 Config {
264 data: Some(std::path::PathBuf::from("/dev/null")),
265 osm_pbf: None,
266 natural_earth: Some(std::path::PathBuf::from("/dev/null")),
267 water_polygons: Some(std::path::PathBuf::from("/dev/null")),
268 land_polygons: Some(std::path::PathBuf::from("/dev/null")),
269 india_boundary: None,
270 india_outline: None,
271 output: Some(std::path::PathBuf::from("/dev/null")),
272 output_format: output_format.to_string(),
273 tile_format: "mvt".to_string(),
274 geocoding_format: "pg-copy".to_string(),
275 pg_index_flavor: crate::config::PgIndexFlavor::default(),
276 geocoding_output: None,
277 wikimedia_importance: None,
278 routing_output: None,
279 routing_predicted_speeds: None,
280 routing_metric_out: None,
281 routing_cch: Vec::new(),
282 routing_default_speeds: None,
283 routing_admins: None,
284 routing_timezones: None,
285 bbox: None,
286 max_zoom: 15,
287 threads: None,
288 chunk_size_mb: 0,
289 tmpdir: None,
290 node_store: None,
291 reuse: crate::config::RunReuse {
292 node_cache: false,
293 resume: false,
294 },
295 buildings_source: "both".to_string(),
296 places_source: "both".to_string(),
297 roads_source: "both".to_string(),
298 pois_source: "both".to_string(),
299 water_source: "both".to_string(),
300 landuse_source: "both".to_string(),
301 divisions_source: "overture".to_string(),
302 landcover_source: "overture".to_string(),
303 bathymetry_source: "overture".to_string(),
304 bridge_dir: None,
305 bridge_files: vec![],
306 no_conflate: false,
307 reclaim_source_after_read: false,
308 }
309 }
310
311 #[test]
312 fn select_action_geocoding() {
313 let cfg = make_config("geocoding");
314 assert_eq!(select_action(&cfg), PipelineAction::Geocoding);
315 }
316
317 #[test]
318 fn select_action_routing_default_path() {
319 let cfg = make_config("routing");
320 assert_eq!(
321 select_action(&cfg),
322 PipelineAction::Routing(std::path::PathBuf::from("planet-routing.glx"))
323 );
324 }
325
326 #[test]
327 fn select_action_routing_explicit_path() {
328 let mut cfg = make_config("routing");
329 cfg.routing_output = Some(std::path::PathBuf::from("/tmp/custom.glx"));
330 assert_eq!(
331 select_action(&cfg),
332 PipelineAction::Routing(std::path::PathBuf::from("/tmp/custom.glx"))
333 );
334 }
335
336 #[test]
337 fn select_action_tiles() {
338 let cfg = make_config("tiles");
339 assert_eq!(select_action(&cfg), PipelineAction::Tiles);
340 }
341
342 #[test]
343 fn select_action_unsupported_format() {
344 let cfg = make_config("osrm");
345 assert_eq!(
346 select_action(&cfg),
347 PipelineAction::UnsupportedFormat("osrm".to_string())
348 );
349 }
350
351 #[test]
352 fn run_with_config_rejects_an_unsupported_format() {
353 let cfg = make_config("unknown");
354 let err = run_with_config(&cfg).expect_err("a typo must not exit 0");
355 assert!(format!("{err}").contains("'unknown'"), "{err}");
356 }
357
358 #[test]
359 fn run_with_config_routing_needs_an_osm_pbf() {
360 let mut cfg = make_config("routing");
361 cfg.routing_output = Some(std::path::PathBuf::from("/tmp/graph.glx"));
362 let err = run_with_config(&cfg).expect_err("no graph without a PBF");
363 assert!(format!("{err}").contains("--osm-pbf"), "{err}");
364 }
365
366 #[test]
367 fn run_with_config_tiles_surfaces_an_unreadable_data_dir() {
368 let cfg = make_config("tiles");
369 let err = run_with_config(&cfg).expect_err("/dev/null is not a source directory");
370 assert!(
371 !format!("{err}").is_empty(),
372 "the failure is reported rather than panicking"
373 );
374 }
375
376 fn with_tracing<T>(body: impl FnOnce() -> T) -> T {
382 let subscriber = tracing_subscriber::fmt()
383 .with_test_writer()
384 .with_max_level(tracing::Level::TRACE)
385 .finish();
386 tracing::subscriber::with_default(subscriber, body)
387 }
388
389 fn write_dem(values: Vec<f32>, nodata: Option<&str>) -> tempfile::NamedTempFile {
395 use std::io::{Seek as _, Write as _};
396
397 use tiff::encoder::{TiffEncoder, colortype};
398 use tiff::tags::Tag;
399
400 let mut buffer = std::io::Cursor::new(Vec::new());
401 {
402 let mut encoder = TiffEncoder::new(&mut buffer).expect("tiff encoder");
403 let mut image = encoder
404 .new_image::<colortype::Gray32Float>(4, 4)
405 .expect("image encoder");
406 let directory = image.encoder();
407 directory
408 .write_tag(Tag::Unknown(33_550), &[10.0_f64, 10.0, 0.0][..])
409 .expect("pixel scale");
410 directory
411 .write_tag(
412 Tag::Unknown(33_922),
413 &[0.0_f64, 0.0, 0.0, 400_000.0, 5_100_000.0, 0.0][..],
414 )
415 .expect("tiepoint");
416 directory
417 .write_tag(
418 Tag::Unknown(34_735),
419 &[1_u32, 1, 0, 1, 3072, 0, 1, 32_632][..],
420 )
421 .expect("geokeys");
422 if let Some(sentinel) = nodata {
423 directory
424 .write_tag(Tag::Unknown(42_113), sentinel)
425 .expect("nodata");
426 }
427 image.write_data(&values).expect("write samples");
428 }
429 buffer.rewind().expect("rewind");
430
431 let mut file = tempfile::Builder::new()
432 .suffix(".tif")
433 .tempfile()
434 .expect("temp file");
435 file.write_all(&buffer.into_inner()).expect("write tiff");
436 file.flush().expect("flush");
437 file
438 }
439
440 fn write_ply(vertex_count: usize) -> tempfile::NamedTempFile {
441 use std::io::Write as _;
442
443 const PROPERTIES: [&str; 14] = [
444 "x", "y", "z", "f_dc_0", "f_dc_1", "f_dc_2", "opacity", "scale_0", "scale_1",
445 "scale_2", "rot_0", "rot_1", "rot_2", "rot_3",
446 ];
447
448 let mut file = tempfile::NamedTempFile::new().expect("temp file");
449 let mut header = String::from("ply\nformat binary_little_endian 1.0\n");
450 header.push_str(&format!("element vertex {vertex_count}\n"));
451 for property in PROPERTIES {
452 header.push_str(&format!("property float {property}\n"));
453 }
454 header.push_str("end_header\n");
455 file.write_all(header.as_bytes()).expect("header");
456
457 for index in 0..vertex_count {
458 let offset = index as f32;
459 for value in [
460 offset,
461 offset * 0.5,
462 offset * 0.25,
463 0.4,
464 0.5,
465 0.6,
466 1.1,
467 -2.0,
468 -2.1,
469 -2.2,
470 1.0,
471 0.0,
472 0.0,
473 0.0,
474 ] {
475 file.write_all(&value.to_le_bytes()).expect("vertex");
476 }
477 }
478 file.flush().expect("flush");
479 file
480 }
481
482 fn terrain_args(dem: &std::path::Path, output: &std::path::Path) -> cli::TerrainArgs {
483 cli::TerrainArgs {
484 dem: vec![dem.to_path_buf()],
485 clip: None,
486 output: output.to_path_buf(),
487 encoding: "mapbox".to_owned(),
488 min_zoom: 12,
489 max_zoom: 13,
490 tile_size: 256,
491 dem_crs: None,
492 name: "terrain".to_owned(),
493 }
494 }
495
496 fn splat_args(ply: &std::path::Path, output: &std::path::Path) -> cli::SplatTilesArgs {
497 cli::SplatTilesArgs {
498 ply: ply.to_path_buf(),
499 output: output.to_path_buf(),
500 longitude: 7.9797,
501 latitude: 45.9756,
502 altitude: 2250.0,
503 max_splats_per_tile: 4,
504 max_depth: 2,
505 root_geometric_error: 64.0,
506 antialiased: false,
507 emit_scene_spz: true,
508 crop_percentile: 0.0,
509 scale: 1.0,
510 coverage_boost_scale: 0.0,
511 }
512 }
513
514 #[test]
515 fn run_terrain_writes_an_archive() {
516 let values: Vec<f32> = (0..16).map(|i| 1000.0 + i as f32).collect();
517 let dem = write_dem(values, None);
518 let dir = tempfile::tempdir().expect("tempdir");
519 let output = dir.path().join("terrain.pmtiles");
520
521 with_tracing(|| run_terrain(&terrain_args(dem.path(), &output)))
522 .expect("terrain pipeline runs");
523
524 let bytes = std::fs::read(&output).expect("archive exists");
525 assert_eq!(&bytes[..7], b"PMTiles");
526 }
527
528 #[test]
529 fn run_terrain_writes_an_archive_for_valid_and_all_nodata_dems() {
530 let dir = tempfile::tempdir().expect("tempdir");
531
532 let values: Vec<f32> = (0..16).map(|i| 1000.0 + i as f32).collect();
533 let dem = write_dem(values, None);
534 let with_samples = dir.path().join("a.pmtiles");
535 with_tracing(|| run_terrain(&terrain_args(dem.path(), &with_samples)))
536 .expect("a DEM with valid samples must tile");
537
538 let dem = write_dem(vec![-9999.0; 16], Some("-9999"));
539 let all_nodata = dir.path().join("b.pmtiles");
540 with_tracing(|| run_terrain(&terrain_args(dem.path(), &all_nodata)))
541 .expect("an all-nodata DEM must still tile");
542
543 for path in [&with_samples, &all_nodata] {
544 let bytes = std::fs::read(path).expect("archive must exist on disk");
545 assert_eq!(
546 &bytes[..7],
547 b"PMTiles",
548 "{path:?} must be a PMTiles archive"
549 );
550 }
551 }
552
553 #[test]
554 fn run_terrain_propagates_failures() {
555 let dir = tempfile::tempdir().expect("tempdir");
556 let mut args = terrain_args(
557 std::path::Path::new("/nonexistent/dem.tif"),
558 &dir.path().join("out.pmtiles"),
559 );
560
561 args.encoding = "rainbow".to_owned();
562 assert!(
563 with_tracing(|| run_terrain(&args)).is_err(),
564 "the encoding is validated before the DEM is opened"
565 );
566
567 args.encoding = "mapbox".to_owned();
568 args.dem_crs = Some(27_700);
569 assert!(
570 with_tracing(|| run_terrain(&args)).is_err(),
571 "an unsupported EPSG fails before the DEM is read"
572 );
573
574 args.dem_crs = None;
575 assert!(
576 with_tracing(|| run_terrain(&args)).is_err(),
577 "a missing DEM surfaces as an error"
578 );
579 }
580
581 #[test]
582 fn run_splat_tiles_writes_a_tileset_and_scene() {
583 let ply = write_ply(32);
584 let dir = tempfile::tempdir().expect("tempdir");
585 let output = dir.path().join("tileset");
586
587 with_tracing(|| run_splat_tiles(&splat_args(ply.path(), &output)))
588 .expect("splat pipeline runs");
589
590 assert!(output.join("tileset.json").is_file());
591 assert!(output.join("tiles/0.glb").is_file());
592 assert!(
593 output.join("scene.spz").is_file(),
594 "--emit-scene-spz writes the standalone packet"
595 );
596 }
597
598 #[test]
599 fn run_splat_tiles_skips_the_scene_when_not_requested() {
600 let ply = write_ply(8);
601 let dir = tempfile::tempdir().expect("tempdir");
602 let output = dir.path().join("tileset");
603
604 let mut args = splat_args(ply.path(), &output);
605 args.emit_scene_spz = false;
606 with_tracing(|| run_splat_tiles(&args)).expect("splat pipeline runs");
607
608 assert!(output.join("tileset.json").is_file());
609 assert!(!output.join("scene.spz").exists());
610 }
611
612 #[test]
613 fn run_splat_tiles_propagates_failures() {
614 let dir = tempfile::tempdir().expect("tempdir");
615 assert!(
616 with_tracing(|| run_splat_tiles(&splat_args(
617 std::path::Path::new("/nonexistent/scene.ply"),
618 &dir.path().join("tileset"),
619 )))
620 .is_err(),
621 "a missing PLY surfaces as an error"
622 );
623
624 let empty = write_ply(0);
625 let err =
626 with_tracing(|| run_splat_tiles(&splat_args(empty.path(), &dir.path().join("empty"))))
627 .expect_err("an empty cloud cannot be tiled");
628 assert!(format!("{err}").contains("empty splat cloud"), "{err}");
629 }
630
631 #[test]
632 fn run_command_dispatches_every_verb() {
633 let dir = tempfile::tempdir().expect("tempdir");
634
635 let values: Vec<f32> = (0..16).map(|i| 1000.0 + i as f32).collect();
636 let dem = write_dem(values, None);
637 let terrain_out = dir.path().join("dispatched.pmtiles");
638 with_tracing(|| {
639 run_command(cli::Command::Terrain(Box::new(terrain_args(
640 dem.path(),
641 &terrain_out,
642 ))))
643 })
644 .expect("the terrain verb reaches run_terrain");
645 assert!(terrain_out.exists());
646
647 let ply = write_ply(8);
648 let splat_out = dir.path().join("dispatched-tileset");
649 with_tracing(|| {
650 run_command(cli::Command::SplatTiles(Box::new(splat_args(
651 ply.path(),
652 &splat_out,
653 ))))
654 })
655 .expect("the splat verb reaches run_splat_tiles");
656 assert!(splat_out.join("tileset.json").exists());
657
658 let config = make_config("not-a-real-format");
659 let err = with_tracing(|| run_command(cli::Command::Tiles(Box::new(config))))
660 .expect_err("the flat invocation reaches run_with_config, which rejects the format");
661 assert!(format!("{err}").contains("not-a-real-format"), "{err}");
662
663 let raster_args = cli::RasterArgs {
664 url_template: "http://127.0.0.1:1/{z}/{x}/{y}.jpg".into(),
665 output: dir.path().join("dispatched-raster.pmtiles"),
666 min_zoom: 0,
667 max_zoom: 0,
668 bbox: None,
669 bbox_min_zoom: 0,
670 format: "jpeg".into(),
671 concurrency: 1,
672 request_delay_ms: 0,
673 attempts: 1,
674 cache_dir: Some(dir.path().join("raster-cache")),
675 name: "dispatch-test".into(),
676 attribution: None,
677 };
678 let err = with_tracing(|| run_command(cli::Command::Raster(Box::new(raster_args))))
679 .expect_err("port 1 refuses connections, proving dispatch reached run_raster");
680 assert!(format!("{err}").contains("raster source error"));
681 }
682}