visloc-rs 0.5.0

Visual localization foundation library using SfM / visual maps.
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
//! A drop-in COLMAP-CLI-compatible shim (`src/colmap/tools/*` parity slice),
//! powered by the same pipeline library as `unordered_sfm_demo`.
//!
//! Scripts written against COLMAP's command surface can drive this pipeline
//! unchanged:
//!
//! ```text
//! colmap feature_extractor --database_path db.db --image_path images/ \
//!     --ImageReader.single_camera 1 --SiftExtraction.max_features 4096
//! colmap exhaustive_matcher --database_path db.db
//! colmap mapper --database_path db.db --output_path sparse_out/
//! ```
//!
//! Self-contained: no separate SQLite database layer is required, since the
//! database module is the one COLMAP subsystem we deliberately do not port.
//! State is instead persisted under a `<db>.d/` directory next to the
//! "database" file (extracted features, verified matches, then the sparse
//! model in COLMAP text format under `--output_path/sparse/`).
//!
//! Supported subcommands and their commonly used flags:
//! - `feature_extractor`: `--database_path`, `--image_path`,
//!   `--SiftExtraction.max_features`, `--SiftExtraction.use_gpu`
//! - `exhaustive_matcher`: `--database_path`, `--SiftMatching.use_gpu`
//! - `mapper`: `--database_path`, `--output_path`, `--Mapper.min_num_matches`,
//!   `--Mapper.ba_use_gpu`, and the GPS-prior flags below
//! - `pose_prior_mapper`: `mapper` with `--Mapper.use_prior_position 1`
//! - `spatial_matcher`: `exhaustive_matcher` restricted to pairs whose GPS
//!   fixes are close (`--SpatialMatching.max_num_neighbors` 50,
//!   `--SpatialMatching.max_distance` 100 m, `--SpatialMatching.ignore_z` 1)
//!
//! GPS priors, as in COLMAP >= 3.10 (`pose_priors` + `use_prior_position`):
//! `feature_extractor` stores each image's EXIF GPS fix under `<db>.d/`, and
//! `mapper --Mapper.use_prior_position 1` (or `pose_prior_mapper`) aligns the
//! model to the fixes and keeps them as covariance-weighted camera-centre
//! priors in every global bundle adjustment, so the model comes out metric in
//! a local ENU frame (origin in `sparse/enu_origin.txt`). Flags:
//! `--prior_position_std_x/_y/_z` (metres, used where a fix states none;
//! default 1 m each, as COLMAP), `--overwrite_priors_covariance 1` (use them everywhere),
//! `--Mapper.prior_position_ransac_max_error` (alignment inlier threshold,
//! default 3 sigma), `--use_robust_loss_on_prior_position` (Cauchy loss, on
//! by default here, unlike COLMAP; `0` turns it off) with
//! `--prior_position_loss_scale` (default sqrt(chi2_95(3))),
//! and this shim's `--pose_priors_path FILE`
//! (`NAME LAT LON ALT [STD_H [STD_V]]` lines, or `NAME X Y Z ...` with
//! `--pose_priors_format cartesian`) in place of the EXIF fixes.
//!
//! The `use_gpu` flags need a build with `--features gpu` (wgpu SIFT, batched
//! GPU matching, GPU global bundle adjustment); pair verification always
//! runs in parallel.
//! - `model_converter`: `--input_path`, `--output_path`, `--output_type TXT`
//!
//! Unknown flags are ignored with a warning (so typical scripts keep going).
use std::collections::HashMap;
use std::path::{Path, PathBuf};

// Everything is reached through the `visloc_rs` facade (`src/lib.rs`).
use rayon::prelude::*;
use visloc_rs::io::gps_prior::{
    read_exif_gps, spatial_pairs, GpsPriorSet, PriorCoordinates, PriorFrame,
};
use visloc_rs::slam::incremental_sfm::{estimate_position_prior_alignment, SfmPositionPriors};
use visloc_rs::vision::features::sift::{extract_sift, GrayImage, SiftConfig};
use visloc_rs::vision::matching::DescriptorMatch;
use visloc_rs::vision::two_view::{
    ConfigurationType, TwoViewCorrespondence, TwoViewGeometryOptions, TwoViewGeometryVerifier,
};
use visloc_rs::{
    incremental_sfm, write_colmap_reconstruction_for_3dgs, BruteForceMatcher, Camera,
    CrossCheckMatcher, FeatureSet, IncrementalSfmConfig, Matcher, PairwiseMatches, Pose,
};

