From f617213b4a48d73acd245580f8551a7c37ce9ad8 Mon Sep 17 00:00:00 2001 From: tom barrett Date: Sun, 10 Feb 2019 03:55:05 -0600 Subject: added vector math and tractorbeam module --- src/math.rs | 91 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 87 insertions(+), 4 deletions(-) (limited to 'src/math.rs') diff --git a/src/math.rs b/src/math.rs index 689ee65..0816149 100644 --- a/src/math.rs +++ b/src/math.rs @@ -4,13 +4,96 @@ use self::rand::distributions::Alphanumeric; use self::rand::Rng; use std::iter::repeat; -pub fn distance(l0: (f64, f64, f64), l1: (f64, f64, f64)) -> f64 { - ((l1.0 - l0.0).powf(2.0) + (l1.1 - l0.1).powf(2.0) + (l1.2 - l0.2).powf(2.0)).sqrt() -} - pub fn rand_name() -> String { repeat(()) .map(|()| rand::thread_rng().sample(Alphanumeric)) .take(8) .collect() } + +#[derive(Serialize, Deserialize, Debug, Clone, Default)] +pub struct Vector { + pub a: f64, + pub b: f64, + pub c: f64, +} + +impl Vector { + pub fn new(v: (f64, f64, f64)) -> Vector { + Vector { + a: v.0, + b: v.1, + c: v.2, + } + } + + pub fn distance_from(&self, other: Vector) -> f64 { + ((self.a - other.a).powf(2.0) + (self.b - other.b).powf(2.0) + (self.c - other.c).powf(2.0)) + .sqrt() + } + + pub fn unitize(&self) -> Vector { + let denominator = self.magnitude(); + Vector { + a: self.a / denominator, + b: self.b / denominator, + c: self.c / denominator, + } + } + + pub fn magnitude(&self) -> f64 { + (self.a.powf(2.0) + self.b.powf(2.0) + self.c.powf(2.0)).sqrt() + } +} + +impl std::fmt::Display for Vector { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + write!(f, "({:.2}, {:.2}, {:.2})", self.a, self.b, self.c) + } +} + +impl std::ops::Add for Vector { + type Output = Vector; + + fn add(self, other: Vector) -> Vector { + Vector { + a: self.a + other.a, + b: self.b + other.b, + c: self.c + other.c, + } + } +} + +impl std::ops::Sub for Vector { + type Output = Vector; + + fn sub(self, other: Vector) -> Vector { + Vector { + a: self.a - other.a, + b: self.b - other.b, + c: self.c - other.c, + } + } +} + +impl std::ops::Mul for Vector { + type Output = Vector; + + fn mul(self, other: f64) -> Vector { + Vector { + a: self.a * other, + b: self.b * other, + c: self.c * other, + } + } +} + +impl std::ops::AddAssign for Vector { + fn add_assign(&mut self, other: Vector) { + *self = Vector { + a: self.a + other.a, + b: self.b + other.b, + c: self.c + other.c, + } + } +} -- cgit v1.2.3