geolith-cli 0.3.4

Rust vector tile generator — OSM + Overture Maps → protomaps PMTiles
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
//! Top-level command dispatch.
//!
//! The tile pipeline predates subcommands and is invoked as bare flags
//! (`geolith --data … --output …`). Introducing `terrain` and `splat-tiles`
//! as clap subcommands on the same parser would make those flags ambiguous,
//! so dispatch keys off the first argument: a recognised verb selects a
//! subcommand, anything else parses as the original flat tile config.

// The clap help text is golden-tested and names placeholders such as <output>.
#![allow(rustdoc::invalid_html_tags)]

use std::path::PathBuf;

use clap::Parser;

use crate::config::Config;
use crate::terrain::TerrainEncoding;

/// Subcommand verb for the terrain pipeline.
const VERB_TERRAIN: &str = "terrain";

/// Subcommand verb for the Gaussian splat pipeline.
const VERB_SPLAT_TILES: &str = "splat-tiles";

/// Subcommand verb for the raster basemap archiver.
const VERB_RASTER: &str = "raster";

/// Subcommand verb for the drone-video photogrammetry pipeline.
const VERB_RECONSTRUCT: &str = "reconstruct";

/// Subcommand verb for the raster dataset builder.
const VERB_DATASET: &str = "dataset";
const VERB_NOTICES: &str = "notices";

/// The notices of the code and data geolith builds on, printed by
/// `geolith notices`.
pub const NOTICE: &str = include_str!("../NOTICE.md");

/// What `geolith --version` prints after the version number.
pub const LONG_VERSION: &str = concat!(
    env!("CARGO_PKG_VERSION"),
    "\n© geolith. Source-available under the FSL-1.1-ALv2 (LICENSE.md).\n",
    "Outputs carry the credit \"© geolith\" after the attribution of their data.\n",
    "Run `geolith notices` for the notices of third-party code and data."
);

/// Build Terrain-RGB `raster-dem` `PMTiles` from a `GeoTIFF` DEM.
#[derive(Debug, Parser)]
#[command(
    name = "geolith terrain",
    about = "GeoTIFF DEM → Terrain-RGB PMTiles",
    version
)]
pub struct TerrainArgs {
    /// Input `GeoTIFF` DEM, or a directory whose `.tif`/`.tiff` files form one
    /// mosaic (files may use different CRSs; on overlap the first by path
    /// wins). Repeat to add fallbacks: a later `--dem` only fills pixels the
    /// earlier ones leave as nodata. Files are read window by window, so any
    /// size fits in memory.
    #[arg(long, required = true)]
    pub dem: Vec<PathBuf>,

    /// `GeoJSON` Polygon or `MultiPolygon`: pixels outside it become nodata and
    /// tiles that miss it are not written.
    #[arg(long)]
    pub clip: Option<PathBuf>,

    /// Output `PMTiles` archive path.
    #[arg(long, short)]
    pub output: PathBuf,

    /// Elevation encoding: "mapbox" (default) or "terrarium".
    #[arg(long, default_value = "mapbox")]
    pub encoding: String,

    /// Minimum zoom level.
    #[arg(long, default_value = "0")]
    pub min_zoom: u8,

    /// Maximum zoom level.
    #[arg(long, default_value = "14")]
    pub max_zoom: u8,

    /// Tile edge length in pixels.
    #[arg(long, default_value = "512")]
    pub tile_size: u32,

    /// Override the DEM's EPSG code when the `GeoTIFF` lacks geokeys.
    #[arg(long)]
    pub dem_crs: Option<u32>,

    /// Layer name recorded in the archive metadata.
    #[arg(long, default_value = "terrain")]
    pub name: String,
}

/// Build an OGC 3D Tiles tileset from a trained Gaussian splat PLY.
#[derive(Debug, Parser)]
#[command(
    name = "geolith splat-tiles",
    about = "3DGS PLY → OGC 3D Tiles (KHR_gaussian_splatting + spz_2)",
    version
)]
pub struct SplatTilesArgs {
    /// Path to the trained 3D Gaussian Splatting PLY.
    #[arg(long)]
    pub ply: PathBuf,

    /// Output directory for `tileset.json` and `tiles/*.glb`.
    #[arg(long, short)]
    pub output: PathBuf,

    /// Longitude of the scene anchor in degrees.
    #[arg(long, allow_hyphen_values = true)]
    pub longitude: f64,

    /// Latitude of the scene anchor in degrees.
    #[arg(long, allow_hyphen_values = true)]
    pub latitude: f64,

    /// Height of the scene anchor above the ellipsoid in metres.
    #[arg(long, default_value = "0", allow_hyphen_values = true)]
    pub altitude: f64,

    /// Maximum splats stored in a single tile.
    #[arg(long, default_value = "100000")]
    pub max_splats_per_tile: usize,