const IMAGE_SUFFIXES: [&str; 5] = [".png", ".jpg", ".jpeg", ".bmp", ".tiff"];

struct Args {
    flags: HashMap<String, String>,
}

impl Args {
    fn parse() -> Self {
        let mut flags = HashMap::new();
        let mut positional: Vec<String> = Vec::new();
        let mut args = std::env::args().skip(1);
        while let Some(arg) = args.next() {
            if arg.starts_with("--") {
                let key = arg.trim_start_matches("--").to_string();
                let mut value = String::new();
                if let Some(v) = args.next() {
                    // COLMAP passes the value on the next token.
                    value = v;
                }
                flags.insert(key, value);
            } else {
                positional.push(arg);
            }
        }
        if let Some(sub) = positional.first() {
            flags.insert("subcommand".to_string(), sub.clone());
        }
        Self { flags }
    }

    /// Lookup by bare key or any dotted suffix (`--SiftExtraction.max_features`
    /// matches key `max_features`).
    fn get(&self, key: &str) -> Option<&str> {
        self.flags.get(key).map(|s| s.as_str()).or_else(|| {
            self.flags
                .iter()
                .find(|(k, _)| k.ends_with(key))
                .map(|(_, v)| v.as_str())
        })
    }

    fn get_or(&self, key: &str, default: &str) -> String {
        self.get(key).unwrap_or(default).to_string()
    }

    /// COLMAP-style boolean flag (`1` / `true`); errors when a GPU flag is
    /// set on a build without the `gpu` feature.
    fn use_gpu(&self, key: &str) -> Result<bool, String> {
        let on = matches!(self.get(key), Some("1") | Some("true") | Some("True"));
        if on && !cfg!(feature = "gpu") {
            return Err(format!("--{key} needs a build with --features gpu"));
        }
        Ok(on)
    }
}

fn warn_unknown_flags(args: &Args, known: &[&str]) {
    for k in args.flags.keys() {
        if k == "subcommand" || k == "help" {
            continue;
        }
        if !known.iter().any(|n| k == n || k.ends_with(n)) {
            eprintln!("colmap-shim: ignoring unsupported flag --{k}");
        }
    }
}

fn data_dir(database_path: &Path) -> PathBuf {
    let mut name = database_path
        .file_name()
        .map(|n| n.to_string_lossy().to_string())
        .unwrap_or_else(|| "db".to_string());
    name.push_str(".d");
    database_path.parent().unwrap_or(Path::new(".")).join(name)
}

fn list_images(dir: &Path) -> Result<Vec<PathBuf>, String> {
    let mut files: Vec<PathBuf> = std::fs::read_dir(dir)
        .map_err(|e| format!("cannot read image dir {dir:?}: {e}"))?
        .filter_map(|e| e.ok())
        .map(|e| e.path())
        .filter(|p| {
            p.extension()
                .map(|x| {
                    let x = format!(".{}", x.to_string_lossy().to_lowercase());
                    IMAGE_SUFFIXES.contains(&x.as_str())
                })
                .unwrap_or(false)
        })
        .collect();
    files.sort();
    if files.is_empty() {
        return Err(format!("no images found under {dir:?}"));
    }
    Ok(files)
}

/// `X Y SCORE D…` text features, one line per keypoint — the external feature
/// format the pipeline's Files-based frontend reads back.
fn write_feature_file(
    path: &Path,
    keypoints: &[(f64, f64)],
    descriptors: &[Vec<f32>],
) -> Result<(), String> {
    let mut out = String::new();
    for ((x, y), descriptor) in keypoints.iter().zip(descriptors) {
        out.push_str(&format!("{x:.4} {y:.4} {:.4}", 1.0));
        for d in descriptor {
            out.push_str(&format!(" {d:.5}"));
        }
        out.push('\n');
    }
    std::fs::write(path, out).map_err(|e| format!("write {path:?}: {e}"))
}

