vec.rs
1.7 kB · rust · 67 lines
1/// A three-component vector of f32.2#[derive(Clone, Copy, Debug, PartialEq)]3pub struct Vec3 {4 /// The x component.5 pub x: f32,6 /// The y component.7 pub y: f32,8 /// The z component.9 pub z: f32,10}1112impl std::ops::Add for Vec3 {13 type Output = Vec3;14 fn add(self, o: Vec3) -> Vec3 {15 Vec3::new(self.x + o.x, self.y + o.y, self.z + o.z)16 }17}1819impl std::ops::Sub for Vec3 {20 type Output = Vec3;21 fn sub(self, o: Vec3) -> Vec3 {22 Vec3::new(self.x - o.x, self.y - o.y, self.z - o.z)23 }24}2526impl Vec3 {27 /// Builds a vector from its components.28 pub fn new(x: f32, y: f32, z: f32) -> Vec3 {29 Vec3 { x, y, z }30 }31 /// Multiplies every component by the scalar.32 pub fn scale(self, s: f32) -> Vec3 {33 Vec3::new(self.x * s, self.y * s, self.z * s)34 }35 /// Returns the dot product of the two vectors.36 pub fn dot(self, o: Vec3) -> f32 {37 self.x * o.x + self.y * o.y + self.z * o.z38 }39 /// Returns the cross product, perpendicular to both vectors.40 ///41 /// ```42 /// use mrlyrs::math::space::Vec3;43 /// let n = Vec3::new(1.0, 0.0, 0.0).cross(Vec3::new(0.0, 1.0, 0.0));44 /// assert_eq!(n, Vec3::new(0.0, 0.0, 1.0));45 /// ```46 pub fn cross(self, o: Vec3) -> Vec3 {47 Vec3::new(48 self.y * o.z - self.z * o.y,49 self.z * o.x - self.x * o.z,50 self.x * o.y - self.y * o.x,51 )52 }53}5455#[cfg(test)]56mod tests {57 use super::*;5859 #[test]60 fn cross_is_perpendicular() {61 let a = Vec3::new(1.0, 2.0, 3.0);62 let b = Vec3::new(-2.0, 0.5, 1.0);63 let c = a.cross(b);64 assert!(c.dot(a).abs() < 1e-6);65 assert!(c.dot(b).abs() < 1e-6);66 }67}