lidar-cli 0.3.0

Command-line interface for lidar-rs: DEM filtering, sink extraction, nested depression/mount delineation, and LiDAR point cloud tools in pure Rust
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
//! Command-line interface for `lidar-rs`: DEM filtering, sink extraction,
//! nested surface depression and mount delineation, and geospatial utilities
//! in pure Rust (powered by `terrio` and `richdem`).

use std::path::PathBuf;
use std::process::ExitCode;

use clap::{Parser, Subcommand, ValueEnum};
use lidar::pointcloud::{GridMethod, GridStat, LidarToDsmOptions, convert_lidar, lidar_to_dsm};
use lidar::{
    AnimateInundationOptions, CatchmentHierarchyOptions, DelineateCatchmentsOptions,
    DelineateFlowPathsOptions, DelineateOptions, ExtractSinksOptions, HillshadeOptions,
    SimulateInundationOptions, Topology, add_crs, animate_inundation, clip_image,
    csv_points_to_vector, delineate_catchment_hierarchy, delineate_catchments,
    delineate_depressions, delineate_flow_paths, delineate_mounts, extract_sinks, flip_dem_file,
    gaussian_filter_file, image_to_cog, join_csv_to_vector, mean_filter_file, median_filter_file,
    mosaic, parse_resampling, polygonize, reproject_image, resample, simulate_inundation,
};

#[derive(Parser)]
#[command(
    name = "lidar",
    version,
    about = "Nested surface depression and mount delineation from DEMs in pure Rust",
    long_about = "Pure-Rust port of opengeos/lidar (Wu et al. 2019; Wu 2021) powered by terrio and richdem, with zero GDAL or C/C++ dependencies."
)]
struct Cli {
    #[command(subcommand)]
    command: Commands,
}

#[derive(Clone, Copy, ValueEnum)]
enum CliTopology {
    D8,
    D4,
}

impl From<CliTopology> for Topology {
    fn from(t: CliTopology) -> Self {
        match t {
            CliTopology::D8 => Topology::D8,
            CliTopology::D4 => Topology::D4,
        }
    }
}

