1use std::ops::{
2 Add, AddAssign, Div, DivAssign, Index, IndexMut, Mul, MulAssign, Neg, Sub, SubAssign,
3};
4
5macro_rules! vector {
6 ($name:ident, $mask:ident, $n:expr, $($field:ident : $index:tt),+) => {
7 #[repr(C)]
8 #[derive(Clone, Copy, Debug, Default, PartialEq)]
9 pub struct $name { $(pub $field: f32),+ }
10
11 #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
12 pub struct $mask { $(pub $field: bool),+ }
13 impl $mask {
14 pub const fn all(self) -> bool { true $(&& self.$field)+ }
15 pub const fn any(self) -> bool { false $(|| self.$field)+ }
16 pub const fn to_array(self) -> [bool; $n] { [$(self.$field),+] }
17 }
18 impl $name {
19 pub const ZERO: Self = Self::splat(0.0);
20 pub const ONE: Self = Self::splat(1.0);
21 pub const NEG_ONE: Self = Self::splat(-1.0);
22 pub const NAN: Self = Self::splat(f32::NAN);
23 pub const INFINITY: Self = Self::splat(f32::INFINITY);
24 pub const NEG_INFINITY: Self = Self::splat(f32::NEG_INFINITY);
25 pub const fn new($($field: f32),+) -> Self { Self {$($field),+} }
26 pub const fn splat(value: f32) -> Self { Self {$($field: value),+} }
27 pub const fn from_array(values: [f32; $n]) -> Self { Self {$($field: values[$index]),+} }
28 pub const fn to_array(self) -> [f32; $n] { [$(self.$field),+] }
29 pub fn from_slice(values: &[f32]) -> Self { Self {$($field: values[$index]),+} }
30 pub fn write_to_slice(self, values: &mut [f32]) { $(values[$index] = self.$field;)+ }
31 pub fn is_finite(self) -> bool { true $(&& self.$field.is_finite())+ }
32 pub fn is_nan(self) -> bool { false $(|| self.$field.is_nan())+ }
33 pub fn dot(self, rhs: Self) -> f32 { 0.0 $(+ self.$field * rhs.$field)+ }
34 pub fn length_squared(self) -> f32 { self.dot(self) }
35 pub fn length(self) -> f32 { self.length_f64() as f32 }
37 fn length_f64(self) -> f64 { (0.0_f64 $(+ f64::from(self.$field).powi(2))+).sqrt() }
38 pub fn length_recip(self) -> f32 { self.length().recip() }
39 pub fn distance(self, other: Self) -> f32 { (self-other).length() }
40 pub fn distance_squared(self, other: Self) -> f32 { (self-other).length_squared() }
41 #[doc = concat!("use ferravex_math::", stringify!($name), " as Vector;")]
49 pub fn try_normalize(self) -> Option<Self> {
55 let length = self.length_f64();
56 if length > 0.0 && length.is_finite() {
57 Some(Self {$($field: (f64::from(self.$field) / length) as f32),+})
58 } else { None }
59 }
60 #[doc = concat!("use ferravex_math::", stringify!($name), " as Vector;")]
70 pub fn try_normalize_with_min_length(self, min_length: f32) -> Option<Self> {
76 if !min_length.is_finite() || min_length < 0.0 { return None; }
77 let length = self.length_f64();
78 if length > f64::from(min_length) && length.is_finite() {
79 Some(Self {$($field: (f64::from(self.$field) / length) as f32),+})
80 } else { None }
81 }
82 pub fn normalize(self) -> Self { self.try_normalize().unwrap_or(Self::NAN) }
83 pub fn normalize_or_zero(self) -> Self { self.try_normalize().unwrap_or(Self::ZERO) }
84 pub fn normalize_or(self, fallback: Self) -> Self { self.try_normalize().unwrap_or(fallback) }
85 pub fn is_normalized(self) -> bool { (self.length_squared()-1.0).abs() <= 1.0e-5 }
86 pub fn min(self, rhs: Self) -> Self { Self {$($field: self.$field.min(rhs.$field)),+} }
87 pub fn max(self, rhs: Self) -> Self { Self {$($field: self.$field.max(rhs.$field)),+} }
88 pub fn min_element(self) -> f32 { self.to_array().into_iter().fold(f32::INFINITY, f32::min) }
89 pub fn max_element(self) -> f32 { self.to_array().into_iter().fold(f32::NEG_INFINITY, f32::max) }
90 pub fn element_sum(self) -> f32 { 0.0 $(+ self.$field)+ }
91 pub fn element_product(self) -> f32 { 1.0 $(* self.$field)+ }
92 pub fn abs(self) -> Self { Self {$($field: self.$field.abs()),+} }
93 pub fn signum(self) -> Self { Self {$($field: self.$field.signum()),+} }
94 pub fn floor(self) -> Self { Self {$($field: self.$field.floor()),+} }
95 pub fn ceil(self) -> Self { Self {$($field: self.$field.ceil()),+} }
96 pub fn round(self) -> Self { Self {$($field: self.$field.round()),+} }
97 pub fn trunc(self) -> Self { Self {$($field: self.$field.trunc()),+} }
98 pub fn fract(self) -> Self { self-self.floor() }
99 pub fn recip(self) -> Self { Self {$($field: self.$field.recip()),+} }
100 pub fn sqrt(self) -> Self { Self {$($field: self.$field.sqrt()),+} }
101 pub fn powf(self, exponent: f32) -> Self { Self {$($field: self.$field.powf(exponent)),+} }
102 pub fn exp(self) -> Self { Self {$($field: self.$field.exp()),+} }
103 pub fn clamp(self, min: Self, max: Self) -> Self { Self {$($field: self.$field.clamp(min.$field, max.$field)),+} }
104 pub fn clamp_length(self, min: f32, max: f32) -> Self {
105 assert!(min.is_finite() && max.is_finite() && min >= 0.0 && min <= max);
106 let length = self.length();
107 if length > max { self.normalize_or_zero()*max }
108 else if length < min { self.normalize_or_zero()*min }
109 else { self }
110 }
111 pub fn clamp_length_max(self, max: f32) -> Self {
112 assert!(max.is_finite() && max >= 0.0);
113 if self.length() > max { self.normalize_or_zero()*max } else { self }
114 }
115 pub fn clamp_length_min(self, min: f32) -> Self {
116 assert!(min.is_finite() && min >= 0.0);
117 if self.length() < min { self.normalize_or_zero()*min } else { self }
118 }
119 #[doc = concat!("use ferravex_math::", stringify!($name), " as Vector;")]
135 pub fn try_clamp_length(self, min: f32, max: f32) -> Option<Self> {
141 if !min.is_finite() || !max.is_finite() || min < 0.0 || min > max {
142 return None;
143 }
144 self.try_clamp_length_f64(f64::from(min), f64::from(max))
145 }
146 #[doc = concat!("use ferravex_math::", stringify!($name), " as Vector;")]
155 pub fn try_clamp_length_max(self, max: f32) -> Option<Self> {
161 self.try_clamp_length(0.0, max)
162 }
163 #[doc = concat!("use ferravex_math::", stringify!($name), " as Vector;")]
172 pub fn try_clamp_length_min(self, min: f32) -> Option<Self> {
179 if !min.is_finite() || min < 0.0 { return None; }
180 self.try_clamp_length_f64(f64::from(min), f64::INFINITY)
181 }
182 fn try_clamp_length_f64(self, min: f64, max: f64) -> Option<Self> {
184 let length = self.length_f64();
185 if !length.is_finite() { return None; }
186 let target = length.clamp(min, max);
187 if target == length { return Some(self); }
188 if length == 0.0 { return None; }
189 let scale = target / length;
192 Some(Self {$($field: (f64::from(self.$field) * scale) as f32),+})
193 }
194 pub fn lerp(self, rhs: Self, t: f32) -> Self { self * (1.0-t) + rhs*t }
195 pub fn mul_add(self, multiplier: Self, add: Self) -> Self { Self {$($field: self.$field.mul_add(multiplier.$field, add.$field)),+} }
196 pub fn abs_diff_eq(self, rhs: Self, tolerance: f32) -> bool { (self-rhs).abs().cmple(Self::splat(tolerance)).all() }
197 pub fn cmpeq(self, rhs: Self) -> $mask { $mask {$($field: self.$field == rhs.$field),+} }
198 pub fn cmpne(self, rhs: Self) -> $mask { $mask {$($field: self.$field != rhs.$field),+} }
199 pub fn cmplt(self, rhs: Self) -> $mask { $mask {$($field: self.$field < rhs.$field),+} }
200 pub fn cmple(self, rhs: Self) -> $mask { $mask {$($field: self.$field <= rhs.$field),+} }
201 pub fn cmpgt(self, rhs: Self) -> $mask { $mask {$($field: self.$field > rhs.$field),+} }
202 pub fn cmpge(self, rhs: Self) -> $mask { $mask {$($field: self.$field >= rhs.$field),+} }
203 pub fn select(mask: $mask, if_true: Self, if_false: Self) -> Self { Self {$($field: if mask.$field {if_true.$field} else {if_false.$field}),+} }
204 pub fn project_onto(self, other: Self) -> Self { other * (self.dot(other)/other.length_squared()) }
205 pub fn reject_from(self, other: Self) -> Self { self-self.project_onto(other) }
206 pub fn project_onto_normalized(self, normal: Self) -> Self { normal*self.dot(normal) }
207 pub fn reject_from_normalized(self, normal: Self) -> Self { self-self.project_onto_normalized(normal) }
208 pub fn reflect(self, normal: Self) -> Self { self-2.0*self.dot(normal)*normal }
210 pub fn move_towards(self, rhs: Self, max_distance: f32) -> Self {
211 assert!(max_distance.is_finite() && max_distance >= 0.0);
212 let difference=rhs-self;
213 if difference.length() <= max_distance {rhs} else {self+difference.normalize_or_zero()*max_distance}
214 }
215 }
216 impl From<[f32; $n]> for $name { fn from(v: [f32; $n]) -> Self { Self::from_array(v) } }
217 impl From<$name> for [f32; $n] { fn from(v: $name) -> Self { v.to_array() } }
218 impl Index<usize> for $name { type Output=f32; fn index(&self,index:usize)->&f32 { match index {$($index=>&self.$field,)+ _=>panic!("vector index {index} is out of range")} } }
219 impl IndexMut<usize> for $name { fn index_mut(&mut self,index:usize)->&mut f32 { match index {$($index=>&mut self.$field,)+ _=>panic!("vector index {index} is out of range")} } }
220 impl Neg for $name { type Output=Self; fn neg(self)->Self { Self {$($field:-self.$field),+} } }
221 impl Add for $name { type Output=Self; fn add(self,rhs:Self)->Self { Self {$($field:self.$field+rhs.$field),+} } }
222 impl Sub for $name { type Output=Self; fn sub(self,rhs:Self)->Self { Self {$($field:self.$field-rhs.$field),+} } }
223 impl Mul for $name { type Output=Self; fn mul(self,rhs:Self)->Self { Self {$($field:self.$field*rhs.$field),+} } }
224 impl Div for $name { type Output=Self; fn div(self,rhs:Self)->Self { Self {$($field:self.$field/rhs.$field),+} } }
225 impl Add<f32> for $name { type Output=Self; fn add(self,rhs:f32)->Self { self+Self::splat(rhs) } }
226 impl Sub<f32> for $name { type Output=Self; fn sub(self,rhs:f32)->Self { self-Self::splat(rhs) } }
227 impl Mul<f32> for $name { type Output=Self; fn mul(self,rhs:f32)->Self { Self {$($field:self.$field*rhs),+} } }
228 impl Div<f32> for $name { type Output=Self; fn div(self,rhs:f32)->Self { Self {$($field:self.$field/rhs),+} } }
229 impl Add<$name> for f32 { type Output=$name; fn add(self,rhs:$name)->$name { $name::splat(self)+rhs } }
230 impl Sub<$name> for f32 { type Output=$name; fn sub(self,rhs:$name)->$name { $name::splat(self)-rhs } }
231 impl Mul<$name> for f32 { type Output=$name; fn mul(self,rhs:$name)->$name { rhs*self } }
232 impl Div<$name> for f32 { type Output=$name; fn div(self,rhs:$name)->$name { $name::splat(self)/rhs } }
233 impl AddAssign for $name { fn add_assign(&mut self,rhs:Self) { *self=*self+rhs; } }
234 impl SubAssign for $name { fn sub_assign(&mut self,rhs:Self) { *self=*self-rhs; } }
235 impl MulAssign for $name { fn mul_assign(&mut self,rhs:Self) { *self=*self*rhs; } }
236 impl DivAssign for $name { fn div_assign(&mut self,rhs:Self) { *self=*self/rhs; } }
237 impl AddAssign<f32> for $name { fn add_assign(&mut self,rhs:f32) { *self=*self+rhs; } }
238 impl SubAssign<f32> for $name { fn sub_assign(&mut self,rhs:f32) { *self=*self-rhs; } }
239 impl MulAssign<f32> for $name { fn mul_assign(&mut self,rhs:f32) { *self=*self*rhs; } }
240 impl DivAssign<f32> for $name { fn div_assign(&mut self,rhs:f32) { *self=*self/rhs; } }
241 impl std::iter::Sum for $name { fn sum<I:Iterator<Item=Self>>(iter:I)->Self { iter.fold(Self::ZERO, |a,b|a+b) } }
242 impl std::iter::Product for $name { fn product<I:Iterator<Item=Self>>(iter:I)->Self { iter.fold(Self::ONE, |a,b|a*b) } }
243 }
244}
245vector!(Vec2, BVec2, 2, x:0,y:1);
246vector!(Vec3, BVec3, 3, x:0,y:1,z:2);
247vector!(Vec4, BVec4, 4, x:0,y:1,z:2,w:3);
248
249pub const fn vec2(x: f32, y: f32) -> Vec2 {
250 Vec2::new(x, y)
251}
252pub const fn vec3(x: f32, y: f32, z: f32) -> Vec3 {
253 Vec3::new(x, y, z)
254}
255pub const fn vec4(x: f32, y: f32, z: f32, w: f32) -> Vec4 {
256 Vec4::new(x, y, z, w)
257}
258impl From<(f32, f32)> for Vec2 {
259 fn from(v: (f32, f32)) -> Self {
260 Self::new(v.0, v.1)
261 }
262}
263impl From<Vec2> for (f32, f32) {
264 fn from(v: Vec2) -> Self {
265 (v.x, v.y)
266 }
267}
268impl From<(f32, f32, f32)> for Vec3 {
269 fn from(v: (f32, f32, f32)) -> Self {
270 Self::new(v.0, v.1, v.2)
271 }
272}
273impl From<(f32, f32, f32, f32)> for Vec4 {
274 fn from(v: (f32, f32, f32, f32)) -> Self {
275 Self::new(v.0, v.1, v.2, v.3)
276 }
277}
278impl Vec2 {
279 pub const X: Self = Self::new(1.0, 0.0);
280 pub const Y: Self = Self::new(0.0, 1.0);
281 pub const NEG_X: Self = Self::new(-1.0, 0.0);
282 pub const NEG_Y: Self = Self::new(0.0, -1.0);
283 pub const AXES: [Self; 2] = [Self::X, Self::Y];
284 pub const fn extend(self, z: f32) -> Vec3 {
285 vec3(self.x, self.y, z)
286 }
287 pub const fn perp(self) -> Self {
288 vec2(-self.y, self.x)
289 }
290 pub fn perp_dot(self, rhs: Self) -> f32 {
291 self.x * rhs.y - self.y * rhs.x
292 }
293 pub fn from_angle(angle: f32) -> Self {
294 let (s, c) = angle.sin_cos();
295 vec2(c, s)
296 }
297 pub fn to_angle(self) -> f32 {
298 self.y.atan2(self.x)
299 }
300 pub fn angle_between(self, rhs: Self) -> f32 {
302 let a = self.normalize();
303 let b = rhs.normalize();
304 a.perp_dot(b).atan2(a.dot(b))
305 }
306 pub fn rotate(self, rhs: Self) -> Self {
308 vec2(
309 self.x * rhs.x - self.y * rhs.y,
310 self.y * rhs.x + self.x * rhs.y,
311 )
312 }
313 pub const fn yx(self) -> Self {
314 vec2(self.y, self.x)
315 }
316 pub const fn xx(self) -> Self {
317 Self::splat(self.x)
318 }
319 pub const fn yy(self) -> Self {
320 Self::splat(self.y)
321 }
322}
323impl Vec3 {
324 pub const X: Self = Self::new(1.0, 0.0, 0.0);
325 pub const Y: Self = Self::new(0.0, 1.0, 0.0);
326 pub const Z: Self = Self::new(0.0, 0.0, 1.0);
327 pub const NEG_X: Self = Self::new(-1.0, 0.0, 0.0);
328 pub const NEG_Y: Self = Self::new(0.0, -1.0, 0.0);
329 pub const NEG_Z: Self = Self::new(0.0, 0.0, -1.0);
330 pub const AXES: [Self; 3] = [Self::X, Self::Y, Self::Z];
331 pub const fn extend(self, w: f32) -> Vec4 {
332 vec4(self.x, self.y, self.z, w)
333 }
334 pub const fn truncate(self) -> Vec2 {
335 vec2(self.x, self.y)
336 }
337 pub fn cross(self, rhs: Self) -> Self {
338 vec3(
339 self.y * rhs.z - self.z * rhs.y,
340 self.z * rhs.x - self.x * rhs.z,
341 self.x * rhs.y - self.y * rhs.x,
342 )
343 }
344 pub fn angle_between(self, rhs: Self) -> f32 {
345 self.normalize()
346 .dot(rhs.normalize())
347 .clamp(-1.0, 1.0)
348 .acos()
349 }
350 pub fn any_orthogonal_vector(self) -> Self {
351 if self.x.abs() < self.y.abs() {
352 self.cross(Self::X)
353 } else {
354 self.cross(Self::Y)
355 }
356 }
357 pub fn any_orthonormal_vector(self) -> Self {
358 self.any_orthogonal_vector().normalize()
359 }
360 pub const fn xy(self) -> Vec2 {
361 vec2(self.x, self.y)
362 }
363 pub const fn xz(self) -> Vec2 {
364 vec2(self.x, self.z)
365 }
366 pub const fn yz(self) -> Vec2 {
367 vec2(self.y, self.z)
368 }
369 pub const fn yx(self) -> Vec2 {
370 vec2(self.y, self.x)
371 }
372 pub const fn zx(self) -> Vec2 {
373 vec2(self.z, self.x)
374 }
375 pub const fn zy(self) -> Vec2 {
376 vec2(self.z, self.y)
377 }
378 pub const fn xyz(self) -> Self {
379 self
380 }
381 pub const fn xzy(self) -> Self {
382 vec3(self.x, self.z, self.y)
383 }
384 pub const fn yxz(self) -> Self {
385 vec3(self.y, self.x, self.z)
386 }
387 pub const fn yzx(self) -> Self {
388 vec3(self.y, self.z, self.x)
389 }
390 pub const fn zxy(self) -> Self {
391 vec3(self.z, self.x, self.y)
392 }
393 pub const fn zyx(self) -> Self {
394 vec3(self.z, self.y, self.x)
395 }
396}
397impl Vec4 {
398 pub const X: Self = Self::new(1.0, 0.0, 0.0, 0.0);
399 pub const Y: Self = Self::new(0.0, 1.0, 0.0, 0.0);
400 pub const Z: Self = Self::new(0.0, 0.0, 1.0, 0.0);
401 pub const W: Self = Self::new(0.0, 0.0, 0.0, 1.0);
402 pub const AXES: [Self; 4] = [Self::X, Self::Y, Self::Z, Self::W];
403 pub const fn truncate(self) -> Vec3 {
404 vec3(self.x, self.y, self.z)
405 }
406 pub const fn xyz(self) -> Vec3 {
407 self.truncate()
408 }
409 pub const fn xy(self) -> Vec2 {
410 vec2(self.x, self.y)
411 }
412 pub const fn xz(self) -> Vec2 {
413 vec2(self.x, self.z)
414 }
415 pub const fn zw(self) -> Vec2 {
416 vec2(self.z, self.w)
417 }
418 pub const fn xyzw(self) -> Self {
419 self
420 }
421 pub const fn wzyx(self) -> Self {
422 vec4(self.w, self.z, self.y, self.x)
423 }
424}
425
426pub trait Vec2Swizzles {}
428pub trait Vec3Swizzles {}
429pub trait Vec4Swizzles {}
430impl Vec2Swizzles for Vec2 {}
431impl Vec3Swizzles for Vec3 {}
432impl Vec4Swizzles for Vec4 {}