    /// Maximum octree depth.
    #[arg(long, default_value = "6")]
    pub max_depth: u8,

    /// Geometric error assigned to the root tile.
    #[arg(long, default_value = "64")]
    pub root_geometric_error: f64,

    /// Mark the splats as trained with antialiasing.
    #[arg(long, default_value = "false")]
    pub antialiased: bool,

    /// Also write a standalone `scene.spz` for single-file splat rendering.
    #[arg(long, default_value = "true")]
    pub emit_scene_spz: bool,

    /// Trim this percentage from both ends of every axis before tiling,
    /// removing the hallucinated far-field shell of inward-facing captures.
    #[arg(long, default_value = "0")]
    pub crop_percentile: f64,

    /// Uniform scale factor applied to the scene (e.g. 0.1 when the trainer
    /// produced a 10x oversized world).
    #[arg(long, default_value = "1")]
    pub scale: f32,

    /// Coverage boost applied before encoding, matching the gsplat post-process:
    /// `opacity_logit += ln(scale)` and `log_scale -= 0.5 * ln(scale)`. Use when
    /// the trainer ran without a coverage boost and the splats render dim and
    /// oversized (e.g. 5–10 for drone captures). `0` disables the boost.
    #[arg(long, default_value = "0")]
    pub coverage_boost_scale: f32,
}

/// Archive raster tiles from an XYZ/WMTS endpoint into `PMTiles`.
#[derive(Debug, Parser)]
#[command(
    name = "geolith raster",
    about = "XYZ/WMTS raster tiles -> PMTiles basemap archive",
    version
)]
pub struct RasterArgs {
    /// Tile URL template containing {z}, {x}, and {y} placeholders.
    #[arg(long)]
    pub url_template: String,

    /// Output `PMTiles` archive path.
    #[arg(long, short)]
    pub output: PathBuf,

    /// Minimum zoom level.
    #[arg(long, default_value = "0")]
    pub min_zoom: u8,

    /// Maximum zoom level.
    #[arg(long, default_value = "8")]
    pub max_zoom: u8,

    /// Restrict coverage to `min_lon,min_lat,max_lon,max_lat`.
    #[arg(long)]
    pub bbox: Option<String>,

    /// First zoom at which --bbox applies; below it the whole planet is
    /// fetched, producing a hybrid planet + deep-zoom-region archive.
    #[arg(long, default_value = "0")]
    pub bbox_min_zoom: u8,

    /// Payload format recorded in the archive: "jpeg", "png", or "webp".
    #[arg(long, default_value = "jpeg")]
    pub format: String,

    /// Concurrent download workers.
    #[arg(long, default_value = "8")]
    pub concurrency: usize,

    /// Delay in milliseconds after each request on every worker.
    #[arg(long, default_value = "50")]
    pub request_delay_ms: u64,

    /// Download attempts per tile before the build fails.
    #[arg(long, default_value = "5")]
    pub attempts: u32,

    /// Resumable tile cache directory (default: <system temp>/geolith-raster).
    #[arg(long)]
    pub cache_dir: Option<PathBuf>,

    /// Layer name recorded in the archive metadata.
    #[arg(long, default_value = "raster")]
    pub name: String,

    /// Attribution recorded in the archive metadata.
    #[arg(long)]
    pub attribution: Option<String>,
}

/// Drone video → OGC 3D Tiles via ffmpeg → COLMAP → brush → splat-tiles.
#[derive(Debug, Parser)]
#[command(
    name = "geolith reconstruct",
    about = "drone video → 3D Tiles (ffmpeg → COLMAP → brush → splat-tiles)",
    version
)]
pub struct ReconstructArgs {
    /// Path to the drone video (mp4/mov/webm).
    #[arg(long)]
    pub video: PathBuf,

    /// Working directory; stage outputs land in `frames/`, `sparse/`,
    /// `exports/`, and `tiles/` beneath it. Re-running reuses completed
    /// stages (resume semantics).
    #[arg(long, short)]
    pub output: PathBuf,

    /// Frame extraction rate in frames per second.
    #[arg(long, default_value = "2.0")]
    pub fps: f64,

    /// Cap the number of extracted frames (optional).
    #[arg(long)]
    pub max_frames: Option<usize>,

    /// COLMAP binary path (default: `colmap` on `$PATH`).
    #[arg(long, default_value = "colmap")]
    pub colmap_bin: String,

    /// Brush CLI binary path (default: `brush-cli` on `$PATH`).
    #[arg(long, default_value = "brush-cli")]
    pub brush_bin: String,

    /// Total brush training iterations.
    #[arg(long, default_value = "30000")]
    pub train_iters: u32,

    /// Longitude of the scene anchor in degrees (default 0).
    #[arg(long, default_value = "0", allow_hyphen_values = true)]
    pub longitude: f64,

