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