fn cmd_feature_extractor(args: &Args) -> Result<(), String> {
    let db = PathBuf::from(args.get_or("database_path", "database.db"));
    let image_dir = PathBuf::from(args.get_or("image_path", "."));
    let max_keypoints: usize = args
        .get_or("SiftExtraction.max_features", "4096")
        .parse()
        .map_err(|e| format!("{e}"))?;
    let gpu = args.use_gpu("SiftExtraction.use_gpu")?;
    warn_unknown_flags(
        args,
        &[
            "database_path",
            "image_path",
            "SiftExtraction.max_features",
            "SiftExtraction.use_gpu",
        ],
    );

    #[cfg(not(feature = "image-io"))]
    {
        let _ = (db, image_dir, max_keypoints, gpu);
        Err("feature_extractor requires building with --features image-io".to_string())
    }
    #[cfg(feature = "image-io")]
    {
        let dir = data_dir(&db);
        std::fs::create_dir_all(dir.join("features"))
            .map_err(|e| format!("mkdir {:?}: {e}", dir.join("features")))?;
        let images = list_images(&image_dir)?;
        // COLMAP's SIFT: the VLFeat-compatible detector (subpixel
        // localization) and descriptor, with `gsplat_photos`' settings. The
        // GPU extractor implements the legacy detector only, so `use_gpu`
        // keeps that.
        let config = if gpu {
            SiftConfig {
                max_keypoints,
                ..SiftConfig::default()
            }
        } else {
            SiftConfig {
                max_keypoints,
                normalization: visloc_rs::vision::features::sift::SiftNormalization::L1Root,
                descriptor_magnification: 3.0,
                max_orientations: 2,
                prefer_larger_scale: true,
                vlfeat_compatible_detector: true,
                vlfeat_compatible_descriptor: true,
                vlfeat_bilinear_orientations: true,
                ..SiftConfig::default()
            }
        };
        #[cfg(feature = "gpu")]
        let mut sift_gpu = if gpu {
            let ctx = visloc_sift_gpu::GpuContext::new().map_err(|e| format!("gpu: {e}"))?;
            Some(visloc_sift_gpu::SiftGpu::new(ctx))
        } else {
            None
        };
        #[cfg(not(feature = "gpu"))]
        let _ = gpu;
        // COLMAP's feature extractor reads each image's EXIF GPS into the
        // database's pose priors; here they go to `<db>.d/gps_priors.txt`.
        let mut gps = String::from("# NAME LAT_DEG LON_DEG ALT_M (EXIF GPS)\n");
        let mut gps_count = 0usize;
        for image in &images {
            if let Some(fix) = read_exif_gps(image) {
                let name = image.file_name().unwrap().to_string_lossy();
                gps.push_str(&format!(
                    "{name} {:.9} {:.9} {}\n",
                    fix.lat_deg,
                    fix.lon_deg,
                    fix.alt_m.map_or("nan".to_string(), |a| format!("{a:.4}"))
                ));
                gps_count += 1;
            }
        }
        if gps_count > 0 {
            let gps_path = dir.join("gps_priors.txt");
            std::fs::write(&gps_path, gps).map_err(|e| format!("write {gps_path:?}: {e}"))?;
            println!(
                "feature_extractor: EXIF GPS on {gps_count}/{} images -> {gps_path:?}",
                images.len()
            );
        }
        for image in &images {
            let name = image.file_name().unwrap().to_string_lossy().to_string();
            let stem = Path::new(&name).file_stem().unwrap().to_string_lossy();
            let out_path = dir.join("features").join(format!("{stem}_features.txt"));
            if out_path.exists() {
                continue;
            }
            let image_bytes = std::fs::read(image).map_err(|e| format!("read {image:?}: {e}"))?;
            let dynamic = image::load_from_memory(&image_bytes)
                .map_err(|e| format!("decode {image:?}: {e}"))?;
            let gray = dynamic.to_luma8();
            let (w, h) = (gray.width(), gray.height());
            let pixels: Vec<f32> = gray.as_raw().iter().map(|&b| b as f32).collect();
            let gray = GrayImage::new(w as usize, h as usize, &pixels)
                .map_err(|e| format!("gray {image:?}: {e}"))?;
            #[cfg(feature = "gpu")]
            let extracted = match sift_gpu.as_mut() {
                Some(g) => g
                    .extract(&gray, &config)
                    .map_err(|e| format!("gpu sift {image:?}: {e}")),
                None => extract_sift(&gray, &config).map_err(|e| format!("sift {image:?}: {e}")),
            };
            #[cfg(not(feature = "gpu"))]
            let extracted =
                extract_sift(&gray, &config).map_err(|e| format!("sift {image:?}: {e}"));
            let (keypoints, descriptors) = extracted?;
            let kp: Vec<(f64, f64)> = keypoints.iter().map(|k| (k.x, k.y)).collect();
            write_feature_file(&out_path, &kp, &descriptors)?;
            println!("extracted {name}: {} keypoints", keypoints.len());
        }
        println!(
            "feature_extractor: {} images -> {:?}",
            images.len(),
            dir.join("features")
        );
        Ok(())
    }
}