    /// Latitude of the scene anchor in degrees (default 0).
    #[arg(long, default_value = "0", allow_hyphen_values = true)]
    pub latitude: f64,

    /// Height of the scene anchor above the ellipsoid in metres.
    #[arg(long, default_value = "0", allow_hyphen_values = true)]
    pub altitude: f64,

    /// Trim this percentage from both ends of every axis before tiling.
    #[arg(long, default_value = "0")]
    pub crop_percentile: f64,

    /// Trim this percentage from the far end of the radial distance
    /// distribution before tiling (removes the far-field halo).
    #[arg(long, default_value = "0")]
    pub crop_radial_percentile: f64,

    /// Uniform scale factor applied to the scene.
    #[arg(long, default_value = "1")]
    pub scale: f32,

    /// Coverage boost applied before encoding (0 disables it).
    #[arg(long, default_value = "0")]
    pub coverage_boost_scale: f32,

    /// Maximum splats stored in a single tile.
    #[arg(long, default_value = "100000")]
    pub max_splats_per_tile: usize,

    /// Maximum octree depth.
    #[arg(long, default_value = "6")]
    pub max_depth: u8,

    /// Geometric error assigned to the root tile.
    #[arg(long, default_value = "64")]
    pub root_geometric_error: f64,

    /// Also write a standalone `scene.spz` alongside the tileset.
    #[arg(long, default_value = "true")]
    pub emit_scene_spz: bool,
}

impl ReconstructArgs {
    /// Resolve the pipeline options this invocation selects.
    #[must_use]
    pub fn options(&self) -> crate::reconstruct::ReconstructOptions {
        crate::reconstruct::ReconstructOptions {
            fps: self.fps,
            max_frames: self.max_frames,
            colmap_bin: self.colmap_bin.clone(),
            brush_bin: self.brush_bin.clone(),
            train_iters: self.train_iters,
            longitude: self.longitude,
            latitude: self.latitude,
            altitude: self.altitude,
            crop_percentile: self.crop_percentile,
            crop_radial_percentile: self.crop_radial_percentile,
            scale: self.scale,
            coverage_boost_scale: self.coverage_boost_scale,
            max_splats_per_tile: self.max_splats_per_tile,
            max_depth: self.max_depth,
            root_geometric_error: self.root_geometric_error,
            emit_scene_spz: self.emit_scene_spz,
        }
    }
}

/// The dataset command tree; the module owns its own args.
pub use crate::dataset::cli::{
    AreasArgs, AreasDownloadArgs, BuildArgs, CheckDownloadArgs, DatasetAction, DatasetArgs,
    DownloadsAction, DownloadsArgs, InspectArgs, KeysArgs, NormalsArgs, NumbersDownloadArgs,
    StageArgs, StatusArgs, ValuesArgs, VerifyArgs,
};

/// Print the notices of the third-party code and data geolith builds on.
#[derive(Debug, Parser)]
#[command(
    name = "geolith notices",
    about = "print the notices of third-party code and data",
    version
)]
pub struct NoticesArgs {}

/// A parsed top-level command.
#[non_exhaustive]
#[derive(Debug)]
pub enum Command {
    /// Run the terrain pipeline.
    Terrain(Box<TerrainArgs>),
    /// Run the Gaussian splat pipeline.
    SplatTiles(Box<SplatTilesArgs>),
    /// Run the raster basemap archiver.
    Raster(Box<RasterArgs>),
    /// Run the drone-video photogrammetry pipeline.
    Reconstruct(Box<ReconstructArgs>),
    /// Run the raster dataset builder.
    Dataset(Box<DatasetArgs>),
    /// Print the notices of third-party code and data.
    Notices,
    /// Run the tile pipeline with the original flat flags.
    Tiles(Box<Config>),
}

/// Whether `argument` names a subcommand rather than a flag.
#[must_use]
pub fn is_subcommand(argument: &str) -> bool {
    matches!(
        argument,
        VERB_TERRAIN
            | VERB_SPLAT_TILES
            | VERB_RASTER
            | VERB_RECONSTRUCT
            | VERB_DATASET
            | VERB_NOTICES
    )
}

