voxelize/libs/
vec.rs

1use num::{cast, Float, Num};
2
3use std::ops::{self, Index, IndexMut};
4
5use serde::{Deserialize, Serialize};
6
7/// Vector2 implementation for Voxelize.
8#[derive(Debug, Eq, PartialEq, Clone, Default, Hash, Serialize, Deserialize)]
9pub struct Vec2<T>(pub T, pub T);
10
11impl<T: Copy + 'static> Vec2<T> {
12    /// Create a new `Vec2` instance in a designated type.
13    pub fn from<U: cast::AsPrimitive<T>>(other: &Vec2<U>) -> Vec2<T> {
14        Vec2(other.0.as_(), other.1.as_())
15    }
16}
17
18/// Vector3 implementation for Voxelize.
19#[derive(Debug, Eq, PartialEq, Clone, Default, Hash, Serialize, Deserialize)]
20pub struct Vec3<T>(pub T, pub T, pub T);
21
22impl<T: Copy> Vec3<T> {
23    pub fn to_arr(&self) -> [T; 3] {
24        [self.0, self.1, self.2]
25    }
26}
27
28impl<T: Copy + 'static, U: cast::AsPrimitive<T>> From<&Vec3<U>> for Vec3<T> {
29    fn from(other: &Vec3<U>) -> Self {
30        Vec3(other.0.as_(), other.1.as_(), other.2.as_())
31    }
32}
33
34impl<T: Copy + 'static, U: cast::AsPrimitive<T>> From<&[U; 3]> for Vec3<T> {
35    fn from(other: &[U; 3]) -> Self {
36        Vec3(other[0].as_(), other[1].as_(), other[2].as_())
37    }
38}
39
40impl<T: Copy + 'static, U: cast::AsPrimitive<T>> Into<[T; 3]> for Vec3<U> {
41    fn into(self) -> [T; 3] {
42        [self.0.as_(), self.1.as_(), self.2.as_()]
43    }
44}
45
46impl<T: Num + Copy + Default> ops::Add<&Vec3<T>> for &Vec3<T> {
47    type Output = Vec3<T>;
48
49    fn add(self, rhs: &Vec3<T>) -> Self::Output {
50        Vec3::<T>(self.0 + rhs.0, self.1 + rhs.1, self.2 + rhs.2)
51    }
52}
53
54impl<T: Num + Copy + Default> ops::Add<Vec3<T>> for Vec3<T> {
55    type Output = Vec3<T>;
56
57    fn add(self, rhs: Vec3<T>) -> Self::Output {
58        Vec3::<T>(self.0 + rhs.0, self.1 + rhs.1, self.2 + rhs.2)
59    }
60}
61
62impl<T: Num + Copy + Default> ops::Sub<&Vec3<T>> for &Vec3<T> {
63    type Output = Vec3<T>;
64
65    fn sub(self, rhs: &Vec3<T>) -> Self::Output {
66        Vec3::<T>(self.0 - rhs.0, self.1 - rhs.1, self.2 - rhs.2)
67    }
68}
69
70impl<T: Num + Copy + Default> ops::Sub<Vec3<T>> for Vec3<T> {
71    type Output = Vec3<T>;
72
73    fn sub(self, rhs: Vec3<T>) -> Self::Output {
74        Vec3::<T>(self.0 - rhs.0, self.1 - rhs.1, self.2 - rhs.2)
75    }
76}
77
78impl<T: Num + Copy + Default> ops::Mul<&Vec3<T>> for &Vec3<T> {
79    type Output = Vec3<T>;
80
81    fn mul(self, rhs: &Vec3<T>) -> Self::Output {
82        let mut result = Vec3::default();
83        result.0 = self.0 * rhs.0;
84        result.1 = self.1 * rhs.1;
85        result.2 = self.2 * rhs.2;
86        result
87    }
88}
89
90impl<T: Num + Copy + Default> ops::Mul<T> for &Vec3<T> {
91    type Output = Vec3<T>;
92
93    fn mul(self, rhs: T) -> Self::Output {
94        let mut result = Vec3::default();
95        result.0 = self.0 * rhs;
96        result.1 = self.1 * rhs;
97        result.2 = self.2 * rhs;
98        result
99    }
100}
101
102impl<T: Num + Copy + Default + ops::AddAssign> ops::AddAssign<Vec3<T>> for Vec3<T> {
103    fn add_assign(&mut self, rhs: Vec3<T>) {
104        self.0 += rhs.0;
105        self.1 += rhs.1;
106        self.2 += rhs.2;
107    }
108}
109
110impl<T: Num + Copy + Default + ops::AddAssign> ops::AddAssign<[T; 3]> for Vec3<T> {
111    fn add_assign(&mut self, rhs: [T; 3]) {
112        self.0 += rhs[0];
113        self.1 += rhs[1];
114        self.2 += rhs[2];
115    }
116}
117
118impl<T: Num + Copy + Default + ops::SubAssign> ops::SubAssign<Vec3<T>> for Vec3<T> {
119    fn sub_assign(&mut self, rhs: Vec3<T>) {
120        self.0 -= rhs.0;
121        self.1 -= rhs.1;
122        self.2 -= rhs.2;
123    }
124}
125
126impl<T: Num + Copy + Default + ops::MulAssign> ops::MulAssign<Vec3<T>> for Vec3<T> {
127    fn mul_assign(&mut self, rhs: Vec3<T>) {
128        self.0 *= rhs.0;
129        self.1 *= rhs.1;
130        self.2 *= rhs.2;
131    }
132}
133
134impl<T: Num + Copy + Default + ops::MulAssign> ops::MulAssign<T> for Vec3<T> {
135    fn mul_assign(&mut self, rhs: T) {
136        self.0 *= rhs;
137        self.1 *= rhs;
138        self.2 *= rhs;
139    }
140}
141
142impl<T: Num + Copy + Default + ops::DivAssign> ops::DivAssign<T> for Vec3<T> {
143    fn div_assign(&mut self, rhs: T) {
144        self.0 /= rhs;
145        self.1 /= rhs;
146        self.2 /= rhs;
147    }
148}
149
150impl<T> Vec3<T>
151where
152    T: Num + Copy,
153{
154    /// Add self to another `Vec3`.
155    pub fn add(&self, other: &Self) -> Self {
156        Vec3(self.0 + other.0, self.1 + other.1, self.2 + other.2)
157    }
158
159    /// Subtract self by another `Vec3`.
160    pub fn sub(&self, other: &Self) -> Self {
161        Vec3(self.0 - other.0, self.1 - other.1, self.2 - other.2)
162    }
163
164    /// Copy anther `Vec3`'s content to self.
165    pub fn copy(&mut self, other: &Self) -> &Self {
166        self.0 = other.0;
167        self.1 = other.1;
168        self.2 = other.2;
169        self
170    }
171
172    /// Set the data of this `Vec3`.
173    pub fn set(&mut self, x: T, y: T, z: T) -> &Self {
174        self.0 = x;
175        self.1 = y;
176        self.2 = z;
177        self
178    }
179
180    /// Scale all elements of self.
181    pub fn scale(&self, scale: T) -> Self {
182        Vec3(self.0 * scale, self.1 * scale, self.2 * scale)
183    }
184
185    /// Add another scaled instance to self.
186    pub fn scale_and_add(&self, other: &Self, scale: T) -> Self {
187        Vec3(
188            self.0 + other.0 * scale,
189            self.1 + other.1 * scale,
190            self.2 + other.2 * scale,
191        )
192    }
193
194    /// Instantiate a `Vec3` instance from a 3-element array.
195    pub fn from_arr(arr: [T; 3]) -> Self {
196        Vec3(arr[0], arr[1], arr[2])
197    }
198}
199
200impl<T> Vec3<T>
201where
202    T: Float,
203{
204    /// Length of the vector.
205    pub fn len(&self) -> T {
206        (self.0 * self.0 + self.1 * self.1 + self.2 * self.2).sqrt()
207    }
208
209    /// Get the maximum element of two vectors.
210    pub fn max(&self, other: &Self) -> Self {
211        Vec3(
212            Float::max(self.0, other.0),
213            Float::max(self.1, other.1),
214            Float::max(self.2, other.2),
215        )
216    }
217
218    /// Get the minimum element of two vectors.
219    pub fn min(&self, other: &Self) -> Self {
220        Vec3(
221            Float::min(self.0, other.0),
222            Float::min(self.1, other.1),
223            Float::min(self.2, other.2),
224        )
225    }
226}
227
228impl Vec3<f32> {
229    /// Rotate this vector by an angle from an origin.
230    pub fn rotate_y(&self, origin: &Self, angle: f32) -> Self {
231        let ox = origin[0];
232        let oz = origin[2];
233
234        // translate point to origin
235        let px = self[0] - ox;
236        let pz = self[2] - oz;
237
238        let sc = angle.sin();
239        let cc = angle.cos();
240
241        // perform rotation and translate to correct position
242        Self(ox + pz * sc + px * cc, self[1], oz + pz * cc - px * sc)
243    }
244
245    /// Normalize this vector.
246    pub fn normalize(&self) -> Self {
247        let Self(x, y, z) = self;
248        let len = x * x + y * y + z * z;
249        if len > 0.0 {
250            let len = 1.0 / len.sqrt();
251            return Self(self.0 * len, self.1 * len, self.2 * len);
252        }
253        self.to_owned()
254    }
255
256    /// Squared distance between two vectors.
257    pub fn sq_distance(&self, other: &Self) -> f32 {
258        let Self(x, y, z) = self;
259        let Self(ox, oy, oz) = other;
260        let dx = x - ox;
261        let dy = y - oy;
262        let dz = z - oz;
263        dx * dx + dy * dy + dz * dz
264    }
265
266    pub fn set_mag(&mut self, mag: f32) -> &Self {
267        let len = self.len();
268        self.0 /= len;
269        self.1 /= len;
270        self.2 /= len;
271        self.scale(mag);
272        self
273    }
274
275    pub fn limit(&mut self, mag: f32) -> &Self {
276        if self.len() > mag {
277            self.set_mag(mag);
278        }
279        self
280    }
281}
282
283impl<T: Num + Clone> Index<usize> for Vec3<T> {
284    type Output = T;
285
286    /// Index for accessing elements of this vector.
287    fn index(&self, index: usize) -> &Self::Output {
288        if index == 0 {
289            &self.0
290        } else if index == 1 {
291            &self.1
292        } else if index == 2 {
293            &self.2
294        } else {
295            panic!("Index out of bounds for accessing Vec3.");
296        }
297    }
298}
299
300impl<T: Num + Clone> IndexMut<usize> for Vec3<T> {
301    /// Index for accessing mutable elements of this vector.
302    fn index_mut(&mut self, index: usize) -> &mut Self::Output {
303        if index == 0 {
304            &mut self.0
305        } else if index == 1 {
306            &mut self.1
307        } else if index == 2 {
308            &mut self.2
309        } else {
310            panic!("Index out of bounds for accessing Vec3.");
311        }
312    }
313}
314
315impl<T: Num + Clone> From<Vec<T>> for Vec3<T> {
316    /// Construct a `Vec3` instance from a primitive vector.
317    fn from(vec: Vec<T>) -> Self {
318        let x = vec[0].clone();
319        let y = vec[1].clone();
320        let z = vec[2].clone();
321
322        Self(x, y, z)
323    }
324}