use std::cmp::Ordering;
use std::fmt;
use nalgebra::{Point2, Point3};
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ViewId(pub u32);
impl ViewId {
pub fn index(self) -> usize {
self.0 as usize
}
}
impl fmt::Display for ViewId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "view {}", self.0)
}
}
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct PairId {
a: ViewId,
b: ViewId,
}
impl PairId {
pub fn new(i: ViewId, j: ViewId) -> Option<Self> {
match i.cmp(&j) {
Ordering::Less => Some(PairId { a: i, b: j }),
Ordering::Greater => Some(PairId { a: j, b: i }),
Ordering::Equal => None,
}
}
pub fn a(self) -> ViewId {
self.a
}
pub fn b(self) -> ViewId {
self.b
}
pub fn contains(self, view: ViewId) -> bool {
self.a == view || self.b == view
}
pub fn other(self, view: ViewId) -> Option<ViewId> {
if view == self.a {
Some(self.b)
} else if view == self.b {
Some(self.a)
} else {
None
}
}
pub fn all(views: u32) -> impl Iterator<Item = PairId> {
(0..views).flat_map(move |a| {
(a + 1..views).map(move |b| PairId {
a: ViewId(a),
b: ViewId(b),
})
})
}
pub fn count(views: usize) -> usize {
views * views.saturating_sub(1) / 2
}
}
impl fmt::Display for PairId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "views {}–{}", self.a.0, self.b.0)
}
}
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct PhotoPx(pub Point2<f32>);
impl PhotoPx {
pub fn new(x: f32, y: f32) -> Self {
PhotoPx(Point2::new(x, y))
}
pub fn x(self) -> f32 {
self.0.x
}
pub fn y(self) -> f32 {
self.0.y
}
}
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct Norm(pub Point2<f64>);
impl Norm {
pub fn new(x: f64, y: f64) -> Self {
Norm(Point2::new(x, y))
}
pub fn x(self) -> f64 {
self.0.x
}
pub fn y(self) -> f64 {
self.0.y
}
}
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct World(pub Point3<f64>);
impl World {
pub fn new(x: f64, y: f64, z: f64) -> Self {
World(Point3::new(x, y, z))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn pairs_are_unordered_and_exclude_self_pairs() {
let (i, j) = (ViewId(3), ViewId(1));
let pair = PairId::new(i, j).expect("distinct views");
assert_eq!(pair, PairId::new(j, i).unwrap());
assert_eq!((pair.a(), pair.b()), (ViewId(1), ViewId(3)));
assert_eq!(pair.other(ViewId(1)), Some(ViewId(3)));
assert_eq!(pair.other(ViewId(2)), None);
assert!(pair.contains(ViewId(3)));
assert!(PairId::new(i, i).is_none());
}
#[test]
fn enumerates_every_pair_once() {
for views in 0..7u32 {
let pairs: Vec<_> = PairId::all(views).collect();
assert_eq!(pairs.len(), PairId::count(views as usize));
assert!(pairs.windows(2).all(|w| w[0] < w[1]), "sorted and distinct");
}
let four: Vec<_> = PairId::all(4).map(|p| (p.a().0, p.b().0)).collect();
assert_eq!(four, [(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)]);
}
}