/// Parse a full argv into a [`Command`].
///
/// # Errors
///
/// Returns the clap error for the selected parser, so `--help` and
/// `--version` still render correctly for each subcommand.
pub fn parse_from<I, T>(args: I) -> Result<Command, clap::Error>
where
    I: IntoIterator<Item = T>,
    T: Into<std::ffi::OsString> + Clone,
{
    let argv: Vec<std::ffi::OsString> = args.into_iter().map(Into::into).collect();
    let verb = argv
        .get(1)
        .and_then(|arg| arg.to_str())
        .filter(|arg| is_subcommand(arg))
        .map(str::to_owned);

    match verb.as_deref() {
        Some(VERB_TERRAIN) => {
            let mut forwarded = vec![std::ffi::OsString::from("geolith terrain")];
            forwarded.extend(argv.into_iter().skip(2));
            TerrainArgs::try_parse_from(forwarded).map(|a| Command::Terrain(Box::new(a)))
        }
        Some(VERB_SPLAT_TILES) => {
            let mut forwarded = vec![std::ffi::OsString::from("geolith splat-tiles")];
            forwarded.extend(argv.into_iter().skip(2));
            SplatTilesArgs::try_parse_from(forwarded).map(|a| Command::SplatTiles(Box::new(a)))
        }
        Some(VERB_RASTER) => {
            let mut forwarded = vec![std::ffi::OsString::from("geolith raster")];
            forwarded.extend(argv.into_iter().skip(2));
            RasterArgs::try_parse_from(forwarded).map(|a| Command::Raster(Box::new(a)))
        }
        Some(VERB_RECONSTRUCT) => {
            let mut forwarded = vec![std::ffi::OsString::from("geolith reconstruct")];
            forwarded.extend(argv.into_iter().skip(2));
            ReconstructArgs::try_parse_from(forwarded).map(|a| Command::Reconstruct(Box::new(a)))
        }
        Some(VERB_NOTICES) => {
            let mut forwarded = vec![std::ffi::OsString::from("geolith notices")];
            forwarded.extend(argv.into_iter().skip(2));
            NoticesArgs::try_parse_from(forwarded).map(|_| Command::Notices)
        }
        Some(VERB_DATASET) => {
            let mut forwarded = vec![std::ffi::OsString::from("geolith dataset")];
            forwarded.extend(argv.into_iter().skip(2));
            DatasetArgs::try_parse_from(forwarded).map(|a| Command::Dataset(Box::new(a)))
        }
        _ => Config::try_parse_from(argv)
            .and_then(|c| c.check_required().map(|()| c))
            .map(|c| Command::Tiles(Box::new(c))),
    }
}

/// Parse the process arguments, exiting with clap's diagnostics on failure.
#[must_use]
pub fn parse_args() -> Command {
    match parse_from(std::env::args_os()) {
        Ok(command) => command,
        Err(error) => error.exit(),
    }
}

impl TerrainArgs {
    /// Resolve the tiler options this invocation selects.
    ///
    /// # Errors
    ///
    /// Returns an error when `--encoding` is not a known encoding name.
    pub fn tiler_options(&self) -> geolith::error::Result<crate::terrain::TerrainTilerOptions> {
        let clip = match &self.clip {
            Some(path) => Some(std::sync::Arc::new(crate::terrain::ClipMask::from_geojson(
                path,
            )?)),
            None => None,
        };
        Ok(crate::terrain::TerrainTilerOptions {
            min_zoom: self.min_zoom,
            max_zoom: self.max_zoom,
            tile_size: self.tile_size,
            encoding: TerrainEncoding::parse(&self.encoding)?,
            clip,
        })
    }
}

impl RasterArgs {
    /// Resolve the archive build options this invocation selects.
    ///
    /// # Errors
    ///
    /// Returns an error when the URL template, bbox, or format is invalid.
    pub fn build_options(&self) -> geolith::error::Result<crate::raster::RasterBuildOptions> {
        let template = crate::raster::UrlTemplate::parse(&self.url_template)?;
        let bbox = match &self.bbox {
            Some(raw) => {
                let parsed = crate::source::bbox_filter::Bbox::parse(raw)?;
                Some((
                    parsed.min_lon,
                    parsed.min_lat,
                    parsed.max_lon,
                    parsed.max_lat,
                ))
            }
            None => None,
        };
        let tile_type = match self.format.as_str() {
            "jpeg" | "jpg" => geolith::output::writer::TileType::Jpeg,
            "png" => geolith::output::writer::TileType::Png,
            "webp" => geolith::output::writer::TileType::Webp,
            other => {
                return Err(geolith::error::GeolithError::RasterSource(format!(
                    "unknown raster format {other:?} — expected jpeg, png, or webp"
                )));
            }
        };
        Ok(crate::raster::RasterBuildOptions {
            template,
            pyramid: crate::raster::PyramidSpec {
                min_zoom: self.min_zoom,
                max_zoom: self.max_zoom,
                bbox,
                bbox_min_zoom: self.bbox_min_zoom,
            },
            tile_type,
            concurrency: self.concurrency,
            request_delay: std::time::Duration::from_millis(self.request_delay_ms),
            attempts: self.attempts,
            cache_dir: self
                .cache_dir
                .clone()
                .unwrap_or_else(|| std::env::temp_dir().join("geolith-raster")),
            name: self.name.clone(),
            attribution: self.attribution.clone(),
        })
    }
}

