vector-space 0.1.0

Useful traits for working with vector spaces
Documentation
use crate::{DotProduct, VectorSpace};
use num_traits::real::Real;

/// This trait defines the dot product and adds commom vector operations.
pub trait InnerSpace: DotProduct<Output = <Self as VectorSpace>::Scalar> {
    /// The squared magnitude.
    ///
    /// This is more efficient than calculating the magnitude.
    /// Useful if you need the squared magnitude anyway.
    fn magnitude2(self) -> Self::Scalar {
        self.dot(self)
    }

    /// The magnitude of a vector.
    fn magnitude(self) -> Self::Scalar {
        self.magnitude2().sqrt()
    }

    /// The normalized vector.
    fn normalize(self) -> Self {
        self / self.magnitude()
    }

    /// The angle between two vectors.
    fn angle(self, other: Self) -> Self::Scalar {
        (self.dot(other) / (self.magnitude() * other.magnitude())).acos()
    }

    /// The distance between two vectors.
    fn distance(self, other: Self) -> Self::Scalar {
        (self - other).magnitude()
    }

    /// Sets the magnitude of a vector.
    fn with_magnitude(self, magnitude: Self::Scalar) -> Self {
        self * (magnitude / self.magnitude())
    }

    /// Sets the direction of a vector.
    fn with_direction(self, dir: Self) -> Self {
        dir * self.magnitude()
    }

    /// The value of the vector along the specified axis.
    fn query_axis(self, dir: Self) -> Self::Scalar {
        self.dot(dir.normalize())
    }

    /// Projects a vector onto an already normalized direction vector.
    fn normalized_project(self, dir: Self) -> Self {
        dir * self.dot(dir)
    }

    /// Projects a vector onto an arbitraty direction vector.
    fn project(self, dir: Self) -> Self {
        self.normalized_project(dir.normalize())
    }

    /// Rejects a vector from an already normalized direction vector.
    fn normalized_reject(self, dir: Self) -> Self {
        self - self.normalized_project(dir)
    }

    /// Rejects a vector from an arbitraty direction vector.
    fn reject(self, dir: Self) -> Self {
        self.normalized_reject(dir.normalize())
    }

    /// Reflects a vector from an already normalized direction vector.
    fn normalized_reflect(self, dir: Self) -> Self {
        let proj = self.normalized_project(dir);
        proj + proj - self
    }

    /// Reflects a vector from an arbitraty direction vector.
    fn reflect(self, dir: Self) -> Self {
        self.normalized_reflect(dir.normalize())
    }
}

impl InnerSpace for f32 {}

impl InnerSpace for f64 {}