#[derive(Subcommand)]
enum Commands {
    /// Apply a moving-window mean filter to a DEM
    MeanFilter {
        /// Input DEM raster
        input: PathBuf,
        /// Output raster
        output: PathBuf,
        /// Square kernel size in pixels
        #[arg(short = 'k', long, default_value_t = 3)]
        kernel_size: usize,
    },
    /// Apply a moving-window median filter to a DEM
    MedianFilter {
        /// Input DEM raster
        input: PathBuf,
        /// Output raster
        output: PathBuf,
        /// Square kernel size in pixels
        #[arg(short = 'k', long, default_value_t = 3)]
        kernel_size: usize,
    },
    /// Apply a 2D Gaussian smoothing filter to a DEM
    GaussianFilter {
        /// Input DEM raster
        input: PathBuf,
        /// Output raster
        output: PathBuf,
        /// Standard deviation (sigma) in pixels
        #[arg(short = 's', long, default_value_t = 1.0)]
        sigma: f64,
    },
    /// Extract surface depressions (sinks) and generate a refined DEM
    ExtractSinks {
        /// Input DEM raster
        input: PathBuf,
        /// Output directory
        out_dir: PathBuf,
        /// Minimum number of pixels for a depression
        #[arg(short = 'm', long, default_value_t = 1000)]
        min_size: usize,
        /// Optional pre-filled DEM raster
        #[arg(long)]
        filled_dem: Option<PathBuf>,
        /// Connectivity topology for depression filling (d8 or d4)
        #[arg(short = 't', long, value_enum, default_value_t = CliTopology::D8)]
        topology: CliTopology,
        /// Remove intermediate files and keep only the joined GeoPackage
        #[arg(long)]
        drop_intermediates: bool,
        /// Compress output GeoTIFFs with DEFLATE
        #[arg(short = 'c', long)]
        compress: bool,
        /// Print summary as JSON
        #[arg(long)]
        json: bool,
    },
    /// Delineate nested surface depression hierarchy using the level-set method (Wu et al. 2019)
    DelineateDepressions {
        /// Input sink raster (e.g., sink.tif produced by extract-sinks)
        in_sink: PathBuf,
        /// Output directory
        out_dir: PathBuf,
        /// Minimum number of pixels for a depression
        #[arg(short = 'm', long, default_value_t = 1000)]
        min_size: usize,
        /// Minimum depth of a depression
        #[arg(short = 'd', long, default_value_t = 0.3)]
        min_depth: f64,
        /// Vertical slicing interval (positive; sliced top-down)
        #[arg(short = 'i', long, default_value_t = 0.3)]
        interval: f64,
        /// Export individual shapefiles per hierarchy level under shp-level/
        #[arg(long)]
        level_shp: bool,
        /// Also export combined level GeoTIFFs when --level-shp is set
        #[arg(long, requires = "level_shp")]
        comb_tif: bool,
        /// Compress output GeoTIFFs with DEFLATE
        #[arg(short = 'c', long)]
        compress: bool,
        /// Print summary as JSON
        #[arg(long)]
        json: bool,
    },
    /// Delineate nested hierarchy of elevated features (mounts / peaks / canopies)
    DelineateMounts {
        /// Input DEM or DSM raster
        input: PathBuf,
        /// Output directory
        out_dir: PathBuf,
        /// Minimum number of pixels for a mount
        #[arg(short = 'm', long, default_value_t = 1000)]
        min_size: usize,
        /// Minimum height of a mount
        #[arg(short = 'H', long, default_value_t = 0.3)]
        min_height: f64,
        /// Vertical slicing interval
        #[arg(short = 'i', long, default_value_t = 0.3)]
        interval: f64,
        /// Export individual shapefiles per hierarchy level
        #[arg(long)]
        level_shp: bool,
        /// Compress output GeoTIFFs with DEFLATE
        #[arg(short = 'c', long)]
        compress: bool,
        /// Print summary as JSON
        #[arg(long)]
        json: bool,
    },
    /// Invert (flip) a DEM upside-down so elevated features become depressions
    FlipDem {
        /// Input DEM raster
        input: PathBuf,
        /// Output inverted DEM raster
        output: PathBuf,
        /// Base elevation offset added to the flipped DEM
        #[arg(long, default_value_t = 100.0, allow_hyphen_values = true)]
        delta: f64,
    },
    /// Polygonize a raster band into a vector file (Shapefile, GeoPackage, GeoJSON, etc.)
    Polygonize {
        /// Input raster
        input: PathBuf,
        /// Output vector file
        output: PathBuf,
        /// Output attribute field name
        #[arg(short = 'f', long, default_value = "id")]
        field_name: String,
    },
    /// Mosaic multiple rasters into a single GeoTIFF
    Mosaic {
        /// Input raster files
        #[arg(required = true)]
        inputs: Vec<PathBuf>,
        /// Output mosaic GeoTIFF
        #[arg(short = 'o', long)]
        output: PathBuf,
    },
    /// Reproject a raster to a target CRS
    Reproject {
        /// Input raster
        input: PathBuf,
        /// Output raster
        output: PathBuf,
        /// Destination CRS (e.g., EPSG:4326, EPSG:5070, WKT, or PROJ)
        #[arg(long)]
        crs: String,
        /// Resampling method (nearest, bilinear, cubic, etc.)
        #[arg(short = 'r', long, default_value = "nearest")]
        resampling: String,
        /// Optional target pixel resolution
        #[arg(long)]
        resolution: Option<f64>,
    },
    /// Resample a raster to a target pixel resolution
    Resample {
        /// Input raster
        input: PathBuf,
        /// Output raster
        output: PathBuf,
        /// Target pixel resolution
        #[arg(long)]
        resolution: f64,
        /// Resampling method (nearest, bilinear, cubic, etc.)
        #[arg(short = 'r', long, default_value = "bilinear")]
        resampling: String,
    },
    /// Clip a raster by a polygon vector mask
    Clip {
        /// Input raster
        input: PathBuf,
        /// Polygon mask vector file (GeoJSON, Shapefile, GeoPackage, etc.)
        mask: PathBuf,
        /// Output clipped raster
        output: PathBuf,
    },
    /// Convert a raster to a Cloud Optimized GeoTIFF (COG)
    ToCog {
        /// Input raster
        input: PathBuf,
        /// Output COG file
        output: PathBuf,
        /// Compression codec (DEFLATE, LZW, ZSTD, etc.)
        #[arg(short = 'c', long, default_value = "DEFLATE")]
        compression: String,
    },
    /// Assign a CRS to a raster without reprojecting pixels
    AddCrs {
        /// Input raster
        input: PathBuf,
        /// CRS string or numeric EPSG code (e.g., 4326 or EPSG:5070)
        crs: String,
        /// Output raster (overwrites input in place if omitted)
        #[arg(short = 'o', long)]
        output: Option<PathBuf>,
    },
    /// Join a CSV attribute table onto a vector file
    JoinTables {
        /// Input vector file
        in_vector: PathBuf,
        /// Input CSV file
        in_csv: PathBuf,
        /// Output vector file (.gpkg, .shp, .geojson, etc.)
        out_vector: PathBuf,
        /// Join column in vector file
        #[arg(long, default_value = "id")]
        vec_col: String,
        /// Join column in CSV file
        #[arg(long, default_value = "region_id")]
        csv_col: String,
    },
    /// Convert a CSV file with latitude/longitude columns into a WGS 84 point vector file
    CsvToVector {
        /// Input CSV file
        in_csv: PathBuf,
        /// Output vector file (.shp, .gpkg, .geojson, etc.)
        out_vector: PathBuf,
        /// Latitude column name
        #[arg(long, default_value = "latitude")]
        latitude: String,
        /// Longitude column name
        #[arg(long, default_value = "longitude")]
        longitude: String,
    },
    /// Convert a LiDAR point cloud between formats (LAS, LAZ, COPC, PLY, E57)
    ConvertLidar {
        /// Input point cloud file
        input: PathBuf,
        /// Output point cloud file
        output: PathBuf,
        /// Optional LAS point data record format (0..=10)
        #[arg(long)]
        point_format: Option<u8>,
        /// Optional LAS minor version (e.g. 4 for LAS 1.4)
        #[arg(long)]
        minor_version: Option<u8>,
    },
    /// Grid a LiDAR point cloud into a Digital Surface Model (DSM) GeoTIFF
    LidarToDsm {
        /// Input point cloud file (LAS, LAZ, COPC, PLY, E57)
        input: PathBuf,
        /// Output DSM GeoTIFF
        output: PathBuf,
        /// Output pixel resolution
        #[arg(long, default_value_t = 1.0)]
        resolution: f64,
        /// Optional search radius around each cell center
        #[arg(long)]
        radius: Option<f64>,
        /// Optional minimum Z filter
        #[arg(long, allow_hyphen_values = true)]
        min_z: Option<f64>,
        /// Optional maximum Z filter
        #[arg(long, allow_hyphen_values = true)]
        max_z: Option<f64>,
        /// Grid statistic (max, min, mean, idw, count, stdev)
        #[arg(long, default_value = "max")]
        stat: String,
        /// Gridding method (statistics, linear, nearest)
        #[arg(long, default_value = "statistics")]
        method: String,
        /// Gap-filling window size in cells (0 = none)
        #[arg(long, default_value_t = 0)]
        window_size: usize,
    },
    /// Delineate contributing catchments for extracted sinks (ports 2_Delineate_Catchment.py)
    DelineateCatchments {
        /// Partially-filled / refined DEM raster (e.g. dem.tif from extract-sinks)
        dem: PathBuf,
        /// Sink region raster (region.tif / sink.tif) or sink polygon vector (.shp / .gpkg)
        sink: PathBuf,
        /// Output directory
        out_dir: PathBuf,
        /// Compress output GeoTIFFs with DEFLATE
        #[arg(short = 'c', long)]
        compress: bool,
        /// Print summary as JSON
        #[arg(long)]
        json: bool,
    },
    /// Delineate overland spill flow paths between sinks (ports 3_Flow_Path.py)
    DelineateFlowPaths {
        /// Fully filled DEM raster (e.g. dem_filled.tif from extract-sinks)
        dem_filled: PathBuf,
        /// Sink region raster (region.tif / sink.tif) or sink polygon vector (.shp / .gpkg)
        sink: PathBuf,
        /// Output polyline vector file (.shp, .gpkg, .geojson)
        output: PathBuf,
        /// Rainfall intensity in cm/h
        #[arg(long, default_value_t = 5.0)]
        rain_intensity: f64,
        /// Optional refined/partially-filled DEM (dem.tif); required to compute sink volume, cat_area, time_inund, and rank (otherwise left 0 / unranked)
        #[arg(long)]
        refined_dem: Option<PathBuf>,
        /// Print summary as JSON
        #[arg(long)]
        json: bool,
    },
    /// Delineate nested catchment hierarchy across depression levels (ports 5_Catchment_Hierarchy.py)
    CatchmentHierarchy {
        /// Partially-filled / refined DEM raster (e.g. dem.tif from extract-sinks)
        dem: PathBuf,
        /// Directory containing Single_level_*.shp (or .tif) from delineate-depressions --level-shp
        level_dir: PathBuf,
        /// Output catchment hierarchy GeoTIFF (e.g. catchment_hir.tif)
        output: PathBuf,
        /// Compress output GeoTIFF with DEFLATE
        #[arg(short = 'c', long)]
        compress: bool,
        /// Print summary as JSON
        #[arg(long)]
        json: bool,
    },
    /// Simulate surface inundation dynamics over time (ports 6_Simulate Inundation.py)
    SimulateInundation {
        /// Input sink elevation raster (sink.tif)
        sink: PathBuf,
        /// Input catchment hierarchy raster (catchment_hir.tif)
        catchment: PathBuf,
        /// Output directory for flood_*.tif frames, fill_time.tif, and summary CSV
        out_dir: PathBuf,
        /// Minimum depression size in pixels
        #[arg(short = 'm', long, default_value_t = 1000)]
        min_size: usize,
        /// Minimum depression depth
        #[arg(short = 'd', long, default_value_t = 0.2)]
        min_depth: f64,
        /// Vertical level-set slicing interval (positive; sliced top-down)
        #[arg(short = 'i', long, default_value_t = 0.2)]
        interval: f64,
        /// Rainfall intensity in cm/h
        #[arg(long, default_value_t = 5.0)]
        rain_intensity: f64,
        /// Total rainfall duration in hours
        #[arg(long, default_value_t = 50.0)]
        duration: f64,
        /// Simulation time step in hours
        #[arg(long, default_value_t = 1.0)]
        time_step: f64,
        /// Compress output GeoTIFFs with DEFLATE
        #[arg(short = 'c', long)]
        compress: bool,
        /// Print summary as JSON
        #[arg(long)]
        json: bool,
    },
    /// Render shaded-relief inundation animation as an animated GIF (ports 7_Play_Animation.py)
    AnimateInundation {
        /// Background DEM raster (e.g. dem.tif)
        dem: PathBuf,
        /// Directory containing flood_*.tif rasters from simulate-inundation
        flood_dir: PathBuf,
        /// Output animated GIF path (e.g. inundation.gif)
        output: PathBuf,
        /// Delay between frames in milliseconds
        #[arg(long, default_value_t = 200)]
        delay_ms: u16,
        /// Play only rising water (disable rising-then-falling ping-pong playback)
        #[arg(long)]
        no_ping_pong: bool,
        /// Number of GIF loops (0 = infinite)
        #[arg(long, default_value_t = 0)]
        loops: u16,
        /// Water overlay opacity (0.0..=1.0)
        #[arg(long, default_value_t = 0.55)]
        water_alpha: f32,
        /// Optional maximum width/height in pixels for downscaling large DEMs
        #[arg(long)]
        max_dim: Option<usize>,
        /// Optional time step in hours for frame labels
        #[arg(long, default_value_t = 1.0)]
        time_step: f64,
        /// Optional rainfall intensity in cm/h for the banner title
        #[arg(long)]
        rain_intensity: Option<f64>,
        /// Hillshade azimuth in degrees
        #[arg(long, default_value_t = 135.0)]
        azimuth: f64,
        /// Hillshade elevation angle in degrees
        #[arg(long, default_value_t = 45.0)]
        elevation: f64,
    },
    /// Print metadata summary for a raster or LiDAR point cloud
    Info {
        /// Input raster or point cloud file
        input: PathBuf,
    },
}

