1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
//! Set of traits to abstract over linear algebra types.
//!
//! Provides an abstraction over vector-like types. This makes it easier to
//! implement generic math algorithms.
//!
//! # Example
//! ```
//! use linear_isomorphic::*;
//!
//! pub fn point_segment_distance<Vec>(start: &Vec, end: &Vec, point: &Vec) -> f32
//! where
//!     Vec: VectorLike<Scalar = f32>,
//! {
//!     let dir = *end - *start;
//!     let t = (*point - *start).dot(&dir) / dir.norm_squared();
//!
//!     let t = t.clamp(0.0, 1.0);
//!
//!     let closest = *start + dir * t;
//!
//!     (closest - *point).norm()
//! }
//! ```


use std::fmt::{Debug, Display};
use std::ops::{
    Add,
    AddAssign,
    Div,
    DivAssign,
    Index,
    IndexMut,
    Mul,
    MulAssign,
    Neg,
    Sub,
    SubAssign,
};

use num::Float;

/// Trait representing a type isomorphic to a lin alg vector in the most basic
/// sense. That is, it supports addition and scalar multiplication. Useful to
/// write functions that work on arithmetic types.
pub trait LinAlg<S>:
    Mul<S, Output = Self>
    + Add<Output = Self>
    + AddAssign<Self>
    + Sub<Output = Self>
    + Div<S, Output = Self>
    + Neg
    + Copy // Consider removing this one out and only requiring clone.
    + Sized
where S: num::Float + AddAssign
{
}

impl<T, S> LinAlg<S> for T
where
    T: Mul<S, Output = Self>
        + Add<Output = Self>
        + AddAssign<Self>
        + Sub<Output = Self>
        + Div<S, Output = Self>
        + Neg
        + Copy
        + Sized,
    S: Mul<T, Output = T>,
    S: num::Float + AddAssign,
{
}

/// Trait representing a type which can be multiplied by, i.e. a scalar.
pub trait ScalarLike:
    Display
    + Debug
    + Default
    + AddAssign
    + Float
    + DivAssign
    + SubAssign
    + MulAssign
    + num::Float
    + 'static
{
}

impl<T> ScalarLike for T where
    T: Display
        + Debug
        + Default
        + AddAssign
        + Float
        + DivAssign
        + SubAssign
        + MulAssign
        + num::Float
        + 'static
{
}

/// Extension of the `LinAlg` trait. It also demands that the type is indexable
/// and can be default initialized (default initialization is assumed to be
/// equivalent to the 0 vector).
/// Additionally, provides methods common to vectors.
pub trait VectorLike:
    LinAlg<Self::Scalar>
    + Index<usize, Output = Self::Scalar>
    + IndexMut<usize, Output = Self::Scalar>
    + Default
{
    type Scalar: ScalarLike;

    /// Get a unit vector in the same direction as this one. Can produce
    /// NAN's.
    fn normalized(&self) -> Self;
    /// Get the current norm/length of this vector.
    fn norm(&self) -> Self::Scalar;
    /// Get the squared norm of the vector, this is faster than getting the norm
    /// in most cases.
    fn norm_squared(&self) -> Self::Scalar;
    /// Inner product between two vectors.
    fn dot(&self, other: &Self) -> Self::Scalar;
    /// Total number of components in thsi vector. Its dimension.
    fn len(&self) -> usize;
    /// Compute the cross product of two vetors. Call only if both vectors are
    /// three dimensional.  
    fn cross(&self, other: &Self) -> Self;
}

/// Blank implementation for a type that is isomorphic to a vector.
impl<T, S> VectorLike for T
where
    T: LinAlg<S> + Index<usize, Output = S> + IndexMut<usize, Output = S> + Default,
    S: ScalarLike,
{
    type Scalar = S;

    fn norm(&self) -> S { self.norm_squared().sqrt() }

    fn norm_squared(&self) -> S { self.dot(&self) }

    fn normalized(&self) -> Self { *self / self.norm() }

    fn dot(&self, other: &Self) -> S
    {
        debug_assert!(self.len() == other.len());
        let mut result = S::from(0.0).unwrap();
        for element in 0..self.len()
        {
            result += self[element] * other[element];
        }

        result
    }

    /// Assumes a 3-dimensional vector.
    fn cross(&self, other: &Self) -> Self
    {
        debug_assert!(self.len() == 3);
        let mut result = *self * S::from(0.0).unwrap();
        result[0] = self[1] * other[2] - self[2] * other[1];
        result[1] = self[2] * other[0] - self[0] * other[2];
        result[2] = self[0] * other[1] - self[1] * other[0];

        result
    }

    fn len(&self) -> usize
    {
        use std::mem;
        mem::size_of::<Self>() / mem::size_of::<S>()
    }
}