Skip to main content

visloc_slam/rig_sfm/
mod.rs

1//! Incremental structure-from-motion for a calibrated, synchronized camera rig.
2//!
3//! Each input frame owns one or more images with fixed `sensor <- rig`
4//! extrinsics.  A frame is registered from all of its 2D-3D observations at
5//! once with generalized PnP; image poses are derived from that single body
6//! pose.  This preserves the physical stereo baseline during initialization
7//! and avoids treating synchronized sensors as unrelated monocular cameras.
8
9use std::cmp::Reverse;
10use std::collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet};
11use std::time::Instant;
12
13/// Coarse stage/progress timing for `incremental_rig_sfm`, opt-in via
14/// `VISLOC_RIG_SFM_TIMING=1`. Prints wall-clock elapsed time and problem-size
15/// counters at track construction, every local-BA checkpoint (registration
16/// count, cumulative triangulation/PnP attempts), conflict recovery, pose
17/// repair passes, and final BA -- enough to localize which stage a stalled
18/// run is spending time in without the very verbose per-attempt
19/// `VISLOC_SFM_DEBUG` stream.
20fn rig_timing_enabled() -> bool {
21    std::env::var_os("VISLOC_RIG_SFM_TIMING").is_some()
22}
23
24use nalgebra::{Matrix3, Point2, Point3, SMatrix, UnitQuaternion, Vector2, Vector3};
25use thiserror::Error;
26use visloc_core::geometry::{Pose, SE3};
27use visloc_vision::features::FeatureSet;
28use visloc_vision::pnp::{
29    GeneralizedCameraRig, GeneralizedCorrespondence2D3D, GeneralizedPnPRansac,
30};
31use visloc_vision::two_view::{RelativePoseEstimator, TwoViewCorrespondence};
32
33use crate::bundle::{
34    BaConfig, BaRigObservation, BundleAdjustment, MatrixFreeBaOptions, MatrixFreeBaRestartOptions,
35};
36use crate::incremental_sfm::{
37    build_tracks_confidence_ordered, build_tracks_confidence_ordered_with_trusted_prefix,
38    build_tracks_detailed, build_tracks_incremental_correspondence,
39    build_tracks_incremental_correspondence_in_order, PairwiseMatches, SfmTrack, TrackBuildOutput,
40    TrackBuildStats,
41};
42use crate::rig_correspondence::{
43    build_rig_correspondence_csr_from_features, RigCorrespondenceCsr, RigObservationId,
44};
45use crate::{LinearSolver, RobustKernel};
46
47mod bundle_adjustment;
48mod deferred;
49mod diagnostics;
50mod driver;
51mod dynamic;
52mod pose_repair;
53mod refinement;
54mod setup;
55mod tracks;
56mod triangulation;
57
58use bundle_adjustment::*;
59use deferred::*;
60use diagnostics::*;
61pub use driver::*;
62use dynamic::*;
63use pose_repair::*;
64pub use refinement::*;
65use setup::*;
66pub use tracks::*;
67use triangulation::*;
68
69/// One image and its calibrated sensor slot within a synchronized rig frame.
70#[derive(Debug, Clone, Copy, PartialEq, Eq)]
71pub struct RigFrameImage {
72    pub image_index: usize,
73    pub sensor_index: usize,
74}
75
76/// Images captured at one timestamp and governed by one `world -> rig` pose.
77#[derive(Debug, Clone, PartialEq, Eq)]
78pub struct RigFrame {
79    pub images: Vec<RigFrameImage>,
80}
81
82/// Deterministic feature-track construction policy for rig reconstruction.
83#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
84pub enum RigTrackBuilder {
85    /// Historical transitive closure; rejects a whole component if one image
86    /// contributes two observations.
87    #[default]
88    LegacyUnionFind,
89    /// Reject only the conflicting edge, in physical endpoint order.
90    ConflictPreserving,
91    /// Reject only conflicting edges while preserving the verified input
92    /// stream. This permits a checksummed trusted prefix followed by
93    /// lower-priority component bridges.
94    StreamOrderConflictPreserving,
95    /// Reject only the conflicting edge, processing stronger verified image
96    /// pairs before weaker pairs.
97    PairConfidence,
98    /// Process a frozen pair prefix in confidence order, then process all
99    /// remaining pairs in confidence order without letting them displace
100    /// trusted observations.
101    TrustedPrefixPairConfidence(usize),
102    /// Prefer correspondences that close through the same feature in one or
103    /// more third images. Common neighbours are intersected from the sparse
104    /// bounded view graph; no image Cartesian product is materialized.
105    SparseCycle,
106    /// Preserve metric stereo ownership first, then use sparse third-view
107    /// cycle support and pair confidence for temporal extension.
108    MetricSparseCycle,
109    /// Preserve metric stereo anchors, then favor short temporal edges before
110    /// cycle support so low-texture bridge chains are not consumed by stronger
111    /// but more distant pair conflicts.
112    MetricTemporalCycle,
113    /// Emit only exact four-edge cycles between two synchronized stereo
114    /// frames: stereo at each timestamp and temporal support on both sensors.
115    /// Each result is an independent four-observation track; no transitive
116    /// union-chain extension is performed.
117    MetricTemporalQuadrilateral,
118    /// Metric-first sparse cycles, retaining only tracks that contain a
119    /// calibrated multi-sensor observation at one synchronized frame.
120    MetricAnchoredCycle,
121}
122
123/// Bundle-adjustment backend used by the native calibrated-rig mapper.
124///
125/// `Legacy` is deliberately the default so existing callers retain their
126/// configured [`BaConfig`] (including its linear-solver choice).  The
127/// matrix-free entry point is an explicit, strict opt-in and never falls back
128/// to the legacy solve when it rejects an input or fails numerically.
129#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
130pub enum RigBaBackend {
131    #[default]
132    Legacy,
133    MatrixFreeStrict,
134    /// Experimental fixed-size (at most eight poses) Schur cluster preconditioner.
135    MatrixFreeCluster8,
136    /// Cluster8 with one true-residual restart inside the same PCG budget.
137    MatrixFreeCluster8Restart1,
138    /// Experimental compact landmark QR with bounded pose-block Jacobi PCG.
139    MatrixFreeQr,
140    /// Choose the direct backend before solving at <=64 variable poses;
141    /// larger systems use compact QR, never a failure-triggered fallback.
142    BoundedDirect64Qr,
143}
144
145const fn select_bounded_rig_backend(
146    requested: RigBaBackend,
147    variable_poses: usize,
148) -> RigBaBackend {
149    match requested {
150        RigBaBackend::BoundedDirect64Qr if variable_poses <= 64 => RigBaBackend::Legacy,
151        RigBaBackend::BoundedDirect64Qr => RigBaBackend::MatrixFreeQr,
152        other => other,
153    }
154}
155
156/// Conservative controls for generalized-rig incremental reconstruction.
157#[derive(Debug, Clone, Copy, PartialEq)]
158pub struct RigSfmConfig {
159    pub min_track_length: usize,
160    pub min_pnp_inliers: usize,
161    pub min_triangulation_angle_deg: f64,
162    /// Admit a triangulated track when a majority of its currently registered
163    /// observations agree, pruning only the inconsistent registered
164    /// observations. Disabled by default until the quality A/B is promoted.
165    pub robust_triangulation_pruning: bool,
166    pub triangulation_min_inlier_fraction: f64,
167    pub max_reprojection_error_px: f64,
168    pub pnp_max_iterations: usize,
169    pub ransac_seed: u64,
170    /// Restrict metric initialization to one caller-selected rig frame.
171    /// `None` preserves support-descending automatic selection. This is useful
172    /// for graph A/B tests where added edges must not silently change the
173    /// initialization frame.
174    pub seed_frame: Option<usize>,
175    /// Cap how many support-descending seed candidates the initial-frame
176    /// search tries before giving up with `InsufficientSeedStructure`. `0`
177    /// means unbounded (search every candidate, matching the historical
178    /// behavior). On a heavily conflict-fragmented graph (many aliased,
179    /// near-duplicate frames that all yield a plausible-looking but
180    /// under-landmarked two-view seed) the candidate list can run to
181    /// thousands of entries; each failed attempt is now cheap (only the
182    /// touched tracks/images are reset, not the whole track/pose arrays), but
183    /// this cap still bounds worst-case wall time and gives a faster, more
184    /// legible `InsufficientSeedStructure` report. Candidates are tried in
185    /// descending support order, so a nonzero cap never skips a
186    /// stronger-looking candidate in favor of a weaker one.
187    pub max_seed_attempts: usize,
188    /// Skip triangulation entirely for any track whose raw observation count
189    /// exceeds this many entries (`0` means unbounded, matching historical
190    /// behavior). A genuine 3-D landmark cannot physically be seen in
191    /// thousands of a rig's images; a track that large is a union-find
192    /// conflict blob produced by heavy visual aliasing (e.g. a long
193    /// repetitive corridor) that happened not to collide two observations
194    /// from the *same* image, so it was never split into
195    /// `conflicting_components`. Left unbounded, `triangulate_frontier`
196    /// re-scans that track's full observation list (building per-observation
197    /// bearing rays) every single time *any* of the thousands of images
198    /// touching it gets registered, before ever reaching the (already
199    /// bounded) widest-baseline ray-pair search -- an O(registrations x
200    /// track size) blowup. The check is a cheap `O(1)` length read before
201    /// that scan, so setting this is unconditionally safe; it defaults to
202    /// `0` (off) purely so existing byte-identical-output tests are
203    /// unaffected by a cap they never needed.
204    pub max_track_observations_for_triangulation: usize,
205    /// Minimum number of distinct rig sensors contributing 2D-3D
206    /// correspondences to a frame registration. One is geometrically valid
207    /// because the calibrated sensor-to-rig transform is fixed.
208    pub min_pnp_sensors: usize,
209    /// Maximum rig-frame distance for a bounded stereo-to-temporal PnP
210    /// fallback. Zero disables it. Each verified pair is consumed at most
211    /// once, keeping work proportional to the sparse pair graph.
212    pub direct_stereo_pnp_max_frame_gap: usize,
213    /// Optional sensor-count gate used only when temporary direct-stereo 3-D
214    /// points contribute to a PnP attempt. `None` preserves `min_pnp_sensors`.
215    pub direct_stereo_min_pnp_sensors: Option<usize>,
216    /// Minimum source-stereo ray angle used only by the direct PnP fallback.
217    /// A separate gate allows long-depth rig points without weakening normal
218    /// multi-view structure triangulation.
219    pub direct_stereo_min_triangulation_angle_deg: f64,
220    /// Maximum frame distance for an essential-rotation/constant-motion
221    /// bridge. Zero disables it. Translation direction and magnitude always
222    /// come from the preceding registered rig motion, never from the
223    /// forward-motion-degenerate essential translation.
224    pub motion_bridge_max_frame_gap: usize,
225    pub motion_bridge_min_inliers: usize,
226    pub motion_bridge_max_rotation_deviation_deg: f64,
227    /// Split the verified-pair stream into a structure-building prefix and a
228    /// deferred registration suffix. Suffix matches never merge or move the
229    /// established structure: after BA and fixed-pose structure refinement,
230    /// they may only register missing frames against existing landmarks and
231    /// append PnP-inlier observations. This preserves the accepted base map
232    /// while allowing a lower-priority retrieval pass to fill coverage gaps.
233    pub deferred_registration_pair_prefix: Option<usize>,
234    /// Optional start of a second, disjoint deferred tail used only for
235    /// post-registration retriangulation. When absent, the registration tail
236    /// is reused exactly as before. When present, pairs between the two
237    /// prefixes remain available to registration but are excluded from the
238    /// retriangulation builder.
239    pub deferred_retriangulation_pair_prefix: Option<usize>,
240    /// Optional PnP controls for the bounded deferred suffix. `None` inherits
241    /// the corresponding primary-mapper setting. A single calibrated sensor
242    /// is geometrically sufficient once metric 3D landmarks are fixed.
243    pub deferred_registration_min_pnp_sensors: Option<usize>,
244    pub deferred_registration_min_pnp_inliers: Option<usize>,
245    pub deferred_registration_pnp_max_iterations: Option<usize>,
246    /// Maximum bounded run of missing temporal frames that may be filled by
247    /// SE(3) interpolation between registered endpoints. Zero disables it;
248    /// every filled frame must also have a verified deferred-pair adjacency.
249    pub deferred_registration_max_interpolation_gap: usize,
250    /// Build an independent track graph from the deferred pair tail only
251    /// after registration, then triangulate previously unowned tracks against
252    /// the frozen poses. This mirrors COLMAP's post-registration
253    /// retriangulation ordering without exposing the added tracks to PnP.
254    pub retriangulate_deferred_tracks_after_registration: bool,
255    /// Build only the deferred post-registration graph with metric-first,
256    /// temporal-first sparse-cycle conflict handling. The registration graph
257    /// and its track builder remain frozen.
258    pub deferred_retriangulation_metric_temporal_cycle_tracks: bool,
259    /// Build deferred tracks only from exact stereo-temporal quadrilaterals.
260    /// This is stricter than temporal sparse-cycle ordering and remains
261    /// independent of the reconstructed poses.
262    pub deferred_retriangulation_metric_temporal_quadrilateral_tracks: bool,
263    /// Inclusive temporal baseline accepted by the exact quadrilateral
264    /// builder. Defaults to adjacent frames; wider ranges remain bounded by
265    /// the supplied sparse verified-pair tail.
266    pub deferred_retriangulation_quadrilateral_min_frame_gap: usize,
267    pub deferred_retriangulation_quadrilateral_max_frame_gap: usize,
268    /// Require a deferred track to contain synchronized multi-sensor support
269    /// in at least this many distinct rig frames before post-registration
270    /// triangulation. Zero preserves the historical deferred-track behavior.
271    pub deferred_retriangulation_min_metric_frames: usize,
272    pub track_builder: RigTrackBuilder,
273    /// Recover at most one metric, cycle-supported 3-D hypothesis from each
274    /// union-find component discarded for a duplicate-image conflict. The
275    /// recovery uses only already-registered poses and verified edges.
276    pub recover_metric_conflict_tracks: bool,
277    pub conflict_recovery_max_hypotheses: usize,
278    pub conflict_recovery_max_reprojection_error_px: f64,
279    pub conflict_recovery_max_mean_reprojection_px: f64,
280    /// COLMAP-style bounded correspondence-graph completion after all
281    /// registrations. It never merges positioned tracks or mutates the PnP
282    /// observation index; a fixed-pose structure pass consumes additions.
283    pub complete_tracks_after_registration: bool,
284    pub track_completion_max_passes: usize,
285    pub track_completion_max_reprojection_error_px: f64,
286    /// Replace a registered frame whose centre makes an implausible one-frame
287    /// detour between two registered temporal neighbours. The test uses only
288    /// reconstructed poses, runs in O(frames * passes), and is disabled by
289    /// default because the absolute threshold is dataset-scale dependent.
290    pub repair_isolated_pose_outliers: bool,
291    pub isolated_pose_max_midpoint_error_m: f64,
292    pub isolated_pose_min_detour_ratio: f64,
293    pub isolated_pose_repair_max_passes: usize,
294    /// Repair a short contiguous segment bracketed by large, mutually
295    /// cancelling translation jumps. Internal segment motion is preserved;
296    /// one world-frame offset is removed from every pose in the segment.
297    pub repair_paired_pose_jumps: bool,
298    pub paired_pose_jump_absolute_step_m: f64,
299    pub paired_pose_jump_min_step_ratio: f64,
300    pub paired_pose_jump_max_frame_span: usize,
301    pub paired_pose_jump_max_closure_ratio: f64,
302    /// Permit all tracks for triangulation/PnP, but let only tracks with a
303    /// synchronized multi-sensor observation contribute pose-moving BA rows.
304    pub ba_metric_tracks_only: bool,
305    /// Keep an active rig pose fixed in BA when fewer than this many usable
306    /// image observations constrain it inside the current window. Zero keeps
307    /// the historical behavior. This prevents an already registered pose
308    /// from becoming numerically free after landmark/reprojection filtering.
309    pub final_ba_min_pose_observations: usize,
310    pub final_bundle_adjustment: bool,
311    pub ba_backend: RigBaBackend,
312    /// Fix the lowest frame ID in each BA observation component lacking a
313    /// fixed pose. Removes its rigid gauge, not every possible degeneracy.
314    pub ba_anchor_disconnected_components: bool,
315    /// Retain eligible outside observations of active tracks with fixed poses.
316    pub ba_fixed_boundary_observations: bool,
317    pub ba_config: BaConfig,
318    pub local_ba_every: usize,
319    pub local_ba_window_size: usize,
320    /// Select bounded neighbors sharing usable landmarks instead of recent frames.
321    pub local_ba_covisibility: bool,
322    pub local_ba_iterations: usize,
323    pub final_ba_passes: usize,
324    pub final_ba_window_size: usize,
325    pub final_ba_fix_window_ends: bool,
326    /// Bounded COLMAP-style final refinement cycles. Each cycle removes
327    /// registered observations outside `max_reprojection_error_px`, then
328    /// reruns the existing windowed BA and fixed-pose structure refinement.
329    /// Zero preserves the historical single-BA behavior.
330    pub final_filter_refinement_passes: usize,
331    /// Fixed-pose, per-landmark Gauss-Newton passes after registration.  This
332    /// is linear in retained observations and never forms a global BA matrix.
333    pub structure_refinement_iterations: usize,
334    /// Build and consume a compact rig-local correspondence CSR during
335    /// registration.  When enabled, tracks are created/continued only as
336    /// their incident correspondence rows become active, matching COLMAP's
337    /// registration-time point-map semantics.  The historical all-pairs
338    /// track builder remains byte-for-byte unchanged when this is `false`.
339    pub dynamic_correspondence_tracking: bool,
340}
341
342impl Default for RigSfmConfig {
343    fn default() -> Self {
344        Self {
345            min_track_length: 2,
346            min_pnp_inliers: 8,
347            min_triangulation_angle_deg: 1.0,
348            robust_triangulation_pruning: false,
349            triangulation_min_inlier_fraction: 0.5,
350            max_reprojection_error_px: 4.0,
351            pnp_max_iterations: 512,
352            ransac_seed: 7,
353            seed_frame: None,
354            max_seed_attempts: 0,
355            max_track_observations_for_triangulation: 0,
356            min_pnp_sensors: 2,
357            direct_stereo_pnp_max_frame_gap: 0,
358            direct_stereo_min_pnp_sensors: None,
359            direct_stereo_min_triangulation_angle_deg: 1.0,
360            motion_bridge_max_frame_gap: 0,
361            motion_bridge_min_inliers: 12,
362            motion_bridge_max_rotation_deviation_deg: 5.0,
363            deferred_registration_pair_prefix: None,
364            deferred_retriangulation_pair_prefix: None,
365            deferred_registration_min_pnp_sensors: None,
366            deferred_registration_min_pnp_inliers: None,
367            deferred_registration_pnp_max_iterations: None,
368            deferred_registration_max_interpolation_gap: 0,
369            retriangulate_deferred_tracks_after_registration: false,
370            deferred_retriangulation_metric_temporal_cycle_tracks: false,
371            deferred_retriangulation_metric_temporal_quadrilateral_tracks: false,
372            deferred_retriangulation_quadrilateral_min_frame_gap: 1,
373            deferred_retriangulation_quadrilateral_max_frame_gap: 1,
374            deferred_retriangulation_min_metric_frames: 0,
375            track_builder: RigTrackBuilder::default(),
376            recover_metric_conflict_tracks: false,
377            conflict_recovery_max_hypotheses: 8,
378            conflict_recovery_max_reprojection_error_px: 2.0,
379            conflict_recovery_max_mean_reprojection_px: 1.0,
380            complete_tracks_after_registration: false,
381            track_completion_max_passes: 2,
382            track_completion_max_reprojection_error_px: 1.0,
383            repair_isolated_pose_outliers: false,
384            isolated_pose_max_midpoint_error_m: 0.25,
385            isolated_pose_min_detour_ratio: 8.0,
386            isolated_pose_repair_max_passes: 1,
387            repair_paired_pose_jumps: false,
388            paired_pose_jump_absolute_step_m: 0.25,
389            paired_pose_jump_min_step_ratio: 8.0,
390            paired_pose_jump_max_frame_span: 16,
391            paired_pose_jump_max_closure_ratio: 0.1,
392            ba_metric_tracks_only: false,
393            final_ba_min_pose_observations: 0,
394            final_bundle_adjustment: true,
395            ba_backend: RigBaBackend::Legacy,
396            ba_anchor_disconnected_components: false,
397            ba_fixed_boundary_observations: false,
398            ba_config: BaConfig {
399                linear_solver: LinearSolver::Sparse,
400                robust_kernel: RobustKernel::Huber { delta: 6.0 },
401                parallel: true,
402                ..BaConfig::default()
403            },
404            local_ba_every: 10,
405            local_ba_window_size: 40,
406            local_ba_covisibility: false,
407            local_ba_iterations: 8,
408            final_ba_passes: 2,
409            final_ba_window_size: 60,
410            final_ba_fix_window_ends: true,
411            final_filter_refinement_passes: 0,
412            structure_refinement_iterations: 5,
413            dynamic_correspondence_tracking: false,
414        }
415    }
416}
417
418/// Output poses retain both the physical frame state and derived image states.
419#[derive(Debug, Clone, PartialEq)]
420pub struct RigSfmResult {
421    pub frame_poses: Vec<Option<Pose>>,
422    pub image_poses: Vec<Option<Pose>>,
423    pub tracks: Vec<SfmTrack>,
424    pub registered_frames: usize,
425    pub registered_images: usize,
426    pub mean_reprojection_error_px: f64,
427    pub seed_frame_index: usize,
428    pub track_build_stats: TrackBuildStats,
429    pub work: RigSfmWorkStats,
430    pub bundle_adjustment: Option<RigBaStats>,
431}
432
433#[derive(Debug, Clone, Copy, PartialEq)]
434pub struct RigBaStats {
435    pub observations: usize,
436    pub initial_cost: f64,
437    pub final_cost: f64,
438    pub iterations: usize,
439    pub converged: bool,
440}
441
442/// Counters used to prove that frontier growth stays proportional to sparse
443/// observation support rather than rescanning the frame/track Cartesian
444/// product.
445#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
446pub struct RigSfmWorkStats {
447    pub triangulation_attempts: usize,
448    pub robust_triangulation_tracks: usize,
449    pub robust_triangulation_pruned_observations: usize,
450    pub robust_triangulation_majority_rejections: usize,
451    pub correspondence_cache_insertions: usize,
452    pub pnp_attempts: usize,
453    pub pnp_insufficient_sensor_attempts: usize,
454    pub pnp_estimation_failures: usize,
455    pub pnp_inlier_rejections: usize,
456    pub pnp_registrations: usize,
457    pub direct_bridge_pair_visits: usize,
458    pub direct_bridge_correspondence_insertions: usize,
459    pub direct_bridge_registrations: usize,
460    pub motion_bridge_pair_visits: usize,
461    pub motion_bridge_estimation_failures: usize,
462    pub motion_bridge_rotation_rejections: usize,
463    pub motion_bridge_registrations: usize,
464    pub deferred_pair_visits: usize,
465    pub deferred_correspondence_insertions: usize,
466    pub deferred_pnp_attempts: usize,
467    pub deferred_pnp_estimation_failures: usize,
468    pub deferred_pnp_inlier_rejections: usize,
469    pub deferred_registrations: usize,
470    pub deferred_interpolation_registrations: usize,
471    pub deferred_observations_attached: usize,
472    pub deferred_retriangulated_tracks: usize,
473    pub deferred_retriangulated_observations: usize,
474    pub unregistered_zero_support_frames: usize,
475    pub unregistered_below_pnp_support_frames: usize,
476    pub unregistered_eligible_pnp_frames: usize,
477    pub unregistered_below_sensor_frames: usize,
478    pub max_unregistered_support: usize,
479    pub local_ba_runs: usize,
480    pub ba_retriangulated_tracks: usize,
481    pub ba_requeued_frames: usize,
482    pub structure_refined_tracks: usize,
483    pub geometry_recovered_tracks: usize,
484    pub geometry_recovered_observations: usize,
485    pub track_completion_passes: usize,
486    pub track_completion_pair_visits: usize,
487    pub track_completion_observations: usize,
488    pub track_completion_reprojection_rejections: usize,
489    pub final_filter_refinement_passes: usize,
490    pub final_filter_refinement_pruned_observations: usize,
491    pub isolated_pose_repair_passes: usize,
492    pub isolated_pose_repairs: usize,
493    pub paired_pose_jump_repairs: usize,
494    pub paired_pose_jump_repaired_frames: usize,
495    /// Number of flattened CSR observation rows activated after a frame
496    /// registration in dynamic correspondence mode.
497    pub dynamic_activated_rows: usize,
498    /// Number of directed CSR neighbour entries visited by those activated
499    /// rows.
500    pub dynamic_activated_edges: usize,
501    /// Number of dynamic two-observation track creations.
502    pub dynamic_track_creates: usize,
503    /// Number of dynamic track continuations into a previously unowned
504    /// observation.
505    pub dynamic_track_continues: usize,
506    /// Edges rejected because both endpoints already belong to different
507    /// owners and the conservative fragment-merge gate did not admit them.
508    pub dynamic_owner_conflicts: usize,
509    /// Edges rejected because continuation would put a second observation
510    /// from one image into a track.
511    pub dynamic_same_image_conflicts: usize,
512    /// Positioned-owner continuations rejected by the current pose/point
513    /// reprojection gate.  PnP cache outliers never become owners.
514    pub dynamic_geometry_rejections: usize,
515    /// Number of compact entries in the flattened observation inverse lookup.
516    /// This is a bounded O(observations) allocation, not a pairwise cache.
517    pub dynamic_observation_lookup_entries: usize,
518    /// Unique observation entries inserted into the dynamic PnP graph cache.
519    pub dynamic_pnp_graph_insertions: usize,
520    /// Number of retained legacy-union tracks inspected for dynamic
521    /// bootstrap.  This is a diagnostic only; the tracks themselves are not
522    /// imported into the registration-time owner map.
523    pub dynamic_bootstrap_legacy_tracks: usize,
524    /// Number of legacy-membership seed frames admitted by the historical
525    /// metric support gate.
526    pub dynamic_bootstrap_candidates: usize,
527    /// Metric support (one canonical stereo pair per retained legacy track)
528    /// of the selected bootstrap frame.
529    pub dynamic_bootstrap_seed_support: usize,
530    /// Number of selected bootstrap stereo pairs installed as owners.
531    pub dynamic_bootstrap_seed_pairs: usize,
532    /// Number of independently triangulated selected bootstrap landmarks.
533    pub dynamic_bootstrap_seed_landmarks: usize,
534    /// Number of times the direct CSR same-frame stereo fallback was used.
535    pub dynamic_bootstrap_direct_fallbacks: usize,
536}
537
538#[derive(Debug, Clone, PartialEq, Error)]
539pub enum RigSfmError {
540    #[error("rig reconstruction requires at least two calibrated sensors")]
541    TooFewSensors,
542    #[error("rig reconstruction contains no frames")]
543    NoFrames,
544    #[error("requested metric seed frame {frame} is outside 0..{frame_count}")]
545    InvalidSeedFrame { frame: usize, frame_count: usize },
546    #[error(
547        "minimum PnP sensor count {requested} is outside the calibrated range 1..={sensor_count}"
548    )]
549    InvalidMinPnpSensors {
550        requested: usize,
551        sensor_count: usize,
552    },
553    #[error("direct-stereo minimum PnP sensor count {requested} is outside 1..={sensor_count}")]
554    InvalidDirectStereoMinPnpSensors {
555        requested: usize,
556        sensor_count: usize,
557    },
558    #[error("direct stereo triangulation angle must be finite and positive, found {0}")]
559    InvalidDirectStereoTriangulationAngle(f64),
560    #[error("triangulation inlier fraction must be finite and in [0.5, 1], found {0}")]
561    InvalidTriangulationInlierFraction(f64),
562    #[error("conflict recovery {name} must be finite and positive, found {value}")]
563    InvalidConflictRecoveryGate { name: &'static str, value: f64 },
564    #[error("motion bridge requires at least 8 essential inliers, found {0}")]
565    InvalidMotionBridgeMinInliers(usize),
566    #[error("motion bridge rotation deviation must be finite and positive, found {0}")]
567    InvalidMotionBridgeRotationDeviation(f64),
568    #[error("deferred registration pair prefix {prefix} exceeds {pair_count} verified pairs")]
569    DeferredPairPrefix { prefix: usize, pair_count: usize },
570    #[error(
571        "deferred retriangulation pair prefix {prefix} is outside {registration_prefix}..={pair_count}"
572    )]
573    DeferredRetriangulationPairPrefix {
574        prefix: usize,
575        registration_prefix: usize,
576        pair_count: usize,
577    },
578    #[error("deferred quadrilateral frame gap range is invalid: {min}..={max}")]
579    InvalidDeferredQuadrilateralFrameGap { min: usize, max: usize },
580    #[error("deferred minimum PnP sensor count {requested} is outside 1..={sensor_count}")]
581    InvalidDeferredMinPnpSensors {
582        requested: usize,
583        sensor_count: usize,
584    },
585    #[error("deferred PnP requires at least one RANSAC iteration")]
586    InvalidDeferredPnpIterations,
587    #[error("deferred PnP requires at least 6 inliers, found {0}")]
588    InvalidDeferredMinPnpInliers(usize),
589    #[error("track completion requires at least one pass")]
590    InvalidTrackCompletionPasses,
591    #[error("track completion reprojection error must be finite and positive, found {0}")]
592    InvalidTrackCompletionReprojectionError(f64),
593    #[error("isolated-pose repair requires at least one pass")]
594    InvalidIsolatedPoseRepairPasses,
595    #[error("isolated-pose midpoint error must be finite and positive, found {0}")]
596    InvalidIsolatedPoseMidpointError(f64),
597    #[error("isolated-pose detour ratio must be finite and greater than one, found {0}")]
598    InvalidIsolatedPoseDetourRatio(f64),
599    #[error("paired-pose jump step must be finite and positive, found {0}")]
600    InvalidPairedPoseJumpStep(f64),
601    #[error("paired-pose jump step ratio must be finite and greater than one, found {0}")]
602    InvalidPairedPoseJumpStepRatio(f64),
603    #[error("paired-pose jump maximum frame span must be positive")]
604    InvalidPairedPoseJumpFrameSpan,
605    #[error("paired-pose jump closure ratio must be finite and in (0, 1), found {0}")]
606    InvalidPairedPoseJumpClosureRatio(f64),
607    #[error("frame {frame} contains no images")]
608    EmptyFrame { frame: usize },
609    #[error("image {image} is outside the feature range 0..{feature_count}")]
610    ImageIndex { image: usize, feature_count: usize },
611    #[error("sensor {sensor} is outside the calibrated range 0..{sensor_count}")]
612    SensorIndex { sensor: usize, sensor_count: usize },
613    #[error("image {image} occurs in more than one frame")]
614    DuplicateImage { image: usize },
615    #[error("sensor {sensor} occurs twice in frame {frame}")]
616    DuplicateSensor { frame: usize, sensor: usize },
617    #[error("image {image} is not assigned to a rig frame")]
618    UnassignedImage { image: usize },
619    #[error("invalid pair ({image_i}, {image_j}) for {feature_count} images")]
620    PairImageIndex {
621        image_i: usize,
622        image_j: usize,
623        feature_count: usize,
624    },
625    #[error("pair ({image_i}, {image_j}) references an invalid keypoint")]
626    PairKeypointIndex { image_i: usize, image_j: usize },
627    #[error("no frame has enough multi-sensor tracks for metric initialization")]
628    NoMetricSeed,
629    #[error("metric seed frame {frame} triangulated fewer than {required} landmarks")]
630    InsufficientSeedStructure {
631        frame: usize,
632        required: usize,
633        triangulated: usize,
634    },
635    #[error("rig bundle adjustment failed: {0}")]
636    BundleAdjustment(String),
637    #[error("fixed frame rotation count {actual} does not match the frame count {expected}")]
638    InvalidFixedFrameRotationCount { expected: usize, actual: usize },
639    #[error("rig refinement frame-pose count {actual} does not match the frame count {expected}")]
640    InvalidResultFramePoseCount { expected: usize, actual: usize },
641    #[error(
642        "rig refinement image-pose count {actual} does not match the feature count {expected}"
643    )]
644    InvalidResultImagePoseCount { expected: usize, actual: usize },
645    #[error("fixed frame rotation {frame} contains non-finite values")]
646    NonFiniteFixedFrameRotation { frame: usize },
647    #[error("fixed frame rotation {frame} is invalid")]
648    InvalidFixedFrameRotation { frame: usize },
649    #[error("rig refinement result contains non-finite state")]
650    NonFiniteResultState,
651    #[error("rig refinement result has invalid track observation {track} ({image}, {keypoint})")]
652    InvalidResultTrackObservation {
653        track: usize,
654        image: usize,
655        keypoint: usize,
656    },
657    #[error("rig refinement result has non-finite track state at index {track}")]
658    NonFiniteResultTrack { track: usize },
659    #[error("rig refinement seed frame {frame} is not registered")]
660    InvalidResultSeedFrame { frame: usize },
661    #[error("rig refinement requires at least one registered frame")]
662    NoRegisteredFrames,
663    #[error("rig refinement bundle adjustment had no usable observations")]
664    NoBundleAdjustmentObservations,
665    #[error("dynamic correspondence tracking cannot build its CSR: {0}")]
666    DynamicCorrespondenceBuild(String),
667    #[error("dynamic correspondence tracking cannot be combined with {0}")]
668    DynamicIncompatible(&'static str),
669    #[error("dynamic correspondence tracking cannot represent {kind} index {index} in a u32 slot")]
670    DynamicIndexOverflow { kind: &'static str, index: usize },
671}
672
673#[derive(Debug, Clone, PartialEq)]
674struct WorkingTrack {
675    observations: Vec<(usize, usize)>,
676    position: Option<Point3<f64>>,
677    metric_anchored: bool,
678}
679
680#[cfg(test)]
681mod tests;