Skip to main content

geolith_tiles_builder/reconstruct/
mod.rs

1//! Drone-video photogrammetry pipeline: video → 3D Gaussian Splatting → 3D Tiles.
2//!
3//! Orchestrates the full end-to-end reconstruction chain that turns a drone
4//! video into OGC 3D Tiles renderable in a web map:
5//!
6//! ```text
7//! drone video
8//!    │  ffmpeg frame extraction (stage 1)
9//!    ▼
10//! frames/  +  COLMAP sparse reconstruction (stage 2)
11//!    │  cameras.bin / images.bin / points3D.bin
12//!    ▼
13//! brush 3DGS training (stage 3)
14//!    │  exported PLY
15//!    ▼
16//! splat-tiles octree subdivision (stage 4)
17//!    │  tileset.json + tiles/*.glb + scene.spz
18//!    ▼
19//! v-maplibre VLayerSplat / VLayer3DTiles
20//! ```
21//!
22//! Each stage shells out to an external tool following the `osmium`
23//! integration precedent: `ffmpeg` (frames), `colmap` (`SfM`), `brush-cli`
24//! (3DGS training). The final tiling stage runs entirely in-process on the
25//! [`crate::splat`] module.
26//!
27//! Stage outputs are written under a single working directory so the
28//! pipeline is resumable: re-running with the same `--output` skips stages
29//! whose outputs already exist.
30
31mod frames;
32mod sfm;
33mod train;
34
35use std::path::{Path, PathBuf};
36
37/// Description of a single pipeline stage, used for status logging.
38#[derive(Debug, Clone, Copy, PartialEq, Eq)]
39enum Stage {
40    /// Video frame extraction via ffmpeg.
41    Frames,
42    /// COLMAP sparse reconstruction (poses + points).
43    Sfm,
44    /// Brush 3DGS training.
45    Train,
46    /// In-process splat-tiles subdivision.
47    Tile,
48}
49
50impl Stage {
51    /// Human-readable stage name for tracing.
52    #[must_use]
53    const fn name(self) -> &'static str {
54        match self {
55            Self::Frames => "frames",
56            Self::Sfm => "sfm",
57            Self::Train => "train",
58            Self::Tile => "tile",
59        }
60    }
61}
62
63/// Output layout of the reconstruction pipeline under the working directory.
64#[derive(Debug)]
65struct Layout {
66    /// Working directory root (`--output`).
67    root: PathBuf,
68    /// Extracted video frames.
69    frames: PathBuf,
70    /// COLMAP database.
71    database: PathBuf,
72    /// COLMAP sparse model output (`sparse/0/`).
73    sparse: PathBuf,
74    /// Brush PLY export directory.
75    exports: PathBuf,
76    /// Final 3D Tiles output directory.
77    tiles: PathBuf,
78}
79
80impl Layout {
81    /// Derive the output layout for a working directory.
82    #[must_use]
83    fn new(root: &Path) -> Self {
84        Self {
85            root: root.to_path_buf(),
86            frames: root.join("frames"),
87            database: root.join("colmap.db"),
88            sparse: root.join("sparse"),
89            exports: root.join("exports"),
90            tiles: root.join("tiles"),
91        }
92    }
93
94    /// Create all output directories.
95    ///
96    /// # Errors
97    ///
98    /// Returns an error if any directory cannot be created.
99    fn create_dirs(&self) -> crate::error::Result<()> {
100        std::fs::create_dir_all(&self.frames)?;
101        std::fs::create_dir_all(&self.sparse)?;
102        std::fs::create_dir_all(&self.exports)?;
103        std::fs::create_dir_all(&self.tiles)?;
104        Ok(())
105    }
106
107    /// Whether a stage's output already exists (used for resume).
108    #[must_use]
109    fn stage_done(&self, stage: Stage) -> bool {
110        match stage {
111            Stage::Frames => std::fs::read_dir(&self.frames)
112                .map(|entries| {
113                    entries.filter_map(std::result::Result::ok).any(|entry| {
114                        entry
115                            .path()
116                            .extension()
117                            .and_then(|ext| ext.to_str())
118                            .is_some_and(|ext| matches!(ext, "jpg" | "jpeg" | "png"))
119                    })
120                })
121                .unwrap_or(false),
122            Stage::Sfm => self.sparse.join("0").join("cameras.bin").is_file(),
123            Stage::Train => self.exports.join("scene.ply").is_file(),
124            Stage::Tile => self.tiles.join("tileset.json").is_file(),
125        }
126    }
127}
128
129/// Options for the drone-video reconstruction pipeline.
130#[derive(Debug, Clone)]
131pub struct ReconstructOptions {
132    /// Frame extraction rate in frames per second.
133    pub fps: f64,
134    /// Maximum number of frames to extract (optional cap).
135    pub max_frames: Option<usize>,
136    /// COLMAP binary path (default: `colmap` on `$PATH`).
137    pub colmap_bin: String,
138    /// Brush CLI binary path (default: `brush-cli` on `$PATH`).
139    pub brush_bin: String,
140    /// Total brush training iterations.
141    pub train_iters: u32,
142    /// Longitude of the scene anchor in degrees.
143    pub longitude: f64,
144    /// Latitude of the scene anchor in degrees.
145    pub latitude: f64,
146    /// Height of the scene anchor above the ellipsoid in metres.
147    pub altitude: f64,
148    /// Trim this percentage from both ends of every axis before tiling.
149    pub crop_percentile: f64,
150    /// Trim this percentage from the far end of the radial distance
151    /// distribution from the cloud centroid before tiling.
152    pub crop_radial_percentile: f64,
153    /// Uniform scale factor applied to the scene.
154    pub scale: f32,
155    /// Coverage boost applied before encoding (0 disables it).
156    pub coverage_boost_scale: f32,
157    /// Maximum splats stored in a single tile.
158    pub max_splats_per_tile: usize,
159    /// Maximum octree depth.
160    pub max_depth: u8,
161    /// Geometric error assigned to the root tile.
162    pub root_geometric_error: f64,
163    /// Whether to emit a standalone `scene.spz` alongside the tileset.
164    pub emit_scene_spz: bool,
165}
166
167impl Default for ReconstructOptions {
168    fn default() -> Self {
169        Self {
170            fps: 2.0,
171            max_frames: None,
172            colmap_bin: "colmap".to_owned(),
173            brush_bin: "brush-cli".to_owned(),
174            train_iters: 30_000,
175            longitude: 0.0,
176            latitude: 0.0,
177            altitude: 0.0,
178            crop_percentile: 0.0,
179            crop_radial_percentile: 0.0,
180            scale: 1.0,
181            coverage_boost_scale: 0.0,
182            max_splats_per_tile: 100_000,
183            max_depth: 6,
184            root_geometric_error: 64.0,
185            emit_scene_spz: true,
186        }
187    }
188}
189
190/// Run the full drone-video reconstruction pipeline into `output`.
191///
192/// Stages whose outputs already exist are skipped, making the pipeline
193/// resumable across partial failures.
194///
195/// # Errors
196///
197/// Returns an error if any stage fails: ffmpeg extraction, COLMAP sparse
198/// reconstruction, brush training, or tile writing.
199pub fn run_reconstruct(
200    video: &Path,
201    output: &Path,
202    options: &ReconstructOptions,
203) -> crate::error::Result<()> {
204    let layout = Layout::new(output);
205    layout.create_dirs()?;
206
207    run_stage(Stage::Frames, &layout, || {
208        frames::extract_frames(video, &layout.frames, options.fps, options.max_frames)
209    })?;
210
211    run_stage(Stage::Sfm, &layout, || {
212        sfm::run_colmap(&layout, &options.colmap_bin)
213    })?;
214
215    run_stage(Stage::Train, &layout, || {
216        train::train_splats(&layout, &options.brush_bin, options.train_iters)
217    })?;
218
219    let ply = layout.exports.join("scene.ply");
220    let stats = run_stage(Stage::Tile, &layout, || {
221        tile_ply(&ply, &layout.tiles, options)
222    })?;
223
224    tracing::info!(
225        output = %layout.tiles.display(),
226        tiles = stats.as_ref().map(|s| s.tiles).unwrap_or_default(),
227        splats = stats.as_ref().map(|s| s.splats).unwrap_or_default(),
228        max_depth = stats.as_ref().map(|s| s.max_depth).unwrap_or_default(),
229        "reconstruction complete — tileset ready"
230    );
231    Ok(())
232}
233
234/// Run a single stage, skipping it when its output already exists.
235///
236/// Returns `None` when the stage was skipped.
237///
238/// # Errors
239///
240/// Returns the stage's error when it runs and fails.
241fn run_stage<T>(
242    stage: Stage,
243    layout: &Layout,
244    f: impl FnOnce() -> crate::error::Result<T>,
245) -> crate::error::Result<Option<T>> {
246    if layout.stage_done(stage) {
247        tracing::info!(stage = stage.name(), "stage already complete — skipping");
248        return Ok(None);
249    }
250    tracing::info!(stage = stage.name(), "running stage");
251    f().map(Some)
252}
253
254/// Subdivide a trained PLY into an OGC 3D Tiles tileset.
255///
256/// Reuses the [`crate::splat`] module in-process; no external tool.
257///
258/// # Errors
259///
260/// Returns an error if the PLY cannot be read or the tileset written.
261fn tile_ply(
262    ply: &Path,
263    tiles_dir: &Path,
264    options: &ReconstructOptions,
265) -> crate::error::Result<crate::splat::tileset::SplatTilesetStats> {
266    tracing::info!(ply = %ply.display(), "reading trained splat PLY");
267    let mut cloud = crate::splat::read_splat_ply(ply)?;
268    tracing::info!(
269        splats = cloud.len(),
270        sh_degree = cloud.sh_degree,
271        "splat cloud loaded"
272    );
273
274    if options.crop_percentile > 0.0 {
275        let before = cloud.len();
276        cloud = cloud.crop_percentile(options.crop_percentile)?;
277        tracing::info!(
278            kept = cloud.len(),
279            dropped = before - cloud.len(),
280            percentile = options.crop_percentile,
281            "cropped far-field splats"
282        );
283    }
284    if options.crop_radial_percentile > 0.0 {
285        let before = cloud.len();
286        cloud = cloud.crop_radial_percentile(options.crop_radial_percentile)?;
287        tracing::info!(
288            kept = cloud.len(),
289            dropped = before - cloud.len(),
290            percentile = options.crop_radial_percentile,
291            "cropped radial far-field splats"
292        );
293    }
294    cloud.rescale(options.scale);
295    if options.coverage_boost_scale > 0.0 {
296        cloud.coverage_boost(options.coverage_boost_scale);
297        tracing::info!(
298            boost = options.coverage_boost_scale,
299            "applied coverage boost"
300        );
301    }
302
303    let tileset_options = crate::splat::tileset::SplatTilesetOptions {
304        longitude: options.longitude,
305        latitude: options.latitude,
306        altitude: options.altitude,
307        max_splats_per_tile: options.max_splats_per_tile,
308        max_depth: options.max_depth,
309        root_geometric_error: options.root_geometric_error,
310        antialiased: false,
311    };
312    let stats = crate::splat::write_splat_tileset(&cloud, tiles_dir, &tileset_options)?;
313    tracing::info!(
314        output = %tiles_dir.display(),
315        tiles = stats.tiles,
316        splats = stats.splats,
317        max_depth = stats.max_depth,
318        "3D Tiles tileset written"
319    );
320
321    if options.emit_scene_spz {
322        let scene = tiles_dir.join("scene.spz");
323        let mut centered = cloud.clone();
324        if let Some((min, max)) = cloud.bounds() {
325            let center = [
326                (min[0] + max[0]) / 2.0,
327                (min[1] + max[1]) / 2.0,
328                (min[2] + max[2]) / 2.0,
329            ];
330            for position in &mut centered.positions {
331                position[0] -= center[0];
332                position[1] -= center[1];
333                position[2] -= center[2];
334            }
335        }
336        std::fs::write(&scene, crate::splat::encode_spz(&centered, false)?)?;
337        tracing::info!(path = %scene.display(), "standalone scene.spz written");
338    }
339
340    Ok(stats)
341}
342
343#[cfg(test)]
344mod tests {
345    use super::*;
346
347    #[test]
348    fn stage_names_are_stable() {
349        assert_eq!(Stage::Frames.name(), "frames");
350        assert_eq!(Stage::Sfm.name(), "sfm");
351        assert_eq!(Stage::Train.name(), "train");
352        assert_eq!(Stage::Tile.name(), "tile");
353    }
354
355    #[test]
356    fn layout_paths_follow_working_dir() {
357        let layout = Layout::new(Path::new("/tmp/recon"));
358        assert_eq!(layout.frames, PathBuf::from("/tmp/recon/frames"));
359        assert_eq!(layout.database, PathBuf::from("/tmp/recon/colmap.db"));
360        assert_eq!(layout.sparse, PathBuf::from("/tmp/recon/sparse"));
361        assert_eq!(layout.exports, PathBuf::from("/tmp/recon/exports"));
362        assert_eq!(layout.tiles, PathBuf::from("/tmp/recon/tiles"));
363    }
364
365    #[test]
366    fn stage_done_detects_frames() {
367        let dir = tempfile::tempdir().expect("tempdir");
368        let layout = Layout::new(dir.path());
369        assert!(!layout.stage_done(Stage::Frames));
370
371        std::fs::create_dir_all(&layout.frames).expect("frames dir");
372        std::fs::write(layout.frames.join("notes.txt"), b"x").expect("write file");
373        assert!(
374            !layout.stage_done(Stage::Frames),
375            "a non-image file is not a frame"
376        );
377        std::fs::write(layout.frames.join("0001.jpg"), b"jpeg").expect("write frame");
378        assert!(layout.stage_done(Stage::Frames));
379    }
380
381    #[test]
382    fn stage_done_detects_sparse_model() {
383        let dir = tempfile::tempdir().expect("tempdir");
384        let layout = Layout::new(dir.path());
385        assert!(!layout.stage_done(Stage::Sfm));
386
387        let model = layout.sparse.join("0");
388        std::fs::create_dir_all(&model).expect("sparse dir");
389        std::fs::write(model.join("cameras.bin"), b"bin").expect("cameras");
390        assert!(layout.stage_done(Stage::Sfm));
391    }
392
393    #[test]
394    fn stage_done_detects_ply_and_tileset() {
395        let dir = tempfile::tempdir().expect("tempdir");
396        let layout = Layout::new(dir.path());
397        assert!(!layout.stage_done(Stage::Train));
398        assert!(!layout.stage_done(Stage::Tile));
399
400        std::fs::create_dir_all(&layout.exports).expect("exports dir");
401        std::fs::write(layout.exports.join("scene.ply"), b"ply").expect("write ply");
402        assert!(layout.stage_done(Stage::Train));
403        assert!(!layout.stage_done(Stage::Tile));
404
405        std::fs::create_dir_all(&layout.tiles).expect("tiles dir");
406        std::fs::write(layout.tiles.join("tileset.json"), b"{}").expect("tileset");
407        assert!(layout.stage_done(Stage::Tile));
408    }
409
410    #[test]
411    fn run_stage_skips_when_done_and_runs_when_not() {
412        let dir = tempfile::tempdir().expect("tempdir");
413        let layout = Layout::new(dir.path());
414
415        // Not done → runs, returns Some.
416        let ran = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
417        let ran_clone = std::sync::Arc::clone(&ran);
418        let result = run_stage(Stage::Frames, &layout, || {
419            ran_clone.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
420            Ok(42)
421        })
422        .expect("run");
423        assert_eq!(result, Some(42));
424        assert_eq!(ran.load(std::sync::atomic::Ordering::SeqCst), 1);
425
426        // Done → skips, returns None without calling the closure.
427        std::fs::create_dir_all(&layout.frames).expect("frames dir");
428        std::fs::write(layout.frames.join("0001.jpg"), b"jpeg").expect("frame");
429        let result = run_stage(Stage::Frames, &layout, || -> crate::error::Result<i32> {
430            panic!("closure must not run on skip");
431        })
432        .expect("skip");
433        assert_eq!(result, None);
434    }
435}