vector-space 0.4.0

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

/// This trait defines the scalar product and adds commom vector operations.
pub trait InnerSpace: VectorSpace {
    /// The scalar product.
    fn scalar(&self, other: &Self) -> Self::Scalar;

    /// The squared magnitude.
    ///
    /// This is more efficient than calculating the magnitude.
    /// Useful if you need the squared magnitude anyway.
    #[inline]
    fn magnitude2(&self) -> Self::Scalar {
        self.scalar(self)
    }

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

    /// The normalized vector.
    #[inline]
    fn normalize(self) -> Self {
        let mag = self.magnitude();
        self / mag
    }

    /// The angle between two vectors.
    #[inline]
    fn angle(&self, other: &Self) -> Self::Scalar {
        (self.scalar(other) / (self.magnitude() * other.magnitude())).acos()
    }

    /// Sets the magnitude of a vector.
    #[inline]
    fn with_magnitude(self, magnitude: Self::Scalar) -> Self {
        let mag = self.magnitude();
        self * (magnitude / mag)
    }

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

    /// The value of the vector along the specified axis.
    #[inline]
    fn query_axis(&self, dir: Self) -> Self::Scalar {
        self.scalar(&dir.normalize())
    }

    /// Projects a vector onto an already normalized direction vector.
    #[inline]
    fn normalized_project(self, dir: Self) -> Self {
        let scalar = self.scalar(&dir);
        dir * scalar
    }

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

    /// Rejects a vector from an already normalized direction vector.
    #[inline]
    fn normalized_reject(self, dir: Self) -> Self {
        let scalar = self.scalar(&dir);
        let proj = dir * scalar;
        self - proj
    }

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

    /// Reflects a vector from an already normalized direction vector.
    #[inline]
    fn normalized_reflect(self, dir: Self) -> Self {
        let scalar = self.scalar(&dir);
        let proj = dir * scalar;
        proj * (Self::Scalar::one() + Self::Scalar::one()) - self
    }

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

impl InnerSpace for f32 {
    fn scalar(&self, other: &Self) -> Self {
        self * other
    }
}
impl InnerSpace for f64 {
    fn scalar(&self, other: &Self) -> Self {
        self * other
    }
}