radiant_utils/math/
mod.rs

1mod angle;
2mod vec2;
3mod vec3;
4mod mat4;
5pub mod matrix;
6
7use prelude::*;
8pub use self::angle::Angle;
9pub use self::vec2::Vec2;
10pub use self::vec3::Vec3;
11pub use self::mat4::Mat4;
12pub use self::matrix::Matrix;
13
14pub type Point2<T = f32> = (T, T);
15pub type Rect<T = f32> = (Point2<T>, Point2<T>);
16
17/// Values that can be converted to a vector.
18pub trait Vector<T> where T: Copy {
19    /// Returns the given value as a Vec3
20    fn as_vec3(self: &Self, neutral: T) -> Vec3<T>;
21}
22
23impl<T> Vector<T> for (T, T, T) where T: Copy {
24    fn as_vec3(self: &Self, _: T) -> Vec3<T> {
25        Vec3::<T>(self.0, self.1, self.2)
26    }
27}
28
29impl<T> Vector<T> for (T, T) where T: Copy {
30    fn as_vec3(self: &Self, neutral: T) -> Vec3<T> {
31        Vec3::<T>(self.0, self.1, neutral)
32    }
33}
34
35impl<T> Vector<T> for T where T: Copy {
36    fn as_vec3(self: &Self, _: T) -> Vec3<T> {
37        Vec3::<T>(*self, *self, *self)
38    }
39}
40
41/// Interpolates between values. Returns source_value for ratio = 0.0 and target_value for ratio = 1.0.
42pub fn lerp<T, S>(source_value: &T, target_value: &T, ratio: S) -> T
43    where T: Add + Mul<S> + From<<<T as Mul<S>>::Output as Add>::Output> + Copy, S: Float, <T as Mul<S>>::Output: Add
44{
45    T::from( (*source_value) * (S::one() - ratio) + (*target_value * ratio) )
46}
47
48/// Mutates source_value to approach target_value at the rate_of_change. Effectively a lerp that writes to source.
49pub fn approach<T, S>(source_value: &mut T, target_value: &T, rate_of_change: S)
50    where T: Add + Mul<S> + From<<<T as Mul<S>>::Output as Add>::Output> + Copy, S: Float, <T as Mul<S>>::Output: Add
51{
52    *source_value = T::from( (*source_value) * (S::one() - rate_of_change) + (*target_value * rate_of_change) );
53}
54
55/// Returns the smaller of the two given values.
56pub fn min<T>(a: T, b: T) -> T where T: PartialOrd {
57    if a.lt(&b) { a } else { b }
58}
59
60/// Returns the greater of the two given values.
61pub fn max<T>(a: T, b: T) -> T where T: PartialOrd {
62    if a.gt(&b) { a } else { b }
63}
64
65/// Returns the given value limited to the bounds min and max.
66pub fn clamp<T>(v: T, min: T, max: T) -> T where T: PartialOrd {
67    if v.lt(&min) { min } else if v.gt(&max) { max } else { v }
68}