use std::ops::{Add, Div, Mul, Neg, Sub};
use inner_space::{DotProduct, InnerSpace, VectorSpace, distance};
use scalars::Zero;
#[derive(Clone, Copy, PartialEq, Debug)]
struct Vector {
x: f32,
y: f32,
}
impl Vector {
fn new(x: f32, y: f32) -> Self {
Self { x, y }
}
}
impl Add for Vector {
type Output = Self;
fn add(self, other: Self) -> Self {
Self {
x: self.x + other.x,
y: self.y + other.y,
}
}
}
impl Sub for Vector {
type Output = Self;
fn sub(self, other: Self) -> Self {
Self {
x: self.x - other.x,
y: self.y - other.y,
}
}
}
impl Mul<f32> for Vector {
type Output = Self;
fn mul(self, other: f32) -> Self {
Self {
x: self.x * other,
y: self.y * other,
}
}
}
impl Div<f32> for Vector {
type Output = Self;
fn div(self, other: f32) -> Self {
Self {
x: self.x / other,
y: self.y / other,
}
}
}
impl Neg for Vector {
type Output = Self;
fn neg(self) -> Self {
Self {
x: -self.x,
y: -self.y,
}
}
}
impl Zero for Vector {
fn zero() -> Self {
Self { x: 0.0, y: 0.0 }
}
fn is_zero(&self) -> bool {
self.x == 0.0 && self.y == 0.0
}
}
impl VectorSpace for Vector {
type Scalar = f32;
}
impl DotProduct for Vector {
type Output = f32;
fn dot(&self, other: &Self) -> f32 {
self.x * other.x + self.y * other.y
}
}
#[test]
fn test_distance() {
let a = Vector::new(-1.0, 2.0);
let b = Vector::new(2.0, 6.0);
assert_eq!(distance(a, b), 5.0);
}
#[test]
fn test_project_reject_reflect() {
let a = Vector::new(-1.0, 3.0);
let b = Vector::new(0.0, 6.0);
assert_eq!(a.project(b), Vector::new(0.0, 3.0));
assert_eq!(a.reject(b), Vector::new(-1.0, 0.0));
assert_eq!(a.reflect(b), Vector::new(1.0, 3.0));
}