fn run() -> lidar::Result<()> {
    let cli = Cli::parse();

    match cli.command {
        Commands::MeanFilter {
            input,
            output,
            kernel_size,
        } => {
            mean_filter_file(&input, kernel_size, Some(&output))?;
            println!("Saved mean-filtered raster to {}", output.display());
        }
        Commands::MedianFilter {
            input,
            output,
            kernel_size,
        } => {
            median_filter_file(&input, kernel_size, Some(&output))?;
            println!("Saved median-filtered raster to {}", output.display());
        }
        Commands::GaussianFilter {
            input,
            output,
            sigma,
        } => {
            gaussian_filter_file(&input, sigma, Some(&output))?;
            println!("Saved Gaussian-filtered raster to {}", output.display());
        }
        Commands::ExtractSinks {
            input,
            out_dir,
            min_size,
            filled_dem,
            topology,
            drop_intermediates,
            compress,
            json,
        } => {
            let opts = ExtractSinksOptions {
                min_size,
                filled_dem,
                topology: topology.into(),
                keep_files: !drop_intermediates,
                compress,
            };
            let res = extract_sinks(&input, &out_dir, &opts)?;
            if json {
                println!(
                    "{}",
                    serde_json::to_string_pretty(&res)
                        .map_err(|e| lidar::Error::Algorithm(e.to_string()))?
                );
            } else {
                println!("Extracted {} sink region(s)", res.depressions.len());
                if let Some(ref sink_path) = res.sink_path {
                    println!("  sink: {}", sink_path.display());
                }
                println!("  gpkg: {}", res.gpkg_path.display());
            }
        }
        Commands::DelineateDepressions {
            in_sink,
            out_dir,
            min_size,
            min_depth,
            interval,
            level_shp,
            comb_tif,
            compress,
            json,
        } => {
            let opts = DelineateOptions {
                min_size,
                min_depth,
                interval,
                bool_level_shp: level_shp,
                bool_comb_tif: comb_tif,
                compress,
            };
            let res = delineate_depressions(&in_sink, &out_dir, &opts)?;
            if json {
                println!(
                    "{}",
                    serde_json::to_string_pretty(&res)
                        .map_err(|e| lidar::Error::Algorithm(e.to_string()))?
                );
            } else {
                println!(
                    "Delineated {} nested depression(s) across {} region(s) (max level = {})",
                    res.depressions.len(),
                    res.num_regions,
                    res.max_level
                );
                println!("  depression_id:    {}", res.depression_id_path.display());
                println!(
                    "  depression_level: {}",
                    res.depression_level_path.display()
                );
                println!("  shapefile:        {}", res.shapefile_path.display());
                println!("  csv:              {}", res.csv_path.display());
            }
        }
        Commands::DelineateMounts {
            input,
            out_dir,
            min_size,
            min_height,
            interval,
            level_shp,
            compress,
            json,
        } => {
            let opts = DelineateOptions {
                min_size,
                min_depth: min_height,
                interval,
                bool_level_shp: level_shp,
                bool_comb_tif: false,
                compress,
            };
            let res = delineate_mounts(&input, &out_dir, &opts)?;
            if json {
                println!(
                    "{}",
                    serde_json::to_string_pretty(&res)
                        .map_err(|e| lidar::Error::Algorithm(e.to_string()))?
                );
            } else {
                println!(
                    "Delineated {} nested mount(s) across {} region(s) (max level = {})",
                    res.mounts.depressions.len(),
                    res.mounts.num_regions,
                    res.mounts.max_level
                );
                println!(
                    "  depression_id:    {}",
                    res.mounts.depression_id_path.display()
                );
                println!(
                    "  depression_level: {}",
                    res.mounts.depression_level_path.display()
                );
            }
        }
        Commands::FlipDem {
            input,
            output,
            delta,
        } => {
            flip_dem_file(&input, delta, Some(&output))?;
            println!("Saved flipped DEM to {}", output.display());
        }
        Commands::Polygonize {
            input,
            output,
            field_name,
        } => {
            let count = polygonize(&input, &output, &field_name)?;
            println!("Polygonized {count} feature(s) to {}", output.display());
        }
        Commands::Mosaic { inputs, output } => {
            mosaic(&inputs, &output)?;
            println!(
                "Mosaicked {} raster(s) to {}",
                inputs.len(),
                output.display()
            );
        }
        Commands::Reproject {
            input,
            output,
            crs,
            resampling,
            resolution,
        } => {
            let r = parse_resampling(&resampling)?;
            let res_pair = resolution.map(|v| (v, v));
            reproject_image(&input, &output, &crs, r, res_pair)?;
            println!("Reprojected to {} ({crs})", output.display());
        }
        Commands::Resample {
            input,
            output,
            resolution,
            resampling,
        } => {
            let r = parse_resampling(&resampling)?;
            resample(&input, &output, resolution, r)?;
            println!(
                "Resampled to {} (resolution={resolution})",
                output.display()
            );
        }
        Commands::Clip {
            input,
            mask,
            output,
        } => {
            clip_image(&input, &mask, &output)?;
            println!("Clipped raster saved to {}", output.display());
        }
        Commands::ToCog {
            input,
            output,
            compression,
        } => {
            image_to_cog(&input, &output, Some(&compression))?;
            println!("Saved COG to {}", output.display());
        }
        Commands::AddCrs { input, crs, output } => {
            add_crs(&input, &crs, output.as_deref())?;
            let target = output.as_deref().unwrap_or(&input);
            println!("Assigned CRS {crs} to {}", target.display());
        }
        Commands::JoinTables {
            in_vector,
            in_csv,
            out_vector,
            vec_col,
            csv_col,
        } => {
            let count = join_csv_to_vector(&in_vector, &in_csv, &out_vector, &vec_col, &csv_col)?;
            println!("Joined {count} feature(s) to {}", out_vector.display());
        }
        Commands::CsvToVector {
            in_csv,
            out_vector,
            latitude,
            longitude,
        } => {
            let count = csv_points_to_vector(&in_csv, &out_vector, &latitude, &longitude)?;
            println!("Converted {count} point(s) to {}", out_vector.display());
        }
        Commands::ConvertLidar {
            input,
            output,
            point_format,
            minor_version,
        } => {
            let n = convert_lidar(&input, &output, point_format, minor_version)?;
            println!("Converted {n} point(s) to {}", output.display());
        }
        Commands::LidarToDsm {
            input,
            output,
            resolution,
            radius,
            min_z,
            max_z,
            stat,
            method,
            window_size,
        } => {
            let opts = LidarToDsmOptions {
                resolution,
                radius,
                min_z,
                max_z,
                stat: GridStat::parse(&stat)?,
                method: GridMethod::parse(&method)?,
                window_size,
                ..Default::default()
            };
            let (cols, rows) = lidar_to_dsm(&input, &output, &opts)?;
            println!("Generated {cols}x{rows} DSM at {}", output.display());
        }
        Commands::DelineateCatchments {
            dem,
            sink,
            out_dir,
            compress,
            json,
        } => {
            let res = delineate_catchments(
                &dem,
                &sink,
                &out_dir,
                &DelineateCatchmentsOptions { compress },
            )?;
            if json {
                println!(
                    "{}",
                    serde_json::to_string_pretty(&res)
                        .map_err(|e| lidar::Error::Algorithm(e.to_string()))?
                );
            } else {
                println!(
                    "Delineated {} catchment(s):\n  watershed: {}\n  vector:    {}\n  csv:       {}",
                    res.records.len(),
                    res.watershed_path.display(),
                    res.vector_path.display(),
                    res.csv_path.display(),
                );
            }
        }
        Commands::DelineateFlowPaths {
            dem_filled,
            sink,
            output,
            rain_intensity,
            refined_dem,
            json,
        } => {
            let res = delineate_flow_paths(
                &dem_filled,
                &sink,
                &output,
                &DelineateFlowPathsOptions {
                    rain_intensity_cm_h: rain_intensity,
                    refined_dem,
                },
            )?;
            if json {
                println!(
                    "{}",
                    serde_json::to_string_pretty(&res)
                        .map_err(|e| lidar::Error::Algorithm(e.to_string()))?
                );
            } else {
                println!(
                    "Delineated {} flow path(s):\n  vector: {}\n  csv:    {}",
                    res.records.len(),
                    res.flowpath_vector_path.display(),
                    res.csv_path.display(),
                );
            }
        }
        Commands::CatchmentHierarchy {
            dem,
            level_dir,
            output,
            compress,
            json,
        } => {
            let res = delineate_catchment_hierarchy(
                &dem,
                &level_dir,
                &output,
                &CatchmentHierarchyOptions { compress },
            )?;
            if json {
                println!(
                    "{}",
                    serde_json::to_string_pretty(&res)
                        .map_err(|e| lidar::Error::Algorithm(e.to_string()))?
                );
            } else {
                println!(
                    "Delineated catchment hierarchy ({} feature(s) across {} level(s)):\n  raster: {}\n  merged: {}\n  csv:    {}",
                    res.records.len(),
                    res.level_shapefiles.len(),
                    res.catchment_raster_path.display(),
                    res.merged_shapefile_path.display(),
                    res.csv_path.display(),
                );
            }
        }
        Commands::SimulateInundation {
            sink,
            catchment,
            out_dir,
            min_size,
            min_depth,
            interval,
            rain_intensity,
            duration,
            time_step,
            compress,
            json,
        } => {
            let opts = SimulateInundationOptions {
                min_size,
                min_depth,
                interval,
                rain_intensity_cm_h: rain_intensity,
                rain_duration_h: duration,
                time_step_h: time_step,
                compress,
            };
            let res = simulate_inundation(&sink, &catchment, &out_dir, &opts)?;
            if json {
                println!(
                    "{}",
                    serde_json::to_string_pretty(&res)
                        .map_err(|e| lidar::Error::Algorithm(e.to_string()))?
                );
            } else {
                println!(
                    "Simulated {} timestep(s) across {} region(s):\n  fill_time: {}\n  summary:   {}",
                    res.steps.len(),
                    res.num_regions,
                    res.fill_time_path.display(),
                    res.summary_csv_path.display(),
                );
            }
        }
        Commands::AnimateInundation {
            dem,
            flood_dir,
            output,
            delay_ms,
            no_ping_pong,
            loops,
            water_alpha,
            max_dim,
            time_step,
            rain_intensity,
            azimuth,
            elevation,
        } => {
            let opts = AnimateInundationOptions {
                frame_delay_ms: delay_ms,
                ping_pong: !no_ping_pong,
                loops,
                water_alpha,
                max_dimension: max_dim,
                time_step_h: Some(time_step),
                rain_intensity_cm_h: rain_intensity,
                hillshade: HillshadeOptions {
                    azimuth_deg: azimuth,
                    elevation_deg: elevation,
                    ..Default::default()
                },
                ..Default::default()
            };
            let res = animate_inundation(&dem, &flood_dir, &output, &opts)?;
            println!(
                "Rendered {} frame(s) ({}x{}) to {}",
                res.frame_count,
                res.width,
                res.height,
                res.gif_path.display(),
            );
        }
        Commands::Info { input } => {
            let p_str = input.to_str().ok_or_else(|| {
                lidar::Error::InvalidArgument(format!("non-UTF-8 path: {}", input.display()))
            })?;
            let opts = terrio::info::InfoOptions {
                statistics: false,
                ..Default::default()
            };
            println!("{}", terrio::info::info_path(p_str, &opts)?.to_text());
        }
    }

    Ok(())
}

fn main() -> ExitCode {
    match run() {
        Ok(()) => ExitCode::SUCCESS,
        Err(e) => {
            eprintln!("error: {e}");
            ExitCode::FAILURE
        }
    }
}