impl SplatTilesArgs {
    /// The splat tileset build this invocation selects.
    #[must_use]
    pub fn job(&self) -> crate::splat::SplatJob {
        crate::splat::SplatJob {
            ply: self.ply.clone(),
            output: self.output.clone(),
            crop_percentile: self.crop_percentile,
            scale: self.scale,
            coverage_boost_scale: self.coverage_boost_scale,
            emit_scene_spz: self.emit_scene_spz,
            options: self.tileset_options(),
        }
    }

    /// The tileset options this invocation selects.
    #[must_use]
    pub const fn tileset_options(&self) -> crate::splat::SplatTilesetOptions {
        crate::splat::SplatTilesetOptions {
            longitude: self.longitude,
            latitude: self.latitude,
            altitude: self.altitude,
            max_splats_per_tile: self.max_splats_per_tile,
            max_depth: self.max_depth,
            root_geometric_error: self.root_geometric_error,
            antialiased: self.antialiased,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn tiles_argv() -> Vec<&'static str> {
        vec![
            "geolith",
            "--data",
            "/tmp/data",
            "--natural-earth",
            "/tmp/ne.sqlite",
            "--water-polygons",
            "/tmp/water",
            "--land-polygons",
            "/tmp/land",
            "--output",
            "/tmp/out.pmtiles",
        ]
    }

    /// Every `geolith dataset` verb (with its downloads verbs) and its
    /// long flags, read from the clap definition.
    fn dataset_verbs() -> Vec<(String, Vec<String>)> {
        use clap::CommandFactory;
        fn walk(cmd: &clap::Command, prefix: &str, out: &mut Vec<(String, Vec<String>)>) {
            for sub in cmd.get_subcommands() {
                let name = format!("{prefix}{}", sub.get_name());
                let flags = sub
                    .get_arguments()
                    .filter_map(clap::Arg::get_long)
                    .filter(|l| !matches!(*l, "help" | "version"))
                    .map(|l| format!("--{l}"))
                    .collect();
                out.push((name.clone(), flags));
                walk(sub, &format!("{name} "), out);
            }
        }
        let mut out = Vec::new();
        walk(&DatasetArgs::command(), "dataset ", &mut out);
        out
    }

    #[test]
    fn every_dataset_verb_and_flag_is_documented() {
        let readme = include_str!("../../README.md");
        let agents = include_str!("../../AGENTS.md");
        let verbs = dataset_verbs();
        assert!(
            verbs.iter().any(|(v, _)| v == "dataset values"),
            "{verbs:?}"
        );
        let mut missing = Vec::new();
        for (verb, flags) in &verbs {
            if verb == "dataset downloads" {
                continue;
            }
            let last = verb.rsplit(' ').next().unwrap_or_default();
            if !readme.contains(&format!("geolith {verb}")) {
                missing.push(format!("README: geolith {verb}"));
            }
            // AGENTS.md lists verbs as `geolith dataset areas|normals|build`.
            if !agents.contains(&format!("geolith {verb}")) && !agents.contains(&format!("|{last}"))
            {
                missing.push(format!("AGENTS.md: {verb}"));
            }
            for flag in flags {
                if !readme.contains(flag.as_str()) {
                    missing.push(format!("README: {verb} {flag}"));
                }
            }
        }
        // The flags P2 added, which AGENTS.md must name as well.
        for flag in ["dataset normals --cache", "dataset values --config"] {
            if !agents.contains(flag) {
                missing.push(format!("AGENTS.md: {flag}"));
            }
        }
        assert!(missing.is_empty(), "undocumented: {missing:?}");
    }

    #[test]
    fn verbs_are_recognised() {
        assert!(is_subcommand("terrain"));
        assert!(is_subcommand("splat-tiles"));
        assert!(is_subcommand("raster"));
        assert!(!is_subcommand("--data"));
        assert!(!is_subcommand("tiles"));
    }

    #[test]
    fn flat_invocation_still_reaches_the_tile_pipeline() {
        let command = parse_from(tiles_argv()).expect("flat flags parse");
        match command {
            Command::Tiles(config) => {
                assert_eq!(config.output_format, "tiles");
                assert_eq!(config.data, Some(PathBuf::from("/tmp/data")));
            }
            other => panic!("expected the tile pipeline, got {other:?}"),
        }
    }

    #[test]
    fn terrain_subcommand_parses_required_flags() {
        let command = parse_from([
            "geolith",
            "terrain",
            "--dem",
            "/tmp/dsm.tif",
            "--output",
            "/tmp/terrain.pmtiles",
        ])
        .expect("terrain parses");

        match command {
            Command::Terrain(args) => {
                assert_eq!(args.dem, [PathBuf::from("/tmp/dsm.tif")]);
                assert_eq!(args.output, PathBuf::from("/tmp/terrain.pmtiles"));
                assert_eq!(args.encoding, "mapbox");
                assert_eq!(args.min_zoom, 0);
                assert_eq!(args.max_zoom, 14);
                assert_eq!(args.tile_size, 512);
                assert_eq!(args.name, "terrain");
                assert!(args.dem_crs.is_none());
            }
            other => panic!("expected terrain, got {other:?}"),
        }
    }

    #[test]
    fn terrain_subcommand_accepts_overrides() {
        let command = parse_from([
            "geolith",
            "terrain",
            "--dem",
            "/tmp/dsm.tif",
            "--output",
            "/tmp/t.pmtiles",
            "--encoding",
            "terrarium",
            "--min-zoom",
            "8",
            "--max-zoom",
            "16",
            "--tile-size",
            "256",
            "--dem-crs",
            "32632",
            "--name",
            "belvedere",
        ])
        .expect("terrain parses");

        match command {
            Command::Terrain(args) => {
                assert_eq!(args.encoding, "terrarium");
                assert_eq!(args.min_zoom, 8);
                assert_eq!(args.max_zoom, 16);
                assert_eq!(args.tile_size, 256);
                assert_eq!(args.dem_crs, Some(32_632));
                assert_eq!(args.name, "belvedere");

                let options = args.tiler_options().expect("known encoding");
                assert_eq!(options.encoding, TerrainEncoding::Terrarium);
                assert_eq!(options.tile_size, 256);
            }
            other => panic!("expected terrain, got {other:?}"),
        }
    }

    #[test]
    fn terrain_rejects_unknown_encoding_when_resolving_options() {
        let command = parse_from([
            "geolith",
            "terrain",
            "--dem",
            "/tmp/dsm.tif",
            "--output",
            "/tmp/t.pmtiles",
            "--encoding",
            "rainbow",
        ])
        .expect("flag parses; validation happens on resolve");

        match command {
            Command::Terrain(args) => assert!(args.tiler_options().is_err()),
            other => panic!("expected terrain, got {other:?}"),
        }
    }

    #[test]
    fn terrain_requires_dem_and_output() {
        assert!(parse_from(["geolith", "terrain"]).is_err());
        assert!(parse_from(["geolith", "terrain", "--dem", "/tmp/d.tif"]).is_err());
    }

    #[test]
    fn splat_subcommand_parses_required_flags() {
        let command = parse_from([
            "geolith",
            "splat-tiles",
            "--ply",
            "/tmp/scene.ply",
            "--output",
            "/tmp/tileset",
            "--longitude",
            "7.9797",
            "--latitude",
            "45.9756",
        ])
        .expect("splat-tiles parses");

        match command {
            Command::SplatTiles(args) => {
                assert_eq!(args.ply, PathBuf::from("/tmp/scene.ply"));
                assert!((args.longitude - 7.9797).abs() < 1e-9);
                assert!((args.latitude - 45.9756).abs() < 1e-9);
                assert!((args.altitude - 0.0).abs() < 1e-9);
                assert_eq!(args.max_splats_per_tile, 100_000);
                assert_eq!(args.max_depth, 6);
                assert!(args.emit_scene_spz);
                assert!(!args.antialiased);
            }
            other => panic!("expected splat-tiles, got {other:?}"),
        }
    }

    #[test]
    fn splat_subcommand_accepts_negative_coordinates() {
        let command = parse_from([
            "geolith",
            "splat-tiles",
            "--ply",
            "/tmp/scene.ply",
            "--output",
            "/tmp/tileset",
            "--longitude",
            "-122.4194",
            "--latitude",
            "-37.7749",
            "--altitude",
            "-50",
        ])
        .expect("negative coordinates parse");

        match command {
            Command::SplatTiles(args) => {
                assert!(args.longitude < 0.0, "southern/western anchors are valid");
                assert!(args.latitude < 0.0);
                assert!(args.altitude < 0.0);
            }
            other => panic!("expected splat-tiles, got {other:?}"),
        }
    }

    #[test]
    fn splat_options_carry_through_to_the_tileset_builder() {
        let command = parse_from([
            "geolith",
            "splat-tiles",
            "--ply",
            "/tmp/scene.ply",
            "--output",
            "/tmp/tileset",
            "--longitude",
            "7.9797",
            "--latitude",
            "45.9756",
            "--altitude",
            "2250",
            "--max-splats-per-tile",
            "50000",
            "--max-depth",
            "4",
            "--root-geometric-error",
            "128",
            "--antialiased",
        ])
        .expect("splat-tiles parses");

        match command {
            Command::SplatTiles(args) => {
                let options = args.tileset_options();
                assert!((options.altitude - 2250.0).abs() < 1e-9);
                assert_eq!(options.max_splats_per_tile, 50_000);
                assert_eq!(options.max_depth, 4);
                assert!((options.root_geometric_error - 128.0).abs() < 1e-9);
                assert!(options.antialiased);
            }
            other => panic!("expected splat-tiles, got {other:?}"),
        }
    }

    #[test]
    fn splat_requires_an_anchor() {
        assert!(
            parse_from([
                "geolith",
                "splat-tiles",
                "--ply",
                "/tmp/s.ply",
                "--output",
                "/tmp/out",
            ])
            .is_err(),
            "a tileset without a geographic anchor cannot be placed on the globe"
        );
    }

    #[test]
    fn raster_subcommand_parses_required_flags() {
        let command = parse_from([
            "geolith",
            "raster",
            "--url-template",
            "https://t.example/{z}/{x}/{y}.jpg",
            "--output",
            "/tmp/planet.pmtiles",
        ])
        .expect("raster parses");

        match command {
            Command::Raster(args) => {
                assert_eq!(args.output, PathBuf::from("/tmp/planet.pmtiles"));
                assert_eq!(args.min_zoom, 0);
                assert_eq!(args.max_zoom, 8);
                assert_eq!(args.format, "jpeg");
                assert_eq!(args.concurrency, 8);
                assert_eq!(args.request_delay_ms, 50);
                assert_eq!(args.attempts, 5);
                assert!(args.bbox.is_none());
                assert!(args.cache_dir.is_none());
            }
            other => panic!("expected raster, got {other:?}"),
        }
    }

    #[test]
    fn raster_build_options_resolve_the_hybrid_pyramid() {
        let command = parse_from([
            "geolith",
            "raster",
            "--url-template",
            "https://t.example/{z}/{x}/{y}.jpg",
            "--output",
            "/tmp/planet.pmtiles",
            "--min-zoom",
            "0",
            "--max-zoom",
            "12",
            "--bbox",
            "68.0,6.5,97.5,37.2",
            "--bbox-min-zoom",
            "9",
            "--format",
            "png",
            "--cache-dir",
            "/tmp/rcache",
            "--attribution",
            "Sentinel-2 cloudless by EOX",
        ])
        .expect("raster parses");

        match command {
            Command::Raster(args) => {
                let options = args.build_options().expect("valid options");
                assert_eq!(options.pyramid.min_zoom, 0);
                assert_eq!(options.pyramid.max_zoom, 12);
                assert_eq!(options.pyramid.bbox_min_zoom, 9);
                let bbox = options.pyramid.bbox.expect("bbox parsed");
                assert!((bbox.0 - 68.0).abs() < 1e-9);
                assert!((bbox.3 - 37.2).abs() < 1e-9);
                assert_eq!(options.tile_type, geolith::output::writer::TileType::Png);
                assert_eq!(options.cache_dir, PathBuf::from("/tmp/rcache"));
                assert_eq!(
                    options.attribution.as_deref(),
                    Some("Sentinel-2 cloudless by EOX")
                );
            }
            other => panic!("expected raster, got {other:?}"),
        }
    }

    #[test]
    fn raster_build_options_reject_bad_inputs() {
        let bad_template = parse_from([
            "geolith",
            "raster",
            "--url-template",
            "https://t.example/{z}/{x}.jpg",
            "--output",
            "/tmp/p.pmtiles",
        ])
        .expect("parses; validation happens on resolve");
        match bad_template {
            Command::Raster(args) => assert!(args.build_options().is_err()),
            other => panic!("expected raster, got {other:?}"),
        }

        let bad_format = parse_from([
            "geolith",
            "raster",
            "--url-template",
            "https://t.example/{z}/{x}/{y}.jpg",
            "--output",
            "/tmp/p.pmtiles",
            "--format",
            "tiff",
        ])
        .expect("parses; validation happens on resolve");
        match bad_format {
            Command::Raster(args) => {
                let err = args.build_options().expect_err("tiff is not a tile format");
                assert!(format!("{err}").contains("tiff"));
            }
            other => panic!("expected raster, got {other:?}"),
        }
    }

    #[test]
    fn raster_requires_template_and_output() {
        assert!(parse_from(["geolith", "raster"]).is_err());
        assert!(
            parse_from([
                "geolith",
                "raster",
                "--url-template",
                "https://t.example/{z}/{x}/{y}.jpg",
            ])
            .is_err()
        );
    }

    #[test]
    fn subcommand_help_renders_for_each_verb() {
        for verb in [VERB_TERRAIN, VERB_SPLAT_TILES, VERB_RASTER] {
            let error = parse_from(["geolith", verb, "--help"]).expect_err("help exits via error");
            assert_eq!(
                error.kind(),
                clap::error::ErrorKind::DisplayHelp,
                "{verb} --help must render its own usage"
            );
        }
    }

    #[test]
    fn unknown_verb_falls_through_to_the_tile_parser() {
        let error = parse_from(["geolith", "wobble"]).expect_err("not a tile invocation");
        assert_ne!(
            error.kind(),
            clap::error::ErrorKind::DisplayHelp,
            "an unknown verb is a tile-parser error, not a subcommand"
        );
    }

    #[test]
    fn bare_invocation_is_a_tile_parser_error() {
        let error = parse_from(["geolith"]).expect_err("the tile pipeline needs flags");
        assert_ne!(error.kind(), clap::error::ErrorKind::DisplayHelp);
    }

    #[test]
    fn subcommand_version_renders_for_each_verb() {
        for verb in [VERB_TERRAIN, VERB_SPLAT_TILES, VERB_RASTER] {
            let error =
                parse_from(["geolith", verb, "--version"]).expect_err("version exits via error");
            assert_eq!(
                error.kind(),
                clap::error::ErrorKind::DisplayVersion,
                "{verb} --version must render its own version"
            );
        }
    }

    #[test]
    fn a_verb_after_the_first_argument_is_not_a_subcommand() {
        let mut argv = tiles_argv();
        argv.push("terrain");
        let error = parse_from(argv).expect_err("'terrain' in tail position is not a verb");
        assert_ne!(
            error.kind(),
            clap::error::ErrorKind::DisplayHelp,
            "only argv[1] selects a subcommand"
        );
    }

    #[test]
    fn terrain_rejects_a_non_numeric_zoom() {
        assert!(
            parse_from([
                "geolith",
                "terrain",
                "--dem",
                "/tmp/d.tif",
                "--output",
                "/tmp/t.pmtiles",
                "--max-zoom",
                "high",
            ])
            .is_err(),
            "zoom levels are numeric"
        );
    }

    #[test]
    fn splat_rejects_a_non_numeric_anchor() {
        assert!(
            parse_from([
                "geolith",
                "splat-tiles",
                "--ply",
                "/tmp/s.ply",
                "--output",
                "/tmp/out",
                "--longitude",
                "west",
                "--latitude",
                "45.0",
            ])
            .is_err(),
            "the anchor is numeric"
        );
    }

    #[test]
    fn dataset_is_a_verb() {
        assert!(is_subcommand("dataset"));
    }

    #[test]
    fn dataset_areas_parses_its_flags() {
        let command = parse_from([
            "geolith",
            "dataset",
            "areas",
            "--overture",
            "/o",
            "--countries",
            "IN",
            "--india-outline",
            "/i.geojson",
            "--out",
            "/d",
        ])
        .expect("dataset areas parses");

        match command {
            Command::Dataset(args) => match args.action {
                DatasetAction::Areas(x) => {
                    assert_eq!(x.countries.as_deref(), Some("IN"));
                    assert_eq!(x.subtype, "county");
                    assert_eq!(x.max_zoom, 8);
                    assert_eq!(x.india_outline, Some(PathBuf::from("/i.geojson")));
                    assert_eq!(x.overture, Some(PathBuf::from("/o")));
                    assert_eq!(x.out, PathBuf::from("/d"));
                    assert!(x.release.is_none());
                }
                other => panic!("expected dataset areas, got {other:?}"),
            },
            other => panic!("expected dataset, got {other:?}"),
        }
    }

    #[test]
    fn dataset_build_needs_out() {
        assert!(
            parse_from([
                "geolith",
                "dataset",
                "build",
                "--config",
                "/c.json",
                "--rasters",
                "/r",
                "--areas",
                "/a.geojson",
            ])
            .is_err(),
            "a build without --out has nowhere to write"
        );
    }

    #[test]
    fn dataset_normals_defaults_the_baseline() {
        let command = parse_from([
            "geolith",
            "dataset",
            "normals",
            "--config",
            "/c.json",
            "--rasters",
            "/r",
            "--areas",
            "/a.geojson",
            "--slots",
            "06-1,06-2",
            "--out",
            "/n.csv",
        ])
        .expect("dataset normals parses");

        match command {
            Command::Dataset(args) => match args.action {
                DatasetAction::Normals(x) => {
                    assert_eq!(x.baseline, "1991-2020");
                    assert_eq!(x.slots, "06-1,06-2");
                    assert_eq!(x.out, PathBuf::from("/n.csv"));
                    assert_eq!(x.cache, None);
                }
                other => panic!("expected dataset normals, got {other:?}"),
            },
            other => panic!("expected dataset, got {other:?}"),
        }
    }

    #[test]
    fn terrain_resolves_the_mapbox_encoding_by_default() {
        let command = parse_from([
            "geolith",
            "terrain",
            "--dem",
            "/tmp/dsm.tif",
            "--output",
            "/tmp/t.pmtiles",
        ])
        .expect("terrain parses");

        match command {
            Command::Terrain(args) => {
                let options = args.tiler_options().expect("default encoding is valid");
                assert_eq!(options.encoding, TerrainEncoding::Mapbox);
                assert_eq!(options.min_zoom, 0);
                assert_eq!(options.max_zoom, 14);
                assert_eq!(options.tile_size, 512);
            }
            other => panic!("expected terrain, got {other:?}"),
        }
    }
}