From 67d7492477808dc1765b1a9ed493dee79dff9320 Mon Sep 17 00:00:00 2001 From: eug-vs Date: Mon, 25 Oct 2021 15:39:58 +0300 Subject: feat: initial commit --- src/vector.rs | 83 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 83 insertions(+) create mode 100644 src/vector.rs (limited to 'src/vector.rs') diff --git a/src/vector.rs b/src/vector.rs new file mode 100644 index 0000000..d4e57cc --- /dev/null +++ b/src/vector.rs @@ -0,0 +1,83 @@ +use std::fmt; +use std::ops; + +#[derive(Debug, Clone, Copy)] +pub struct Vector { + pub x: f32, + pub y: f32, + pub z: f32, +} + +impl fmt::Display for Vector { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "({:.2}, {:.2}, {:.2})", self.x, self.y, self.z) + } +} + +impl ops::Add for Vector { + type Output = Vector; + fn add(self, rhs: Self) -> Self::Output { + Vector { + x: self.x + rhs.x, + y: self.y + rhs.y, + z: self.z + rhs.z, + } + } +} + +impl ops::Sub for Vector { + type Output = Vector; + fn sub(self, rhs: Self) -> Self::Output { + Vector { + x: self.x - rhs.x, + y: self.y - rhs.y, + z: self.z - rhs.z, + } + } +} + +impl ops::Mul for Vector { + type Output = Vector; + fn mul(self, rhs: f32) -> Self::Output { + Vector { + x: self.x * rhs, + y: self.y * rhs, + z: self.z * rhs, + } + } +} + +impl ops::Div for Vector { + type Output = Vector; + fn div(self, rhs: f32) -> Self::Output { + Vector { + x: self.x / rhs, + y: self.y / rhs, + z: self.z / rhs, + } + } +} + +impl Vector { + pub fn magnitude_squared(self) -> f32 { + self.x * self.x + self.y * self.y + self.z * self.z + } + + pub fn magnitude(self) -> f32 { + self.magnitude_squared().sqrt() + } + + pub fn normalized(self) -> Vector { + let mag = self.magnitude(); + self / mag + } + + pub fn rotate_z(self, angle: f32) -> Vector { + // TODO: multiply by a matirx + Vector { + x: self.x * angle.cos() + self.y * angle.sin(), + y: self.y * angle.cos() - self.x * angle.sin(), + z: self.z, + } + } +} -- cgit v1.2.3