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