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