fn load_stored_features(db: &Path) -> Result<(Vec<FeatureSet>, Vec<String>), String> {
    let dir = data_dir(db).join("features");
    let mut files: Vec<String> = std::fs::read_dir(&dir)
        .map_err(|e| format!("read {dir:?}: {e}"))?
        .filter_map(|e| e.ok())
        .filter_map(|e| e.file_name().into_string().ok())
        .filter(|n| n.ends_with("_features.txt"))
        .collect();
    files.sort();
    let mut features = Vec::new();
    let mut names = Vec::new();
    for f in files {
        let path = dir.join(&f);
        let text = std::fs::read_to_string(&path).map_err(|e| format!("read {path:?}: {e}"))?;
        let mut keypoints = Vec::new();
        let mut descriptors = Vec::new();
        for line in text.lines().filter(|l| !l.trim().is_empty()) {
            let tokens: Vec<&str> = line.split_whitespace().collect();
            if tokens.len() < 7 {
                continue;
            }
            keypoints.push(nalgebra::Point2::new(
                tokens[0].parse().map_err(|e| format!("{e}"))?,
                tokens[1].parse().map_err(|e| format!("{e}"))?,
            ));
            // `write_feature_file` stores `x y scale` then the descriptor, so
            // a 128-D SIFT row is its last 128 tokens (the old fixed offset
            // of 6 silently dropped three descriptor values).
            let start = if tokens.len() >= 3 + 128 {
                tokens.len() - 128
            } else {
                3
            };
            descriptors.push(
                tokens[start..]
                    .iter()
                    .map(|t| t.parse::<f32>().map_err(|e| format!("{e}")))
                    .collect::<Result<Vec<f32>, _>>()?,
            );
        }
        names.push(format!(
            "{}.jpg",
            f.strip_suffix("_features.txt").unwrap_or(&f)
        ));
        features.push(FeatureSet::new(keypoints, descriptors).map_err(|e| format!("{e}"))?);
    }
    Ok((features, names))
}

fn cpu_matches(fi: &FeatureSet, fj: &FeatureSet) -> Vec<DescriptorMatch> {
    let matcher = BruteForceMatcher { ratio: Some(0.8) };
    CrossCheckMatcher::new(matcher).match_descriptors(&fi.descriptors, &fj.descriptors)
}

fn verify_pair(
    camera: &Camera,
    fi: &FeatureSet,
    fj: &FeatureSet,
    dm: &[DescriptorMatch],
    min_matches: usize,
) -> Option<Vec<(usize, usize)>> {
    if dm.len() < min_matches {
        return None;
    }
    let corrs: Vec<TwoViewCorrespondence> = dm
        .iter()
        .map(|m| {
            TwoViewCorrespondence::new(fi.keypoints[m.query_index], fj.keypoints[m.train_index])
        })
        .collect();
    let verifier = TwoViewGeometryVerifier::new(TwoViewGeometryOptions::for_camera(camera, 4.0));
    let report = verifier.classify(&corrs, camera);
    let keep = matches!(
        report.config,
        ConfigurationType::Calibrated | ConfigurationType::Uncalibrated
    );
    if !keep || report.inliers.len() < min_matches {
        return None;
    }
    Some(
        report
            .inliers
            .iter()
            .map(|&idx| (dm[idx].query_index, dm[idx].train_index))
            .collect(),
    )
}

fn cmd_exhaustive_matcher(args: &Args) -> Result<(), String> {
    cmd_matcher(args, false)
}

