geolith-tiles-builder 0.4.2

Builds tiles from OpenStreetMap and Overture Maps: protomaps-schema vector PMTiles, Terrain-RGB, raster archives and 3D Tiles from Gaussian splats
Documentation
//! Stage 3: 3D Gaussian Splatting training via brush.
//!
//! Invokes the `brush-cli` headless trainer against the COLMAP sparse model
//! produced by stage 2. Brush consumes COLMAP format natively (it searches
//! the dataset for `sparse/*/cameras.bin`), trains a Gaussian splat
//! representation, and exports a standard Nerfstudio-style PLY that the
//! [`crate::splat`] tiler reads in-process in stage 4.
//!
//! The export path is resolved relative to the layout root; `{dataset}`
//! interpolation is not needed since we pass an absolute export directory.

use std::process::{Command, Stdio};

use super::Layout;

/// Train a 3DGS scene with brush for `train_iters` iterations.
///
/// The trained PLY is written to `exports/scene.ply` under the layout root.
///
/// # Errors
///
/// Returns an error if `brush-cli` is missing, training exits non-zero, or
/// the exported PLY is not produced.
pub fn train_splats(
    layout: &Layout,
    brush_bin: &str,
    train_iters: u32,
) -> crate::error::Result<()> {
    let sparse_model = layout.sparse.join("0");
    if !sparse_model.join("cameras.bin").is_file() {
        return Err(crate::error::GeolithError::Brush(format!(
            "no COLMAP sparse model in {} — run the sfm stage first",
            sparse_model.display()
        )));
    }

    // Brush reads the dataset rooted at the layout root: it discovers
    // `sparse/0/` and resolves image names relative to the same root.
    let dataset_root = &layout.root;
    let export_dir = &layout.exports;
    std::fs::create_dir_all(export_dir)?;

    let export_path = export_dir.join("scene.ply");
    // Brush resolves a relative export path against the dataset's PARENT
    // directory; make it absolute so the PLY lands exactly where the layout
    // declares it regardless of how the CLI was invoked.
    let export_arg = std::path::absolute(export_dir)
        .unwrap_or_else(|_| export_dir.clone())
        .to_str()
        .unwrap_or_default()
        .to_owned();

    let mut command = Command::new(brush_bin);
    command
        .arg(dataset_root)
        // `with-viewer` defaults to false when a source is present; passing
        // it explicitly would force the viewer-required value semantics.
        .arg("--total-train-iters")
        .arg(train_iters.to_string())
        .arg("--export-every")
        .arg(train_iters.to_string()) // only the final iteration
        .arg("--export-path")
        .arg(export_arg)
        .arg("--export-name")
        .arg("scene.ply")
        .stdin(Stdio::null())
        .stdout(Stdio::null())
        .stderr(Stdio::piped());

    tracing::info!(
        bin = brush_bin,
        dataset = %dataset_root.display(),
        iters = train_iters,
        export = %export_path.display(),
        "running brush training"
    );
    let output = command.output().map_err(|error| {
        crate::error::GeolithError::Brush(format!(
            "failed to spawn {brush_bin}: {error} (is brush installed?)"
        ))
    })?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        let last = stderr.lines().rev().take(15).collect::<Vec<_>>().join("\n");
        return Err(crate::error::GeolithError::Brush(format!(
            "{brush_bin} exited with {:?}\n{last}",
            output.status.code()
        )));
    }

    if !export_path.is_file() {
        return Err(crate::error::GeolithError::Brush(format!(
            "training finished but no PLY exported at {}",
            export_path.display()
        )));
    }

    tracing::info!(
        iters = train_iters,
        export = %export_path.display(),
        "brush training complete"
    );
    Ok(())
}

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

    #[test]
    fn train_splats_reports_missing_model() {
        let dir = tempfile::tempdir().expect("tempdir");
        let layout = Layout::new(dir.path());
        let err = train_splats(&layout, "brush-cli", 1).expect_err("must fail");
        assert!(err.to_string().contains("sfm stage"));
    }
}