Skip to main content

xtk_core/num/
mod.rs

1//! Basic arithmetic utilities
2
3use num_traits::Float;
4
5pub mod sizes;
6
7/// Linear interpolation, see
8/// [Linear Interpolation on Wikipedia](https://en.wikipedia.org/wiki/Linear_interpolation#Programming_language_support)
9/// for more information.
10///
11/// The expression being used is: `(1 - t) * a + t * b`
12///
13/// Example:
14///
15/// ```
16/// use xtk_core::math::lerp;
17/// println!("{}", lerp(0.0, 100.0, 0.25)); // 25
18/// ```
19#[doc(alias = "mix")]
20pub fn lerp<T: Float>(a: T, b: T, t: T) -> T {
21    (T::one() - t) * a + t * b
22}
23
24/// Generic floating-point angle, can be represented in Degrees or Radians.
25#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
26pub enum Angle<T: Float> {
27    /// Degrees
28    Deg(T),
29
30    /// Radians
31    Rad(T),
32}
33
34impl<T: Float> Angle<T> {
35    /// Convert the wrapped value to degrees
36    pub fn degrees(self) -> T {
37        match self {
38            Self::Deg(d) => d,
39            Self::Rad(r) => r.to_degrees(),
40        }
41    }
42
43    /// Convert the wrapped value to radians
44    pub fn radians(self) -> T {
45        match self {
46            Self::Deg(d) => d.to_radians(),
47            Self::Rad(r) => r,
48        }
49    }
50}
51
52#[cfg(test)]
53mod tests {
54    use super::*;
55
56    #[test]
57    fn test_lerp() {
58        assert_eq!(lerp(0., 100., 0.25), 25.0);
59        assert_eq!(lerp(0., 100., 1.435), 143.5);
60    }
61}