/// COLMAP's `spatial_matcher`: only pairs whose GPS fixes are near each
/// other (`--SpatialMatching.max_num_neighbors` 50,
/// `--SpatialMatching.max_distance` 100 m, `--SpatialMatching.ignore_z` 1).
fn cmd_spatial_matcher(args: &Args) -> Result<(), String> {
    cmd_matcher(args, true)
}

fn cmd_matcher(args: &Args, spatial: bool) -> Result<(), String> {
    let db = PathBuf::from(args.get_or("database_path", "database.db"));
    let gpu = args.use_gpu("SiftMatching.use_gpu")?;
    warn_unknown_flags(
        args,
        &[
            "database_path",
            "SiftMatching.use_gpu",
            "SpatialMatching.max_num_neighbors",
            "SpatialMatching.max_distance",
            "SpatialMatching.ignore_z",
            "pose_priors_path",
            "pose_priors_format",
        ],
    );
    #[cfg(not(feature = "gpu"))]
    let _ = gpu;
    let (features, names) = load_stored_features(&db)?;
    let (w, h) = (1600u32, 1066u32);
    let fx = 0.55 * w as f64;
    let camera = Camera::pinhole(1, w, h, fx, fx, w as f64 / 2.0, h as f64 / 2.0);

    let all: Vec<(usize, usize)> = if spatial {
        let (priors, _) = load_position_priors(args, &db, &names)?;
        let positions: Vec<_> = priors
            .priors
            .iter()
            .map(|p| p.map(|p| p.position))
            .collect();
        let max_neighbors: usize = args
            .get_or("SpatialMatching.max_num_neighbors", "50")
            .parse()
            .map_err(|e| format!("max_num_neighbors: {e}"))?;
        let max_distance = parse_f64(args, "SpatialMatching.max_distance", 100.0)?;
        let ignore_z = !matches!(
            args.get("SpatialMatching.ignore_z"),
            Some("0") | Some("false")
        );
        let pairs = spatial_pairs(&positions, max_neighbors, max_distance, ignore_z);
        println!(
            "spatial_matcher: {} candidate pairs (up to {max_neighbors} neighbours within {max_distance} m)",
            pairs.len()
        );
        pairs
    } else {
        (0..names.len())
            .flat_map(|i| ((i + 1)..names.len()).map(move |j| (i, j)))
            .collect()
    };
    let total = all.len();
    #[cfg(feature = "gpu")]
    let gpu_bank = if gpu {
        let ctx = visloc_sift_gpu::GpuContext::new().map_err(|e| format!("gpu: {e}"))?;
        let sets: Vec<&[Vec<f32>]> = features.iter().map(|f| f.descriptors.as_slice()).collect();
        let bank = visloc_sift_gpu::FeatureBank::upload(&ctx, &sets)
            .map_err(|e| format!("gpu feature bank: {e}"))?;
        let matcher = visloc_sift_gpu::GpuMatcher::new(&ctx);
        Some((ctx, bank, matcher))
    } else {
        None
    };
    // Chunked so the raw matches of an exhaustive run never all sit in
    // memory at once: match a chunk (one batched GPU pass, or per pair on
    // the CPU), then verify it in parallel (seeded RANSAC: deterministic).
    let mut pairs: Vec<PairwiseMatches> = Vec::new();
    let mut done = 0usize;
    for chunk in all.chunks(2048) {
        #[cfg(feature = "gpu")]
        let chunk_matches: Option<Vec<Vec<DescriptorMatch>>> =
            gpu_bank.as_ref().and_then(|(ctx, bank, m)| {
                m.match_pairs(ctx, bank, chunk, Some(0.8), true)
                    .map_err(|e| eprintln!("GPU matching failed ({e}); this chunk on the CPU"))
                    .ok()
            });
        #[cfg(not(feature = "gpu"))]
        let chunk_matches: Option<Vec<Vec<DescriptorMatch>>> = None;
        let verified: Vec<PairwiseMatches> = chunk
            .par_iter()
            .enumerate()
            .filter_map(|(c, &(i, j))| {
                let dm = match &chunk_matches {
                    Some(all) => std::borrow::Cow::Borrowed(&all[c]),
                    None => std::borrow::Cow::Owned(cpu_matches(&features[i], &features[j])),
                };
                verify_pair(&camera, &features[i], &features[j], &dm, 20).map(|matches| {
                    PairwiseMatches {
                        image_i: i,
                        image_j: j,
                        matches,
                        two_view_config: None,
                        essential_matches: None,
                        essential_matrix: None,
                    }
                })
            })
            .collect();
        pairs.extend(verified);
        done += chunk.len();
        println!("matched {done}/{total}");
    }
    let dir = data_dir(&db);
    std::fs::create_dir_all(&dir).map_err(|e| format!("{e}"))?;
    let path = dir.join("matches.txt");
    let mut text = format!("{}\n", names.len());
    for n in &names {
        text.push_str(&format!("{n}\n"));
    }
    text.push_str(&format!("{}\n", pairs.len()));
    for pair in &pairs {
        text.push_str(&format!(
            "{} {} {}\n",
            pair.image_i,
            pair.image_j,
            pair.matches.len()
        ));
        for (qi, tj) in &pair.matches {
            text.push_str(&format!("{qi} {tj}\n"));
        }
    }
    std::fs::write(&path, text).map_err(|e| format!("write {path:?}: {e}"))?;
    println!(
        "{}: verified {}/{} pairs -> {path:?}",
        if spatial {
            "spatial_matcher"
        } else {
            "exhaustive_matcher"
        },
        pairs.len(),
        total
    );
    Ok(())
}

