Skip to main content

geolith_cli/
cli.rs

1//! Top-level command dispatch.
2//!
3//! The tile pipeline predates subcommands and is invoked as bare flags
4//! (`geolith --data … --output …`). Introducing `terrain` and `splat-tiles`
5//! as clap subcommands on the same parser would make those flags ambiguous,
6//! so dispatch keys off the first argument: a recognised verb selects a
7//! subcommand, anything else parses as the original flat tile config.
8
9// The clap help text is golden-tested and names placeholders such as <output>.
10#![allow(rustdoc::invalid_html_tags)]
11
12use std::path::PathBuf;
13
14use clap::Parser;
15
16use crate::config::Config;
17use crate::terrain::TerrainEncoding;
18
19/// Subcommand verb for the terrain pipeline.
20const VERB_TERRAIN: &str = "terrain";
21
22/// Subcommand verb for the Gaussian splat pipeline.
23const VERB_SPLAT_TILES: &str = "splat-tiles";
24
25/// Subcommand verb for the raster basemap archiver.
26const VERB_RASTER: &str = "raster";
27
28/// Subcommand verb for the drone-video photogrammetry pipeline.
29const VERB_RECONSTRUCT: &str = "reconstruct";
30
31/// Subcommand verb for the raster dataset builder.
32const VERB_DATASET: &str = "dataset";
33const VERB_NOTICES: &str = "notices";
34
35/// The notices of the code and data geolith builds on, printed by
36/// `geolith notices`.
37pub const NOTICE: &str = include_str!("../NOTICE.md");
38
39/// What `geolith --version` prints after the version number.
40pub const LONG_VERSION: &str = concat!(
41    env!("CARGO_PKG_VERSION"),
42    "\n© geolith. Source-available under the FSL-1.1-ALv2 (LICENSE.md).\n",
43    "Outputs carry the credit \"© geolith\" after the attribution of their data.\n",
44    "Run `geolith notices` for the notices of third-party code and data."
45);
46
47/// Build Terrain-RGB `raster-dem` `PMTiles` from a `GeoTIFF` DEM.
48#[derive(Debug, Parser)]
49#[command(
50    name = "geolith terrain",
51    about = "GeoTIFF DEM → Terrain-RGB PMTiles",
52    version
53)]
54pub struct TerrainArgs {
55    /// Input `GeoTIFF` DEM, or a directory whose `.tif`/`.tiff` files form one
56    /// mosaic (files may use different CRSs; on overlap the first by path
57    /// wins). Repeat to add fallbacks: a later `--dem` only fills pixels the
58    /// earlier ones leave as nodata. Files are read window by window, so any
59    /// size fits in memory.
60    #[arg(long, required = true)]
61    pub dem: Vec<PathBuf>,
62
63    /// `GeoJSON` Polygon or `MultiPolygon`: pixels outside it become nodata and
64    /// tiles that miss it are not written.
65    #[arg(long)]
66    pub clip: Option<PathBuf>,
67
68    /// Output `PMTiles` archive path.
69    #[arg(long, short)]
70    pub output: PathBuf,
71
72    /// Elevation encoding: "mapbox" (default) or "terrarium".
73    #[arg(long, default_value = "mapbox")]
74    pub encoding: String,
75
76    /// Minimum zoom level.
77    #[arg(long, default_value = "0")]
78    pub min_zoom: u8,
79
80    /// Maximum zoom level.
81    #[arg(long, default_value = "14")]
82    pub max_zoom: u8,
83
84    /// Tile edge length in pixels.
85    #[arg(long, default_value = "512")]
86    pub tile_size: u32,
87
88    /// Override the DEM's EPSG code when the `GeoTIFF` lacks geokeys.
89    #[arg(long)]
90    pub dem_crs: Option<u32>,
91
92    /// Layer name recorded in the archive metadata.
93    #[arg(long, default_value = "terrain")]
94    pub name: String,
95}
96
97/// Build an OGC 3D Tiles tileset from a trained Gaussian splat PLY.
98#[derive(Debug, Parser)]
99#[command(
100    name = "geolith splat-tiles",
101    about = "3DGS PLY → OGC 3D Tiles (KHR_gaussian_splatting + spz_2)",
102    version
103)]
104pub struct SplatTilesArgs {
105    /// Path to the trained 3D Gaussian Splatting PLY.
106    #[arg(long)]
107    pub ply: PathBuf,
108
109    /// Output directory for `tileset.json` and `tiles/*.glb`.
110    #[arg(long, short)]
111    pub output: PathBuf,
112
113    /// Longitude of the scene anchor in degrees.
114    #[arg(long, allow_hyphen_values = true)]
115    pub longitude: f64,
116
117    /// Latitude of the scene anchor in degrees.
118    #[arg(long, allow_hyphen_values = true)]
119    pub latitude: f64,
120
121    /// Height of the scene anchor above the ellipsoid in metres.
122    #[arg(long, default_value = "0", allow_hyphen_values = true)]
123    pub altitude: f64,
124
125    /// Maximum splats stored in a single tile.
126    #[arg(long, default_value = "100000")]
127    pub max_splats_per_tile: usize,
128
129    /// Maximum octree depth.
130    #[arg(long, default_value = "6")]
131    pub max_depth: u8,
132
133    /// Geometric error assigned to the root tile.
134    #[arg(long, default_value = "64")]
135    pub root_geometric_error: f64,
136
137    /// Mark the splats as trained with antialiasing.
138    #[arg(long, default_value = "false")]
139    pub antialiased: bool,
140
141    /// Also write a standalone `scene.spz` for single-file splat rendering.
142    #[arg(long, default_value = "true")]
143    pub emit_scene_spz: bool,
144
145    /// Trim this percentage from both ends of every axis before tiling,
146    /// removing the hallucinated far-field shell of inward-facing captures.
147    #[arg(long, default_value = "0")]
148    pub crop_percentile: f64,
149
150    /// Uniform scale factor applied to the scene (e.g. 0.1 when the trainer
151    /// produced a 10x oversized world).
152    #[arg(long, default_value = "1")]
153    pub scale: f32,
154
155    /// Coverage boost applied before encoding, matching the gsplat post-process:
156    /// `opacity_logit += ln(scale)` and `log_scale -= 0.5 * ln(scale)`. Use when
157    /// the trainer ran without a coverage boost and the splats render dim and
158    /// oversized (e.g. 5–10 for drone captures). `0` disables the boost.
159    #[arg(long, default_value = "0")]
160    pub coverage_boost_scale: f32,
161}
162
163/// Archive raster tiles from an XYZ/WMTS endpoint into `PMTiles`.
164#[derive(Debug, Parser)]
165#[command(
166    name = "geolith raster",
167    about = "XYZ/WMTS raster tiles -> PMTiles basemap archive",
168    version
169)]
170pub struct RasterArgs {
171    /// Tile URL template containing {z}, {x}, and {y} placeholders.
172    #[arg(long)]
173    pub url_template: String,
174
175    /// Output `PMTiles` archive path.
176    #[arg(long, short)]
177    pub output: PathBuf,
178
179    /// Minimum zoom level.
180    #[arg(long, default_value = "0")]
181    pub min_zoom: u8,
182
183    /// Maximum zoom level.
184    #[arg(long, default_value = "8")]
185    pub max_zoom: u8,
186
187    /// Restrict coverage to `min_lon,min_lat,max_lon,max_lat`.
188    #[arg(long)]
189    pub bbox: Option<String>,
190
191    /// First zoom at which --bbox applies; below it the whole planet is
192    /// fetched, producing a hybrid planet + deep-zoom-region archive.
193    #[arg(long, default_value = "0")]
194    pub bbox_min_zoom: u8,
195
196    /// Payload format recorded in the archive: "jpeg", "png", or "webp".
197    #[arg(long, default_value = "jpeg")]
198    pub format: String,
199
200    /// Concurrent download workers.
201    #[arg(long, default_value = "8")]
202    pub concurrency: usize,
203
204    /// Delay in milliseconds after each request on every worker.
205    #[arg(long, default_value = "50")]
206    pub request_delay_ms: u64,
207
208    /// Download attempts per tile before the build fails.
209    #[arg(long, default_value = "5")]
210    pub attempts: u32,
211
212    /// Resumable tile cache directory (default: <system temp>/geolith-raster).
213    #[arg(long)]
214    pub cache_dir: Option<PathBuf>,
215
216    /// Layer name recorded in the archive metadata.
217    #[arg(long, default_value = "raster")]
218    pub name: String,
219
220    /// Attribution recorded in the archive metadata.
221    #[arg(long)]
222    pub attribution: Option<String>,
223}
224
225/// Drone video → OGC 3D Tiles via ffmpeg → COLMAP → brush → splat-tiles.
226#[derive(Debug, Parser)]
227#[command(
228    name = "geolith reconstruct",
229    about = "drone video → 3D Tiles (ffmpeg → COLMAP → brush → splat-tiles)",
230    version
231)]
232pub struct ReconstructArgs {
233    /// Path to the drone video (mp4/mov/webm).
234    #[arg(long)]
235    pub video: PathBuf,
236
237    /// Working directory; stage outputs land in `frames/`, `sparse/`,
238    /// `exports/`, and `tiles/` beneath it. Re-running reuses completed
239    /// stages (resume semantics).
240    #[arg(long, short)]
241    pub output: PathBuf,
242
243    /// Frame extraction rate in frames per second.
244    #[arg(long, default_value = "2.0")]
245    pub fps: f64,
246
247    /// Cap the number of extracted frames (optional).
248    #[arg(long)]
249    pub max_frames: Option<usize>,
250
251    /// COLMAP binary path (default: `colmap` on `$PATH`).
252    #[arg(long, default_value = "colmap")]
253    pub colmap_bin: String,
254
255    /// Brush CLI binary path (default: `brush-cli` on `$PATH`).
256    #[arg(long, default_value = "brush-cli")]
257    pub brush_bin: String,
258
259    /// Total brush training iterations.
260    #[arg(long, default_value = "30000")]
261    pub train_iters: u32,
262
263    /// Longitude of the scene anchor in degrees (default 0).
264    #[arg(long, default_value = "0", allow_hyphen_values = true)]
265    pub longitude: f64,
266
267    /// Latitude of the scene anchor in degrees (default 0).
268    #[arg(long, default_value = "0", allow_hyphen_values = true)]
269    pub latitude: f64,
270
271    /// Height of the scene anchor above the ellipsoid in metres.
272    #[arg(long, default_value = "0", allow_hyphen_values = true)]
273    pub altitude: f64,
274
275    /// Trim this percentage from both ends of every axis before tiling.
276    #[arg(long, default_value = "0")]
277    pub crop_percentile: f64,
278
279    /// Trim this percentage from the far end of the radial distance
280    /// distribution before tiling (removes the far-field halo).
281    #[arg(long, default_value = "0")]
282    pub crop_radial_percentile: f64,
283
284    /// Uniform scale factor applied to the scene.
285    #[arg(long, default_value = "1")]
286    pub scale: f32,
287
288    /// Coverage boost applied before encoding (0 disables it).
289    #[arg(long, default_value = "0")]
290    pub coverage_boost_scale: f32,
291
292    /// Maximum splats stored in a single tile.
293    #[arg(long, default_value = "100000")]
294    pub max_splats_per_tile: usize,
295
296    /// Maximum octree depth.
297    #[arg(long, default_value = "6")]
298    pub max_depth: u8,
299
300    /// Geometric error assigned to the root tile.
301    #[arg(long, default_value = "64")]
302    pub root_geometric_error: f64,
303
304    /// Also write a standalone `scene.spz` alongside the tileset.
305    #[arg(long, default_value = "true")]
306    pub emit_scene_spz: bool,
307}
308
309impl ReconstructArgs {
310    /// Resolve the pipeline options this invocation selects.
311    #[must_use]
312    pub fn options(&self) -> crate::reconstruct::ReconstructOptions {
313        crate::reconstruct::ReconstructOptions {
314            fps: self.fps,
315            max_frames: self.max_frames,
316            colmap_bin: self.colmap_bin.clone(),
317            brush_bin: self.brush_bin.clone(),
318            train_iters: self.train_iters,
319            longitude: self.longitude,
320            latitude: self.latitude,
321            altitude: self.altitude,
322            crop_percentile: self.crop_percentile,
323            crop_radial_percentile: self.crop_radial_percentile,
324            scale: self.scale,
325            coverage_boost_scale: self.coverage_boost_scale,
326            max_splats_per_tile: self.max_splats_per_tile,
327            max_depth: self.max_depth,
328            root_geometric_error: self.root_geometric_error,
329            emit_scene_spz: self.emit_scene_spz,
330        }
331    }
332}
333
334/// The dataset command tree; the module owns its own args.
335pub use crate::dataset::cli::{
336    AreasArgs, AreasDownloadArgs, BuildArgs, CheckDownloadArgs, DatasetAction, DatasetArgs,
337    DownloadsAction, DownloadsArgs, InspectArgs, KeysArgs, NormalsArgs, NumbersDownloadArgs,
338    StageArgs, StatusArgs, ValuesArgs, VerifyArgs,
339};
340
341/// Print the notices of the third-party code and data geolith builds on.
342#[derive(Debug, Parser)]
343#[command(
344    name = "geolith notices",
345    about = "print the notices of third-party code and data",
346    version
347)]
348pub struct NoticesArgs {}
349
350/// A parsed top-level command.
351#[non_exhaustive]
352#[derive(Debug)]
353pub enum Command {
354    /// Run the terrain pipeline.
355    Terrain(Box<TerrainArgs>),
356    /// Run the Gaussian splat pipeline.
357    SplatTiles(Box<SplatTilesArgs>),
358    /// Run the raster basemap archiver.
359    Raster(Box<RasterArgs>),
360    /// Run the drone-video photogrammetry pipeline.
361    Reconstruct(Box<ReconstructArgs>),
362    /// Run the raster dataset builder.
363    Dataset(Box<DatasetArgs>),
364    /// Print the notices of third-party code and data.
365    Notices,
366    /// Run the tile pipeline with the original flat flags.
367    Tiles(Box<Config>),
368}
369
370/// Whether `argument` names a subcommand rather than a flag.
371#[must_use]
372pub fn is_subcommand(argument: &str) -> bool {
373    matches!(
374        argument,
375        VERB_TERRAIN
376            | VERB_SPLAT_TILES
377            | VERB_RASTER
378            | VERB_RECONSTRUCT
379            | VERB_DATASET
380            | VERB_NOTICES
381    )
382}
383
384/// Parse a full argv into a [`Command`].
385///
386/// # Errors
387///
388/// Returns the clap error for the selected parser, so `--help` and
389/// `--version` still render correctly for each subcommand.
390pub fn parse_from<I, T>(args: I) -> Result<Command, clap::Error>
391where
392    I: IntoIterator<Item = T>,
393    T: Into<std::ffi::OsString> + Clone,
394{
395    let argv: Vec<std::ffi::OsString> = args.into_iter().map(Into::into).collect();
396    let verb = argv
397        .get(1)
398        .and_then(|arg| arg.to_str())
399        .filter(|arg| is_subcommand(arg))
400        .map(str::to_owned);
401
402    match verb.as_deref() {
403        Some(VERB_TERRAIN) => {
404            let mut forwarded = vec![std::ffi::OsString::from("geolith terrain")];
405            forwarded.extend(argv.into_iter().skip(2));
406            TerrainArgs::try_parse_from(forwarded).map(|a| Command::Terrain(Box::new(a)))
407        }
408        Some(VERB_SPLAT_TILES) => {
409            let mut forwarded = vec![std::ffi::OsString::from("geolith splat-tiles")];
410            forwarded.extend(argv.into_iter().skip(2));
411            SplatTilesArgs::try_parse_from(forwarded).map(|a| Command::SplatTiles(Box::new(a)))
412        }
413        Some(VERB_RASTER) => {
414            let mut forwarded = vec![std::ffi::OsString::from("geolith raster")];
415            forwarded.extend(argv.into_iter().skip(2));
416            RasterArgs::try_parse_from(forwarded).map(|a| Command::Raster(Box::new(a)))
417        }
418        Some(VERB_RECONSTRUCT) => {
419            let mut forwarded = vec![std::ffi::OsString::from("geolith reconstruct")];
420            forwarded.extend(argv.into_iter().skip(2));
421            ReconstructArgs::try_parse_from(forwarded).map(|a| Command::Reconstruct(Box::new(a)))
422        }
423        Some(VERB_NOTICES) => {
424            let mut forwarded = vec![std::ffi::OsString::from("geolith notices")];
425            forwarded.extend(argv.into_iter().skip(2));
426            NoticesArgs::try_parse_from(forwarded).map(|_| Command::Notices)
427        }
428        Some(VERB_DATASET) => {
429            let mut forwarded = vec![std::ffi::OsString::from("geolith dataset")];
430            forwarded.extend(argv.into_iter().skip(2));
431            DatasetArgs::try_parse_from(forwarded).map(|a| Command::Dataset(Box::new(a)))
432        }
433        _ => Config::try_parse_from(argv)
434            .and_then(|c| c.check_required().map(|()| c))
435            .map(|c| Command::Tiles(Box::new(c))),
436    }
437}
438
439/// Parse the process arguments, exiting with clap's diagnostics on failure.
440#[must_use]
441pub fn parse_args() -> Command {
442    match parse_from(std::env::args_os()) {
443        Ok(command) => command,
444        Err(error) => error.exit(),
445    }
446}
447
448impl TerrainArgs {
449    /// Resolve the tiler options this invocation selects.
450    ///
451    /// # Errors
452    ///
453    /// Returns an error when `--encoding` is not a known encoding name.
454    pub fn tiler_options(&self) -> geolith::error::Result<crate::terrain::TerrainTilerOptions> {
455        let clip = match &self.clip {
456            Some(path) => Some(std::sync::Arc::new(crate::terrain::ClipMask::from_geojson(
457                path,
458            )?)),
459            None => None,
460        };
461        Ok(crate::terrain::TerrainTilerOptions {
462            min_zoom: self.min_zoom,
463            max_zoom: self.max_zoom,
464            tile_size: self.tile_size,
465            encoding: TerrainEncoding::parse(&self.encoding)?,
466            clip,
467        })
468    }
469}
470
471impl RasterArgs {
472    /// Resolve the archive build options this invocation selects.
473    ///
474    /// # Errors
475    ///
476    /// Returns an error when the URL template, bbox, or format is invalid.
477    pub fn build_options(&self) -> geolith::error::Result<crate::raster::RasterBuildOptions> {
478        let template = crate::raster::UrlTemplate::parse(&self.url_template)?;
479        let bbox = match &self.bbox {
480            Some(raw) => {
481                let parsed = crate::source::bbox_filter::Bbox::parse(raw)?;
482                Some((
483                    parsed.min_lon,
484                    parsed.min_lat,
485                    parsed.max_lon,
486                    parsed.max_lat,
487                ))
488            }
489            None => None,
490        };
491        let tile_type = match self.format.as_str() {
492            "jpeg" | "jpg" => geolith::output::writer::TileType::Jpeg,
493            "png" => geolith::output::writer::TileType::Png,
494            "webp" => geolith::output::writer::TileType::Webp,
495            other => {
496                return Err(geolith::error::GeolithError::RasterSource(format!(
497                    "unknown raster format {other:?} — expected jpeg, png, or webp"
498                )));
499            }
500        };
501        Ok(crate::raster::RasterBuildOptions {
502            template,
503            pyramid: crate::raster::PyramidSpec {
504                min_zoom: self.min_zoom,
505                max_zoom: self.max_zoom,
506                bbox,
507                bbox_min_zoom: self.bbox_min_zoom,
508            },
509            tile_type,
510            concurrency: self.concurrency,
511            request_delay: std::time::Duration::from_millis(self.request_delay_ms),
512            attempts: self.attempts,
513            cache_dir: self
514                .cache_dir
515                .clone()
516                .unwrap_or_else(|| std::env::temp_dir().join("geolith-raster")),
517            name: self.name.clone(),
518            attribution: self.attribution.clone(),
519        })
520    }
521}
522
523impl SplatTilesArgs {
524    /// The splat tileset build this invocation selects.
525    #[must_use]
526    pub fn job(&self) -> crate::splat::SplatJob {
527        crate::splat::SplatJob {
528            ply: self.ply.clone(),
529            output: self.output.clone(),
530            crop_percentile: self.crop_percentile,
531            scale: self.scale,
532            coverage_boost_scale: self.coverage_boost_scale,
533            emit_scene_spz: self.emit_scene_spz,
534            options: self.tileset_options(),
535        }
536    }
537
538    /// The tileset options this invocation selects.
539    #[must_use]
540    pub const fn tileset_options(&self) -> crate::splat::SplatTilesetOptions {
541        crate::splat::SplatTilesetOptions {
542            longitude: self.longitude,
543            latitude: self.latitude,
544            altitude: self.altitude,
545            max_splats_per_tile: self.max_splats_per_tile,
546            max_depth: self.max_depth,
547            root_geometric_error: self.root_geometric_error,
548            antialiased: self.antialiased,
549        }
550    }
551}
552
553#[cfg(test)]
554mod tests {
555    use super::*;
556
557    fn tiles_argv() -> Vec<&'static str> {
558        vec![
559            "geolith",
560            "--data",
561            "/tmp/data",
562            "--natural-earth",
563            "/tmp/ne.sqlite",
564            "--water-polygons",
565            "/tmp/water",
566            "--land-polygons",
567            "/tmp/land",
568            "--output",
569            "/tmp/out.pmtiles",
570        ]
571    }
572
573    /// Every `geolith dataset` verb (with its downloads verbs) and its
574    /// long flags, read from the clap definition.
575    fn dataset_verbs() -> Vec<(String, Vec<String>)> {
576        use clap::CommandFactory;
577        fn walk(cmd: &clap::Command, prefix: &str, out: &mut Vec<(String, Vec<String>)>) {
578            for sub in cmd.get_subcommands() {
579                let name = format!("{prefix}{}", sub.get_name());
580                let flags = sub
581                    .get_arguments()
582                    .filter_map(clap::Arg::get_long)
583                    .filter(|l| !matches!(*l, "help" | "version"))
584                    .map(|l| format!("--{l}"))
585                    .collect();
586                out.push((name.clone(), flags));
587                walk(sub, &format!("{name} "), out);
588            }
589        }
590        let mut out = Vec::new();
591        walk(&DatasetArgs::command(), "dataset ", &mut out);
592        out
593    }
594
595    #[test]
596    fn every_dataset_verb_and_flag_is_documented() {
597        let readme = include_str!("../../README.md");
598        let agents = include_str!("../../AGENTS.md");
599        let verbs = dataset_verbs();
600        assert!(
601            verbs.iter().any(|(v, _)| v == "dataset values"),
602            "{verbs:?}"
603        );
604        let mut missing = Vec::new();
605        for (verb, flags) in &verbs {
606            if verb == "dataset downloads" {
607                continue;
608            }
609            let last = verb.rsplit(' ').next().unwrap_or_default();
610            if !readme.contains(&format!("geolith {verb}")) {
611                missing.push(format!("README: geolith {verb}"));
612            }
613            // AGENTS.md lists verbs as `geolith dataset areas|normals|build`.
614            if !agents.contains(&format!("geolith {verb}")) && !agents.contains(&format!("|{last}"))
615            {
616                missing.push(format!("AGENTS.md: {verb}"));
617            }
618            for flag in flags {
619                if !readme.contains(flag.as_str()) {
620                    missing.push(format!("README: {verb} {flag}"));
621                }
622            }
623        }
624        // The flags P2 added, which AGENTS.md must name as well.
625        for flag in ["dataset normals --cache", "dataset values --config"] {
626            if !agents.contains(flag) {
627                missing.push(format!("AGENTS.md: {flag}"));
628            }
629        }
630        assert!(missing.is_empty(), "undocumented: {missing:?}");
631    }
632
633    #[test]
634    fn verbs_are_recognised() {
635        assert!(is_subcommand("terrain"));
636        assert!(is_subcommand("splat-tiles"));
637        assert!(is_subcommand("raster"));
638        assert!(!is_subcommand("--data"));
639        assert!(!is_subcommand("tiles"));
640    }
641
642    #[test]
643    fn flat_invocation_still_reaches_the_tile_pipeline() {
644        let command = parse_from(tiles_argv()).expect("flat flags parse");
645        match command {
646            Command::Tiles(config) => {
647                assert_eq!(config.output_format, "tiles");
648                assert_eq!(config.data, Some(PathBuf::from("/tmp/data")));
649            }
650            other => panic!("expected the tile pipeline, got {other:?}"),
651        }
652    }
653
654    #[test]
655    fn terrain_subcommand_parses_required_flags() {
656        let command = parse_from([
657            "geolith",
658            "terrain",
659            "--dem",
660            "/tmp/dsm.tif",
661            "--output",
662            "/tmp/terrain.pmtiles",
663        ])
664        .expect("terrain parses");
665
666        match command {
667            Command::Terrain(args) => {
668                assert_eq!(args.dem, [PathBuf::from("/tmp/dsm.tif")]);
669                assert_eq!(args.output, PathBuf::from("/tmp/terrain.pmtiles"));
670                assert_eq!(args.encoding, "mapbox");
671                assert_eq!(args.min_zoom, 0);
672                assert_eq!(args.max_zoom, 14);
673                assert_eq!(args.tile_size, 512);
674                assert_eq!(args.name, "terrain");
675                assert!(args.dem_crs.is_none());
676            }
677            other => panic!("expected terrain, got {other:?}"),
678        }
679    }
680
681    #[test]
682    fn terrain_subcommand_accepts_overrides() {
683        let command = parse_from([
684            "geolith",
685            "terrain",
686            "--dem",
687            "/tmp/dsm.tif",
688            "--output",
689            "/tmp/t.pmtiles",
690            "--encoding",
691            "terrarium",
692            "--min-zoom",
693            "8",
694            "--max-zoom",
695            "16",
696            "--tile-size",
697            "256",
698            "--dem-crs",
699            "32632",
700            "--name",
701            "belvedere",
702        ])
703        .expect("terrain parses");
704
705        match command {
706            Command::Terrain(args) => {
707                assert_eq!(args.encoding, "terrarium");
708                assert_eq!(args.min_zoom, 8);
709                assert_eq!(args.max_zoom, 16);
710                assert_eq!(args.tile_size, 256);
711                assert_eq!(args.dem_crs, Some(32_632));
712                assert_eq!(args.name, "belvedere");
713
714                let options = args.tiler_options().expect("known encoding");
715                assert_eq!(options.encoding, TerrainEncoding::Terrarium);
716                assert_eq!(options.tile_size, 256);
717            }
718            other => panic!("expected terrain, got {other:?}"),
719        }
720    }
721
722    #[test]
723    fn terrain_rejects_unknown_encoding_when_resolving_options() {
724        let command = parse_from([
725            "geolith",
726            "terrain",
727            "--dem",
728            "/tmp/dsm.tif",
729            "--output",
730            "/tmp/t.pmtiles",
731            "--encoding",
732            "rainbow",
733        ])
734        .expect("flag parses; validation happens on resolve");
735
736        match command {
737            Command::Terrain(args) => assert!(args.tiler_options().is_err()),
738            other => panic!("expected terrain, got {other:?}"),
739        }
740    }
741
742    #[test]
743    fn terrain_requires_dem_and_output() {
744        assert!(parse_from(["geolith", "terrain"]).is_err());
745        assert!(parse_from(["geolith", "terrain", "--dem", "/tmp/d.tif"]).is_err());
746    }
747
748    #[test]
749    fn splat_subcommand_parses_required_flags() {
750        let command = parse_from([
751            "geolith",
752            "splat-tiles",
753            "--ply",
754            "/tmp/scene.ply",
755            "--output",
756            "/tmp/tileset",
757            "--longitude",
758            "7.9797",
759            "--latitude",
760            "45.9756",
761        ])
762        .expect("splat-tiles parses");
763
764        match command {
765            Command::SplatTiles(args) => {
766                assert_eq!(args.ply, PathBuf::from("/tmp/scene.ply"));
767                assert!((args.longitude - 7.9797).abs() < 1e-9);
768                assert!((args.latitude - 45.9756).abs() < 1e-9);
769                assert!((args.altitude - 0.0).abs() < 1e-9);
770                assert_eq!(args.max_splats_per_tile, 100_000);
771                assert_eq!(args.max_depth, 6);
772                assert!(args.emit_scene_spz);
773                assert!(!args.antialiased);
774            }
775            other => panic!("expected splat-tiles, got {other:?}"),
776        }
777    }
778
779    #[test]
780    fn splat_subcommand_accepts_negative_coordinates() {
781        let command = parse_from([
782            "geolith",
783            "splat-tiles",
784            "--ply",
785            "/tmp/scene.ply",
786            "--output",
787            "/tmp/tileset",
788            "--longitude",
789            "-122.4194",
790            "--latitude",
791            "-37.7749",
792            "--altitude",
793            "-50",
794        ])
795        .expect("negative coordinates parse");
796
797        match command {
798            Command::SplatTiles(args) => {
799                assert!(args.longitude < 0.0, "southern/western anchors are valid");
800                assert!(args.latitude < 0.0);
801                assert!(args.altitude < 0.0);
802            }
803            other => panic!("expected splat-tiles, got {other:?}"),
804        }
805    }
806
807    #[test]
808    fn splat_options_carry_through_to_the_tileset_builder() {
809        let command = parse_from([
810            "geolith",
811            "splat-tiles",
812            "--ply",
813            "/tmp/scene.ply",
814            "--output",
815            "/tmp/tileset",
816            "--longitude",
817            "7.9797",
818            "--latitude",
819            "45.9756",
820            "--altitude",
821            "2250",
822            "--max-splats-per-tile",
823            "50000",
824            "--max-depth",
825            "4",
826            "--root-geometric-error",
827            "128",
828            "--antialiased",
829        ])
830        .expect("splat-tiles parses");
831
832        match command {
833            Command::SplatTiles(args) => {
834                let options = args.tileset_options();
835                assert!((options.altitude - 2250.0).abs() < 1e-9);
836                assert_eq!(options.max_splats_per_tile, 50_000);
837                assert_eq!(options.max_depth, 4);
838                assert!((options.root_geometric_error - 128.0).abs() < 1e-9);
839                assert!(options.antialiased);
840            }
841            other => panic!("expected splat-tiles, got {other:?}"),
842        }
843    }
844
845    #[test]
846    fn splat_requires_an_anchor() {
847        assert!(
848            parse_from([
849                "geolith",
850                "splat-tiles",
851                "--ply",
852                "/tmp/s.ply",
853                "--output",
854                "/tmp/out",
855            ])
856            .is_err(),
857            "a tileset without a geographic anchor cannot be placed on the globe"
858        );
859    }
860
861    #[test]
862    fn raster_subcommand_parses_required_flags() {
863        let command = parse_from([
864            "geolith",
865            "raster",
866            "--url-template",
867            "https://t.example/{z}/{x}/{y}.jpg",
868            "--output",
869            "/tmp/planet.pmtiles",
870        ])
871        .expect("raster parses");
872
873        match command {
874            Command::Raster(args) => {
875                assert_eq!(args.output, PathBuf::from("/tmp/planet.pmtiles"));
876                assert_eq!(args.min_zoom, 0);
877                assert_eq!(args.max_zoom, 8);
878                assert_eq!(args.format, "jpeg");
879                assert_eq!(args.concurrency, 8);
880                assert_eq!(args.request_delay_ms, 50);
881                assert_eq!(args.attempts, 5);
882                assert!(args.bbox.is_none());
883                assert!(args.cache_dir.is_none());
884            }
885            other => panic!("expected raster, got {other:?}"),
886        }
887    }
888
889    #[test]
890    fn raster_build_options_resolve_the_hybrid_pyramid() {
891        let command = parse_from([
892            "geolith",
893            "raster",
894            "--url-template",
895            "https://t.example/{z}/{x}/{y}.jpg",
896            "--output",
897            "/tmp/planet.pmtiles",
898            "--min-zoom",
899            "0",
900            "--max-zoom",
901            "12",
902            "--bbox",
903            "68.0,6.5,97.5,37.2",
904            "--bbox-min-zoom",
905            "9",
906            "--format",
907            "png",
908            "--cache-dir",
909            "/tmp/rcache",
910            "--attribution",
911            "Sentinel-2 cloudless by EOX",
912        ])
913        .expect("raster parses");
914
915        match command {
916            Command::Raster(args) => {
917                let options = args.build_options().expect("valid options");
918                assert_eq!(options.pyramid.min_zoom, 0);
919                assert_eq!(options.pyramid.max_zoom, 12);
920                assert_eq!(options.pyramid.bbox_min_zoom, 9);
921                let bbox = options.pyramid.bbox.expect("bbox parsed");
922                assert!((bbox.0 - 68.0).abs() < 1e-9);
923                assert!((bbox.3 - 37.2).abs() < 1e-9);
924                assert_eq!(options.tile_type, geolith::output::writer::TileType::Png);
925                assert_eq!(options.cache_dir, PathBuf::from("/tmp/rcache"));
926                assert_eq!(
927                    options.attribution.as_deref(),
928                    Some("Sentinel-2 cloudless by EOX")
929                );
930            }
931            other => panic!("expected raster, got {other:?}"),
932        }
933    }
934
935    #[test]
936    fn raster_build_options_reject_bad_inputs() {
937        let bad_template = parse_from([
938            "geolith",
939            "raster",
940            "--url-template",
941            "https://t.example/{z}/{x}.jpg",
942            "--output",
943            "/tmp/p.pmtiles",
944        ])
945        .expect("parses; validation happens on resolve");
946        match bad_template {
947            Command::Raster(args) => assert!(args.build_options().is_err()),
948            other => panic!("expected raster, got {other:?}"),
949        }
950
951        let bad_format = parse_from([
952            "geolith",
953            "raster",
954            "--url-template",
955            "https://t.example/{z}/{x}/{y}.jpg",
956            "--output",
957            "/tmp/p.pmtiles",
958            "--format",
959            "tiff",
960        ])
961        .expect("parses; validation happens on resolve");
962        match bad_format {
963            Command::Raster(args) => {
964                let err = args.build_options().expect_err("tiff is not a tile format");
965                assert!(format!("{err}").contains("tiff"));
966            }
967            other => panic!("expected raster, got {other:?}"),
968        }
969    }
970
971    #[test]
972    fn raster_requires_template_and_output() {
973        assert!(parse_from(["geolith", "raster"]).is_err());
974        assert!(
975            parse_from([
976                "geolith",
977                "raster",
978                "--url-template",
979                "https://t.example/{z}/{x}/{y}.jpg",
980            ])
981            .is_err()
982        );
983    }
984
985    #[test]
986    fn subcommand_help_renders_for_each_verb() {
987        for verb in [VERB_TERRAIN, VERB_SPLAT_TILES, VERB_RASTER] {
988            let error = parse_from(["geolith", verb, "--help"]).expect_err("help exits via error");
989            assert_eq!(
990                error.kind(),
991                clap::error::ErrorKind::DisplayHelp,
992                "{verb} --help must render its own usage"
993            );
994        }
995    }
996
997    #[test]
998    fn unknown_verb_falls_through_to_the_tile_parser() {
999        let error = parse_from(["geolith", "wobble"]).expect_err("not a tile invocation");
1000        assert_ne!(
1001            error.kind(),
1002            clap::error::ErrorKind::DisplayHelp,
1003            "an unknown verb is a tile-parser error, not a subcommand"
1004        );
1005    }
1006
1007    #[test]
1008    fn bare_invocation_is_a_tile_parser_error() {
1009        let error = parse_from(["geolith"]).expect_err("the tile pipeline needs flags");
1010        assert_ne!(error.kind(), clap::error::ErrorKind::DisplayHelp);
1011    }
1012
1013    #[test]
1014    fn subcommand_version_renders_for_each_verb() {
1015        for verb in [VERB_TERRAIN, VERB_SPLAT_TILES, VERB_RASTER] {
1016            let error =
1017                parse_from(["geolith", verb, "--version"]).expect_err("version exits via error");
1018            assert_eq!(
1019                error.kind(),
1020                clap::error::ErrorKind::DisplayVersion,
1021                "{verb} --version must render its own version"
1022            );
1023        }
1024    }
1025
1026    #[test]
1027    fn a_verb_after_the_first_argument_is_not_a_subcommand() {
1028        let mut argv = tiles_argv();
1029        argv.push("terrain");
1030        let error = parse_from(argv).expect_err("'terrain' in tail position is not a verb");
1031        assert_ne!(
1032            error.kind(),
1033            clap::error::ErrorKind::DisplayHelp,
1034            "only argv[1] selects a subcommand"
1035        );
1036    }
1037
1038    #[test]
1039    fn terrain_rejects_a_non_numeric_zoom() {
1040        assert!(
1041            parse_from([
1042                "geolith",
1043                "terrain",
1044                "--dem",
1045                "/tmp/d.tif",
1046                "--output",
1047                "/tmp/t.pmtiles",
1048                "--max-zoom",
1049                "high",
1050            ])
1051            .is_err(),
1052            "zoom levels are numeric"
1053        );
1054    }
1055
1056    #[test]
1057    fn splat_rejects_a_non_numeric_anchor() {
1058        assert!(
1059            parse_from([
1060                "geolith",
1061                "splat-tiles",
1062                "--ply",
1063                "/tmp/s.ply",
1064                "--output",
1065                "/tmp/out",
1066                "--longitude",
1067                "west",
1068                "--latitude",
1069                "45.0",
1070            ])
1071            .is_err(),
1072            "the anchor is numeric"
1073        );
1074    }
1075
1076    #[test]
1077    fn dataset_is_a_verb() {
1078        assert!(is_subcommand("dataset"));
1079    }
1080
1081    #[test]
1082    fn dataset_areas_parses_its_flags() {
1083        let command = parse_from([
1084            "geolith",
1085            "dataset",
1086            "areas",
1087            "--overture",
1088            "/o",
1089            "--countries",
1090            "IN",
1091            "--india-outline",
1092            "/i.geojson",
1093            "--out",
1094            "/d",
1095        ])
1096        .expect("dataset areas parses");
1097
1098        match command {
1099            Command::Dataset(args) => match args.action {
1100                DatasetAction::Areas(x) => {
1101                    assert_eq!(x.countries.as_deref(), Some("IN"));
1102                    assert_eq!(x.subtype, "county");
1103                    assert_eq!(x.max_zoom, 8);
1104                    assert_eq!(x.india_outline, Some(PathBuf::from("/i.geojson")));
1105                    assert_eq!(x.overture, Some(PathBuf::from("/o")));
1106                    assert_eq!(x.out, PathBuf::from("/d"));
1107                    assert!(x.release.is_none());
1108                }
1109                other => panic!("expected dataset areas, got {other:?}"),
1110            },
1111            other => panic!("expected dataset, got {other:?}"),
1112        }
1113    }
1114
1115    #[test]
1116    fn dataset_build_needs_out() {
1117        assert!(
1118            parse_from([
1119                "geolith",
1120                "dataset",
1121                "build",
1122                "--config",
1123                "/c.json",
1124                "--rasters",
1125                "/r",
1126                "--areas",
1127                "/a.geojson",
1128            ])
1129            .is_err(),
1130            "a build without --out has nowhere to write"
1131        );
1132    }
1133
1134    #[test]
1135    fn dataset_normals_defaults_the_baseline() {
1136        let command = parse_from([
1137            "geolith",
1138            "dataset",
1139            "normals",
1140            "--config",
1141            "/c.json",
1142            "--rasters",
1143            "/r",
1144            "--areas",
1145            "/a.geojson",
1146            "--slots",
1147            "06-1,06-2",
1148            "--out",
1149            "/n.csv",
1150        ])
1151        .expect("dataset normals parses");
1152
1153        match command {
1154            Command::Dataset(args) => match args.action {
1155                DatasetAction::Normals(x) => {
1156                    assert_eq!(x.baseline, "1991-2020");
1157                    assert_eq!(x.slots, "06-1,06-2");
1158                    assert_eq!(x.out, PathBuf::from("/n.csv"));
1159                    assert_eq!(x.cache, None);
1160                }
1161                other => panic!("expected dataset normals, got {other:?}"),
1162            },
1163            other => panic!("expected dataset, got {other:?}"),
1164        }
1165    }
1166
1167    #[test]
1168    fn terrain_resolves_the_mapbox_encoding_by_default() {
1169        let command = parse_from([
1170            "geolith",
1171            "terrain",
1172            "--dem",
1173            "/tmp/dsm.tif",
1174            "--output",
1175            "/tmp/t.pmtiles",
1176        ])
1177        .expect("terrain parses");
1178
1179        match command {
1180            Command::Terrain(args) => {
1181                let options = args.tiler_options().expect("default encoding is valid");
1182                assert_eq!(options.encoding, TerrainEncoding::Mapbox);
1183                assert_eq!(options.min_zoom, 0);
1184                assert_eq!(options.max_zoom, 14);
1185                assert_eq!(options.tile_size, 512);
1186            }
1187            other => panic!("expected terrain, got {other:?}"),
1188        }
1189    }
1190}