1use std::collections::{HashMap, HashSet};
25
26use nalgebra::Point2;
27use visloc_core::geometry::{Pose, SE3};
28use visloc_core::types::{Camera, FrameId, VisualMap};
29use visloc_vision::features::FeatureSet;
30use visloc_vision::matching::BruteForceMatcher;
31use visloc_vision::stereo_bootstrap::{bootstrap_stereo_landmarks, StereoBootstrapConfig};
32
33use crate::{LandmarkCandidate, LandmarkCandidateId, LandmarkCandidateObservation};
34
35#[derive(Debug, Clone, PartialEq)]
43pub struct StereoReplenishConfig {
44 pub max_candidates_per_frame: usize,
48 pub bootstrap_config: StereoBootstrapConfig,
51 pub anchor_keypoint_match_radius_px: f64,
58 pub anchor_keypoint_max_descriptor_distance: Option<f32>,
65 pub duplicate_suppression_radius_px: f64,
75 pub min_parallax_deg: f64,
83 pub min_depth_meters: f64,
86 pub max_depth_meters: f64,
89}
90
91impl Default for StereoReplenishConfig {
92 fn default() -> Self {
93 Self {
94 max_candidates_per_frame: 100,
96 bootstrap_config: StereoBootstrapConfig::default(),
97 anchor_keypoint_match_radius_px: 5.0,
102 anchor_keypoint_max_descriptor_distance: None,
105 duplicate_suppression_radius_px: 3.0,
109 min_parallax_deg: 0.5,
113 min_depth_meters: 0.1,
115 max_depth_meters: 50.0,
116 }
117 }
118}
119
120pub fn build_stereo_metric_points(
125 cam0_camera: &Camera,
126 cam1_camera: &Camera,
127 cam0_to_cam1: &SE3,
128 cam0_features: &FeatureSet,
129 cam1_features: &FeatureSet,
130 config: &StereoReplenishConfig,
131) -> HashMap<usize, nalgebra::Point3<f64>> {
132 bootstrap_stereo_landmarks(
133 cam0_camera,
134 cam1_camera,
135 cam0_to_cam1,
136 cam0_features,
137 cam1_features,
138 &config.bootstrap_config,
139 )
140 .into_iter()
141 .filter(|survivor| {
142 let depth = survivor.point_left_camera_frame.z;
143 depth.is_finite() && depth >= config.min_depth_meters && depth <= config.max_depth_meters
144 })
145 .map(|survivor| {
146 (
147 survivor.left_keypoint_index,
148 survivor.point_left_camera_frame,
149 )
150 })
151 .collect()
152}
153
154#[allow(clippy::too_many_arguments)]
191pub fn build_stereo_replenish_candidates(
192 map: &VisualMap,
193 anchor_frame_id: FrameId,
194 frame_id: FrameId,
195 cam1_camera: &Camera,
196 cam0_to_cam1: &SE3,
197 cam0_features: &FeatureSet,
198 cam1_features: &FeatureSet,
199 matched_cam0_indices: &HashSet<usize>,
200 current_pose: &Pose,
201 next_candidate_id: LandmarkCandidateId,
202 config: &StereoReplenishConfig,
203) -> Vec<LandmarkCandidate> {
204 let Some(anchor_keyframe) = map.keyframes.get(&anchor_frame_id) else {
206 return Vec::new();
207 };
208 let Some(anchor_pose) = anchor_keyframe.frame.pose.as_ref() else {
209 return Vec::new();
210 };
211 let Some(cam0_camera) = map.cameras.get(&anchor_keyframe.frame.camera_id) else {
214 return Vec::new();
215 };
216 if anchor_keyframe.frame.keypoints.is_empty() {
217 return Vec::new();
218 }
219
220 let survivors = bootstrap_stereo_landmarks(
221 cam0_camera,
222 cam1_camera,
223 cam0_to_cam1,
224 cam0_features,
225 cam1_features,
226 &config.bootstrap_config,
227 );
228 if survivors.is_empty() {
229 return Vec::new();
230 }
231
232 let mut existing_reprojections: Vec<Point2<f64>> =
240 Vec::with_capacity(anchor_keyframe.observations.len());
241 let mut claimed_anchor_indices: HashSet<usize> =
242 HashSet::with_capacity(anchor_keyframe.observations.len());
243 for observation in &anchor_keyframe.observations {
244 claimed_anchor_indices.insert(observation.keypoint_index);
245 if let Some(landmark) = map.landmarks.get(&observation.landmark_id) {
246 let point_current = current_pose.transform_world_point(&landmark.position);
247 if let Some(pixel) = cam0_camera.project(&point_current) {
248 existing_reprojections.push(pixel);
249 }
250 }
251 }
252
253 let camera_to_world = current_pose.camera_to_world();
254 let anchor_center = anchor_pose.camera_center_world();
255 let current_center = current_pose.camera_center_world();
256 let min_parallax_cos = config.min_parallax_deg.to_radians().cos();
257 let width = cam0_camera.width as f64;
258 let height = cam0_camera.height as f64;
259
260 let mut candidates: Vec<LandmarkCandidate> = Vec::new();
261 let mut next_id = next_candidate_id;
262
263 for survivor in &survivors {
264 if candidates.len() >= config.max_candidates_per_frame {
267 break;
268 }
269
270 if matched_cam0_indices.contains(&survivor.left_keypoint_index) {
272 continue;
273 }
274
275 let raw_left_pixel = cam0_features.keypoints[survivor.left_keypoint_index];
276
277 if existing_reprojections.iter().any(|reprojection| {
280 (reprojection - raw_left_pixel).norm() <= config.duplicate_suppression_radius_px
281 }) {
282 continue;
283 }
284
285 let world_point = camera_to_world.transform_point(&survivor.point_left_camera_frame);
288 let anchor_camera_point = anchor_pose.transform_world_point(&world_point);
289
290 if anchor_camera_point.z <= 0.0 {
294 continue;
295 }
296 let Some(anchor_xy) = cam0_camera.project(&anchor_camera_point) else {
297 continue;
298 };
299 if anchor_xy.x < 0.0 || anchor_xy.x > width || anchor_xy.y < 0.0 || anchor_xy.y > height {
302 continue;
303 }
304
305 let depth = survivor.point_left_camera_frame.z;
308 if !depth.is_finite() || depth < config.min_depth_meters || depth > config.max_depth_meters
309 {
310 continue;
311 }
312
313 let anchor_ray = world_point - anchor_center;
315 let current_ray = world_point - current_center;
316 let anchor_ray_norm = anchor_ray.norm();
317 let current_ray_norm = current_ray.norm();
318 if anchor_ray_norm <= f64::EPSILON || current_ray_norm <= f64::EPSILON {
319 continue;
320 }
321 let cos_parallax = anchor_ray.dot(¤t_ray) / (anchor_ray_norm * current_ray_norm);
322 if cos_parallax.clamp(-1.0, 1.0) >= min_parallax_cos {
325 continue;
326 }
327
328 let mut best_index: Option<usize> = None;
332 let mut best_distance = config.anchor_keypoint_match_radius_px;
333 for (index, keypoint) in anchor_keyframe.frame.keypoints.iter().enumerate() {
334 if claimed_anchor_indices.contains(&index) {
335 continue;
336 }
337 let distance = (keypoint - anchor_xy).norm();
338 if distance <= best_distance {
339 best_distance = distance;
340 best_index = Some(index);
341 }
342 }
343 let Some(anchor_keypoint_index) = best_index else {
344 continue;
347 };
348 let anchor_measured_xy = anchor_keyframe.frame.keypoints[anchor_keypoint_index];
349
350 let candidate_descriptor = &cam0_features.descriptors[survivor.left_keypoint_index];
351
352 if let Some(max_descriptor_distance) = config.anchor_keypoint_max_descriptor_distance {
354 let Some(anchor_descriptor) =
355 anchor_keyframe.frame.descriptors.get(anchor_keypoint_index)
356 else {
357 continue;
358 };
359 match BruteForceMatcher::l2_distance(candidate_descriptor, anchor_descriptor) {
360 Some(distance) if distance <= max_descriptor_distance => {}
361 _ => continue,
362 }
363 }
364
365 claimed_anchor_indices.insert(anchor_keypoint_index);
366 let candidate_id = next_id;
367 next_id += 1;
368 let rotation_camera_to_world = camera_to_world.rotation.to_rotation_matrix().into_inner();
369 let covariance_world = rotation_camera_to_world
370 * survivor.point_covariance_left_camera_frame
371 * rotation_camera_to_world.transpose();
372 candidates.push(
373 LandmarkCandidate::new(candidate_id)
374 .with_observation(
375 LandmarkCandidateObservation::new(
376 frame_id,
377 survivor.left_keypoint_index,
378 raw_left_pixel,
379 )
380 .with_stereo_measurement(
381 cam1_camera.id,
382 cam1_features.keypoints[survivor.right_keypoint_index],
383 cam0_to_cam1.clone(),
384 ),
385 )
386 .with_observation(LandmarkCandidateObservation::new(
387 anchor_frame_id,
388 anchor_keypoint_index,
389 anchor_measured_xy,
390 ))
391 .with_descriptor(candidate_descriptor.clone())
392 .with_position_covariance_world(covariance_world),
393 );
394 }
395
396 candidates
397}
398
399#[cfg(test)]
400mod tests {
401 use super::*;
402 use nalgebra::{Point2, Point3, UnitQuaternion, Vector3};
403 use visloc_core::types::{Frame, Keyframe, Landmark, Observation};
404
405 fn cam0() -> Camera {
406 Camera::pinhole(1, 752, 480, 458.0, 457.0, 367.0, 248.0)
407 }
408
409 fn cam0_to_cam1() -> SE3 {
411 SE3::new(UnitQuaternion::identity(), Vector3::new(-0.11, 0.0, 0.0))
412 }
413
414 fn anchor_keyframe(frame_id: u64, keypoints: Vec<Point2<f64>>) -> Keyframe {
417 let mut frame = Frame::new(frame_id, 1);
418 frame.descriptors = keypoints.iter().map(|_| vec![1.0_f32, 0.0]).collect();
419 frame.keypoints = keypoints;
420 frame.pose = Some(Pose::identity());
421 Keyframe {
422 frame,
423 observations: Vec::new(),
424 }
425 }
426
427 fn base_map(anchor: Keyframe) -> VisualMap {
428 let mut map = VisualMap::new();
429 map.cameras.insert(1, cam0());
430 map.keyframes.insert(anchor.frame.id, anchor);
431 map
432 }
433
434 fn project_identity(point: &Point3<f64>) -> Point2<f64> {
436 cam0().project(point).expect("in front of camera")
437 }
438
439 fn stereo_features(
443 world_points: &[Point3<f64>],
444 current_pose: &Pose,
445 ) -> (FeatureSet, FeatureSet) {
446 let cam = cam0();
447 let l2r = cam0_to_cam1();
448 let mut cam0_kps = Vec::new();
449 let mut cam1_kps = Vec::new();
450 let mut cam0_desc = Vec::new();
451 let mut cam1_desc = Vec::new();
452 for (i, world) in world_points.iter().enumerate() {
453 let point_left = current_pose.transform_world_point(world);
454 let point_right = l2r.transform_point(&point_left);
455 cam0_kps.push(cam.project(&point_left).expect("left in front"));
456 cam1_kps.push(cam.project(&point_right).expect("right in front"));
457 let mut desc = vec![0.0_f32; world_points.len()];
458 desc[i] = 1.0;
459 cam0_desc.push(desc.clone());
460 cam1_desc.push(desc);
461 }
462 (
463 FeatureSet::new(cam0_kps, cam0_desc).unwrap(),
464 FeatureSet::new(cam1_kps, cam1_desc).unwrap(),
465 )
466 }
467
468 fn current_pose_shifted(tx: f64) -> Pose {
471 Pose::from_world_to_camera(UnitQuaternion::identity(), Vector3::new(-tx, 0.0, 0.0))
473 }
474
475 #[test]
476 fn happy_path_builds_candidate_with_real_anchor_keypoint_index() {
477 let current = current_pose_shifted(0.3);
478 let world = Point3::new(0.2, -0.1, 4.0);
480 let (cam0_features, cam1_features) = stereo_features(&[world], ¤t);
481
482 let anchor_pixel = project_identity(&world);
486 let anchor = anchor_keyframe(
487 10,
488 vec![
489 Point2::new(5.0, 5.0),
490 Point2::new(700.0, 400.0),
491 anchor_pixel,
492 ],
493 );
494 let map = base_map(anchor);
495
496 let candidates = build_stereo_replenish_candidates(
497 &map,
498 10,
499 42,
500 &cam0(),
501 &cam0_to_cam1(),
502 &cam0_features,
503 &cam1_features,
504 &HashSet::new(),
505 ¤t,
506 1000,
507 &StereoReplenishConfig::default(),
508 );
509
510 assert_eq!(candidates.len(), 1);
511 let candidate = &candidates[0];
512 assert_eq!(candidate.id, 1000);
513 assert_eq!(candidate.observations.len(), 2);
514 assert_eq!(candidate.observations[0].frame_id, 42);
516 assert_eq!(candidate.observations[0].keypoint_index, 0);
517 let stereo = candidate.observations[0]
518 .stereo
519 .as_ref()
520 .expect("current observation retains its cam1 measurement");
521 assert_eq!(stereo.right_camera_id, cam0().id);
522 assert_eq!(stereo.xy_right, cam1_features.keypoints[0]);
523 assert_eq!(stereo.left_to_right, cam0_to_cam1());
524 assert_eq!(candidate.observations[1].frame_id, 10);
526 assert_eq!(candidate.observations[1].keypoint_index, 2);
527 assert_eq!(candidate.observations[1].xy, anchor_pixel);
528 assert!(candidate.observations[1].stereo.is_none());
529 assert!(candidate.descriptor.is_some());
530 let covariance = candidate
531 .position_covariance_world
532 .expect("stereo uncertainty is retained for downstream backend factors");
533 assert!(covariance.iter().all(|value| value.is_finite()));
534 assert!(covariance.trace() > 0.0);
535 }
536
537 #[test]
538 fn anchor_observation_uses_measured_pixel_not_stereo_prediction() {
539 let current = current_pose_shifted(0.3);
540 let world = Point3::new(0.2, -0.1, 4.0);
541 let (cam0_features, cam1_features) = stereo_features(&[world], ¤t);
542 let predicted = project_identity(&world);
543 let measured = predicted + nalgebra::Vector2::new(1.25, -0.75);
546 let map = base_map(anchor_keyframe(10, vec![measured]));
547
548 let candidates = build_stereo_replenish_candidates(
549 &map,
550 10,
551 42,
552 &cam0(),
553 &cam0_to_cam1(),
554 &cam0_features,
555 &cam1_features,
556 &HashSet::new(),
557 ¤t,
558 1000,
559 &StereoReplenishConfig::default(),
560 );
561
562 assert_eq!(candidates.len(), 1);
563 assert_eq!(candidates[0].observations[1].keypoint_index, 0);
564 assert_eq!(candidates[0].observations[1].xy, measured);
565 assert_ne!(candidates[0].observations[1].xy, predicted);
566 }
567
568 #[test]
569 fn matched_index_is_excluded() {
570 let current = current_pose_shifted(0.3);
571 let world = Point3::new(0.2, -0.1, 4.0);
572 let (cam0_features, cam1_features) = stereo_features(&[world], ¤t);
573 let anchor_pixel = project_identity(&world);
574 let anchor = anchor_keyframe(10, vec![anchor_pixel]);
575 let map = base_map(anchor);
576
577 let mut matched = HashSet::new();
579 matched.insert(0usize);
580
581 let candidates = build_stereo_replenish_candidates(
582 &map,
583 10,
584 42,
585 &cam0(),
586 &cam0_to_cam1(),
587 &cam0_features,
588 &cam1_features,
589 &matched,
590 ¤t,
591 1000,
592 &StereoReplenishConfig::default(),
593 );
594 assert!(candidates.is_empty());
595 }
596
597 #[test]
598 fn duplicate_suppression_drops_survivor_near_existing_landmark() {
599 let current = current_pose_shifted(0.3);
600 let world = Point3::new(0.2, -0.1, 4.0);
601 let (cam0_features, cam1_features) = stereo_features(&[world], ¤t);
602 let anchor_pixel = project_identity(&world);
603 let mut anchor = anchor_keyframe(10, vec![anchor_pixel]);
604
605 let mut map = base_map(anchor.clone());
608 map.landmarks.insert(500, Landmark::new(500, world));
609 anchor.observations.push(Observation {
610 frame_id: 10,
611 landmark_id: 500,
612 keypoint_index: 0,
613 xy: anchor_pixel,
614 });
615 map.keyframes.insert(10, anchor);
616
617 let candidates = build_stereo_replenish_candidates(
618 &map,
619 10,
620 42,
621 &cam0(),
622 &cam0_to_cam1(),
623 &cam0_features,
624 &cam1_features,
625 &HashSet::new(),
626 ¤t,
627 1000,
628 &StereoReplenishConfig::default(),
629 );
630 assert!(candidates.is_empty());
631 }
632
633 #[test]
634 fn parallax_gate_drops_zero_baseline_geometry() {
635 let current = Pose::identity();
638 let world = Point3::new(0.2, -0.1, 4.0);
639 let (cam0_features, cam1_features) = stereo_features(&[world], ¤t);
640 let anchor_pixel = project_identity(&world);
641 let anchor = anchor_keyframe(10, vec![anchor_pixel]);
642 let map = base_map(anchor);
643
644 let candidates = build_stereo_replenish_candidates(
645 &map,
646 10,
647 42,
648 &cam0(),
649 &cam0_to_cam1(),
650 &cam0_features,
651 &cam1_features,
652 &HashSet::new(),
653 ¤t,
654 1000,
655 &StereoReplenishConfig::default(),
656 );
657 assert!(
658 candidates.is_empty(),
659 "zero anchor/current baseline must fail the parallax gate"
660 );
661 }
662
663 #[test]
664 fn anchor_reprojection_out_of_bounds_is_dropped() {
665 let current = current_pose_shifted(0.3);
670 let world = Point3::new(0.2, -0.1, 4.0);
671 let (cam0_features, cam1_features) = stereo_features(&[world], ¤t);
672
673 let mut anchor = anchor_keyframe(10, vec![Point2::new(367.0, 248.0)]);
675 anchor.frame.pose = Some(Pose::from_world_to_camera(
676 UnitQuaternion::from_axis_angle(&Vector3::y_axis(), std::f64::consts::PI),
677 Vector3::zeros(),
678 ));
679 let map = base_map(anchor);
680
681 let candidates = build_stereo_replenish_candidates(
682 &map,
683 10,
684 42,
685 &cam0(),
686 &cam0_to_cam1(),
687 &cam0_features,
688 &cam1_features,
689 &HashSet::new(),
690 ¤t,
691 1000,
692 &StereoReplenishConfig::default(),
693 );
694 assert!(
695 candidates.is_empty(),
696 "point behind the anchor camera must be dropped"
697 );
698 }
699
700 #[test]
701 fn no_anchor_keypoint_within_radius_is_dropped() {
702 let current = current_pose_shifted(0.3);
703 let world = Point3::new(0.2, -0.1, 4.0);
704 let (cam0_features, cam1_features) = stereo_features(&[world], ¤t);
705 let anchor = anchor_keyframe(10, vec![Point2::new(5.0, 5.0)]);
707 let map = base_map(anchor);
708
709 let candidates = build_stereo_replenish_candidates(
710 &map,
711 10,
712 42,
713 &cam0(),
714 &cam0_to_cam1(),
715 &cam0_features,
716 &cam1_features,
717 &HashSet::new(),
718 ¤t,
719 1000,
720 &StereoReplenishConfig::default(),
721 );
722 assert!(
723 candidates.is_empty(),
724 "no real anchor keypoint nearby → no fabricated index"
725 );
726 }
727
728 #[test]
729 fn per_frame_cap_truncates_returned_candidates() {
730 let current = current_pose_shifted(0.3);
731 let worlds = [
733 Point3::new(-0.4, 0.1, 4.0),
734 Point3::new(0.0, -0.2, 5.0),
735 Point3::new(0.5, 0.2, 3.5),
736 ];
737 let (cam0_features, cam1_features) = stereo_features(&worlds, ¤t);
738 let anchor_pixels: Vec<Point2<f64>> = worlds.iter().map(project_identity).collect();
740 let anchor = anchor_keyframe(10, anchor_pixels);
741 let map = base_map(anchor);
742
743 let config = StereoReplenishConfig {
744 max_candidates_per_frame: 2,
745 ..StereoReplenishConfig::default()
746 };
747 let candidates = build_stereo_replenish_candidates(
748 &map,
749 10,
750 42,
751 &cam0(),
752 &cam0_to_cam1(),
753 &cam0_features,
754 &cam1_features,
755 &HashSet::new(),
756 ¤t,
757 2000,
758 &config,
759 );
760 assert_eq!(candidates.len(), 2, "cap must truncate to 2");
761 assert_eq!(candidates[0].id, 2000);
763 assert_eq!(candidates[1].id, 2001);
764 assert_ne!(
766 candidates[0].observations[1].keypoint_index,
767 candidates[1].observations[1].keypoint_index
768 );
769 }
770
771 #[test]
772 fn missing_anchor_keyframe_returns_empty() {
773 let current = current_pose_shifted(0.3);
774 let world = Point3::new(0.2, -0.1, 4.0);
775 let (cam0_features, cam1_features) = stereo_features(&[world], ¤t);
776 let map = VisualMap::new(); let candidates = build_stereo_replenish_candidates(
779 &map,
780 10,
781 42,
782 &cam0(),
783 &cam0_to_cam1(),
784 &cam0_features,
785 &cam1_features,
786 &HashSet::new(),
787 ¤t,
788 1000,
789 &StereoReplenishConfig::default(),
790 );
791 assert!(candidates.is_empty());
792 }
793}