/// A COLMAP-style `0`/`1` flag.
fn flag(args: &Args, key: &str) -> bool {
    matches!(args.get(key), Some("1") | Some("true") | Some("True"))
}

fn parse_f64(args: &Args, key: &str, default: f64) -> Result<f64, String> {
    args.get(key).map_or(Ok(default), |v| {
        v.parse().map_err(|e| format!("--{key} {v:?}: {e}"))
    })
}

/// The GPS priors of `names` for `--Mapper.use_prior_position`: the
/// `--pose_priors_path` file, else the feature extractor's EXIF fixes.
fn load_position_priors(
    args: &Args,
    db: &Path,
    names: &[String],
) -> Result<(SfmPositionPriors, PriorFrame), String> {
    let (path, coordinates) = match args.get("pose_priors_path") {
        Some(path) => (
            PathBuf::from(path),
            args.get_or("pose_priors_format", "wgs84")
                .parse::<PriorCoordinates>()?,
        ),
        None => (data_dir(db).join("gps_priors.txt"), PriorCoordinates::Wgs84),
    };
    if !path.exists() {
        return Err(format!(
            "GPS priors needed: no {path:?} (the feature extractor \
             writes it from EXIF GPS; or pass --pose_priors_path)"
        ));
    }
    let mut set = GpsPriorSet::read(&path, coordinates).map_err(|e| e.to_string())?;
    let std_x = parse_f64(args, "prior_position_std_x", 1.0)?;
    let std_y = parse_f64(args, "prior_position_std_y", std_x)?;
    let std_z = parse_f64(args, "prior_position_std_z", 1.0)?;
    if flag(args, "overwrite_priors_covariance") {
        for prior in set.priors.values_mut() {
            prior.std_horizontal_m = None;
            prior.std_vertical_m = None;
        }
    }
    let (local, frame) = set.to_local_enu(names, None, nalgebra::Vector3::new(std_x, std_y, std_z));
    let mut priors = SfmPositionPriors::from_local_priors(&local);
    // Cauchy loss on by default (COLMAP's default is off): see
    // docs/gps_prior_sfm.md. `--use_robust_loss_on_prior_position 0` turns it off.
    priors.robust_loss_scale = None;
    if !matches!(
        args.get("use_robust_loss_on_prior_position"),
        Some("0") | Some("false") | Some("False")
    ) {
        priors.robust_loss_scale = Some(parse_f64(
            args,
            "prior_position_loss_scale",
            visloc_rs::slam::incremental_sfm::DEFAULT_PRIOR_LOSS_SCALE,
        )?);
    }
    if let Some(max_error) = args.get("prior_position_ransac_max_error") {
        priors.alignment_max_error = Some(
            max_error
                .parse()
                .map_err(|e| format!("ransac max error: {e}"))?,
        );
    }
    println!(
        "GPS priors for {}/{} images from {path:?}",
        priors.num_priors(),
        names.len()
    );
    Ok((priors, frame))
}

