Skip to main content

visloc_slam/incremental_sfm/
mod.rs

1//! Incremental structure-from-motion from an **unordered** image set.
2//!
3//! The stereo-VO SfM path ([`crate::stereo_vo_ba`]) assumes an *ordered* video
4//! stream: temporal frame→frame matches give forward feature tracks, and stereo
5//! gives metric scale for free. That is the wrong shape for a photo collection,
6//! where the images have no temporal order, no known overlap graph, and (in the
7//! monocular case) no metric scale. This module is the COLMAP-style answer: it
8//! takes per-image features plus a set of **geometrically verified pairwise
9//! matches** (any source — VLAD-retrieved candidate pairs filtered by an
10//! essential-matrix RANSAC) and grows one consistent reconstruction.
11//!
12//! Pipeline:
13//! 1. **Tracks.** Union-find over every `(image, keypoint)` node joined by a
14//!    pairwise match. Each connected component is a feature track — one 3D
15//!    point seen by many images. Tracks with two keypoints in the *same* image
16//!    are inconsistent and dropped.
17//! 2. **Seed.** Candidate pairs (most matches first, enough parallax) bootstrap
18//!    the reconstruction via two-view relative pose ([`visloc_vision::two_view`]);
19//!    the candidate that grows the most images is kept, so a repetitive scene
20//!    whose strongest pair is an isolated cluster of adjacent frames is not
21//!    trapped. This fixes the gauge (seed image at the origin) and the arbitrary
22//!    monocular scale.
23//! 3. **Grow.** Repeatedly register the unregistered image that observes the
24//!    most already-triangulated tracks, by PnP RANSAC
25//!    ([`visloc_vision::ransac`]); then triangulate every track that two
26//!    registered views now share with sufficient parallax.
27//! 4. **Bundle-adjust.** Periodically and at the end, refine all registered
28//!    poses and triangulated points jointly with the Schur-complement BA
29//!    ([`crate::bundle`]). Monocular has a 7-DoF gauge (6 rigid + scale), so two
30//!    poses are fixed — the anchor and the longest-baseline pose — to pin scale
31//!    as well as the frame.
32//! 5. **Filter (+ optional re-triangulate).** Post-BA, strip observations that
33//!    reproject past the gate (a contaminated union-find track) and drop tracks
34//!    whose re-measured parallax is below the gate (depth-ambiguous far-flung
35//!    points); optionally also **re-triangulate** against the BA-refined poses
36//!    (`retriangulate`, off by default) — completing tracks the narrow seed-time
37//!    baseline could not triangulate and re-seeding noisy points (guarded so an
38//!    already-better point is never regressed), a density lever for downstream
39//!    3DGS/NeRF — then re-optimise, a few rounds. No image is ever un-posed, so
40//!    registration is invariant.
41//!
42//! The output ([`IncrementalSfmResult`]) carries per-image poses (`None` for
43//! images that never registered) and merged multi-view tracks, ready for a
44//! COLMAP `points3D.txt` export and downstream 3DGS / NeRF training.
45
46use std::cmp::Ordering;
47use std::collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet};
48use std::io::Write;
49
50use nalgebra::{Matrix2x3, Matrix3, Point2, Point3, UnitQuaternion, Vector3};
51use visloc_core::geometry::Pose;
52use visloc_core::types::Camera;
53use visloc_vision::features::FeatureSet;
54use visloc_vision::pnp::{Correspondence2D3D, GaussNewtonPoseRefiner, P3PGrunert, PoseRefiner};
55use visloc_vision::ransac::{PnPRansac, RobustPoseEstimator};
56use visloc_vision::stereo_bootstrap::triangulate_two_view_left_frame;
57use visloc_vision::two_view::{
58    recover_relative_pose_with_options, CheiralityOptions, ConfigurationType, CorrespondenceGraph,
59    RelativePoseEstimator, TwoViewCorrespondence,
60};
61
62use crate::process_memory;
63use crate::{BaConfig, BaError, BaObservation, BaResult, BundleAdjustment, RobustKernel};
64
65mod debug;
66mod driver;
67mod growth;
68mod pose_guided;
69mod position_priors;
70mod refinement;
71mod sequence_fallback;
72mod structureless;
73mod tracks;
74mod triangulation;
75
76pub use debug::*;
77pub use driver::*;
78pub(crate) use growth::*;
79use pose_guided::*;
80pub use position_priors::*;
81pub use refinement::*;
82use sequence_fallback::*;
83use structureless::*;
84pub use tracks::*;
85pub(crate) use triangulation::*;
86
87/// Geometrically verified matches between two images of the set. The match
88/// indices are keypoint indices into `features[image_i]` / `features[image_j]`,
89/// and are assumed to have already survived an essential-matrix RANSAC (i.e.
90/// they are inliers, not raw descriptor nearest neighbours).
91#[derive(Debug, Clone, PartialEq)]
92pub struct PairwiseMatches {
93    /// Index of the first image into the `features` slice.
94    pub image_i: usize,
95    /// Index of the second image into the `features` slice.
96    pub image_j: usize,
97    /// Verified `(keypoint_in_i, keypoint_in_j)` correspondences.
98    pub matches: Vec<(usize, usize)>,
99    /// COLMAP two-view configuration when known (full E/F/H verifier). Used by
100    /// global SfM to drop planar/panoramic pairs whose essential translation is
101    /// ill-conditioned. `None` preserves legacy behaviour for essential-only
102    /// verification paths.
103    pub two_view_config: Option<ConfigurationType>,
104    /// Essential-matrix inliers when the full verifier estimated E (may differ
105    /// from [`Self::matches`] when F/H won the COLMAP inlier selection). Used
106    /// by opt-in global edge construction so tracks stay dense while bearings
107    /// come from E.
108    pub essential_matches: Option<Vec<(usize, usize)>>,
109    /// Essential matrix from full two-view verification (when estimated).
110    /// Global SfM can decompose this directly for prefer-E edges instead of
111    /// re-running E RANSAC on the inlier subset (which can flip chirality).
112    pub essential_matrix: Option<Matrix3<f64>>,
113}
114
115impl PairwiseMatches {
116    /// Construct matches without a known two-view configuration.
117    pub const fn new(image_i: usize, image_j: usize, matches: Vec<(usize, usize)>) -> Self {
118        Self {
119            image_i,
120            image_j,
121            matches,
122            two_view_config: None,
123            essential_matches: None,
124            essential_matrix: None,
125        }
126    }
127}
128
129/// Tunable knobs for [`incremental_sfm`].
130#[derive(Debug, Clone, PartialEq)]
131pub struct IncrementalSfmConfig {
132    /// A pair must contribute at least this many verified matches to be a
133    /// candidate seed pair. (Track building still uses *all* pairs.)
134    pub min_seed_matches: usize,
135    /// COLMAP `Mapper.init_min_tri_angle`: a seed pair is accepted only when
136    /// the median triangulation angle of its well-triangulated inliers is at
137    /// least this many degrees. `None` (default) keeps the count-only gate.
138    pub seed_min_median_tri_angle_deg: Option<f64>,
139    /// How many candidate seeds to grow before committing. The highest-match
140    /// pair is not always a good seed: on repetitive structure (a building with
141    /// near-identical façades) the most-overlapping pair can be an isolated local
142    /// cluster of a few adjacent frames that the reconstruction cannot grow out
143    /// of. So up to `seed_trials` candidate pairs are each grown and the one that
144    /// registers the most images is kept — the COLMAP-style robust-initialisation
145    /// pattern — committing early as soon as a seed reaches most of its connected
146    /// component (so a well-connected scene still grows exactly one). Pairs that
147    /// fail the two-view baseline gate place nothing and don't count against the
148    /// budget. `1` restores the old first-qualifying-seed behaviour.
149    pub seed_trials: usize,
150    /// Maximum number of *growth attempts* in the seed search. Independent of
151    /// [`Self::seed_trials`], which counts successful grows: a weak success
152    /// (a temporally adjacent seed that only reaches a small fraction of the
153    /// connected component) keeps consuming `seed_trials` under the old rule
154    /// and exhausts the budget before the wide-baseline seeds later in the
155    /// order are tried — the failure mode behind the OpenLORIS 10k collapse.
156    /// `0` falls back to [`Self::seed_trials`] so existing configs are
157    /// unchanged.
158    pub seed_attempts: usize,
159    /// Optional diagnostic restriction to one normalized `(image_i, image_j)`
160    /// seed pair. `None` preserves the normal descending-match candidate list;
161    /// this is intentionally opt-in so controlled seed replays do not alter
162    /// ordinary reconstruction behavior.
163    pub seed_pair: Option<(usize, usize)>,
164    /// Minimum triangulation (parallax) angle in degrees for a point to be
165    /// accepted. Small-angle triangulations are depth-unstable and dropped.
166    pub min_triangulation_angle_deg: f64,
167    /// Maximum reprojection error (px) for a triangulated point in each of the
168    /// two views used to triangulate it, and the PnP inlier threshold.
169    pub max_reprojection_error_px: f64,
170    /// A track must span at least this many distinct images to be kept.
171    pub min_track_length: usize,
172    /// Optional final-only minimum track length.  When set, tracks shorter
173    /// than this value are removed only after registration and all configured
174    /// pose-guided splitting/recovery passes have completed, then the
175    /// remaining support is re-triangulated and bundle-adjusted.  `None`
176    /// preserves the historical growth/PnP/final-support behavior exactly.
177    /// The example CLI currently exposes only `Some(3)` as its first guarded
178    /// experiment; keeping this separate from `min_track_length` is what makes
179    /// the diagnostic unable to change registration history.
180    pub final_min_track_length: Option<usize>,
181    /// Minimum PnP inliers to accept a new image registration.
182    pub min_pnp_inliers: usize,
183    /// Run a global bundle adjustment after every `ba_every` registrations.
184    /// `0` disables the periodic BA (only the final BA runs).
185    pub ba_every: usize,
186    /// Defer the plain-growth periodic BA until at least this many cameras are
187    /// registered. `0` preserves the historical `ba_every` schedule. This is
188    /// intentionally scoped to the simple periodic path; COLMAP-style growth
189    /// uses its own local/global schedule, and this knob never suppresses the
190    /// configured final BA.
191    pub periodic_ba_min_registered_images: usize,
192    /// Run a final global bundle adjustment over the whole reconstruction.
193    pub final_global_ba: bool,
194    /// Bundle-adjustment configuration shared by the periodic and final solves.
195    pub ba_config: BaConfig,
196    /// Optional final fixed-support least-squares polish. When non-zero, one
197    /// additional BA solve runs after all registration/refinement passes with
198    /// the exact existing pose/track/observation support, no retriangulation or
199    /// filtering, fixed intrinsics, and a pure L2 objective. A failed or
200    /// cost-increasing solve is rolled back. `0` preserves the historical
201    /// schedule exactly.
202    pub final_ba_polish_iterations: usize,
203    /// Minimal solver the PnP RANSAC uses to register each new image.
204    pub pnp_solver: PnpSolver,
205    /// Maximum absolute-pose RANSAC iterations. The dynamic termination
206    /// (confidence 0.999) usually exits far earlier; this cap governs
207    /// heavily contaminated correspondence sets.
208    pub pnp_max_iterations: usize,
209    /// Post-BA track-refinement rounds. Each round removes observations that
210    /// reproject worse than `max_reprojection_error_px` after the global BA —
211    /// the symptom of a contaminated union-find track whose merged 3D point
212    /// fits none of its observations — and re-optimises. Registration is
213    /// **invariant** (no image is ever un-posed), so this only cleans structure
214    /// and can never drop a registered camera; on a clean reconstruction it is
215    /// a near-no-op. `0` disables it.
216    pub track_filter_iterations: usize,
217    /// Re-triangulate tracks in each post-BA refinement round (COLMAP's
218    /// completeness/refinement step the single-pass growth lacks). Once a global
219    /// BA has moved the poses, two things change: a track that failed the
220    /// parallax gate at growth time (a narrow baseline *then*) can now triangulate
221    /// against the BA-refined wide-baseline views, and a point first triangulated
222    /// from a narrow seed-time baseline can be re-seeded from the current widest
223    /// pair. Completion is unconditional; the re-seed of an existing point is a
224    /// **guarded swap** — kept only if it lowers that track's mean reprojection —
225    /// so a multi-view point BA already placed better is never regressed. When
226    /// enabled, at least one post-BA refinement round always runs (even if
227    /// `track_filter_iterations` is `0`).
228    ///
229    /// **`false` by default.** Growth already triangulates greedily (every
230    /// un-triangulated track is retried after *every* registration against all
231    /// registered views), so by the end the structure is near-complete and the
232    /// post-BA pass only mops up the marginal, gate-grazing tracks. Measured on a
233    /// 300-frame EuRoC MH_03 monocular subset it adds ~3 % more tracks / ~1.5 %
234    /// more observations — useful **density** for a downstream 3DGS/NeRF model —
235    /// but is **ATE-neutral-to-slightly-negative** (Sim(3) 2.13 → 2.27 cm), since
236    /// the extra tracks are the weakly-constrained ones. Enable it when you want
237    /// the densest possible structure and can spend the extra BA rounds; leave it
238    /// off when trajectory accuracy is the goal. See
239    /// `docs/sfm_vs_colmap_benchmark.md`.
240    pub retriangulate: bool,
241    /// Build conflict-free tracks from the verified correspondence stream and
242    /// re-triangulate every live point whenever registration adds an
243    /// observation.  This is the incremental correspondence/point-map path:
244    /// the ordinary union-find track builder remains the default, while this
245    /// opt-in mode keeps one observation-to-point owner and refuses a merge
246    /// that would create a same-image conflict.  It deliberately uses the
247    /// plain seed/growth/PnP schedule; `--colmap-style` is rejected by the
248    /// example CLI when this mode is selected.
249    pub incremental_correspondence_triangulation: bool,
250    /// Use COLMAP's `IncrementalMapper` bundle-adjustment **schedule** instead of
251    /// the simple "global BA every `ba_every` registrations + final BA" path.
252    /// This is a faithful port of COLMAP's defaults — the lever that closes the
253    /// small-scene monocular accuracy gap on COLMAP's home turf:
254    ///
255    ///  - **Local BA after every registration.** Optimise only the new image and
256    ///    its most-covisible neighbours (`local_ba_num_images`) plus the points
257    ///    they see, holding the rest of the reconstruction fixed — cheap, and it
258    ///    keeps the freshly added geometry tight before drift can compound.
259    ///  - **Growth-triggered global refinement.** When the registered-image count
260    ///    has grown by `global_ba_images_ratio` since the last global solve, run
261    ///    an iterative global refinement: global BA → re-triangulate/complete →
262    ///    filter, looped until the changed-observation fraction falls below
263    ///    `global_ba_change_rate` (≤ `global_ba_max_refinements` rounds).
264    ///  - **Registration retries.** A PnP failure is not permanent; after a
265    ///    global refinement adds structure, failed images are retried, up to
266    ///    `max_registration_trials` attempts each — COLMAP registers every frame
267    ///    where the simple single-attempt path leaves a tail unregistered.
268    ///
269    /// The final refinement is always the iterative global form when this is on.
270    /// `false` by default (preserves the simple schedule and every existing test).
271    pub colmap_style_mapper: bool,
272    /// After plain (non-`colmap_style_mapper`) growth, run COLMAP's iterative
273    /// global refinement (multi-round BA + filter + re-triangulate) instead of
274    /// the simple one-shot final BA. Keeps the simple growth schedule (no
275    /// per-registration local BA) while borrowing only the final polish pass.
276    /// `false` by default.
277    pub final_iterative_global_refinement: bool,
278    /// COLMAP `Mapper.ba_local_num_images`: how many most-covisible registered
279    /// images (besides the newly registered one) the per-registration local BA
280    /// optimises. Only used when `colmap_style_mapper` is set.
281    pub local_ba_num_images: usize,
282    /// Stop a local BA once an accepted LM step lowers the cost by less than
283    /// this fraction (COLMAP's function tolerance). `None` keeps the shared
284    /// `ba_config` tolerances, under which local windows almost always run
285    /// the full iteration budget.
286    pub local_ba_relative_cost_tolerance: Option<f64>,
287    /// COLMAP `Mapper.ba_global_images_ratio`: trigger a global refinement once
288    /// the registered-image count has grown by this factor since the last one.
289    /// Only used when `colmap_style_mapper` is set.
290    pub global_ba_images_ratio: f64,
291    /// COLMAP `Mapper.ba_global_max_refinements`: max global BA → complete →
292    /// filter rounds per global refinement. Only used when `colmap_style_mapper`.
293    pub global_ba_max_refinements: usize,
294    /// COLMAP `Mapper.ba_global_max_refinement_change_rate`: stop the global
295    /// refinement loop once `changed_observations / total_observations` drops
296    /// below this. Only used when `colmap_style_mapper` is set.
297    pub global_ba_change_rate: f64,
298    /// COLMAP `Mapper.max_reg_trials`: how many times a single image may be
299    /// retried for registration (across global-refinement boundaries) before it
300    /// is given up on. Only used when `colmap_style_mapper` is set.
301    pub max_registration_trials: usize,
302    /// After the final global refinement has tightened/re-triangulated the
303    /// committed model, give every still-unregistered image one fresh PnP
304    /// attempt against that updated structure. This is a bounded completion
305    /// pass: counters are reset exactly once, no retry cycle is possible, and a
306    /// second final refinement runs only when at least one image registers.
307    /// Experimental and off by default.
308    pub post_refinement_registration: bool,
309    /// After ordinary 2D-3D PnP completion, try to place still-missing images
310    /// from three or more registered neighbours' independently recovered
311    /// relative poses. Translation scale is recovered by intersecting the
312    /// neighbour-to-missing camera-centre direction lines in the existing
313    /// reconstruction frame; a single essential pair is never sufficient.
314    /// Experimental and off by default.
315    pub structureless_registration: bool,
316    /// After a successful PnP, require the absolute pose to agree (same
317    /// translation hemisphere) with independent two-view essentials against
318    /// already-registered neighbours. Rejects chirality-flipped façade
319    /// registrations that still have low local reprojection. Default false.
320    pub verify_registration_two_view: bool,
321    /// Minimum neighbours with a usable two-view check before the gate may
322    /// reject. Only used when `verify_registration_two_view` is set.
323    pub verify_registration_min_neighbors: usize,
324    /// Minimum fraction of checked neighbours that must agree (dot > 0).
325    pub verify_registration_min_agree_fraction: f64,
326    /// Maximum ascending-scan rounds of the structure-less completion pass.
327    /// A single scan registers an image only when its consensus neighbours are
328    /// *already* registered at the moment the scan reaches it, so a chain whose
329    /// bridge image has a higher index than its dependent images (an island's
330    /// entry point numbered above the images it unlocks — the courtyard-class
331    /// second-component failure) is left behind by one pass. Each round feeds
332    /// the images it registered back in as neighbours for the next round; the
333    /// loop stops as soon as a round registers nothing. One round therefore
334    /// reproduces the historical single-pass behaviour exactly.
335    pub structureless_max_rounds: usize,
336    /// Minimum registered relative-pose neighbours required to propose one
337    /// structure-less camera pose.
338    pub structureless_min_neighbors: usize,
339    /// Minimum independently re-estimated essential inliers per neighbour.
340    pub structureless_min_pair_inliers: usize,
341    /// Maximum angular disagreement between neighbour-implied missing-camera
342    /// rotations.
343    pub structureless_max_rotation_disagreement_deg: f64,
344    /// Minimum acute angle between any two camera-centre direction lines.
345    pub structureless_min_intersection_angle_deg: f64,
346    /// Maximum RMS line-intersection residual divided by the registered
347    /// neighbour-centre spread.
348    pub structureless_max_center_line_error_ratio: f64,
349    /// Minimum signed neighbour-line parameter divided by neighbour spread.
350    /// A small negative tolerance absorbs noisy intersections at an almost
351    /// coincident adjacent frame without accepting a materially reversed
352    /// essential translation direction.
353    pub structureless_min_forward_ratio: f64,
354    /// Minimum triangulated/reprojecting tracks required after tentative pose
355    /// insertion and local refinement.
356    pub structureless_min_support_tracks: usize,
357    /// Maximum independent local-submap tracks synthesized from verified
358    /// pairwise edges for one tentative structure-less insertion.
359    pub structureless_max_local_tracks: usize,
360    /// Minimum views per synthesized local-submap landmark. Two-view points
361    /// are allowed because the camera pose itself already requires a separate
362    /// multi-neighbour consensus.
363    pub structureless_min_local_track_views: usize,
364    /// Maximum mean reprojection error over the tentative image's supported
365    /// tracks after local refinement.
366    pub structureless_max_reprojection_error_px: f64,
367    /// Maximum relative increase in the pre-existing model's mean reprojection
368    /// error allowed when admitting one structure-less pose.
369    pub structureless_max_clean_error_increase_ratio: f64,
370    /// Revisit same-image-conflicted union-find components only after the normal
371    /// reconstruction has produced trustworthy poses. Candidate landmarks are
372    /// triangulated from verified edges, must agree in at least three registered
373    /// views with cycle support, and enter one guarded global BA. The recovery is
374    /// rolled back if it worsens the clean model's reprojection objective.
375    /// Experimental and off by default.
376    pub geometry_guided_conflict_recovery: bool,
377    /// When enabled, allow a bounded sequence-aware registration fallback
378    /// after ordinary PnP cannot place an image.  The example supplies unique
379    /// numeric image-stem values through [`Self::sequence_stem_values`]; only
380    /// an image whose stem is exactly one greater than an already registered
381    /// predecessor is eligible.  The fallback uses a stable essential pose,
382    /// the robust recent consecutive-step scale, and the normal triangulation
383    /// gates before admitting a provisional pose.  `false` preserves the
384    /// ordinary unordered PnP schedule exactly.
385    pub sequence_relative_pose_fallback: bool,
386    /// Defer sequence-relative fallback until the ordinary growth, conflict
387    /// recovery, and post-refinement PnP stage has stalled.  After one
388    /// provisional sequence pose is admitted, ordinary post-refinement PnP is
389    /// resumed before another fallback is attempted.  This is experimental
390    /// and off by default; `false` preserves eager fallback timing.
391    pub sequence_fallback_after_post: bool,
392    /// Use a constant-velocity projection of recent world-frame consecutive
393    /// steps for the sequence fallback scale.  The projection is accepted
394    /// only when positive, finite, and inside the existing robust median/MAD
395    /// fence.  `false` preserves the historical median-magnitude estimator.
396    pub sequence_constant_velocity_scale: bool,
397    /// Use the constant-velocity projection without its strict local
398    /// median/MAD fence.  Positive finite projections are still constrained
399    /// to a broad 0.25x..4x recent-median scale range.  This is a separate
400    /// experimental policy; `false` preserves both the strict projected mode
401    /// and the historical median-magnitude mode.
402    pub sequence_relaxed_constant_velocity_scale: bool,
403    /// In the after-post sequence fallback, carry the accepted baseline
404    /// magnitude from one consecutive provisional pose to the next.  The
405    /// first fallback still uses the selected constant-velocity projection;
406    /// a carried value is admitted only inside the broad 0.25x..4x
407    /// recent-median sanity bounds.  A normal PnP/post registration clears
408    /// the carry chain.  Experimental and off by default.
409    pub sequence_fallback_carry_scale: bool,
410    /// Trailing numeric stem values indexed like the feature/pose slices.
411    /// `None` disables sequence lookup.  This metadata is intentionally kept
412    /// outside `FeatureSet`, so library callers can opt in without changing
413    /// feature files or the default unordered API.
414    pub sequence_stem_values: Option<Vec<u64>>,
415    /// Rebuild all legacy union-find components after a complete posed model
416    /// exists.  The opt-in pass splits conflicting (and, when necessary,
417    /// poorly fitting clean) components into deterministic 3-D hypotheses
418    /// using fixed camera poses, then runs the ordinary final BA.  The legacy
419    /// track builder and default schedule are unchanged when this is false.
420    pub pose_guided_track_splitting: bool,
421    /// Number of bounded outer pose-guided split attempts.  The value is
422    /// ignored while `pose_guided_track_splitting` is false; its default of
423    /// one preserves the original single-pass diagnostic.
424    pub pose_guided_track_splitting_iterations: usize,
425    /// Optional reprojection gate used only by pose-guided splitting.  `None`
426    /// reuses `max_reprojection_error_px`, preserving the prior split exactly;
427    /// the ordinary mapper's triangulation/PnP/filter gates are unaffected.
428    pub pose_guided_split_max_reprojection_error_px: Option<f64>,
429    /// When pose-guided splitting is enabled, require every observation added
430    /// beyond its two-view anchor to have direct verified support from at
431    /// least two distinct observations/images already in that hypothesis.
432    /// Tracks with only the two-view anchor remain valid.  This is a separate
433    /// experimental admission rule and is off by default so the original
434    /// pose-guided partition remains reproducible.
435    pub pose_guided_graph_support: bool,
436    /// Before pose-guided splitting, opt into deterministic bridge-cut
437    /// refinement of original correspondence components.  Only bridges whose
438    /// two sides independently fit posed 3-D points while the combined side
439    /// does not fit one point are cut; the legacy/default path is unchanged.
440    pub pose_guided_bridge_cuts: bool,
441    /// After pose-guided splitting, iteratively merge complementary tracks
442    /// only when a verified cross-track edge exists and their union fits one
443    /// posed 3-D point under the split reprojection gate.  The image sets of
444    /// the two tracks must be disjoint, and one observation per image is
445    /// enforced throughout.  `false` preserves the split-only partition.
446    pub pose_guided_track_merging: bool,
447    /// Optional reprojection gate used only while fitting post-split unions.
448    /// `None` inherits `pose_guided_split_max_reprojection_error_px` (or the
449    /// ordinary gate when the split override is absent).  The post-BA hard
450    /// validation still uses `max_reprojection_error_px`.
451    pub pose_guided_merge_max_reprojection_error_px: Option<f64>,
452    /// Minimum registered views supporting a geometry-recovered conflict track.
453    /// Values below three are clamped to three.
454    pub conflict_recovery_min_views: usize,
455    /// Maximum verified anchor edges tested per conflicted component, ranked by
456    /// descending posed-view parallax. This bounds recovery work on large chains.
457    pub conflict_recovery_max_hypotheses: usize,
458    /// Per-observation reprojection gate for a geometry-recovered track.
459    pub conflict_recovery_max_reprojection_error_px: f64,
460    /// Maximum mean reprojection error of a recovered track before guarded BA.
461    pub conflict_recovery_max_mean_reprojection_px: f64,
462    /// Maximum relative increase allowed in the original clean tracks' mean
463    /// reprojection after the single guarded recovery BA.
464    pub conflict_recovery_max_clean_error_increase_ratio: f64,
465    /// Multi-view exemption to the `min_triangulation_angle_deg` gate. A point on
466    /// a forward-flying trajectory often subtends a parallax angle below the gate
467    /// yet is **well-constrained** when many views observe it (each view adds a
468    /// reprojection constraint on its 3 DoF). `None` keeps the strict angle gate
469    /// for every track (the simple path). `Some(n)` keeps — and triangulates — a
470    /// track whose widest parallax is between `low_parallax_min_angle_deg` and
471    /// `min_triangulation_angle_deg` **if it has ≥ n registered observations**, so
472    /// long low-parallax tracks survive while 2-view depth-ambiguous ones (which
473    /// would slide freely along their ray and corrupt the poses) are still
474    /// rejected. This is the lever that recovers COLMAP-grade structure density on
475    /// forward-motion video without the accuracy collapse a blanket low gate
476    /// causes. Used by both the simple and COLMAP-style paths when set.
477    pub low_parallax_min_observations: Option<usize>,
478    /// Lower parallax floor (degrees) for the multi-view exemption above: a track
479    /// below this angle is dropped regardless of how many views see it (truly
480    /// degenerate). Only consulted when `low_parallax_min_observations` is `Some`.
481    pub low_parallax_min_angle_deg: f64,
482    /// Refine the shared pinhole intrinsics `(fx, fy, cx, cy)` in the **final**
483    /// global refinement (alternating BA ↔ intrinsics, see
484    /// [`crate::BaConfig::refine_intrinsics`]). A slightly-off fixed calibration
485    /// forces a residual onto the poses; letting the camera absorb it is COLMAP's
486    /// lever for the last of the small-scene accuracy gap. Growth keeps the input
487    /// intrinsics fixed; the refined camera emerges from the final solve and is
488    /// returned in [`IncrementalSfmResult::refined_camera`]. `false` by default.
489    pub refine_intrinsics: bool,
490    /// COLMAP `Reconstruction::FilterImages`: after each growth global refinement,
491    /// **de-register** any image whose count of well-supported 3D-point
492    /// observations (triangulated, within `max_reprojection_error_px`) has fallen
493    /// below `filter_min_image_observations`. A pose that BA + point filtering
494    /// stripped of support is unreliable; dropping it (its trial counter resets, so
495    /// it can re-register once the structure around it improves) keeps a bad pose
496    /// from dragging the global solve. The two seed images are never filtered (they
497    /// anchor the gauge), and the registered count is never taken below 3. Only
498    /// used when `colmap_style_mapper` is set. `false` by default.
499    pub filter_images: bool,
500    /// Minimum well-supported observations an image must keep to stay registered
501    /// under `filter_images`. Only consulted when `filter_images` is set.
502    pub filter_min_image_observations: usize,
503    /// Which algorithm builds step 1's feature tracks from `pairwise`. See
504    /// [`TrackSource`]'s doc for the M2 background; `UnionFind` by default.
505    pub track_source: TrackSource,
506    /// Build tracks by processing verified correspondences in descending
507    /// pair-level confidence and rejecting a merge that would introduce two
508    /// keypoints from one image into a track. The confidence is deliberately
509    /// limited to metadata retained by [`PairwiseMatches`]: verified inlier
510    /// count, then essential-inlier count, with deterministic image/keypoint
511    /// tie-breaks. When enabled it takes precedence over `track_source`.
512    /// `false` preserves the legacy union-find/graph path exactly.
513    pub confidence_ordered_tracks: bool,
514    /// Build tracks with an opt-in per-correspondence geometric order. For
515    /// finite E-supported matches from a `Calibrated` two-view model, the
516    /// normalized Sampson residual is ordered first; F/H, degenerate, missing
517    /// or invalid models deliberately fall back to the pair-level confidence
518    /// order above rather than mixing incomparable residuals. Takes precedence
519    /// over [`Self::confidence_ordered_tracks`]. `false` preserves the legacy
520    /// path exactly.
521    pub geometric_confidence_tracks: bool,
522    /// Canonicalize track and observation iteration by stable physical
523    /// feature keys (image id, quantized pixel coordinates, then descriptor
524    /// contents) instead of input feature indices. This is useful when a
525    /// caller has permuted feature rows but kept their coordinates and
526    /// descriptors paired; `false` preserves the legacy index order exactly.
527    pub stable_track_order: bool,
528    /// Build tracks by prioritising accepted correspondences with stronger
529    /// multi-view cycle support. For an edge `(i,a)-(j,b)`, a third image
530    /// contributes support when both endpoints connect to the same feature in
531    /// that image; distinct supporting images are ordered before the exact
532    /// number of matching third-image features. Pair-level and, when safely
533    /// available, calibrated-E residual confidence break ties. The legacy
534    /// union-find path remains unchanged when this is `false`.
535    pub cycle_supported_tracks: bool,
536    /// Run one opt-in final fixed-support BA with observation weights derived
537    /// from the pre-BA triangulation geometry. The proxy is a clamped,
538    /// median-normalized `sin²(parallax)` information score; it changes no
539    /// track or observation membership and is disabled by default.
540    pub geometry_weighted_ba: bool,
541    /// Apply a conditioning safeguard to landmark variables whose pre-BA point
542    /// block is numerically ill-conditioned and whose current residual is
543    /// already outside the reprojection gate. Such landmarks are excluded
544    /// from this BA's residual rows (a fixed, high-residual point would exert
545    /// a misleading camera pull). The deterministic geometry gate is disabled
546    /// by default; well-fitting weak points remain ordinary BA variables.
547    pub freeze_ill_conditioned_landmarks: bool,
548    /// Run a bounded point-only BA with all currently registered camera poses
549    /// and intrinsics fixed immediately before each global/periodic joint BA.
550    /// This can absorb a large landmark correction before it enters the joint
551    /// camera Schur system. `0` preserves the historical schedule exactly.
552    pub landmark_ba_warm_start_iterations: usize,
553    /// Minimum registered-camera count at which the landmark warm start is
554    /// enabled. `0` applies it to every global/periodic BA; a positive value
555    /// permits evidence-scoped experiments such as the first 27-camera BA.
556    pub landmark_ba_warm_start_min_registered_images: usize,
557    /// Optional COLMAP sparse-model poses used only by the registration-time
558    /// `sfm-debug-oracle` transition log. The entries are indexed like
559    /// `features` and `poses`; `None` disables the diagnostic completely.
560    /// Supplying this field never changes registration, triangulation, or BA.
561    pub debug_oracle_poses: Option<Vec<Option<Pose>>>,
562    /// Optional GPS / position priors (COLMAP's `use_prior_position`), indexed
563    /// like `features`. Once enough registered images carry one, every global
564    /// and periodic BA first aligns the reconstruction to them with a robust
565    /// Sim(3) and then adds a covariance-weighted camera-centre prior in place
566    /// of the anchor/scale-anchor gauge poses, so the model comes out in the
567    /// priors' metric frame. See [`SfmPositionPriors`]. `None` (default)
568    /// leaves every solve unchanged.
569    pub position_priors: Option<SfmPositionPriors>,
570    /// How unregistered images are ranked for the next PnP attempt. Raw
571    /// correspondence count is the historical default; the visibility pyramid
572    /// is an explicit opt-in for experiments that prefer spatial coverage.
573    pub next_image_policy: NextImagePolicy,
574    /// Seed pairs (`image_i`, `image_j`, normalized to `(min, max)`) that
575    /// [`seed_candidate_order`] must skip. Empty by default. This is the
576    /// mechanism `LocalSubmapBuilder::build`'s scale-pathology retry (see
577    /// `crate::local_submap`, `NOROBUSTFIT_CLUSTER_DIAGNOSIS.md` §6(b)) uses
578    /// to force a rebuild onto the *next*-ranked seed candidate after a
579    /// previous seed pair (which reached `88/88` registration with
580    /// unremarkable per-observation gates) produced an internally
581    /// scale-exploded reconstruction: excluding the offending pair and
582    /// re-running `incremental_sfm` deterministically walks to the next
583    /// candidate in the same descending-match-count order, without
584    /// perturbing any other seed-selection behaviour.
585    pub excluded_seed_pairs: HashSet<(usize, usize)>,
586}
587
588/// Ranking policy for the next image offered to incremental PnP registration.
589#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
590pub enum NextImagePolicy {
591    /// Try [`VisibilityPyramid`] first and, when it leaves any input image
592    /// unregistered, rerun from the same immutable inputs with
593    /// [`CorrespondenceCount`].  The better reconstruction is chosen
594    /// deterministically by registered images, valid observations, tracks,
595    /// then lower reprojection error.  Ties retain the visibility result.
596    /// This policy is explicit and does not change the library default.
597    Auto,
598    /// Prefer spatially distributed 2D-3D support, then raw support count.
599    VisibilityPyramid,
600    /// Prefer the largest raw 2D-3D support count (the historical policy).
601    #[default]
602    CorrespondenceCount,
603}
604
605/// Which algorithm builds step 1's feature tracks from `pairwise` — the M2
606/// port in `docs/colmap_port_plan.md` ("Persistent `CorrespondenceGraph`").
607/// [`Self::UnionFind`] is the original ad hoc union-find
608/// ([`build_tracks`]), kept as the default (see the M2 results section in
609/// that doc for the ETH3D A/B that motivated staying opt-in rather than
610/// flipping the default). [`Self::CorrespondenceGraph`] instead builds the
611/// same tracks by routing through
612/// `visloc_vision::two_view::correspondence_graph::CorrespondenceGraph`
613/// ([`build_tracks_via_graph`]) — COLMAP's persistent view-graph object,
614/// which also exposes `NumObservationsForImage`/`NumCorrespondencesForImage`/
615/// `ExtractTransitiveCorrespondences`-style queries the union-find has no way
616/// to answer, for future milestones (M4's transitive pairing, in particular).
617/// Both paths are proven to produce byte-identical tracks on this crate's
618/// existing fixtures (see the `graph_tracks_match_union_find_tracks_*` tests).
619#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
620pub enum TrackSource {
621    /// The original ad hoc union-find over `(image, keypoint)` nodes.
622    #[default]
623    UnionFind,
624    /// COLMAP-style persistent [`CorrespondenceGraph`] (M2 port).
625    CorrespondenceGraph,
626}
627
628/// Minimal PnP solver used to register a new image against the reconstruction.
629#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
630pub enum PnpSolver {
631    /// 6-point Direct Linear Transform. Linear and fast, but **degenerate on
632    /// coplanar points** — a flat building façade or planar patch yields a
633    /// garbage pose. Kept for parity with the classic path.
634    Dlt,
635    /// Grunert's Perspective-Three-Point minimal solver. Geometrically
636    /// well-posed for any three non-collinear points whether or not the scene
637    /// is planar, so it registers planar façades the DLT cannot. The default.
638    #[default]
639    P3p,
640}
641
642impl Default for IncrementalSfmConfig {
643    fn default() -> Self {
644        Self {
645            min_seed_matches: 30,
646            seed_min_median_tri_angle_deg: None,
647            seed_trials: 12,
648            seed_attempts: 0,
649            seed_pair: None,
650            min_triangulation_angle_deg: 2.0,
651            max_reprojection_error_px: 4.0,
652            min_track_length: 2,
653            final_min_track_length: None,
654            min_pnp_inliers: 12,
655            ba_every: 5,
656            periodic_ba_min_registered_images: 0,
657            final_global_ba: true,
658            ba_config: BaConfig {
659                robust_kernel: RobustKernel::Huber { delta: 3.0 },
660                ..BaConfig::default()
661            },
662            final_ba_polish_iterations: 0,
663            pnp_solver: PnpSolver::default(),
664            // Legacy default: fixed 128-sample PnP with no dynamic
665            // termination. Raising this above 128 opts into the COLMAP-style
666            // confidence-based adaptive budget for large correspondence
667            // sets.
668            pnp_max_iterations: 128,
669            track_filter_iterations: 2,
670            retriangulate: false,
671            incremental_correspondence_triangulation: false,
672            // COLMAP IncrementalMapper defaults (off unless colmap_style_mapper).
673            colmap_style_mapper: false,
674            final_iterative_global_refinement: false,
675            local_ba_num_images: 8,
676            local_ba_relative_cost_tolerance: None,
677            global_ba_images_ratio: 1.1,
678            global_ba_max_refinements: 5,
679            global_ba_change_rate: 0.0005,
680            max_registration_trials: 3,
681            post_refinement_registration: false,
682            structureless_registration: false,
683            verify_registration_two_view: false,
684            verify_registration_min_neighbors: 2,
685            verify_registration_min_agree_fraction: 0.5,
686            structureless_max_rounds: 4,
687            structureless_min_neighbors: 3,
688            structureless_min_pair_inliers: 30,
689            structureless_max_rotation_disagreement_deg: 3.0,
690            structureless_min_intersection_angle_deg: 2.0,
691            structureless_max_center_line_error_ratio: 0.25,
692            structureless_min_forward_ratio: -0.005,
693            structureless_min_support_tracks: 20,
694            structureless_max_local_tracks: 512,
695            structureless_min_local_track_views: 2,
696            structureless_max_reprojection_error_px: 2.0,
697            structureless_max_clean_error_increase_ratio: 0.001,
698            geometry_guided_conflict_recovery: false,
699            sequence_relative_pose_fallback: false,
700            sequence_fallback_after_post: false,
701            sequence_constant_velocity_scale: false,
702            sequence_relaxed_constant_velocity_scale: false,
703            sequence_fallback_carry_scale: false,
704            sequence_stem_values: None,
705            pose_guided_track_splitting: false,
706            pose_guided_track_splitting_iterations: 1,
707            pose_guided_split_max_reprojection_error_px: None,
708            pose_guided_graph_support: false,
709            pose_guided_bridge_cuts: false,
710            pose_guided_track_merging: false,
711            pose_guided_merge_max_reprojection_error_px: None,
712            conflict_recovery_min_views: 3,
713            conflict_recovery_max_hypotheses: 32,
714            conflict_recovery_max_reprojection_error_px: 2.0,
715            conflict_recovery_max_mean_reprojection_px: 1.0,
716            conflict_recovery_max_clean_error_increase_ratio: 0.001,
717            low_parallax_min_observations: None,
718            low_parallax_min_angle_deg: 1.0,
719            refine_intrinsics: false,
720            filter_images: false,
721            filter_min_image_observations: 15,
722            track_source: TrackSource::default(),
723            confidence_ordered_tracks: false,
724            geometric_confidence_tracks: false,
725            stable_track_order: false,
726            cycle_supported_tracks: false,
727            geometry_weighted_ba: false,
728            freeze_ill_conditioned_landmarks: false,
729            landmark_ba_warm_start_iterations: 0,
730            landmark_ba_warm_start_min_registered_images: 0,
731            debug_oracle_poses: None,
732            position_priors: None,
733            next_image_policy: NextImagePolicy::default(),
734            excluded_seed_pairs: HashSet::new(),
735        }
736    }
737}
738
739/// One reconstructed 3D point and the image observations that support it.
740#[derive(Debug, Clone, PartialEq)]
741pub struct SfmTrack {
742    /// World-frame position (metres up to the monocular gauge scale).
743    pub position: Point3<f64>,
744    /// `(image_index, keypoint_index, pixel)` for every registered image that
745    /// observes this point.
746    pub observations: Vec<(usize, usize, Point2<f64>)>,
747}
748
749/// Diagnostics from feature-track construction before triangulation.
750#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
751pub struct TrackBuildStats {
752    /// Verified pairwise correspondences offered to the track builder.
753    pub input_correspondences: usize,
754    /// Connected components formed before the minimum-length gate.
755    pub connected_components: usize,
756    /// Legacy components discarded because they contain one image twice.
757    pub conflicting_components: usize,
758    /// Observations contained in those discarded legacy components.
759    pub conflicting_observations: usize,
760    /// Tracks retained after conflict and minimum-length gates.
761    pub retained_tracks: usize,
762    /// Observations in retained tracks.
763    pub retained_observations: usize,
764}
765
766/// Bounded topology diagnostics for the confidence-ordered rig-track policy.
767///
768/// This preview intentionally reports only the conflict regions induced by
769/// rejected confidence-ordered edges. It does not change the normal builder,
770/// materialize alternate tracks, or retain any state for a mapper run.
771#[derive(Debug, Clone, Default, PartialEq, Eq)]
772pub struct PairConfidenceConflictStats {
773    /// Number of verified match rows offered to the confidence ordering.
774    pub correspondences: usize,
775    /// Number of distinct `(image, keypoint)` endpoints touched by a row.
776    pub nodes: usize,
777    /// Number of edges that joined two previously distinct, image-compatible
778    /// DSU components.
779    pub accepted_edges: usize,
780    /// Number of edges rejected because their two components shared an image.
781    pub rejected_edges: usize,
782    /// Number of final DSU components after accepted unions.
783    pub final_components: usize,
784    /// Number of connected regions in the graph of final components induced by
785    /// rejected edges.
786    pub conflict_regions: usize,
787    /// Number of final components involved in at least one conflict region.
788    pub involved_components: usize,
789    /// Sum of observations in each involved final component, counted once per
790    /// disjoint region.
791    pub involved_observations: usize,
792    /// Largest number of final components in one conflict region.
793    pub max_region_components: usize,
794    /// Largest number of observations in one conflict region.
795    pub max_region_observations: usize,
796    /// Largest number of images shared by the two components at a rejected
797    /// edge, measured at the rejection point.
798    pub max_overlapping_images_per_rejected_edge: usize,
799    /// Histogram of conflict-region component counts as deterministic
800    /// ascending `(component_count, region_count)` entries.
801    pub region_component_count_histogram: Vec<(usize, usize)>,
802}
803
804/// Output of [`incremental_sfm`].
805#[derive(Debug, Clone)]
806pub struct IncrementalSfmResult {
807    /// Refined pose per input image; `None` for images that never registered.
808    pub poses: Vec<Option<Pose>>,
809    /// Reconstructed multi-view tracks (after the final BA, if enabled).
810    pub tracks: Vec<SfmTrack>,
811    /// Track-construction diagnostics measured before triangulation and BA.
812    pub track_build_stats: TrackBuildStats,
813    /// Number of images that registered into the reconstruction.
814    pub registered_images: usize,
815    /// Images added by the optional one-shot post-refinement completion pass.
816    pub post_refinement_registered_images: usize,
817    /// Images placed by the optional multi-neighbour relative-pose recovery
818    /// after the ordinary post-refinement PnP pass.
819    pub structureless_registered_images: usize,
820    /// Conflict tracks admitted by the optional geometry-guided recovery gate.
821    pub geometry_recovered_tracks: usize,
822    /// Observations contained in admitted geometry-recovered tracks.
823    pub geometry_recovered_observations: usize,
824    /// Whether recovery was allowed to update poses through its guarded BA.
825    /// Complete models use structure-only recovery and report `false`.
826    pub geometry_recovery_pose_ba_applied: bool,
827    /// Mean reprojection error (px) over every observation of every track.
828    pub mean_reprojection_px: f64,
829    /// Result of the final BA solve, if one ran.
830    pub ba_result: Option<BaResult>,
831    /// Refined camera intrinsics, when `config.refine_intrinsics` was set. The
832    /// poses, tracks, and `mean_reprojection_px` are all expressed against *this*
833    /// camera, so a COLMAP / 3DGS export must use it rather than the input camera.
834    /// `None` when intrinsics refinement was off.
835    pub refined_camera: Option<Camera>,
836    /// Local index (into this call's `features`/`pairwise`) of the first
837    /// image of the seed pair the winning growth trial started from.
838    /// Purely observational — does not influence poses/tracks/gates.
839    pub seed_image_i: usize,
840    /// Local index of the second image of the winning seed pair.
841    pub seed_image_j: usize,
842    /// Number of verified matches in the winning seed pair (`pairwise[..].matches.len()`).
843    pub seed_match_count: usize,
844}
845
846/// Why [`incremental_sfm`] could not build a reconstruction.
847#[derive(Debug, Clone, PartialEq, Eq)]
848pub enum IncrementalSfmError {
849    /// No verified pair met `min_seed_matches` / parallax to bootstrap from.
850    NoSeedPair,
851    /// The chosen seed pair's relative pose / initial triangulation failed.
852    SeedInitFailed,
853    /// An externally supplied diagnostic track partition violated the mapper's
854    /// one-observation-per-image/index contract.
855    InvalidTrackMembership(String),
856    /// An opt-in initial-pose model did not satisfy the mapper's input
857    /// contract (one pose per image, at least two finite poses).
858    InvalidInitialPoses(String),
859    /// A bundle-adjustment solve failed.
860    Ba(BaError),
861}
862
863impl std::fmt::Display for IncrementalSfmError {
864    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
865        match self {
866            IncrementalSfmError::NoSeedPair => {
867                write!(f, "no verified pair met the seed criteria")
868            }
869            IncrementalSfmError::SeedInitFailed => {
870                write!(f, "seed pair relative-pose / triangulation failed")
871            }
872            IncrementalSfmError::InvalidTrackMembership(message) => {
873                write!(f, "invalid track membership: {message}")
874            }
875            IncrementalSfmError::InvalidInitialPoses(message) => {
876                write!(f, "invalid initial poses: {message}")
877            }
878            IncrementalSfmError::Ba(e) => write!(f, "bundle adjustment failed: {e:?}"),
879        }
880    }
881}
882
883impl std::error::Error for IncrementalSfmError {}
884
885#[cfg(test)]
886mod tests;