#![warn(missing_docs)]
pub mod cli;
mod cli_error;
pub mod config;
pub use cli_error::CliError;
pub use geolith::error;
pub use geolith::output;
pub use geolith::{conflation, progress, source};
pub use geolith_dataset_builder as dataset;
pub use geolith_search_builder as geocoding;
pub use geolith_tiles_builder::{
geometry, layers, raster, reconstruct, sort, splat, terrain, tile, timing,
};
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PipelineAction {
Geocoding,
Routing(std::path::PathBuf),
Tiles,
UnsupportedFormat(String),
}
#[must_use]
pub fn select_action(config: &config::Config) -> PipelineAction {
match config.output_format.as_str() {
"geocoding" => PipelineAction::Geocoding,
"routing" => {
let out = config
.routing_output
.clone()
.unwrap_or_else(|| std::path::PathBuf::from("planet-routing.glx"));
PipelineAction::Routing(out)
}
"tiles" => PipelineAction::Tiles,
other => PipelineAction::UnsupportedFormat(other.to_owned()),
}
}
fn init_tracing() {
timing::init();
tracing_subscriber::fmt()
.with_timer(timing::ElapsedTimer)
.with_env_filter(
tracing_subscriber::EnvFilter::try_from_default_env()
.unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("info")),
)
.with_writer(std::io::stderr)
.init();
}
pub fn run() -> Result<(), CliError> {
let command = cli::parse_args();
init_tracing();
run_command(command)
}
pub fn run_command(command: cli::Command) -> Result<(), CliError> {
tracing::info!("geolith v{}", env!("CARGO_PKG_VERSION"));
match command {
cli::Command::Terrain(args) => run_terrain(&args),
cli::Command::SplatTiles(args) => run_splat_tiles(&args),
cli::Command::Raster(args) => run_raster(&args),
cli::Command::Reconstruct(args) => run_reconstruct(&args),
cli::Command::Dataset(args) => dataset::run(&args).map_err(CliError::from),
cli::Command::Notices => {
print!("{}", cli::NOTICE);
Ok(())
}
cli::Command::Tiles(config) => {
tracing::info!("config: {:?}", config);
run_with_config(&config)
}
}
}
#[must_use]
pub fn exit_code(error: &CliError) -> i32 {
match error {
CliError::Dataset(error) => error.exit_code(),
_ => 1,
}
}
pub fn run_raster(args: &cli::RasterArgs) -> Result<(), CliError> {
let options = args.build_options()?;
raster::run(&options, &args.output).map_err(CliError::from)
}
pub fn run_terrain(args: &cli::TerrainArgs) -> Result<(), CliError> {
let options = args.tiler_options()?;
terrain::run(&args.dem, args.dem_crs, &args.output, &args.name, &options)
.map_err(CliError::from)
}
pub fn run_splat_tiles(args: &cli::SplatTilesArgs) -> Result<(), CliError> {
splat::run(&args.job()).map_err(CliError::from)
}
pub fn run_reconstruct(args: &cli::ReconstructArgs) -> Result<(), CliError> {
reconstruct::run_reconstruct(&args.video, &args.output, &args.options()).map_err(CliError::from)
}
pub fn run_with_config(config: &config::Config) -> Result<(), CliError> {
match select_action(config) {
PipelineAction::Geocoding => run_search(config),
PipelineAction::Routing(out) => run_routing(config, &out),
PipelineAction::UnsupportedFormat(format) => Err(CliError::UnsupportedFormat { format }),
PipelineAction::Tiles => {
geolith_tiles_builder::run(&config.tiles()?).map_err(CliError::from)
}
}
}
fn run_search(config: &config::Config) -> Result<(), CliError> {
let data = config.required_path(config::PathFlag::Data)?;
let output = match config.geocoding_output.clone() {
Some(path) => path,
None => geocoding::pipeline::default_geocoding_output(
config.required_path(config::PathFlag::Output)?,
&config.geocoding_format,
),
};
let mut options = geolith_search_builder::SearchOptions::new(data, output);
options.format.clone_from(&config.geocoding_format);
options.osm_pbf.clone_from(&config.osm_pbf);
options.india_outline.clone_from(&config.india_outline);
options.bbox.clone_from(&config.bbox);
options.tmpdir.clone_from(&config.tmpdir);
options.node_store.clone_from(&config.node_store);
options.reuse_node_cache = config.reuse.node_cache;
options
.wikimedia_importance
.clone_from(&config.wikimedia_importance);
options.pg_index_flavor = config.pg_index_flavor;
geolith_search_builder::run(&options).map_err(CliError::from)
}
fn run_routing(config: &config::Config, out: &std::path::Path) -> Result<(), CliError> {
let Some(pbf) = config.osm_pbf.as_deref() else {
return Err(CliError::RoutingNeedsOsmPbf);
};
let mut options = geolith_routing_builder::RoutingOptions::new(pbf, out);
options.tmpdir.clone_from(&config.tmpdir);
options
.default_speeds
.clone_from(&config.routing_default_speeds);
options.admins.clone_from(&config.routing_admins);
options.timezones.clone_from(&config.routing_timezones);
options
.predicted_speeds
.clone_from(&config.routing_predicted_speeds);
options.metric_out.clone_from(&config.routing_metric_out);
options.cch.clone_from(&config.routing_cch);
if let (Some(_), Some(path)) = (
config.routing_admins.as_deref(),
config.india_outline.as_deref(),
) {
options.india = Some(
geocoding::india::IndiaOutline::load(path)?
.polygons()
.clone(),
);
}
geolith_routing_builder::run(&options).map_err(CliError::from)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::config::Config;
fn make_config(output_format: &str) -> Config {
Config {
data: Some(std::path::PathBuf::from("/dev/null")),
osm_pbf: None,
natural_earth: Some(std::path::PathBuf::from("/dev/null")),
water_polygons: Some(std::path::PathBuf::from("/dev/null")),
land_polygons: Some(std::path::PathBuf::from("/dev/null")),
india_boundary: None,
india_outline: None,
output: Some(std::path::PathBuf::from("/dev/null")),
output_format: output_format.to_string(),
tile_format: "mvt".to_string(),
geocoding_format: "pg-copy".to_string(),
pg_index_flavor: crate::config::PgIndexFlavor::default(),
geocoding_output: None,
wikimedia_importance: None,
routing_output: None,
routing_predicted_speeds: None,
routing_metric_out: None,
routing_cch: Vec::new(),
routing_default_speeds: None,
routing_admins: None,
routing_timezones: None,
bbox: None,
max_zoom: 15,
threads: None,
chunk_size_mb: 0,
tmpdir: None,
node_store: None,
reuse: crate::config::RunReuse {
node_cache: false,
resume: false,
},
buildings_source: "both".to_string(),
places_source: "both".to_string(),
roads_source: "both".to_string(),
pois_source: "both".to_string(),
water_source: "both".to_string(),
landuse_source: "both".to_string(),
divisions_source: "overture".to_string(),
landcover_source: "overture".to_string(),
bathymetry_source: "overture".to_string(),
bridge_dir: None,
bridge_files: vec![],
no_conflate: false,
reclaim_source_after_read: false,
}
}
#[test]
fn select_action_geocoding() {
let cfg = make_config("geocoding");
assert_eq!(select_action(&cfg), PipelineAction::Geocoding);
}
#[test]
fn select_action_routing_default_path() {
let cfg = make_config("routing");
assert_eq!(
select_action(&cfg),
PipelineAction::Routing(std::path::PathBuf::from("planet-routing.glx"))
);
}
#[test]
fn select_action_routing_explicit_path() {
let mut cfg = make_config("routing");
cfg.routing_output = Some(std::path::PathBuf::from("/tmp/custom.glx"));
assert_eq!(
select_action(&cfg),
PipelineAction::Routing(std::path::PathBuf::from("/tmp/custom.glx"))
);
}
#[test]
fn select_action_tiles() {
let cfg = make_config("tiles");
assert_eq!(select_action(&cfg), PipelineAction::Tiles);
}
#[test]
fn select_action_unsupported_format() {
let cfg = make_config("osrm");
assert_eq!(
select_action(&cfg),
PipelineAction::UnsupportedFormat("osrm".to_string())
);
}
#[test]
fn run_with_config_rejects_an_unsupported_format() {
let cfg = make_config("unknown");
let err = run_with_config(&cfg).expect_err("a typo must not exit 0");
assert!(format!("{err}").contains("'unknown'"), "{err}");
}
#[test]
fn run_with_config_routing_needs_an_osm_pbf() {
let mut cfg = make_config("routing");
cfg.routing_output = Some(std::path::PathBuf::from("/tmp/graph.glx"));
let err = run_with_config(&cfg).expect_err("no graph without a PBF");
assert!(format!("{err}").contains("--osm-pbf"), "{err}");
}
#[test]
fn run_with_config_tiles_surfaces_an_unreadable_data_dir() {
let cfg = make_config("tiles");
let err = run_with_config(&cfg).expect_err("/dev/null is not a source directory");
assert!(
!format!("{err}").is_empty(),
"the failure is reported rather than panicking"
);
}
fn with_tracing<T>(body: impl FnOnce() -> T) -> T {
let subscriber = tracing_subscriber::fmt()
.with_test_writer()
.with_max_level(tracing::Level::TRACE)
.finish();
tracing::subscriber::with_default(subscriber, body)
}
fn write_dem(values: Vec<f32>, nodata: Option<&str>) -> tempfile::NamedTempFile {
use std::io::{Seek as _, Write as _};
use tiff::encoder::{TiffEncoder, colortype};
use tiff::tags::Tag;
let mut buffer = std::io::Cursor::new(Vec::new());
{
let mut encoder = TiffEncoder::new(&mut buffer).expect("tiff encoder");
let mut image = encoder
.new_image::<colortype::Gray32Float>(4, 4)
.expect("image encoder");
let directory = image.encoder();
directory
.write_tag(Tag::Unknown(33_550), &[10.0_f64, 10.0, 0.0][..])
.expect("pixel scale");
directory
.write_tag(
Tag::Unknown(33_922),
&[0.0_f64, 0.0, 0.0, 400_000.0, 5_100_000.0, 0.0][..],
)
.expect("tiepoint");
directory
.write_tag(
Tag::Unknown(34_735),
&[1_u32, 1, 0, 1, 3072, 0, 1, 32_632][..],
)
.expect("geokeys");
if let Some(sentinel) = nodata {
directory
.write_tag(Tag::Unknown(42_113), sentinel)
.expect("nodata");
}
image.write_data(&values).expect("write samples");
}
buffer.rewind().expect("rewind");
let mut file = tempfile::Builder::new()
.suffix(".tif")
.tempfile()
.expect("temp file");
file.write_all(&buffer.into_inner()).expect("write tiff");
file.flush().expect("flush");
file
}
fn write_ply(vertex_count: usize) -> tempfile::NamedTempFile {
use std::io::Write as _;
const PROPERTIES: [&str; 14] = [
"x", "y", "z", "f_dc_0", "f_dc_1", "f_dc_2", "opacity", "scale_0", "scale_1",
"scale_2", "rot_0", "rot_1", "rot_2", "rot_3",
];
let mut file = tempfile::NamedTempFile::new().expect("temp file");
let mut header = String::from("ply\nformat binary_little_endian 1.0\n");
header.push_str(&format!("element vertex {vertex_count}\n"));
for property in PROPERTIES {
header.push_str(&format!("property float {property}\n"));
}
header.push_str("end_header\n");
file.write_all(header.as_bytes()).expect("header");
for index in 0..vertex_count {
let offset = index as f32;
for value in [
offset,
offset * 0.5,
offset * 0.25,
0.4,
0.5,
0.6,
1.1,
-2.0,
-2.1,
-2.2,
1.0,
0.0,
0.0,
0.0,
] {
file.write_all(&value.to_le_bytes()).expect("vertex");
}
}
file.flush().expect("flush");
file
}
fn terrain_args(dem: &std::path::Path, output: &std::path::Path) -> cli::TerrainArgs {
cli::TerrainArgs {
dem: vec![dem.to_path_buf()],
clip: None,
output: output.to_path_buf(),
encoding: "mapbox".to_owned(),
min_zoom: 12,
max_zoom: 13,
tile_size: 256,
dem_crs: None,
name: "terrain".to_owned(),
}
}
fn splat_args(ply: &std::path::Path, output: &std::path::Path) -> cli::SplatTilesArgs {
cli::SplatTilesArgs {
ply: ply.to_path_buf(),
output: output.to_path_buf(),
longitude: 7.9797,
latitude: 45.9756,
altitude: 2250.0,
max_splats_per_tile: 4,
max_depth: 2,
root_geometric_error: 64.0,
antialiased: false,
emit_scene_spz: true,
crop_percentile: 0.0,
scale: 1.0,
coverage_boost_scale: 0.0,
}
}
#[test]
fn run_terrain_writes_an_archive() {
let values: Vec<f32> = (0..16).map(|i| 1000.0 + i as f32).collect();
let dem = write_dem(values, None);
let dir = tempfile::tempdir().expect("tempdir");
let output = dir.path().join("terrain.pmtiles");
with_tracing(|| run_terrain(&terrain_args(dem.path(), &output)))
.expect("terrain pipeline runs");
let bytes = std::fs::read(&output).expect("archive exists");
assert_eq!(&bytes[..7], b"PMTiles");
}
#[test]
fn run_terrain_writes_an_archive_for_valid_and_all_nodata_dems() {
let dir = tempfile::tempdir().expect("tempdir");
let values: Vec<f32> = (0..16).map(|i| 1000.0 + i as f32).collect();
let dem = write_dem(values, None);
let with_samples = dir.path().join("a.pmtiles");
with_tracing(|| run_terrain(&terrain_args(dem.path(), &with_samples)))
.expect("a DEM with valid samples must tile");
let dem = write_dem(vec![-9999.0; 16], Some("-9999"));
let all_nodata = dir.path().join("b.pmtiles");
with_tracing(|| run_terrain(&terrain_args(dem.path(), &all_nodata)))
.expect("an all-nodata DEM must still tile");
for path in [&with_samples, &all_nodata] {
let bytes = std::fs::read(path).expect("archive must exist on disk");
assert_eq!(
&bytes[..7],
b"PMTiles",
"{path:?} must be a PMTiles archive"
);
}
}
#[test]
fn run_terrain_propagates_failures() {
let dir = tempfile::tempdir().expect("tempdir");
let mut args = terrain_args(
std::path::Path::new("/nonexistent/dem.tif"),
&dir.path().join("out.pmtiles"),
);
args.encoding = "rainbow".to_owned();
assert!(
with_tracing(|| run_terrain(&args)).is_err(),
"the encoding is validated before the DEM is opened"
);
args.encoding = "mapbox".to_owned();
args.dem_crs = Some(27_700);
assert!(
with_tracing(|| run_terrain(&args)).is_err(),
"an unsupported EPSG fails before the DEM is read"
);
args.dem_crs = None;
assert!(
with_tracing(|| run_terrain(&args)).is_err(),
"a missing DEM surfaces as an error"
);
}
#[test]
fn run_splat_tiles_writes_a_tileset_and_scene() {
let ply = write_ply(32);
let dir = tempfile::tempdir().expect("tempdir");
let output = dir.path().join("tileset");
with_tracing(|| run_splat_tiles(&splat_args(ply.path(), &output)))
.expect("splat pipeline runs");
assert!(output.join("tileset.json").is_file());
assert!(output.join("tiles/0.glb").is_file());
assert!(
output.join("scene.spz").is_file(),
"--emit-scene-spz writes the standalone packet"
);
}
#[test]
fn run_splat_tiles_skips_the_scene_when_not_requested() {
let ply = write_ply(8);
let dir = tempfile::tempdir().expect("tempdir");
let output = dir.path().join("tileset");
let mut args = splat_args(ply.path(), &output);
args.emit_scene_spz = false;
with_tracing(|| run_splat_tiles(&args)).expect("splat pipeline runs");
assert!(output.join("tileset.json").is_file());
assert!(!output.join("scene.spz").exists());
}
#[test]
fn run_splat_tiles_propagates_failures() {
let dir = tempfile::tempdir().expect("tempdir");
assert!(
with_tracing(|| run_splat_tiles(&splat_args(
std::path::Path::new("/nonexistent/scene.ply"),
&dir.path().join("tileset"),
)))
.is_err(),
"a missing PLY surfaces as an error"
);
let empty = write_ply(0);
let err =
with_tracing(|| run_splat_tiles(&splat_args(empty.path(), &dir.path().join("empty"))))
.expect_err("an empty cloud cannot be tiled");
assert!(format!("{err}").contains("empty splat cloud"), "{err}");
}
#[test]
fn run_command_dispatches_every_verb() {
let dir = tempfile::tempdir().expect("tempdir");
let values: Vec<f32> = (0..16).map(|i| 1000.0 + i as f32).collect();
let dem = write_dem(values, None);
let terrain_out = dir.path().join("dispatched.pmtiles");
with_tracing(|| {
run_command(cli::Command::Terrain(Box::new(terrain_args(
dem.path(),
&terrain_out,
))))
})
.expect("the terrain verb reaches run_terrain");
assert!(terrain_out.exists());
let ply = write_ply(8);
let splat_out = dir.path().join("dispatched-tileset");
with_tracing(|| {
run_command(cli::Command::SplatTiles(Box::new(splat_args(
ply.path(),
&splat_out,
))))
})
.expect("the splat verb reaches run_splat_tiles");
assert!(splat_out.join("tileset.json").exists());
let config = make_config("not-a-real-format");
let err = with_tracing(|| run_command(cli::Command::Tiles(Box::new(config))))
.expect_err("the flat invocation reaches run_with_config, which rejects the format");
assert!(format!("{err}").contains("not-a-real-format"), "{err}");
let raster_args = cli::RasterArgs {
url_template: "http://127.0.0.1:1/{z}/{x}/{y}.jpg".into(),
output: dir.path().join("dispatched-raster.pmtiles"),
min_zoom: 0,
max_zoom: 0,
bbox: None,
bbox_min_zoom: 0,
format: "jpeg".into(),
concurrency: 1,
request_delay_ms: 0,
attempts: 1,
cache_dir: Some(dir.path().join("raster-cache")),
name: "dispatch-test".into(),
attribution: None,
};
let err = with_tracing(|| run_command(cli::Command::Raster(Box::new(raster_args))))
.expect_err("port 1 refuses connections, proving dispatch reached run_raster");
assert!(format!("{err}").contains("raster source error"));
}
}