fn cmd_mapper(args: &Args) -> Result<(), String> {
    cmd_mapper_with(args, false)
}

fn cmd_mapper_with(args: &Args, force_prior_position: bool) -> Result<(), String> {
    let db = PathBuf::from(args.get_or("database_path", "database.db"));
    let output = PathBuf::from(args.get_or("output_path", "sparse"));
    let min_matches: usize = args
        .get_or("Mapper.min_num_matches", "20")
        .parse()
        .map_err(|e| format!("{e}"))?;
    let ba_gpu = args.use_gpu("Mapper.ba_use_gpu")?;
    warn_unknown_flags(
        args,
        &[
            "database_path",
            "output_path",
            "Mapper.min_num_matches",
            "Mapper.ba_use_gpu",
            "use_prior_position",
            "prior_position_std_x",
            "prior_position_std_y",
            "prior_position_std_z",
            "overwrite_priors_covariance",
            "prior_position_ransac_max_error",
            "use_robust_loss_on_prior_position",
            "prior_position_loss_scale",
            "pose_priors_path",
            "pose_priors_format",
        ],
    );
    #[cfg(feature = "gpu")]
    if ba_gpu {
        // Global bundle adjustments of the incremental mapper on the GPU.
        let ctx = visloc_ba_gpu::GpuContext::new().map_err(|e| format!("gpu: {e}"))?;
        visloc_rs::slam::set_ba_accelerator(Box::new(visloc_ba_gpu::GpuBundleAdjuster::new(ctx)));
    }
    #[cfg(not(feature = "gpu"))]
    let _ = ba_gpu;
    let (features, names) = load_stored_features(&db)?;
    let matches_path = data_dir(&db).join("matches.txt");
    if !matches_path.exists() {
        return Err(format!(
            "no matches at {matches_path:?}; run `exhaustive_matcher` first"
        ));
    }
    let matches_text = std::fs::read_to_string(&matches_path).map_err(|e| format!("{e}"))?;
    let lines: Vec<&str> = matches_text.lines().collect();
    let mut cursor = 0usize;
    let next_line = |cursor: &mut usize| -> &str {
        let l = lines[*cursor];
        *cursor += 1;
        l
    };
    let name_count: usize = next_line(&mut cursor)
        .trim()
        .parse()
        .map_err(|e| format!("{e}"))?;
    for _ in 0..name_count {
        next_line(&mut cursor);
    }
    let pair_count: usize = next_line(&mut cursor)
        .trim()
        .parse()
        .map_err(|e| format!("{e}"))?;
    let mut pairwise = Vec::new();
    for _ in 0..pair_count {
        let head: Vec<usize> = next_line(&mut cursor)
            .split_whitespace()
            .map(|t| t.parse().map_err(|e| format!("{e}")))
            .collect::<Result<_, _>>()?;
        let count = head[2];
        let mut matches = Vec::with_capacity(count);
        for _ in 0..count {
            let m: Vec<usize> = next_line(&mut cursor)
                .split_whitespace()
                .map(|t| t.parse().map_err(|e| format!("{e}")))
                .collect::<Result<_, _>>()?;
            matches.push((m[0], m[1]));
        }
        pairwise.push(PairwiseMatches {
            image_i: head[0],
            image_j: head[1],
            matches,
            two_view_config: None,
            essential_matches: None,
            essential_matrix: None,
        });
    }

    let (w, h) = (1600u32, 1066u32);
    let fx = 0.55 * w as f64;
    let camera = Camera::pinhole(1, w, h, fx, fx, w as f64 / 2.0, h as f64 / 2.0);
    let use_prior_position = force_prior_position || flag(args, "Mapper.use_prior_position");
    let (position_priors, prior_frame) = if use_prior_position {
        let (priors, frame) = load_position_priors(args, &db, &names)?;
        (Some(priors), Some(frame))
    } else {
        (None, None)
    };
    let config = IncrementalSfmConfig {
        min_seed_matches: min_matches,
        position_priors: position_priors.clone(),
        ..IncrementalSfmConfig::default()
    };
    let result = incremental_sfm(&camera, &features, &pairwise, &config)
        .map_err(|e| format!("mapper failed: {e}"))?;
    if let (Some(priors), Some(frame)) = (position_priors.as_ref(), prior_frame.as_ref()) {
        match estimate_position_prior_alignment(&result.poses, priors) {
            Some(check) => {
                println!(
                    "mapper: GPS priors: {}/{} registered prior images agree, RMSE {:.3} m (residual scale {:.4})",
                    check.inliers.len(),
                    check.num_candidates,
                    check.inlier_rmse,
                    check.similarity.scale
                );
                let sparse = output.join("sparse");
                std::fs::create_dir_all(&sparse).map_err(|e| format!("mkdir {sparse:?}: {e}"))?;
                let origin = sparse.join("enu_origin.txt");
                std::fs::write(&origin, frame.describe())
                    .map_err(|e| format!("write {origin:?}: {e}"))?;
            }
            None => println!(
                "mapper: GPS priors were not used (fewer than {} registered images with a prior); the model keeps an arbitrary frame and scale",
                priors.min_num_priors
            ),
        }
    }

    // Write a COLMAP text model (cameras/images/points3D) via the exporter.
    type LandmarkObs = (usize, usize, nalgebra::Point2<f64>);
    type Landmark = (nalgebra::Point3<f64>, Vec<LandmarkObs>);
    let mut poses_out: Vec<Pose> = Vec::new();
    let mut features_out: Vec<FeatureSet> = Vec::new();
    let mut landmarks: Vec<Landmark> = Vec::new();
    // Align exporters to registered images only: build an index map from
    // original image id -> compact writer slot.
    let mut slot = 0usize;
    let mut id_slot = std::collections::HashMap::new();
    for (id, pose) in result.poses.iter().enumerate() {
        if let Some(p) = pose {
            id_slot.insert(id, slot);
            poses_out.push(p.clone());
            features_out.push(features[id].clone());
            slot += 1;
        }
    }
    for track in &result.tracks {
        let obs: Vec<LandmarkObs> = track
            .observations
            .iter()
            .filter_map(|(img, kp, px)| {
                let slot = *id_slot.get(img)?;
                Some((slot, *kp, *px))
            })
            .collect();
        if obs.is_empty() {
            continue;
        }
        landmarks.push((track.position, obs));
    }
    write_colmap_reconstruction_for_3dgs(
        output.join("sparse"),
        &camera,
        &poses_out,
        &features_out,
        &landmarks,
        |k| {
            names[result
                .poses
                .iter()
                .enumerate()
                .filter(|(_, p)| p.is_some())
                .nth(k)
                .map(|(id, _)| id)
                .unwrap_or(0)]
            .clone()
        },
    )
    .map_err(|e| format!("export failed: {e}"))?;
    println!(
        "mapper: registered {}/{} images, {} points, mean reprojection {:.3} px",
        result.registered_images,
        names.len(),
        result.tracks.len(),
        result.mean_reprojection_px
    );
    Ok(())
}

