diff options
Diffstat (limited to 'engine/src/vector.rs')
-rw-r--r-- | engine/src/vector.rs | 97 |
1 files changed, 97 insertions, 0 deletions
diff --git a/engine/src/vector.rs b/engine/src/vector.rs index c25a258..88a8198 100644 --- a/engine/src/vector.rs +++ b/engine/src/vector.rs @@ -1,3 +1,5 @@ +use std::ops::{Neg, Sub}; + #[derive(Debug)] pub struct Vec2<Value> { @@ -18,3 +20,98 @@ pub struct Vec3<Value> pub y: Value, pub z: Value, } + +impl Vec3<f32> +{ + pub const UP: Self = Self { + x: 0.0, + y: 1.0, + z: 0.0, + }; + + /// Returns the length of the vector. + #[must_use] + pub fn length(&self) -> f32 + { + (self.x.powi(2) + self.y.powi(2) + self.z.powi(2)).sqrt() + } + + /// Normalizes the vector, returning a unit vector. + #[must_use] + pub fn normalize(&self) -> Self + { + let length = self.length(); + + Self { + x: self.x / length, + y: self.y / length, + z: self.z / length, + } + } + + /// Returns the cross product of this and another vector. + #[must_use] + pub fn cross(&self, rhs: &Self) -> Self + { + Self { + x: (self.y * rhs.z) - (self.z * rhs.y), + y: (self.z * rhs.x) - (self.x * rhs.z), + z: (self.x * rhs.y) - (self.y * rhs.x), + } + } + + /// Returns the dot product of this and another vector. + #[must_use] + pub fn dot(&self, rhs: &Self) -> f32 + { + (self.x * rhs.x) + (self.y * rhs.y) + (self.z * rhs.z) + } +} + +impl<Value> Sub for Vec3<Value> +where + Value: Sub<Value, Output = Value>, +{ + type Output = Self; + + fn sub(self, rhs: Self) -> Self::Output + { + Self::Output { + x: self.x - rhs.x, + y: self.y - rhs.y, + z: self.z - rhs.z, + } + } +} + +impl<Value> Sub for &Vec3<Value> +where + for<'a, 'b> &'a Value: Sub<&'b Value, Output = Value>, +{ + type Output = Vec3<Value>; + + fn sub(self, rhs: Self) -> Self::Output + { + Self::Output { + x: &self.x - &rhs.x, + y: &self.y - &rhs.y, + z: &self.z - &rhs.z, + } + } +} + +impl<Value> Neg for Vec3<Value> +where + Value: Neg<Output = Value>, +{ + type Output = Self; + + fn neg(mut self) -> Self::Output + { + self.x = -self.x; + self.y = -self.y; + self.z = -self.z; + + self + } +} |