crystal_ball 0.3.0

A path tracing library written in Rust.
Documentation
use std::convert::TryFrom;
use std::ops::{
    Add, AddAssign, Div, DivAssign, Index, IndexMut, Mul, MulAssign, Neg, Sub, SubAssign,
};

use nanorand::tls::TlsWyRand;

use crate::math::{Point2, Vec3};
use crate::util::random_float;

/// A 2-dimensional vector.
#[derive(Copy, Clone, Default, Debug, PartialEq)]
pub struct Vec2 {
    pub x: f64,
    pub y: f64,
}

impl Vec2 {
    pub const X: Vec2 = Vec2 { x: 1.0, y: 0.0 };

    pub const Y: Vec2 = Vec2 { x: 0.0, y: 1.0 };

    pub const ZERO: Vec2 = Vec2 { x: 0.0, y: 0.0 };

    /// Create a new [`Vec2`].
    pub fn new(x: f64, y: f64) -> Self {
        Vec2 { x, y }
    }

    /// Create a new [`Vec2`] with all elements set to `value`.
    pub fn splat(value: f64) -> Self {
        Vec2 { x: value, y: value }
    }

    /// Generate a [`Vec2`] where each component is a uniform random number between `min` and `max`.
    pub fn random(rng: &mut TlsWyRand, min: f64, max: f64) -> Self {
        Vec2 {
            x: random_float(rng, min, max),
            y: random_float(rng, min, max),
        }
    }

    /// Generate a random [`Vec2`] inside the unit disk with uniform distribution.
    pub fn random_in_unit_disk(rng: &mut TlsWyRand) -> Self {
        loop {
            let random_vec2 = Vec2::random(rng, -1.0, 1.0);

            if random_vec2.magnitude() < 1.0 {
                return random_vec2;
            }
        }
    }

    /// Convert the [`Vec2`] to a [`Point2`].
    pub fn to_point2(&self) -> Point2 {
        (*self).into()
    }

    /// Calculate the vector's magnitude (length).
    #[doc(alias = "length")]
    pub fn magnitude(&self) -> f64 {
        Self::dot(*self, *self).sqrt()
    }

    /// Calculate the square of the vector's magnitude (length).
    #[doc(alias = "length_squared")]
    pub fn magnitude_squared(&self) -> f64 {
        Self::dot(*self, *self)
    }

    /// Return the absolute value (synonym [`magnitude`](Self::magnitude)).
    pub fn abs(&self) -> f64 {
        self.magnitude()
    }

    /// Return the unit vector parallel to self.
    ///
    /// # Panics
    ///
    /// Panics if `self` cannot be normalized.
    pub fn normalize(&self) -> Self {
        assert_ne!(self.magnitude(), 0.0, "Can't normalize zero vector");

        *self / self.magnitude()
    }

    /// Calculate the dot product between two [`Vec2`]s.
    pub fn dot(vec_a: Vec2, vec_b: Vec2) -> f64 {
        vec_a.x * vec_b.x + vec_a.y * vec_b.y
    }

    /// Create a new [`Vec3`] using the x, y values of `self` and the given `z` value.
    pub fn extend(&self, z: f64) -> Vec3 {
        Vec3::new(self.x, self.y, z)
    }
}

impl Add<Vec2> for Vec2 {
    type Output = Vec2;

    fn add(self, rhs: Vec2) -> Self::Output {
        Vec2 {
            x: self.x + rhs.x,
            y: self.y + rhs.y,
        }
    }
}

impl AddAssign<Vec2> for Vec2 {
    fn add_assign(&mut self, rhs: Vec2) {
        *self = *self + rhs;
    }
}

impl Sub<Vec2> for Vec2 {
    type Output = Vec2;

    fn sub(self, rhs: Vec2) -> Self::Output {
        Vec2 {
            x: self.x - rhs.x,
            y: self.y - rhs.y,
        }
    }
}

impl SubAssign<Vec2> for Vec2 {
    fn sub_assign(&mut self, rhs: Vec2) {
        *self = *self - rhs;
    }
}

impl Mul<f64> for Vec2 {
    type Output = Vec2;

    fn mul(self, rhs: f64) -> Self::Output {
        Vec2 {
            x: self.x * rhs,
            y: self.y * rhs,
        }
    }
}

impl MulAssign<f64> for Vec2 {
    fn mul_assign(&mut self, rhs: f64) {
        *self = *self * rhs;
    }
}

impl Mul<Vec2> for f64 {
    type Output = Vec2;

    fn mul(self, rhs: Vec2) -> Self::Output {
        rhs * self
    }
}

impl Div<f64> for Vec2 {
    type Output = Vec2;

    fn div(self, rhs: f64) -> Self::Output {
        let rhs_inverse = 1.0 / rhs;

        Vec2 {
            x: self.x * rhs_inverse,
            y: self.y * rhs_inverse,
        }
    }
}

impl DivAssign<f64> for Vec2 {
    fn div_assign(&mut self, rhs: f64) {
        *self = *self / rhs;
    }
}

impl Neg for Vec2 {
    type Output = Vec2;

    fn neg(self) -> Self::Output {
        Vec2 {
            x: -self.x,
            y: -self.y,
        }
    }
}

impl From<[f64; 2]> for Vec2 {
    fn from(s: [f64; 2]) -> Self {
        Vec2 { x: s[0], y: s[1] }
    }
}

impl From<(f64, f64)> for Vec2 {
    fn from(t: (f64, f64)) -> Self {
        Vec2 { x: t.0, y: t.1 }
    }
}

impl From<Point2> for Vec2 {
    fn from(p: Point2) -> Self {
        Vec2 { x: p.x, y: p.y }
    }
}

impl TryFrom<Vec<f64>> for Vec2 {
    type Error = &'static str;

    fn try_from(v: Vec<f64>) -> Result<Self, Self::Error> {
        if v.len() != 2 {
            Err("Vec2 can only be build from a vector of length 3.")
        } else {
            Ok(Vec2 { x: v[0], y: v[1] })
        }
    }
}

impl TryFrom<&[f64]> for Vec2 {
    type Error = &'static str;

    fn try_from(s: &[f64]) -> Result<Self, Self::Error> {
        if s.len() != 2 {
            Err("Vec2 can only be build from a slice of length 3.")
        } else {
            Ok(Vec2 { x: s[0], y: s[1] })
        }
    }
}

impl Index<usize> for Vec2 {
    type Output = f64;

    fn index(&self, index: usize) -> &Self::Output {
        match index {
            0 => &self.x,
            1 => &self.y,
            _ => panic!(
                "index out of bounds: the len is 2 but the index is {}",
                index
            ),
        }
    }
}

impl IndexMut<usize> for Vec2 {
    fn index_mut(&mut self, index: usize) -> &mut Self::Output {
        match index {
            0 => &mut self.x,
            1 => &mut self.y,
            _ => panic!(
                "index out of bounds: the len is 2 but the index is {}",
                index
            ),
        }
    }
}