use std::borrow::Cow;
use std::fmt;
use std::ops::ControlFlow;
use crate::sfm::DropReason;
use crate::twoview::Degeneracy;
use crate::types::{PairId, PhotoPx, ViewId};
pub type Flow = ControlFlow<()>;
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum Level {
Info,
Warning,
}
impl fmt::Display for Level {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
Level::Info => "info",
Level::Warning => "warning",
})
}
}
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub struct PairMap {
pub pair: PairId,
pub columns: usize,
pub rows: usize,
pub cell_size: f32,
pub points: Vec<f32>,
pub coverage: f32,
}
impl PairMap {
pub fn pixel(&self, column: usize, row: usize) -> PhotoPx {
PhotoPx::new(column as f32 * self.cell_size, row as f32 * self.cell_size)
}
pub fn point(&self, column: usize, row: usize) -> Option<PhotoPx> {
let i = (row * self.columns + column) * 2;
let (x, y) = (*self.points.get(i)?, *self.points.get(i + 1)?);
(x.is_finite() && y.is_finite()).then(|| PhotoPx::new(x, y))
}
pub fn mapped(&self) -> usize {
self.points
.iter()
.step_by(2)
.filter(|x| x.is_finite())
.count()
}
}
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[non_exhaustive]
pub enum Stage {
Input,
Pairs,
TwoView,
Tracks,
Registration,
BundleAdjustment,
Depth,
Fusion,
Texture,
}
impl Stage {
pub const ALL: [Stage; 9] = [
Stage::Input,
Stage::Pairs,
Stage::TwoView,
Stage::Tracks,
Stage::Registration,
Stage::BundleAdjustment,
Stage::Depth,
Stage::Fusion,
Stage::Texture,
];
pub fn name(self) -> &'static str {
match self {
Stage::Input => "input",
Stage::Pairs => "pairwise correspondence",
Stage::TwoView => "two-view geometry",
Stage::Tracks => "tracks",
Stage::Registration => "registration",
Stage::BundleAdjustment => "bundle adjustment",
Stage::Depth => "dense depth",
Stage::Fusion => "fusion",
Stage::Texture => "texturing",
}
}
fn weight(self) -> f32 {
match self {
Stage::Input => 0.01,
Stage::Pairs => 0.70,
Stage::TwoView => 0.03,
Stage::Tracks => 0.02,
Stage::Registration => 0.02,
Stage::BundleAdjustment => 0.03,
Stage::Depth => 0.08,
Stage::Fusion => 0.08,
Stage::Texture => 0.03,
}
}
fn overall(self, fraction: f32) -> f32 {
let finished: f32 = Stage::ALL
.iter()
.take_while(|&&s| s < self)
.map(|s| s.weight())
.sum();
(finished + self.weight() * fraction.clamp(0.0, 1.0)).min(1.0)
}
}
impl fmt::Display for Stage {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.name())
}
}
#[derive(Clone, Debug)]
#[non_exhaustive]
pub enum Event {
Started {
views: usize,
pairs: usize,
},
Stage {
stage: Stage,
fraction: f32,
message: String,
},
PairProgress {
pair: PairId,
index: usize,
of: usize,
step: u32,
steps: u32,
},
PairMapped {
pair: PairId,
index: usize,
of: usize,
map: Box<PairMap>,
},
PairRejected {
pair: PairId,
index: usize,
of: usize,
reason: Degeneracy,
},
ViewDropped {
stage: Stage,
view: ViewId,
reason: DropReason,
},
Log {
stage: Stage,
level: Level,
message: String,
},
}
impl Event {
pub fn stage(&self) -> Stage {
match self {
Event::Started { .. } => Stage::Input,
Event::Stage { stage, .. } => *stage,
Event::PairProgress { .. } | Event::PairMapped { .. } => Stage::Pairs,
Event::PairRejected { .. } => Stage::TwoView,
Event::ViewDropped { stage, .. } | Event::Log { stage, .. } => *stage,
}
}
pub fn progress(&self) -> Option<f32> {
let within =
|index: usize, of: usize, extra: f32| (index as f32 + extra) / of.max(1) as f32;
let fraction = match self {
Event::Started { .. } => 0.0,
Event::Stage { fraction, .. } => *fraction,
Event::PairProgress {
index,
of,
step,
steps,
..
} => within(*index, *of, *step as f32 / (*steps).max(1) as f32),
Event::PairMapped { index, of, .. } | Event::PairRejected { index, of, .. } => {
within(*index + 1, *of, 0.0)
}
Event::ViewDropped { .. } | Event::Log { .. } => return None,
};
Some(self.stage().overall(fraction))
}
pub fn message(&self) -> Cow<'_, str> {
match self {
Event::Started { views, pairs } => {
Cow::Owned(format!("{views} photos, {pairs} pairs to map"))
}
Event::Stage { message, .. } => Cow::Borrowed(message),
Event::PairProgress {
pair, step, steps, ..
} => Cow::Owned(format!("mapping {pair}, step {step}/{steps}")),
Event::PairMapped { pair, map, .. } => Cow::Owned(format!(
"mapped {pair}: {:.0}% coverage",
map.coverage * 100.0
)),
Event::PairRejected { pair, reason, .. } => {
Cow::Owned(format!("{pair}: not usable, {reason}"))
}
Event::ViewDropped { view, reason, .. } => {
Cow::Owned(format!("{view} was left out: {reason}"))
}
Event::Log { message, .. } => Cow::Borrowed(message),
}
}
}
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub struct Status {
pub stage: Stage,
pub progress: f32,
pub pairs_mapped: usize,
pub pairs_total: usize,
pub message: String,
}
impl Default for Status {
fn default() -> Self {
Status {
stage: Stage::Input,
progress: 0.0,
pairs_mapped: 0,
pairs_total: 0,
message: String::new(),
}
}
}
impl Status {
pub fn new() -> Self {
Status::default()
}
pub fn update(&mut self, event: &Event) {
self.stage = event.stage();
if let Some(progress) = event.progress() {
self.progress = self.progress.max(progress);
}
match event {
Event::Started { pairs, .. } => self.pairs_total = *pairs,
Event::PairMapped { .. } => self.pairs_mapped += 1,
_ => {}
}
self.message = event.message().into_owned();
}
}
pub(crate) fn emit(
on_event: &mut dyn FnMut(Event) -> Flow,
event: Event,
) -> Result<(), crate::Error> {
let stage = event.stage();
if on_event(event).is_break() {
return Err(crate::Error::Cancelled { stage });
}
Ok(())
}
pub(crate) fn report(
on_event: &mut dyn FnMut(Event) -> Flow,
stage: Stage,
fraction: f32,
message: String,
) -> Result<(), crate::Error> {
emit(
on_event,
Event::Stage {
stage,
fraction: fraction.clamp(0.0, 1.0),
message,
},
)
}
pub(crate) fn silent(_: Event) -> Flow {
Flow::Continue(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn weights_cover_the_whole_run() {
let total: f32 = Stage::ALL.iter().map(|s| s.weight()).sum();
assert!((total - 1.0).abs() < 1e-4, "weights sum to {total}");
assert!(Stage::ALL.windows(2).all(|w| w[0] < w[1]));
}
#[test]
fn overall_progress_only_moves_forwards() {
let mut last = 0.0;
for stage in Stage::ALL {
for step in 0..=4 {
let event = Event::Stage {
stage,
fraction: step as f32 / 4.0,
message: String::new(),
};
let progress = event.progress().expect("a stage event reports progress");
assert!(progress >= last, "{stage} at {step}/4 went backwards");
last = progress;
}
}
assert!((last - 1.0).abs() < 1e-4);
}
#[test]
fn a_log_line_does_not_move_the_bar() {
let log = Event::Log {
stage: Stage::Depth,
level: Level::Warning,
message: "something".into(),
};
assert!(log.progress().is_none());
let mut status = Status::new();
status.update(&Event::Stage {
stage: Stage::Depth,
fraction: 0.5,
message: String::new(),
});
let halfway = status.progress;
status.update(&log);
assert_eq!(status.progress, halfway, "a log line left the bar alone");
assert_eq!(status.message, "something");
}
#[test]
fn a_pair_reports_where_it_is_without_the_caller_counting() {
let started = Event::PairProgress {
pair: PairId::new(ViewId(0), ViewId(2)).expect("distinct views"),
index: 1,
of: 3,
step: 2,
steps: 5,
};
let expected = Stage::Pairs.overall((1.0 + 2.0 / 5.0) / 3.0);
assert_eq!(started.progress(), Some(expected));
assert_eq!(started.message(), "mapping views 0–2, step 2/5");
}
}