Skip to main content

ty_math/
ty_vector3.rs

1use std::ops::{Add, Mul, Sub};
2
3/// A 3D vector with `f64` components.
4#[derive(Clone, Copy, Debug, Default, PartialEq)]
5pub struct TyVector3 {
6    pub x: f64,
7    pub y: f64,
8    pub z: f64,
9}
10
11impl TyVector3 {
12    /// Creates a new vector from `x`, `y`, and `z` components.
13    pub fn new(x: f64, y: f64, z: f64) -> Self {
14        Self { x, y, z }
15    }
16
17    /// Returns the cross product of `self` and `other`.
18    pub fn cross(&self, other: &Self) -> Self {
19        Self {
20            x: self.y * other.z - self.z * other.y,
21            y: self.z * other.x - self.x * other.z,
22            z: self.x * other.y - self.y * other.x,
23        }
24    }
25
26    /// Returns the dot product of `self` and `other`.
27    pub fn dot(&self, other: &Self) -> f64 {
28        self.x * other.x + self.y * other.y + self.z * other.z
29    }
30
31    /// Returns the Euclidean length of this vector.
32    pub fn magnitude(&self) -> f64 {
33        (self.x * self.x + self.y * self.y + self.z * self.z).sqrt()
34    }
35}
36
37impl Add for TyVector3 {
38    type Output = Self;
39
40    fn add(self, rhs: Self) -> Self {
41        Self {
42            x: self.x + rhs.x,
43            y: self.y + rhs.y,
44            z: self.z + rhs.z,
45        }
46    }
47}
48
49impl Sub for TyVector3 {
50    type Output = Self;
51
52    fn sub(self, rhs: Self) -> Self {
53        Self {
54            x: self.x - rhs.x,
55            y: self.y - rhs.y,
56            z: self.z - rhs.z,
57        }
58    }
59}
60
61impl Mul<f64> for TyVector3 {
62    type Output = Self;
63
64    fn mul(self, rhs: f64) -> Self {
65        Self {
66            x: self.x * rhs,
67            y: self.y * rhs,
68            z: self.z * rhs,
69        }
70    }
71}
72
73impl Mul<TyVector3> for f64 {
74    type Output = TyVector3;
75
76    fn mul(self, rhs: TyVector3) -> TyVector3 {
77        TyVector3 {
78            x: self * rhs.x,
79            y: self * rhs.y,
80            z: self * rhs.z,
81        }
82    }
83}