fn cmd_model_converter(args: &Args) -> Result<(), String> {
    let input = PathBuf::from(args.get_or("input_path", "."));
    let output_type = args.get_or("output_type", "TXT");
    warn_unknown_flags(args, &["input_path", "output_path", "output_type"]);
    if output_type != "TXT" {
        return Err(format!("output type {output_type} unsupported (TXT only)"));
    }
    for file in ["cameras.txt", "images.txt", "points3D.txt"] {
        let src = input.join(file);
        if src.exists() {
            println!("{}", src.display());
        }
    }
    Ok(())
}

fn main() {
    let args = Args::parse();
    let result = match args.flags.get("subcommand").map(String::as_str) {
        Some("feature_extractor") => cmd_feature_extractor(&args),
        Some("exhaustive_matcher") => cmd_exhaustive_matcher(&args),
        Some("spatial_matcher") => cmd_spatial_matcher(&args),
        Some("mapper") => cmd_mapper(&args),
        Some("pose_prior_mapper") => cmd_mapper_with(&args, true),
        Some("model_converter") => cmd_model_converter(&args),
        Some(other) => Err(format!(
            "unknown subcommand `{other}` (expected feature_extractor | exhaustive_matcher | spatial_matcher | mapper | pose_prior_mapper | model_converter)"
        )),
        None => Err("usage: colmap <subcommand> [--flags] — see module docs".to_string()),
    };
    if let Err(error) = result {
        eprintln!("colmap: {error}");
        std::process::exit(1);
    }
}