Skip to main content

visloc_mapping/
lib.rs

1#![forbid(unsafe_code)]
2//! Local mapping scaffolding.
3//!
4//! This crate intentionally does not mutate maps yet. It starts v0.3 by
5//! defining keyframe-selection interfaces that can consume tracking results and
6//! later feed staged map updates, triangulation, and local refinement.
7
8use nalgebra::{DMatrix, Matrix3, Point2, Point3};
9use visloc_core::geometry::{Pose, SE3};
10use visloc_core::types::{
11    CameraId, FrameId, Keyframe, Landmark, LandmarkId, Observation, StereoObservation, VisualMap,
12};
13use visloc_tracking::{TrackingEvent, TrackingResult};
14
15mod stereo_replenish;
16pub use stereo_replenish::{
17    build_stereo_metric_points, build_stereo_replenish_candidates, StereoReplenishConfig,
18};
19
20pub trait KeyframePolicy {
21    fn evaluate(&mut self, result: &TrackingResult) -> KeyframeDecision;
22
23    fn reset(&mut self);
24}
25
26#[derive(Debug, Clone, PartialEq)]
27pub struct KeyframePolicyConfig {
28    pub min_frame_id_gap: u64,
29    /// Force a new keyframe once this many frame ids have elapsed, even when
30    /// estimated translation remains below `min_translation`. The optional
31    /// tracking-quality floors still apply, preventing a weak localization
32    /// from being promoted merely because it is old.
33    pub max_frame_id_gap: Option<u64>,
34    pub min_translation: f64,
35    pub select_relocalized_frames: bool,
36    pub tracked_landmark_keyframe_ratio: Option<f64>,
37    pub min_tracked_landmarks_for_quality_keyframe: usize,
38    /// When `Some(n)`, a frame that would otherwise be promoted to a
39    /// keyframe (i.e. it already cleared the frame-id-gap and translation
40    /// gates) is instead rejected with
41    /// [`KeyframeDecisionReason::InsufficientTrackingQuality`] if its PnP
42    /// inlier count is below `n`. Guards against promoting a keyframe from
43    /// a marginal localization (e.g. a handful of inliers surviving a
44    /// tracking failure) that would poison the covisibility graph and
45    /// local map for subsequent frames. `None` (the default) preserves
46    /// legacy always-promote behaviour.
47    pub min_inliers: Option<usize>,
48    /// Companion to `min_inliers`: when `Some(r)`, also requires the PnP
49    /// inlier ratio to be at least `r`. Either configured threshold not
50    /// being met rejects the promotion. `None` (the default) preserves
51    /// legacy always-promote behaviour.
52    pub min_inlier_ratio: Option<f64>,
53}
54
55impl Default for KeyframePolicyConfig {
56    fn default() -> Self {
57        Self {
58            min_frame_id_gap: 5,
59            max_frame_id_gap: None,
60            min_translation: 1.0,
61            select_relocalized_frames: true,
62            tracked_landmark_keyframe_ratio: None,
63            min_tracked_landmarks_for_quality_keyframe: 20,
64            min_inliers: None,
65            min_inlier_ratio: None,
66        }
67    }
68}
69
70#[derive(Debug, Clone, PartialEq)]
71pub struct KeyframeDecision {
72    pub frame_id: FrameId,
73    pub selected: bool,
74    pub reason: KeyframeDecisionReason,
75    pub last_keyframe_frame_id: Option<FrameId>,
76    pub selected_keyframe_count: usize,
77}
78
79#[derive(Debug, Clone, PartialEq)]
80pub enum KeyframeDecisionReason {
81    NotLocalized,
82    MissingPose,
83    FirstSuccessfulFrame,
84    Relocalized,
85    TrackedLandmarkDrop {
86        frame_id_gap: u64,
87        tracked_landmarks: usize,
88        last_keyframe_tracked_landmarks: usize,
89        min_tracked_landmark_ratio: f64,
90    },
91    ThresholdsMet {
92        frame_id_gap: u64,
93        translation: f64,
94    },
95    FrameIdGapTooSmall {
96        frame_id_gap: u64,
97        min_frame_id_gap: u64,
98    },
99    MaximumFrameIdGap {
100        frame_id_gap: u64,
101        max_frame_id_gap: u64,
102    },
103    TranslationTooSmall {
104        translation: f64,
105        min_translation: f64,
106    },
107    InsufficientTrackingQuality {
108        inlier_count: usize,
109        inlier_ratio: f64,
110        min_inliers: Option<usize>,
111        min_inlier_ratio: Option<f64>,
112    },
113}
114
115#[derive(Debug, Clone, Default, PartialEq)]
116pub struct SimpleKeyframePolicy {
117    config: KeyframePolicyConfig,
118    last_keyframe_frame_id: Option<FrameId>,
119    last_keyframe_pose: Option<Pose>,
120    last_keyframe_tracked_landmark_count: Option<usize>,
121    selected_keyframe_count: usize,
122}
123
124impl SimpleKeyframePolicy {
125    pub const fn new(config: KeyframePolicyConfig) -> Self {
126        Self {
127            config,
128            last_keyframe_frame_id: None,
129            last_keyframe_pose: None,
130            last_keyframe_tracked_landmark_count: None,
131            selected_keyframe_count: 0,
132        }
133    }
134
135    pub const fn config(&self) -> &KeyframePolicyConfig {
136        &self.config
137    }
138
139    pub const fn last_keyframe_frame_id(&self) -> Option<FrameId> {
140        self.last_keyframe_frame_id
141    }
142
143    pub const fn last_keyframe_pose(&self) -> Option<&Pose> {
144        self.last_keyframe_pose.as_ref()
145    }
146
147    pub const fn selected_keyframe_count(&self) -> usize {
148        self.selected_keyframe_count
149    }
150
151    pub const fn last_keyframe_tracked_landmark_count(&self) -> Option<usize> {
152        self.last_keyframe_tracked_landmark_count
153    }
154
155    fn selected(
156        &mut self,
157        result: &TrackingResult,
158        pose: &Pose,
159        reason: KeyframeDecisionReason,
160    ) -> KeyframeDecision {
161        self.last_keyframe_frame_id = Some(result.frame_id);
162        self.last_keyframe_pose = Some(pose.clone());
163        self.last_keyframe_tracked_landmark_count = Some(result.localization.inlier_count);
164        self.selected_keyframe_count += 1;
165        self.decision(result.frame_id, true, reason)
166    }
167
168    const fn rejected(
169        &self,
170        result: &TrackingResult,
171        reason: KeyframeDecisionReason,
172    ) -> KeyframeDecision {
173        self.decision(result.frame_id, false, reason)
174    }
175
176    const fn decision(
177        &self,
178        frame_id: FrameId,
179        selected: bool,
180        reason: KeyframeDecisionReason,
181    ) -> KeyframeDecision {
182        KeyframeDecision {
183            frame_id,
184            selected,
185            reason,
186            last_keyframe_frame_id: self.last_keyframe_frame_id,
187            selected_keyframe_count: self.selected_keyframe_count,
188        }
189    }
190
191    fn tracked_landmark_drop_reason(
192        &self,
193        result: &TrackingResult,
194        frame_id_gap: u64,
195    ) -> Option<KeyframeDecisionReason> {
196        let min_tracked_landmark_ratio = self.config.tracked_landmark_keyframe_ratio?;
197        if !(0.0..=1.0).contains(&min_tracked_landmark_ratio) {
198            return None;
199        }
200
201        let last_keyframe_tracked_landmarks = self.last_keyframe_tracked_landmark_count?;
202        if last_keyframe_tracked_landmarks < self.config.min_tracked_landmarks_for_quality_keyframe
203        {
204            return None;
205        }
206
207        let tracked_landmarks = result.localization.inlier_count;
208        if tracked_landmarks < self.config.min_tracked_landmarks_for_quality_keyframe {
209            return None;
210        }
211
212        let threshold = last_keyframe_tracked_landmarks as f64 * min_tracked_landmark_ratio;
213        if tracked_landmarks < last_keyframe_tracked_landmarks
214            && (tracked_landmarks as f64) <= threshold
215        {
216            return Some(KeyframeDecisionReason::TrackedLandmarkDrop {
217                frame_id_gap,
218                tracked_landmarks,
219                last_keyframe_tracked_landmarks,
220                min_tracked_landmark_ratio,
221            });
222        }
223
224        None
225    }
226
227    /// When a frame has cleared the frame-id-gap and translation gates and
228    /// would otherwise be promoted, check it against the optional
229    /// `min_inliers` / `min_inlier_ratio` tracking-quality floors. Returns
230    /// `Some` (rejecting the promotion) when either configured threshold is
231    /// not met; `None` (both thresholds absent, or both satisfied) leaves
232    /// the promotion to proceed as `ThresholdsMet`.
233    fn insufficient_tracking_quality_reason(
234        &self,
235        result: &TrackingResult,
236    ) -> Option<KeyframeDecisionReason> {
237        let min_inliers = self.config.min_inliers;
238        let min_inlier_ratio = self.config.min_inlier_ratio;
239        let inlier_count = result.localization.inlier_count;
240        let inlier_ratio = result.localization.inlier_ratio;
241
242        let fails_min_inliers = min_inliers.is_some_and(|min| inlier_count < min);
243        let fails_min_inlier_ratio = min_inlier_ratio.is_some_and(|min| inlier_ratio < min);
244        if fails_min_inliers || fails_min_inlier_ratio {
245            Some(KeyframeDecisionReason::InsufficientTrackingQuality {
246                inlier_count,
247                inlier_ratio,
248                min_inliers,
249                min_inlier_ratio,
250            })
251        } else {
252            None
253        }
254    }
255}
256
257impl KeyframePolicy for SimpleKeyframePolicy {
258    fn evaluate(&mut self, result: &TrackingResult) -> KeyframeDecision {
259        if !result.localization.success {
260            return self.rejected(result, KeyframeDecisionReason::NotLocalized);
261        }
262
263        let Some(pose) = result.localization.pose.as_ref() else {
264            return self.rejected(result, KeyframeDecisionReason::MissingPose);
265        };
266
267        let Some(last_frame_id) = self.last_keyframe_frame_id else {
268            return self.selected(result, pose, KeyframeDecisionReason::FirstSuccessfulFrame);
269        };
270
271        if result.event == TrackingEvent::Relocalized && self.config.select_relocalized_frames {
272            return self.selected(result, pose, KeyframeDecisionReason::Relocalized);
273        }
274
275        let frame_id_gap = result.frame_id.saturating_sub(last_frame_id);
276        if frame_id_gap < self.config.min_frame_id_gap {
277            return self.rejected(
278                result,
279                KeyframeDecisionReason::FrameIdGapTooSmall {
280                    frame_id_gap,
281                    min_frame_id_gap: self.config.min_frame_id_gap,
282                },
283            );
284        }
285
286        if let Some(reason) = self.tracked_landmark_drop_reason(result, frame_id_gap) {
287            return self.selected(result, pose, reason);
288        }
289
290        if self
291            .config
292            .max_frame_id_gap
293            .is_some_and(|maximum| frame_id_gap >= maximum)
294        {
295            if let Some(reason) = self.insufficient_tracking_quality_reason(result) {
296                return self.rejected(result, reason);
297            }
298            return self.selected(
299                result,
300                pose,
301                KeyframeDecisionReason::MaximumFrameIdGap {
302                    frame_id_gap,
303                    max_frame_id_gap: self.config.max_frame_id_gap.unwrap_or(frame_id_gap),
304                },
305            );
306        }
307
308        let translation = self
309            .last_keyframe_pose
310            .as_ref()
311            .map_or(f64::INFINITY, |last_pose| {
312                (pose.camera_center_world() - last_pose.camera_center_world()).norm()
313            });
314        if translation < self.config.min_translation {
315            return self.rejected(
316                result,
317                KeyframeDecisionReason::TranslationTooSmall {
318                    translation,
319                    min_translation: self.config.min_translation,
320                },
321            );
322        }
323
324        if let Some(reason) = self.insufficient_tracking_quality_reason(result) {
325            return self.rejected(result, reason);
326        }
327
328        self.selected(
329            result,
330            pose,
331            KeyframeDecisionReason::ThresholdsMet {
332                frame_id_gap,
333                translation,
334            },
335        )
336    }
337
338    fn reset(&mut self) {
339        self.last_keyframe_frame_id = None;
340        self.last_keyframe_pose = None;
341        self.last_keyframe_tracked_landmark_count = None;
342        self.selected_keyframe_count = 0;
343    }
344}
345
346#[derive(Debug, Clone, Default, PartialEq)]
347pub struct StagedMapUpdate {
348    pub keyframes: Vec<Keyframe>,
349    pub landmarks: Vec<Landmark>,
350    pub landmark_position_covariances: Vec<(LandmarkId, Matrix3<f64>)>,
351    pub observations: Vec<Observation>,
352    pub stereo_observations: Vec<StereoObservation>,
353}
354
355impl StagedMapUpdate {
356    pub fn new() -> Self {
357        Self::default()
358    }
359
360    pub fn stage_keyframe(&mut self, keyframe: Keyframe) {
361        self.keyframes.push(keyframe);
362    }
363
364    pub fn stage_landmark(&mut self, landmark: Landmark) {
365        self.landmarks.push(landmark);
366    }
367
368    pub fn stage_landmark_position_covariance(
369        &mut self,
370        landmark_id: LandmarkId,
371        covariance_world: Matrix3<f64>,
372    ) {
373        self.landmark_position_covariances
374            .push((landmark_id, covariance_world));
375    }
376
377    pub fn stage_observation(&mut self, observation: Observation) {
378        self.observations.push(observation);
379    }
380
381    pub fn stage_stereo_observation(&mut self, observation: StereoObservation) {
382        self.stereo_observations.push(observation);
383    }
384
385    pub fn with_keyframe(mut self, keyframe: Keyframe) -> Self {
386        self.stage_keyframe(keyframe);
387        self
388    }
389
390    pub fn with_landmark(mut self, landmark: Landmark) -> Self {
391        self.stage_landmark(landmark);
392        self
393    }
394
395    pub fn with_landmark_position_covariance(
396        mut self,
397        landmark_id: LandmarkId,
398        covariance_world: Matrix3<f64>,
399    ) -> Self {
400        self.stage_landmark_position_covariance(landmark_id, covariance_world);
401        self
402    }
403
404    pub fn with_observation(mut self, observation: Observation) -> Self {
405        self.stage_observation(observation);
406        self
407    }
408
409    pub fn stage_triangulated_landmark(&mut self, triangulated: TriangulatedLandmark) {
410        let TriangulatedLandmark {
411            mut landmark,
412            position_covariance_world,
413            stereo_observations,
414            ..
415        } = triangulated;
416        let observations = std::mem::take(&mut landmark.observations);
417        let landmark_id = landmark.id;
418        self.stage_landmark(landmark);
419        if let Some(covariance) = position_covariance_world {
420            self.stage_landmark_position_covariance(landmark_id, covariance);
421        }
422        for observation in observations {
423            self.stage_observation(observation);
424        }
425        for observation in stereo_observations {
426            self.stage_stereo_observation(observation);
427        }
428    }
429
430    pub fn is_empty(&self) -> bool {
431        self.keyframes.is_empty()
432            && self.landmarks.is_empty()
433            && self.landmark_position_covariances.is_empty()
434            && self.observations.is_empty()
435            && self.stereo_observations.is_empty()
436    }
437
438    pub fn validate_against(&self, map: &VisualMap) -> MapUpdateValidationReport {
439        let mut report = MapUpdateValidationReport::default();
440        self.validate_keyframes(map, &mut report);
441        self.validate_landmarks(map, &mut report);
442        self.validate_landmark_covariances(map, &mut report);
443        self.validate_observations(map, &mut report);
444        self.validate_stereo_observations(map, &mut report);
445        report
446    }
447
448    pub fn apply_to(
449        self,
450        map: &mut VisualMap,
451    ) -> Result<AppliedMapUpdate, MapUpdateValidationReport> {
452        let report = self.validate_against(map);
453        if !report.is_valid() {
454            return Err(report);
455        }
456
457        let applied = AppliedMapUpdate {
458            keyframe_count: self.keyframes.len(),
459            landmark_count: self.landmarks.len(),
460            observation_count: self.observations.len(),
461            stereo_observation_count: self.stereo_observations.len(),
462        };
463
464        let mut embedded_keyframe_observations = Vec::new();
465        for keyframe in self.keyframes {
466            embedded_keyframe_observations.extend(keyframe.observations.iter().cloned());
467            map.keyframes.insert(keyframe.frame.id, keyframe);
468        }
469        for landmark in self.landmarks {
470            map.landmarks.insert(landmark.id, landmark);
471        }
472        for (landmark_id, covariance) in self.landmark_position_covariances {
473            map.landmark_position_covariances
474                .insert(landmark_id, covariance);
475        }
476        // A tracking-produced keyframe already carries its inlier
477        // observations. Mirror those into the existing landmark records just
478        // like explicitly staged observations; otherwise VisualMap's two
479        // observation indices silently diverge and later covariance /
480        // covisibility queries see an empty landmark history.
481        for observation in embedded_keyframe_observations {
482            if let Some(landmark) = map.landmarks.get_mut(&observation.landmark_id) {
483                if !landmark.observations.iter().any(|existing| {
484                    existing.frame_id == observation.frame_id
485                        && existing.landmark_id == observation.landmark_id
486                        && existing.keypoint_index == observation.keypoint_index
487                }) {
488                    landmark.observations.push(observation);
489                }
490            }
491        }
492        for observation in self.observations {
493            if let Some(keyframe) = map.keyframes.get_mut(&observation.frame_id) {
494                if !keyframe.observations.iter().any(|existing| {
495                    existing.frame_id == observation.frame_id
496                        && existing.landmark_id == observation.landmark_id
497                        && existing.keypoint_index == observation.keypoint_index
498                }) {
499                    keyframe.observations.push(observation.clone());
500                }
501            }
502            if let Some(landmark) = map.landmarks.get_mut(&observation.landmark_id) {
503                if !landmark.observations.iter().any(|existing| {
504                    existing.frame_id == observation.frame_id
505                        && existing.landmark_id == observation.landmark_id
506                        && existing.keypoint_index == observation.keypoint_index
507                }) {
508                    landmark.observations.push(observation);
509                }
510            }
511        }
512        map.stereo_observations.extend(self.stereo_observations);
513
514        Ok(applied)
515    }
516
517    fn validate_keyframes(&self, map: &VisualMap, report: &mut MapUpdateValidationReport) {
518        let mut staged_frame_ids = Vec::new();
519        for keyframe in &self.keyframes {
520            let frame_id = keyframe.frame.id;
521            if map.keyframes.contains_key(&frame_id) {
522                report.push(MapUpdateValidationIssue::KeyframeAlreadyExists { frame_id });
523            }
524            if staged_frame_ids.contains(&frame_id) {
525                report.push(MapUpdateValidationIssue::DuplicateStagedKeyframe { frame_id });
526            }
527            staged_frame_ids.push(frame_id);
528
529            if !map.cameras.contains_key(&keyframe.frame.camera_id) {
530                report.push(MapUpdateValidationIssue::MissingCameraForKeyframe {
531                    frame_id,
532                    camera_id: keyframe.frame.camera_id,
533                });
534            }
535        }
536    }
537
538    fn validate_landmarks(&self, map: &VisualMap, report: &mut MapUpdateValidationReport) {
539        let mut staged_landmark_ids = Vec::new();
540        for landmark in &self.landmarks {
541            if map.landmarks.contains_key(&landmark.id) {
542                report.push(MapUpdateValidationIssue::LandmarkAlreadyExists {
543                    landmark_id: landmark.id,
544                });
545            }
546            if staged_landmark_ids.contains(&landmark.id) {
547                report.push(MapUpdateValidationIssue::DuplicateStagedLandmark {
548                    landmark_id: landmark.id,
549                });
550            }
551            staged_landmark_ids.push(landmark.id);
552        }
553    }
554
555    fn validate_landmark_covariances(
556        &self,
557        map: &VisualMap,
558        report: &mut MapUpdateValidationReport,
559    ) {
560        let mut seen = Vec::new();
561        for (landmark_id, covariance) in &self.landmark_position_covariances {
562            if seen.contains(landmark_id) {
563                report.push(
564                    MapUpdateValidationIssue::DuplicateStagedLandmarkCovariance {
565                        landmark_id: *landmark_id,
566                    },
567                );
568            }
569            seen.push(*landmark_id);
570            let landmark_exists = self
571                .landmarks
572                .iter()
573                .any(|landmark| landmark.id == *landmark_id)
574                || map.landmarks.contains_key(landmark_id);
575            if !landmark_exists {
576                report.push(MapUpdateValidationIssue::CovarianceMissingLandmark {
577                    landmark_id: *landmark_id,
578                });
579            }
580            let symmetry_error = (covariance - covariance.transpose()).norm();
581            let scale = 1.0 + covariance.norm();
582            let finite = covariance.iter().all(|value| value.is_finite());
583            let positive_semidefinite = finite
584                && ((covariance + covariance.transpose()) * 0.5)
585                    .symmetric_eigen()
586                    .eigenvalues
587                    .iter()
588                    .all(|value| *value >= -1.0e-12);
589            if !finite || symmetry_error > 1.0e-9 * scale || !positive_semidefinite {
590                report.push(MapUpdateValidationIssue::InvalidStagedLandmarkCovariance {
591                    landmark_id: *landmark_id,
592                });
593            }
594        }
595    }
596
597    fn validate_observations(&self, map: &VisualMap, report: &mut MapUpdateValidationReport) {
598        let mut staged_observations = Vec::new();
599        for observation in &self.observations {
600            if staged_observations.contains(&observation_key(observation)) {
601                report.push(MapUpdateValidationIssue::DuplicateStagedObservation {
602                    frame_id: observation.frame_id,
603                    landmark_id: observation.landmark_id,
604                    keypoint_index: observation.keypoint_index,
605                });
606            }
607            staged_observations.push(observation_key(observation));
608
609            let keyframe = self
610                .keyframes
611                .iter()
612                .find(|keyframe| keyframe.frame.id == observation.frame_id)
613                .or_else(|| map.keyframes.get(&observation.frame_id));
614            if keyframe.is_none() {
615                report.push(MapUpdateValidationIssue::ObservationMissingKeyframe {
616                    frame_id: observation.frame_id,
617                    landmark_id: observation.landmark_id,
618                    keypoint_index: observation.keypoint_index,
619                });
620            }
621
622            let landmark_exists = self
623                .landmarks
624                .iter()
625                .any(|landmark| landmark.id == observation.landmark_id)
626                || map.landmarks.contains_key(&observation.landmark_id);
627            if !landmark_exists {
628                report.push(MapUpdateValidationIssue::ObservationMissingLandmark {
629                    frame_id: observation.frame_id,
630                    landmark_id: observation.landmark_id,
631                    keypoint_index: observation.keypoint_index,
632                });
633            }
634
635            let Some(keyframe) = keyframe else {
636                continue;
637            };
638            if observation.keypoint_index >= keyframe.frame.keypoints.len() {
639                report.push(MapUpdateValidationIssue::ObservationKeypointOutOfBounds {
640                    frame_id: observation.frame_id,
641                    landmark_id: observation.landmark_id,
642                    keypoint_index: observation.keypoint_index,
643                    keypoint_count: keyframe.frame.keypoints.len(),
644                });
645            }
646        }
647    }
648
649    fn validate_stereo_observations(
650        &self,
651        map: &VisualMap,
652        report: &mut MapUpdateValidationReport,
653    ) {
654        let mut seen = Vec::new();
655        for stereo in &self.stereo_observations {
656            let key = (stereo.frame_id, stereo.landmark_id);
657            if seen.contains(&key)
658                || map.stereo_observations.iter().any(|existing| {
659                    existing.frame_id == stereo.frame_id
660                        && existing.landmark_id == stereo.landmark_id
661                })
662            {
663                report.push(MapUpdateValidationIssue::DuplicateStagedStereoObservation {
664                    frame_id: stereo.frame_id,
665                    landmark_id: stereo.landmark_id,
666                });
667            }
668            seen.push(key);
669            let keyframe_exists = self
670                .keyframes
671                .iter()
672                .any(|keyframe| keyframe.frame.id == stereo.frame_id)
673                || map.keyframes.contains_key(&stereo.frame_id);
674            if !keyframe_exists {
675                report.push(MapUpdateValidationIssue::StereoObservationMissingKeyframe {
676                    frame_id: stereo.frame_id,
677                    landmark_id: stereo.landmark_id,
678                });
679            }
680            let landmark_exists = self
681                .landmarks
682                .iter()
683                .any(|landmark| landmark.id == stereo.landmark_id)
684                || map.landmarks.contains_key(&stereo.landmark_id);
685            if !landmark_exists {
686                report.push(MapUpdateValidationIssue::StereoObservationMissingLandmark {
687                    frame_id: stereo.frame_id,
688                    landmark_id: stereo.landmark_id,
689                });
690            }
691            if !map.cameras.contains_key(&stereo.right_camera_id) {
692                report.push(
693                    MapUpdateValidationIssue::StereoObservationMissingRightCamera {
694                        frame_id: stereo.frame_id,
695                        landmark_id: stereo.landmark_id,
696                        camera_id: stereo.right_camera_id,
697                    },
698                );
699            }
700            let staged_left = self.observations.iter().any(|observation| {
701                observation.frame_id == stereo.frame_id
702                    && observation.landmark_id == stereo.landmark_id
703            }) || self.keyframes.iter().any(|keyframe| {
704                keyframe.frame.id == stereo.frame_id
705                    && keyframe
706                        .observations
707                        .iter()
708                        .any(|observation| observation.landmark_id == stereo.landmark_id)
709            });
710            let existing_left = map.keyframes.get(&stereo.frame_id).is_some_and(|keyframe| {
711                keyframe
712                    .observations
713                    .iter()
714                    .any(|observation| observation.landmark_id == stereo.landmark_id)
715            });
716            if !staged_left && !existing_left {
717                report.push(
718                    MapUpdateValidationIssue::StereoObservationMissingLeftObservation {
719                        frame_id: stereo.frame_id,
720                        landmark_id: stereo.landmark_id,
721                    },
722                );
723            }
724        }
725    }
726}
727
728#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
729pub struct AppliedMapUpdate {
730    pub keyframe_count: usize,
731    pub landmark_count: usize,
732    pub observation_count: usize,
733    pub stereo_observation_count: usize,
734}
735
736#[derive(Debug, Clone, Default, PartialEq, Eq)]
737pub struct MapUpdateValidationReport {
738    pub issues: Vec<MapUpdateValidationIssue>,
739}
740
741impl MapUpdateValidationReport {
742    pub fn is_valid(&self) -> bool {
743        self.issues.is_empty()
744    }
745
746    pub fn issue_count(&self) -> usize {
747        self.issues.len()
748    }
749
750    pub fn push(&mut self, issue: MapUpdateValidationIssue) {
751        self.issues.push(issue);
752    }
753
754    pub fn into_result(self) -> Result<(), Self> {
755        if self.is_valid() {
756            Ok(())
757        } else {
758            Err(self)
759        }
760    }
761}
762
763#[derive(Debug, Clone, PartialEq, Eq)]
764pub enum MapUpdateValidationIssue {
765    KeyframeAlreadyExists {
766        frame_id: FrameId,
767    },
768    DuplicateStagedKeyframe {
769        frame_id: FrameId,
770    },
771    MissingCameraForKeyframe {
772        frame_id: FrameId,
773        camera_id: CameraId,
774    },
775    LandmarkAlreadyExists {
776        landmark_id: LandmarkId,
777    },
778    DuplicateStagedLandmark {
779        landmark_id: LandmarkId,
780    },
781    DuplicateStagedLandmarkCovariance {
782        landmark_id: LandmarkId,
783    },
784    CovarianceMissingLandmark {
785        landmark_id: LandmarkId,
786    },
787    InvalidStagedLandmarkCovariance {
788        landmark_id: LandmarkId,
789    },
790    ObservationMissingKeyframe {
791        frame_id: FrameId,
792        landmark_id: LandmarkId,
793        keypoint_index: usize,
794    },
795    ObservationMissingLandmark {
796        frame_id: FrameId,
797        landmark_id: LandmarkId,
798        keypoint_index: usize,
799    },
800    ObservationKeypointOutOfBounds {
801        frame_id: FrameId,
802        landmark_id: LandmarkId,
803        keypoint_index: usize,
804        keypoint_count: usize,
805    },
806    DuplicateStagedObservation {
807        frame_id: FrameId,
808        landmark_id: LandmarkId,
809        keypoint_index: usize,
810    },
811    DuplicateStagedStereoObservation {
812        frame_id: FrameId,
813        landmark_id: LandmarkId,
814    },
815    StereoObservationMissingKeyframe {
816        frame_id: FrameId,
817        landmark_id: LandmarkId,
818    },
819    StereoObservationMissingLandmark {
820        frame_id: FrameId,
821        landmark_id: LandmarkId,
822    },
823    StereoObservationMissingRightCamera {
824        frame_id: FrameId,
825        landmark_id: LandmarkId,
826        camera_id: CameraId,
827    },
828    StereoObservationMissingLeftObservation {
829        frame_id: FrameId,
830        landmark_id: LandmarkId,
831    },
832}
833
834const fn observation_key(observation: &Observation) -> (FrameId, LandmarkId, usize) {
835    (
836        observation.frame_id,
837        observation.landmark_id,
838        observation.keypoint_index,
839    )
840}
841
842#[derive(Debug, Clone, PartialEq, Eq)]
843pub struct LocalMapWindowConfig {
844    pub max_keyframes: usize,
845}
846
847impl Default for LocalMapWindowConfig {
848    fn default() -> Self {
849        Self { max_keyframes: 5 }
850    }
851}
852
853#[derive(Debug, Clone, Default, PartialEq, Eq)]
854pub struct LocalMapWindow {
855    pub anchor_frame_id: Option<FrameId>,
856    pub keyframe_ids: Vec<FrameId>,
857    pub landmark_ids: Vec<LandmarkId>,
858    pub observation_count: usize,
859}
860
861impl LocalMapWindow {
862    pub fn from_anchor(
863        map: &VisualMap,
864        anchor_frame_id: FrameId,
865        config: &LocalMapWindowConfig,
866    ) -> Self {
867        let max_keyframes = config.max_keyframes.max(1);
868        let mut keyframe_ids = map
869            .keyframes
870            .keys()
871            .copied()
872            .filter(|frame_id| *frame_id <= anchor_frame_id)
873            .collect::<Vec<_>>();
874        keyframe_ids.sort_unstable();
875        if keyframe_ids.len() > max_keyframes {
876            keyframe_ids = keyframe_ids[keyframe_ids.len() - max_keyframes..].to_vec();
877        }
878
879        Self::from_keyframe_ids(map, Some(anchor_frame_id), keyframe_ids)
880    }
881
882    pub fn from_recent(map: &VisualMap, config: &LocalMapWindowConfig) -> Self {
883        let Some(anchor_frame_id) = map.keyframes.keys().max().copied() else {
884            return Self::default();
885        };
886        Self::from_anchor(map, anchor_frame_id, config)
887    }
888
889    pub fn from_keyframe_ids(
890        map: &VisualMap,
891        anchor_frame_id: Option<FrameId>,
892        mut keyframe_ids: Vec<FrameId>,
893    ) -> Self {
894        keyframe_ids.sort_unstable();
895        keyframe_ids.dedup();
896        keyframe_ids.retain(|frame_id| map.keyframes.contains_key(frame_id));
897
898        let mut landmark_ids = Vec::new();
899        let mut observation_count = 0;
900        for keyframe_id in &keyframe_ids {
901            let Some(keyframe) = map.keyframes.get(keyframe_id) else {
902                continue;
903            };
904            observation_count += keyframe.observations.len();
905            for observation in &keyframe.observations {
906                if map.landmarks.contains_key(&observation.landmark_id) {
907                    landmark_ids.push(observation.landmark_id);
908                }
909            }
910        }
911        landmark_ids.sort_unstable();
912        landmark_ids.dedup();
913
914        Self {
915            anchor_frame_id,
916            keyframe_ids,
917            landmark_ids,
918            observation_count,
919        }
920    }
921
922    pub fn keyframe_count(&self) -> usize {
923        self.keyframe_ids.len()
924    }
925
926    pub fn landmark_count(&self) -> usize {
927        self.landmark_ids.len()
928    }
929
930    pub fn is_empty(&self) -> bool {
931        self.keyframe_ids.is_empty()
932    }
933}
934
935pub type LandmarkCandidateId = u64;
936
937#[derive(Debug, Clone, PartialEq)]
938pub struct LandmarkCandidate {
939    pub id: LandmarkCandidateId,
940    pub observations: Vec<LandmarkCandidateObservation>,
941    pub descriptor: Option<Vec<f32>>,
942    /// Optional world-frame covariance supplied by a metric depth source.
943    /// The multi-view triangulator may update the point mean while retaining
944    /// this first-order uncertainty model for covariance-aware backend factors.
945    pub position_covariance_world: Option<Matrix3<f64>>,
946}
947
948impl LandmarkCandidate {
949    pub const fn new(id: LandmarkCandidateId) -> Self {
950        Self {
951            id,
952            observations: Vec::new(),
953            descriptor: None,
954            position_covariance_world: None,
955        }
956    }
957
958    pub fn with_observation(mut self, observation: LandmarkCandidateObservation) -> Self {
959        self.observations.push(observation);
960        self
961    }
962
963    pub fn with_descriptor(mut self, descriptor: Vec<f32>) -> Self {
964        self.descriptor = Some(descriptor);
965        self
966    }
967
968    pub const fn with_position_covariance_world(mut self, covariance: Matrix3<f64>) -> Self {
969        self.position_covariance_world = Some(covariance);
970        self
971    }
972
973    pub fn observation_count(&self) -> usize {
974        self.observations.len()
975    }
976
977    pub fn is_triangulatable(&self, min_observations: usize) -> bool {
978        self.observations.len() >= min_observations.max(2)
979    }
980
981    pub fn validate_against(
982        &self,
983        map: &VisualMap,
984        window: Option<&LocalMapWindow>,
985        config: &LandmarkCandidateValidationConfig,
986    ) -> LandmarkCandidateValidationReport {
987        let mut report = LandmarkCandidateValidationReport::default();
988        let min_observations = config.min_observations.max(2);
989        if self.observations.len() < min_observations {
990            report.push(LandmarkCandidateValidationIssue::TooFewObservations {
991                observation_count: self.observations.len(),
992                min_observations,
993            });
994        }
995        let mut seen = Vec::new();
996        for observation in &self.observations {
997            let key = candidate_observation_key(observation);
998            if seen.contains(&key) {
999                report.push(LandmarkCandidateValidationIssue::DuplicateObservation {
1000                    frame_id: observation.frame_id,
1001                    keypoint_index: observation.keypoint_index,
1002                });
1003            }
1004            seen.push(key);
1005
1006            let Some(keyframe) = map.keyframes.get(&observation.frame_id) else {
1007                report.push(LandmarkCandidateValidationIssue::MissingKeyframe {
1008                    frame_id: observation.frame_id,
1009                });
1010                continue;
1011            };
1012
1013            if observation.keypoint_index >= keyframe.frame.keypoints.len() {
1014                report.push(LandmarkCandidateValidationIssue::KeypointOutOfBounds {
1015                    frame_id: observation.frame_id,
1016                    keypoint_index: observation.keypoint_index,
1017                    keypoint_count: keyframe.frame.keypoints.len(),
1018                });
1019            }
1020
1021            if let Some(window) = window {
1022                if !window.keyframe_ids.contains(&observation.frame_id) {
1023                    report.push(
1024                        LandmarkCandidateValidationIssue::ObservationOutsideLocalWindow {
1025                            frame_id: observation.frame_id,
1026                        },
1027                    );
1028                }
1029            }
1030        }
1031
1032        report
1033    }
1034}
1035
1036#[derive(Debug, Clone, PartialEq)]
1037pub struct LandmarkCandidateObservation {
1038    pub frame_id: FrameId,
1039    pub keypoint_index: usize,
1040    pub xy: Point2<f64>,
1041    pub stereo: Option<LandmarkCandidateStereoMeasurement>,
1042}
1043
1044#[derive(Debug, Clone, PartialEq)]
1045pub struct LandmarkCandidateStereoMeasurement {
1046    pub right_camera_id: CameraId,
1047    pub xy_right: Point2<f64>,
1048    pub left_to_right: SE3,
1049}
1050
1051impl LandmarkCandidateObservation {
1052    pub const fn new(frame_id: FrameId, keypoint_index: usize, xy: Point2<f64>) -> Self {
1053        Self {
1054            frame_id,
1055            keypoint_index,
1056            xy,
1057            stereo: None,
1058        }
1059    }
1060
1061    pub const fn with_stereo_measurement(
1062        mut self,
1063        right_camera_id: CameraId,
1064        xy_right: Point2<f64>,
1065        left_to_right: SE3,
1066    ) -> Self {
1067        self.stereo = Some(LandmarkCandidateStereoMeasurement {
1068            right_camera_id,
1069            xy_right,
1070            left_to_right,
1071        });
1072        self
1073    }
1074}
1075
1076#[derive(Debug, Clone, PartialEq, Eq)]
1077pub struct LandmarkCandidateValidationConfig {
1078    pub min_observations: usize,
1079}
1080
1081impl Default for LandmarkCandidateValidationConfig {
1082    fn default() -> Self {
1083        Self {
1084            min_observations: 2,
1085        }
1086    }
1087}
1088
1089#[derive(Debug, Clone, Default, PartialEq, Eq)]
1090pub struct LandmarkCandidateValidationReport {
1091    pub issues: Vec<LandmarkCandidateValidationIssue>,
1092}
1093
1094impl LandmarkCandidateValidationReport {
1095    pub fn is_valid(&self) -> bool {
1096        self.issues.is_empty()
1097    }
1098
1099    pub fn issue_count(&self) -> usize {
1100        self.issues.len()
1101    }
1102
1103    pub fn push(&mut self, issue: LandmarkCandidateValidationIssue) {
1104        self.issues.push(issue);
1105    }
1106
1107    pub fn into_result(self) -> Result<(), Self> {
1108        if self.is_valid() {
1109            Ok(())
1110        } else {
1111            Err(self)
1112        }
1113    }
1114}
1115
1116#[derive(Debug, Clone, PartialEq, Eq)]
1117pub enum LandmarkCandidateValidationIssue {
1118    TooFewObservations {
1119        observation_count: usize,
1120        min_observations: usize,
1121    },
1122    MissingKeyframe {
1123        frame_id: FrameId,
1124    },
1125    KeypointOutOfBounds {
1126        frame_id: FrameId,
1127        keypoint_index: usize,
1128        keypoint_count: usize,
1129    },
1130    DuplicateObservation {
1131        frame_id: FrameId,
1132        keypoint_index: usize,
1133    },
1134    ObservationOutsideLocalWindow {
1135        frame_id: FrameId,
1136    },
1137}
1138
1139const fn candidate_observation_key(observation: &LandmarkCandidateObservation) -> (FrameId, usize) {
1140    (observation.frame_id, observation.keypoint_index)
1141}
1142
1143pub trait Triangulator {
1144    fn triangulate(
1145        &self,
1146        candidate: &LandmarkCandidate,
1147        map: &VisualMap,
1148    ) -> Result<TriangulatedLandmark, TriangulationFailureReason>;
1149}
1150
1151#[derive(Debug, Clone, PartialEq)]
1152pub struct LinearTriangulator {
1153    pub config: TriangulationConfig,
1154}
1155
1156impl Default for LinearTriangulator {
1157    fn default() -> Self {
1158        Self::new(TriangulationConfig::default())
1159    }
1160}
1161
1162impl LinearTriangulator {
1163    pub const fn new(config: TriangulationConfig) -> Self {
1164        Self { config }
1165    }
1166}
1167
1168impl Triangulator for LinearTriangulator {
1169    fn triangulate(
1170        &self,
1171        candidate: &LandmarkCandidate,
1172        map: &VisualMap,
1173    ) -> Result<TriangulatedLandmark, TriangulationFailureReason> {
1174        let validation_config = LandmarkCandidateValidationConfig {
1175            min_observations: self.config.min_observations,
1176        };
1177        let validation = candidate.validate_against(map, None, &validation_config);
1178        if !validation.is_valid() {
1179            return Err(TriangulationFailureReason::CandidateValidationFailed(
1180                validation,
1181            ));
1182        }
1183
1184        let mut a = DMatrix::<f64>::zeros(candidate.observations.len() * 2, 4);
1185        for (observation_index, observation) in candidate.observations.iter().enumerate() {
1186            let keyframe = map
1187                .keyframes
1188                .get(&observation.frame_id)
1189                .expect("candidate validation ensures keyframe exists");
1190            let camera = map.cameras.get(&keyframe.frame.camera_id).ok_or(
1191                TriangulationFailureReason::MissingCamera {
1192                    frame_id: keyframe.frame.id,
1193                    camera_id: keyframe.frame.camera_id,
1194                },
1195            )?;
1196            let pose =
1197                keyframe
1198                    .frame
1199                    .pose
1200                    .as_ref()
1201                    .ok_or(TriangulationFailureReason::MissingPose {
1202                        frame_id: keyframe.frame.id,
1203                    })?;
1204            let normalized = camera.normalize_pixel(&observation.xy).ok_or(
1205                TriangulationFailureReason::UnsupportedCameraModel {
1206                    frame_id: keyframe.frame.id,
1207                    camera_id: keyframe.frame.camera_id,
1208                },
1209            )?;
1210            let matrix = pose.matrix();
1211            let row0 = matrix.row(0);
1212            let row1 = matrix.row(1);
1213            let row2 = matrix.row(2);
1214            let row_x = observation_index * 2;
1215            let row_y = row_x + 1;
1216            for column in 0..4 {
1217                a[(row_x, column)] = normalized.x * row2[column] - row0[column];
1218                a[(row_y, column)] = normalized.y * row2[column] - row1[column];
1219            }
1220        }
1221
1222        let svd = a.svd(false, true);
1223        let Some(v_t) = svd.v_t else {
1224            return Err(TriangulationFailureReason::DegenerateGeometry);
1225        };
1226        let homogeneous = v_t.row(v_t.nrows() - 1);
1227        let w = homogeneous[3];
1228        if w.abs() <= self.config.min_homogeneous_scale {
1229            return Err(TriangulationFailureReason::DegenerateGeometry);
1230        }
1231        let position = Point3::new(homogeneous[0] / w, homogeneous[1] / w, homogeneous[2] / w);
1232
1233        let mut reprojection_errors = Vec::new();
1234        for observation in &candidate.observations {
1235            let keyframe = map
1236                .keyframes
1237                .get(&observation.frame_id)
1238                .expect("candidate validation ensures keyframe exists");
1239            let camera = map
1240                .cameras
1241                .get(&keyframe.frame.camera_id)
1242                .expect("camera was checked before solving");
1243            let pose = keyframe
1244                .frame
1245                .pose
1246                .as_ref()
1247                .expect("pose was checked before solving");
1248            let point_camera = pose.transform_world_point(&position);
1249            if self.config.require_positive_depth && point_camera.z <= 0.0 {
1250                return Err(TriangulationFailureReason::PointBehindCamera {
1251                    frame_id: keyframe.frame.id,
1252                });
1253            }
1254            let projected = camera.project(&point_camera).ok_or(
1255                TriangulationFailureReason::ProjectionFailed {
1256                    frame_id: keyframe.frame.id,
1257                    camera_id: keyframe.frame.camera_id,
1258                },
1259            )?;
1260            reprojection_errors.push((projected - observation.xy).norm());
1261        }
1262
1263        let mean_reprojection_error = mean(&reprojection_errors);
1264        let max_reprojection_error = reprojection_errors.iter().copied().fold(0.0_f64, f64::max);
1265        if let Some(max_mean_reprojection_error) = self.config.max_mean_reprojection_error {
1266            if mean_reprojection_error > max_mean_reprojection_error {
1267                return Err(TriangulationFailureReason::ReprojectionErrorTooHigh {
1268                    mean_reprojection_error,
1269                    max_mean_reprojection_error,
1270                });
1271            }
1272        }
1273
1274        let mut landmark = Landmark::new(candidate.id, position);
1275        landmark.descriptor = candidate.descriptor.clone();
1276        landmark.observations = candidate
1277            .observations
1278            .iter()
1279            .map(|observation| Observation {
1280                frame_id: observation.frame_id,
1281                landmark_id: candidate.id,
1282                keypoint_index: observation.keypoint_index,
1283                xy: observation.xy,
1284            })
1285            .collect();
1286
1287        Ok(TriangulatedLandmark {
1288            landmark,
1289            position_covariance_world: candidate.position_covariance_world,
1290            stereo_observations: candidate
1291                .observations
1292                .iter()
1293                .filter_map(|observation| {
1294                    observation.stereo.as_ref().map(|stereo| StereoObservation {
1295                        frame_id: observation.frame_id,
1296                        landmark_id: candidate.id,
1297                        right_camera_id: stereo.right_camera_id,
1298                        xy_right: stereo.xy_right,
1299                        left_to_right: stereo.left_to_right.clone(),
1300                    })
1301                })
1302                .collect(),
1303            observation_count: candidate.observations.len(),
1304            mean_reprojection_error,
1305            max_reprojection_error,
1306            reprojection_errors,
1307        })
1308    }
1309}
1310
1311#[derive(Debug, Clone, PartialEq)]
1312pub struct TriangulationConfig {
1313    pub min_observations: usize,
1314    pub min_homogeneous_scale: f64,
1315    pub require_positive_depth: bool,
1316    pub max_mean_reprojection_error: Option<f64>,
1317}
1318
1319impl Default for TriangulationConfig {
1320    fn default() -> Self {
1321        Self {
1322            min_observations: 2,
1323            min_homogeneous_scale: 1.0e-12,
1324            require_positive_depth: true,
1325            max_mean_reprojection_error: Some(2.0),
1326        }
1327    }
1328}
1329
1330#[derive(Debug, Clone, PartialEq)]
1331pub struct TriangulatedLandmark {
1332    pub landmark: Landmark,
1333    pub position_covariance_world: Option<Matrix3<f64>>,
1334    pub stereo_observations: Vec<StereoObservation>,
1335    pub observation_count: usize,
1336    pub mean_reprojection_error: f64,
1337    pub max_reprojection_error: f64,
1338    pub reprojection_errors: Vec<f64>,
1339}
1340
1341#[derive(Debug, Clone, PartialEq)]
1342pub enum TriangulationFailureReason {
1343    CandidateValidationFailed(LandmarkCandidateValidationReport),
1344    MissingCamera {
1345        frame_id: FrameId,
1346        camera_id: CameraId,
1347    },
1348    UnsupportedCameraModel {
1349        frame_id: FrameId,
1350        camera_id: CameraId,
1351    },
1352    MissingPose {
1353        frame_id: FrameId,
1354    },
1355    DegenerateGeometry,
1356    PointBehindCamera {
1357        frame_id: FrameId,
1358    },
1359    ProjectionFailed {
1360        frame_id: FrameId,
1361        camera_id: CameraId,
1362    },
1363    ReprojectionErrorTooHigh {
1364        mean_reprojection_error: f64,
1365        max_mean_reprojection_error: f64,
1366    },
1367}
1368
1369fn mean(values: &[f64]) -> f64 {
1370    if values.is_empty() {
1371        0.0
1372    } else {
1373        values.iter().sum::<f64>() / values.len() as f64
1374    }
1375}
1376
1377pub trait LocalRefiner {
1378    fn refine(
1379        &self,
1380        map: &VisualMap,
1381        local_window: &LocalMapWindow,
1382        staged_update: &mut StagedMapUpdate,
1383    ) -> LocalRefinementResult;
1384}
1385
1386#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
1387pub struct NoopLocalRefiner;
1388
1389impl LocalRefiner for NoopLocalRefiner {
1390    fn refine(
1391        &self,
1392        _map: &VisualMap,
1393        _local_window: &LocalMapWindow,
1394        _staged_update: &mut StagedMapUpdate,
1395    ) -> LocalRefinementResult {
1396        LocalRefinementResult {
1397            refined: false,
1398            reason: LocalRefinementReason::Noop,
1399            keyframe_count: 0,
1400            landmark_count: 0,
1401        }
1402    }
1403}
1404
1405#[derive(Debug, Clone, PartialEq, Eq)]
1406pub struct LocalRefinementResult {
1407    pub refined: bool,
1408    pub reason: LocalRefinementReason,
1409    pub keyframe_count: usize,
1410    pub landmark_count: usize,
1411}
1412
1413impl LocalRefinementResult {
1414    pub const fn skipped(reason: LocalRefinementReason) -> Self {
1415        Self {
1416            refined: false,
1417            reason,
1418            keyframe_count: 0,
1419            landmark_count: 0,
1420        }
1421    }
1422}
1423
1424#[derive(Debug, Clone, PartialEq, Eq)]
1425pub enum LocalRefinementReason {
1426    Noop,
1427    NoSelectedKeyframe,
1428    Refined,
1429}
1430
1431#[derive(Debug, Clone, PartialEq)]
1432pub struct LocalMappingPipeline<
1433    K = SimpleKeyframePolicy,
1434    T = LinearTriangulator,
1435    R = NoopLocalRefiner,
1436> {
1437    pub keyframe_policy: K,
1438    pub triangulator: T,
1439    pub local_refiner: R,
1440    pub local_window_config: LocalMapWindowConfig,
1441    pub candidate_validation_config: LandmarkCandidateValidationConfig,
1442}
1443
1444impl Default for LocalMappingPipeline<SimpleKeyframePolicy, LinearTriangulator, NoopLocalRefiner> {
1445    fn default() -> Self {
1446        Self {
1447            keyframe_policy: SimpleKeyframePolicy::default(),
1448            triangulator: LinearTriangulator::default(),
1449            local_refiner: NoopLocalRefiner,
1450            local_window_config: LocalMapWindowConfig::default(),
1451            candidate_validation_config: LandmarkCandidateValidationConfig::default(),
1452        }
1453    }
1454}
1455
1456impl<K, T> LocalMappingPipeline<K, T, NoopLocalRefiner>
1457where
1458    K: KeyframePolicy,
1459    T: Triangulator,
1460{
1461    pub const fn new(
1462        keyframe_policy: K,
1463        triangulator: T,
1464        local_window_config: LocalMapWindowConfig,
1465        candidate_validation_config: LandmarkCandidateValidationConfig,
1466    ) -> Self {
1467        Self {
1468            keyframe_policy,
1469            triangulator,
1470            local_refiner: NoopLocalRefiner,
1471            local_window_config,
1472            candidate_validation_config,
1473        }
1474    }
1475}
1476
1477impl<K, T, R> LocalMappingPipeline<K, T, R>
1478where
1479    K: KeyframePolicy,
1480    T: Triangulator,
1481    R: LocalRefiner,
1482{
1483    pub const fn with_refiner(
1484        keyframe_policy: K,
1485        triangulator: T,
1486        local_refiner: R,
1487        local_window_config: LocalMapWindowConfig,
1488        candidate_validation_config: LandmarkCandidateValidationConfig,
1489    ) -> Self {
1490        Self {
1491            keyframe_policy,
1492            triangulator,
1493            local_refiner,
1494            local_window_config,
1495            candidate_validation_config,
1496        }
1497    }
1498
1499    pub fn reset(&mut self) {
1500        self.keyframe_policy.reset();
1501    }
1502
1503    pub fn process_keyframe<I>(
1504        &mut self,
1505        map: &VisualMap,
1506        tracking_result: &TrackingResult,
1507        keyframe: Keyframe,
1508        candidates: I,
1509    ) -> LocalMappingResult
1510    where
1511        I: IntoIterator<Item = LandmarkCandidate>,
1512    {
1513        let keyframe_decision = self.keyframe_policy.evaluate(tracking_result);
1514        let mut staged_update = StagedMapUpdate::new();
1515        let mut triangulated_landmarks = Vec::new();
1516        let mut candidate_failures = Vec::new();
1517
1518        if !keyframe_decision.selected {
1519            let local_window = LocalMapWindow::from_recent(map, &self.local_window_config);
1520            let staged_update_validation = staged_update.validate_against(map);
1521            let refinement =
1522                LocalRefinementResult::skipped(LocalRefinementReason::NoSelectedKeyframe);
1523            return LocalMappingResult {
1524                keyframe_decision,
1525                local_window,
1526                staged_update,
1527                triangulated_landmarks,
1528                candidate_failures,
1529                refinement,
1530                staged_update_validation,
1531            };
1532        }
1533
1534        staged_update.stage_keyframe(keyframe.clone());
1535
1536        let mut working_map = map.clone();
1537        working_map.keyframes.insert(keyframe.frame.id, keyframe);
1538        let local_window = LocalMapWindow::from_anchor(
1539            &working_map,
1540            tracking_result.frame_id,
1541            &self.local_window_config,
1542        );
1543
1544        for candidate in candidates {
1545            let validation = candidate.validate_against(
1546                &working_map,
1547                Some(&local_window),
1548                &self.candidate_validation_config,
1549            );
1550            if !validation.is_valid() {
1551                candidate_failures.push(LandmarkCandidateMappingFailure {
1552                    candidate_id: candidate.id,
1553                    reason: LandmarkCandidateMappingFailureReason::CandidateValidationFailed(
1554                        validation,
1555                    ),
1556                });
1557                continue;
1558            }
1559
1560            match self.triangulator.triangulate(&candidate, &working_map) {
1561                Ok(triangulated) => {
1562                    staged_update.stage_triangulated_landmark(triangulated.clone());
1563                    triangulated_landmarks.push(triangulated);
1564                }
1565                Err(reason) => {
1566                    candidate_failures.push(LandmarkCandidateMappingFailure {
1567                        candidate_id: candidate.id,
1568                        reason: LandmarkCandidateMappingFailureReason::TriangulationFailed(reason),
1569                    });
1570                }
1571            }
1572        }
1573
1574        let refinement = self
1575            .local_refiner
1576            .refine(&working_map, &local_window, &mut staged_update);
1577        let staged_update_validation = staged_update.validate_against(map);
1578        LocalMappingResult {
1579            keyframe_decision,
1580            local_window,
1581            staged_update,
1582            triangulated_landmarks,
1583            candidate_failures,
1584            refinement,
1585            staged_update_validation,
1586        }
1587    }
1588}
1589
1590#[derive(Debug, Clone, PartialEq)]
1591pub struct LocalMappingResult {
1592    pub keyframe_decision: KeyframeDecision,
1593    pub local_window: LocalMapWindow,
1594    pub staged_update: StagedMapUpdate,
1595    pub triangulated_landmarks: Vec<TriangulatedLandmark>,
1596    pub candidate_failures: Vec<LandmarkCandidateMappingFailure>,
1597    pub refinement: LocalRefinementResult,
1598    pub staged_update_validation: MapUpdateValidationReport,
1599}
1600
1601impl LocalMappingResult {
1602    pub fn is_ready_to_apply(&self) -> bool {
1603        self.keyframe_decision.selected
1604            && self.staged_update_validation.is_valid()
1605            && self.candidate_failures.is_empty()
1606    }
1607}
1608
1609#[derive(Debug, Clone, PartialEq)]
1610pub struct LandmarkCandidateMappingFailure {
1611    pub candidate_id: LandmarkCandidateId,
1612    pub reason: LandmarkCandidateMappingFailureReason,
1613}
1614
1615#[derive(Debug, Clone, PartialEq)]
1616pub enum LandmarkCandidateMappingFailureReason {
1617    CandidateValidationFailed(LandmarkCandidateValidationReport),
1618    TriangulationFailed(TriangulationFailureReason),
1619}