1 // Generated from vec.rs.tera template. Edit the template, not the generated file.
2
3 use crate::{BVec3, Vec2, Vec4};
4
5 #[cfg(not(target_arch = "spirv"))]
6 use core::fmt;
7 use core::iter::{Product, Sum};
8 use core::{f32, ops::*};
9
10 #[cfg(feature = "libm")]
11 #[allow(unused_imports)]
12 use num_traits::Float;
13
14 /// Creates a 3-dimensional vector.
15 #[inline(always)]
vec3(x: f32, y: f32, z: f32) -> Vec316 pub const fn vec3(x: f32, y: f32, z: f32) -> Vec3 {
17 Vec3::new(x, y, z)
18 }
19
20 /// A 3-dimensional vector.
21 #[derive(Clone, Copy, PartialEq)]
22 #[cfg_attr(not(target_arch = "spirv"), repr(C))]
23 #[cfg_attr(target_arch = "spirv", repr(simd))]
24 pub struct Vec3 {
25 pub x: f32,
26 pub y: f32,
27 pub z: f32,
28 }
29
30 impl Vec3 {
31 /// All zeroes.
32 pub const ZERO: Self = Self::splat(0.0);
33
34 /// All ones.
35 pub const ONE: Self = Self::splat(1.0);
36
37 /// All negative ones.
38 pub const NEG_ONE: Self = Self::splat(-1.0);
39
40 /// All NAN.
41 pub const NAN: Self = Self::splat(f32::NAN);
42
43 /// A unit-length vector pointing along the positive X axis.
44 pub const X: Self = Self::new(1.0, 0.0, 0.0);
45
46 /// A unit-length vector pointing along the positive Y axis.
47 pub const Y: Self = Self::new(0.0, 1.0, 0.0);
48
49 /// A unit-length vector pointing along the positive Z axis.
50 pub const Z: Self = Self::new(0.0, 0.0, 1.0);
51
52 /// A unit-length vector pointing along the negative X axis.
53 pub const NEG_X: Self = Self::new(-1.0, 0.0, 0.0);
54
55 /// A unit-length vector pointing along the negative Y axis.
56 pub const NEG_Y: Self = Self::new(0.0, -1.0, 0.0);
57
58 /// A unit-length vector pointing along the negative Z axis.
59 pub const NEG_Z: Self = Self::new(0.0, 0.0, -1.0);
60
61 /// The unit axes.
62 pub const AXES: [Self; 3] = [Self::X, Self::Y, Self::Z];
63
64 /// Creates a new vector.
65 #[inline(always)]
new(x: f32, y: f32, z: f32) -> Self66 pub const fn new(x: f32, y: f32, z: f32) -> Self {
67 Self { x, y, z }
68 }
69
70 /// Creates a vector with all elements set to `v`.
71 #[inline]
splat(v: f32) -> Self72 pub const fn splat(v: f32) -> Self {
73 Self { x: v, y: v, z: v }
74 }
75
76 /// Creates a vector from the elements in `if_true` and `if_false`, selecting which to use
77 /// for each element of `self`.
78 ///
79 /// A true element in the mask uses the corresponding element from `if_true`, and false
80 /// uses the element from `if_false`.
81 #[inline]
select(mask: BVec3, if_true: Self, if_false: Self) -> Self82 pub fn select(mask: BVec3, if_true: Self, if_false: Self) -> Self {
83 Self {
84 x: if mask.x { if_true.x } else { if_false.x },
85 y: if mask.y { if_true.y } else { if_false.y },
86 z: if mask.z { if_true.z } else { if_false.z },
87 }
88 }
89
90 /// Creates a new vector from an array.
91 #[inline]
from_array(a: [f32; 3]) -> Self92 pub const fn from_array(a: [f32; 3]) -> Self {
93 Self::new(a[0], a[1], a[2])
94 }
95
96 /// `[x, y, z]`
97 #[inline]
to_array(&self) -> [f32; 3]98 pub const fn to_array(&self) -> [f32; 3] {
99 [self.x, self.y, self.z]
100 }
101
102 /// Creates a vector from the first 3 values in `slice`.
103 ///
104 /// # Panics
105 ///
106 /// Panics if `slice` is less than 3 elements long.
107 #[inline]
from_slice(slice: &[f32]) -> Self108 pub const fn from_slice(slice: &[f32]) -> Self {
109 Self::new(slice[0], slice[1], slice[2])
110 }
111
112 /// Writes the elements of `self` to the first 3 elements in `slice`.
113 ///
114 /// # Panics
115 ///
116 /// Panics if `slice` is less than 3 elements long.
117 #[inline]
write_to_slice(self, slice: &mut [f32])118 pub fn write_to_slice(self, slice: &mut [f32]) {
119 slice[0] = self.x;
120 slice[1] = self.y;
121 slice[2] = self.z;
122 }
123
124 /// Internal method for creating a 3D vector from a 4D vector, discarding `w`.
125 #[allow(dead_code)]
126 #[inline]
from_vec4(v: Vec4) -> Self127 pub(crate) fn from_vec4(v: Vec4) -> Self {
128 Self {
129 x: v.x,
130 y: v.y,
131 z: v.z,
132 }
133 }
134
135 /// Creates a 4D vector from `self` and the given `w` value.
136 #[inline]
extend(self, w: f32) -> Vec4137 pub fn extend(self, w: f32) -> Vec4 {
138 Vec4::new(self.x, self.y, self.z, w)
139 }
140
141 /// Creates a 2D vector from the `x` and `y` elements of `self`, discarding `z`.
142 ///
143 /// Truncation may also be performed by using `self.xy()` or `Vec2::from()`.
144 #[inline]
truncate(self) -> Vec2145 pub fn truncate(self) -> Vec2 {
146 use crate::swizzles::Vec3Swizzles;
147 self.xy()
148 }
149
150 /// Computes the dot product of `self` and `rhs`.
151 #[inline]
dot(self, rhs: Self) -> f32152 pub fn dot(self, rhs: Self) -> f32 {
153 (self.x * rhs.x) + (self.y * rhs.y) + (self.z * rhs.z)
154 }
155
156 /// Returns a vector where every component is the dot product of `self` and `rhs`.
157 #[inline]
dot_into_vec(self, rhs: Self) -> Self158 pub fn dot_into_vec(self, rhs: Self) -> Self {
159 Self::splat(self.dot(rhs))
160 }
161
162 /// Computes the cross product of `self` and `rhs`.
163 #[inline]
cross(self, rhs: Self) -> Self164 pub fn cross(self, rhs: Self) -> Self {
165 Self {
166 x: self.y * rhs.z - rhs.y * self.z,
167 y: self.z * rhs.x - rhs.z * self.x,
168 z: self.x * rhs.y - rhs.x * self.y,
169 }
170 }
171
172 /// Returns a vector containing the minimum values for each element of `self` and `rhs`.
173 ///
174 /// In other words this computes `[self.x.min(rhs.x), self.y.min(rhs.y), ..]`.
175 #[inline]
min(self, rhs: Self) -> Self176 pub fn min(self, rhs: Self) -> Self {
177 Self {
178 x: self.x.min(rhs.x),
179 y: self.y.min(rhs.y),
180 z: self.z.min(rhs.z),
181 }
182 }
183
184 /// Returns a vector containing the maximum values for each element of `self` and `rhs`.
185 ///
186 /// In other words this computes `[self.x.max(rhs.x), self.y.max(rhs.y), ..]`.
187 #[inline]
max(self, rhs: Self) -> Self188 pub fn max(self, rhs: Self) -> Self {
189 Self {
190 x: self.x.max(rhs.x),
191 y: self.y.max(rhs.y),
192 z: self.z.max(rhs.z),
193 }
194 }
195
196 /// Component-wise clamping of values, similar to [`f32::clamp`].
197 ///
198 /// Each element in `min` must be less-or-equal to the corresponding element in `max`.
199 ///
200 /// # Panics
201 ///
202 /// Will panic if `min` is greater than `max` when `glam_assert` is enabled.
203 #[inline]
clamp(self, min: Self, max: Self) -> Self204 pub fn clamp(self, min: Self, max: Self) -> Self {
205 glam_assert!(min.cmple(max).all(), "clamp: expected min <= max");
206 self.max(min).min(max)
207 }
208
209 /// Returns the horizontal minimum of `self`.
210 ///
211 /// In other words this computes `min(x, y, ..)`.
212 #[inline]
min_element(self) -> f32213 pub fn min_element(self) -> f32 {
214 self.x.min(self.y.min(self.z))
215 }
216
217 /// Returns the horizontal maximum of `self`.
218 ///
219 /// In other words this computes `max(x, y, ..)`.
220 #[inline]
max_element(self) -> f32221 pub fn max_element(self) -> f32 {
222 self.x.max(self.y.max(self.z))
223 }
224
225 /// Returns a vector mask containing the result of a `==` comparison for each element of
226 /// `self` and `rhs`.
227 ///
228 /// In other words, this computes `[self.x == rhs.x, self.y == rhs.y, ..]` for all
229 /// elements.
230 #[inline]
cmpeq(self, rhs: Self) -> BVec3231 pub fn cmpeq(self, rhs: Self) -> BVec3 {
232 BVec3::new(self.x.eq(&rhs.x), self.y.eq(&rhs.y), self.z.eq(&rhs.z))
233 }
234
235 /// Returns a vector mask containing the result of a `!=` comparison for each element of
236 /// `self` and `rhs`.
237 ///
238 /// In other words this computes `[self.x != rhs.x, self.y != rhs.y, ..]` for all
239 /// elements.
240 #[inline]
cmpne(self, rhs: Self) -> BVec3241 pub fn cmpne(self, rhs: Self) -> BVec3 {
242 BVec3::new(self.x.ne(&rhs.x), self.y.ne(&rhs.y), self.z.ne(&rhs.z))
243 }
244
245 /// Returns a vector mask containing the result of a `>=` comparison for each element of
246 /// `self` and `rhs`.
247 ///
248 /// In other words this computes `[self.x >= rhs.x, self.y >= rhs.y, ..]` for all
249 /// elements.
250 #[inline]
cmpge(self, rhs: Self) -> BVec3251 pub fn cmpge(self, rhs: Self) -> BVec3 {
252 BVec3::new(self.x.ge(&rhs.x), self.y.ge(&rhs.y), self.z.ge(&rhs.z))
253 }
254
255 /// Returns a vector mask containing the result of a `>` comparison for each element of
256 /// `self` and `rhs`.
257 ///
258 /// In other words this computes `[self.x > rhs.x, self.y > rhs.y, ..]` for all
259 /// elements.
260 #[inline]
cmpgt(self, rhs: Self) -> BVec3261 pub fn cmpgt(self, rhs: Self) -> BVec3 {
262 BVec3::new(self.x.gt(&rhs.x), self.y.gt(&rhs.y), self.z.gt(&rhs.z))
263 }
264
265 /// Returns a vector mask containing the result of a `<=` comparison for each element of
266 /// `self` and `rhs`.
267 ///
268 /// In other words this computes `[self.x <= rhs.x, self.y <= rhs.y, ..]` for all
269 /// elements.
270 #[inline]
cmple(self, rhs: Self) -> BVec3271 pub fn cmple(self, rhs: Self) -> BVec3 {
272 BVec3::new(self.x.le(&rhs.x), self.y.le(&rhs.y), self.z.le(&rhs.z))
273 }
274
275 /// Returns a vector mask containing the result of a `<` comparison for each element of
276 /// `self` and `rhs`.
277 ///
278 /// In other words this computes `[self.x < rhs.x, self.y < rhs.y, ..]` for all
279 /// elements.
280 #[inline]
cmplt(self, rhs: Self) -> BVec3281 pub fn cmplt(self, rhs: Self) -> BVec3 {
282 BVec3::new(self.x.lt(&rhs.x), self.y.lt(&rhs.y), self.z.lt(&rhs.z))
283 }
284
285 /// Returns a vector containing the absolute value of each element of `self`.
286 #[inline]
abs(self) -> Self287 pub fn abs(self) -> Self {
288 Self {
289 x: self.x.abs(),
290 y: self.y.abs(),
291 z: self.z.abs(),
292 }
293 }
294
295 /// Returns a vector with elements representing the sign of `self`.
296 ///
297 /// - `1.0` if the number is positive, `+0.0` or `INFINITY`
298 /// - `-1.0` if the number is negative, `-0.0` or `NEG_INFINITY`
299 /// - `NAN` if the number is `NAN`
300 #[inline]
signum(self) -> Self301 pub fn signum(self) -> Self {
302 Self {
303 x: self.x.signum(),
304 y: self.y.signum(),
305 z: self.z.signum(),
306 }
307 }
308
309 /// Returns a vector with signs of `rhs` and the magnitudes of `self`.
310 #[inline]
copysign(self, rhs: Self) -> Self311 pub fn copysign(self, rhs: Self) -> Self {
312 Self {
313 x: self.x.copysign(rhs.x),
314 y: self.y.copysign(rhs.y),
315 z: self.z.copysign(rhs.z),
316 }
317 }
318
319 /// Returns a bitmask with the lowest 3 bits set to the sign bits from the elements of `self`.
320 ///
321 /// A negative element results in a `1` bit and a positive element in a `0` bit. Element `x` goes
322 /// into the first lowest bit, element `y` into the second, etc.
323 #[inline]
is_negative_bitmask(self) -> u32324 pub fn is_negative_bitmask(self) -> u32 {
325 (self.x.is_sign_negative() as u32)
326 | (self.y.is_sign_negative() as u32) << 1
327 | (self.z.is_sign_negative() as u32) << 2
328 }
329
330 /// Returns `true` if, and only if, all elements are finite. If any element is either
331 /// `NaN`, positive or negative infinity, this will return `false`.
332 #[inline]
is_finite(self) -> bool333 pub fn is_finite(self) -> bool {
334 self.x.is_finite() && self.y.is_finite() && self.z.is_finite()
335 }
336
337 /// Returns `true` if any elements are `NaN`.
338 #[inline]
is_nan(self) -> bool339 pub fn is_nan(self) -> bool {
340 self.x.is_nan() || self.y.is_nan() || self.z.is_nan()
341 }
342
343 /// Performs `is_nan` on each element of self, returning a vector mask of the results.
344 ///
345 /// In other words, this computes `[x.is_nan(), y.is_nan(), z.is_nan(), w.is_nan()]`.
346 #[inline]
is_nan_mask(self) -> BVec3347 pub fn is_nan_mask(self) -> BVec3 {
348 BVec3::new(self.x.is_nan(), self.y.is_nan(), self.z.is_nan())
349 }
350
351 /// Computes the length of `self`.
352 #[doc(alias = "magnitude")]
353 #[inline]
length(self) -> f32354 pub fn length(self) -> f32 {
355 self.dot(self).sqrt()
356 }
357
358 /// Computes the squared length of `self`.
359 ///
360 /// This is faster than `length()` as it avoids a square root operation.
361 #[doc(alias = "magnitude2")]
362 #[inline]
length_squared(self) -> f32363 pub fn length_squared(self) -> f32 {
364 self.dot(self)
365 }
366
367 /// Computes `1.0 / length()`.
368 ///
369 /// For valid results, `self` must _not_ be of length zero.
370 #[inline]
length_recip(self) -> f32371 pub fn length_recip(self) -> f32 {
372 self.length().recip()
373 }
374
375 /// Computes the Euclidean distance between two points in space.
376 #[inline]
distance(self, rhs: Self) -> f32377 pub fn distance(self, rhs: Self) -> f32 {
378 (self - rhs).length()
379 }
380
381 /// Compute the squared euclidean distance between two points in space.
382 #[inline]
distance_squared(self, rhs: Self) -> f32383 pub fn distance_squared(self, rhs: Self) -> f32 {
384 (self - rhs).length_squared()
385 }
386
387 /// Returns `self` normalized to length 1.0.
388 ///
389 /// For valid results, `self` must _not_ be of length zero, nor very close to zero.
390 ///
391 /// See also [`Self::try_normalize`] and [`Self::normalize_or_zero`].
392 ///
393 /// Panics
394 ///
395 /// Will panic if `self` is zero length when `glam_assert` is enabled.
396 #[must_use]
397 #[inline]
normalize(self) -> Self398 pub fn normalize(self) -> Self {
399 #[allow(clippy::let_and_return)]
400 let normalized = self.mul(self.length_recip());
401 glam_assert!(normalized.is_finite());
402 normalized
403 }
404
405 /// Returns `self` normalized to length 1.0 if possible, else returns `None`.
406 ///
407 /// In particular, if the input is zero (or very close to zero), or non-finite,
408 /// the result of this operation will be `None`.
409 ///
410 /// See also [`Self::normalize_or_zero`].
411 #[must_use]
412 #[inline]
try_normalize(self) -> Option<Self>413 pub fn try_normalize(self) -> Option<Self> {
414 let rcp = self.length_recip();
415 if rcp.is_finite() && rcp > 0.0 {
416 Some(self * rcp)
417 } else {
418 None
419 }
420 }
421
422 /// Returns `self` normalized to length 1.0 if possible, else returns zero.
423 ///
424 /// In particular, if the input is zero (or very close to zero), or non-finite,
425 /// the result of this operation will be zero.
426 ///
427 /// See also [`Self::try_normalize`].
428 #[must_use]
429 #[inline]
normalize_or_zero(self) -> Self430 pub fn normalize_or_zero(self) -> Self {
431 let rcp = self.length_recip();
432 if rcp.is_finite() && rcp > 0.0 {
433 self * rcp
434 } else {
435 Self::ZERO
436 }
437 }
438
439 /// Returns whether `self` is length `1.0` or not.
440 ///
441 /// Uses a precision threshold of `1e-6`.
442 #[inline]
is_normalized(self) -> bool443 pub fn is_normalized(self) -> bool {
444 // TODO: do something with epsilon
445 (self.length_squared() - 1.0).abs() <= 1e-4
446 }
447
448 /// Returns the vector projection of `self` onto `rhs`.
449 ///
450 /// `rhs` must be of non-zero length.
451 ///
452 /// # Panics
453 ///
454 /// Will panic if `rhs` is zero length when `glam_assert` is enabled.
455 #[must_use]
456 #[inline]
project_onto(self, rhs: Self) -> Self457 pub fn project_onto(self, rhs: Self) -> Self {
458 let other_len_sq_rcp = rhs.dot(rhs).recip();
459 glam_assert!(other_len_sq_rcp.is_finite());
460 rhs * self.dot(rhs) * other_len_sq_rcp
461 }
462
463 /// Returns the vector rejection of `self` from `rhs`.
464 ///
465 /// The vector rejection is the vector perpendicular to the projection of `self` onto
466 /// `rhs`, in rhs words the result of `self - self.project_onto(rhs)`.
467 ///
468 /// `rhs` must be of non-zero length.
469 ///
470 /// # Panics
471 ///
472 /// Will panic if `rhs` has a length of zero when `glam_assert` is enabled.
473 #[must_use]
474 #[inline]
reject_from(self, rhs: Self) -> Self475 pub fn reject_from(self, rhs: Self) -> Self {
476 self - self.project_onto(rhs)
477 }
478
479 /// Returns the vector projection of `self` onto `rhs`.
480 ///
481 /// `rhs` must be normalized.
482 ///
483 /// # Panics
484 ///
485 /// Will panic if `rhs` is not normalized when `glam_assert` is enabled.
486 #[must_use]
487 #[inline]
project_onto_normalized(self, rhs: Self) -> Self488 pub fn project_onto_normalized(self, rhs: Self) -> Self {
489 glam_assert!(rhs.is_normalized());
490 rhs * self.dot(rhs)
491 }
492
493 /// Returns the vector rejection of `self` from `rhs`.
494 ///
495 /// The vector rejection is the vector perpendicular to the projection of `self` onto
496 /// `rhs`, in rhs words the result of `self - self.project_onto(rhs)`.
497 ///
498 /// `rhs` must be normalized.
499 ///
500 /// # Panics
501 ///
502 /// Will panic if `rhs` is not normalized when `glam_assert` is enabled.
503 #[must_use]
504 #[inline]
reject_from_normalized(self, rhs: Self) -> Self505 pub fn reject_from_normalized(self, rhs: Self) -> Self {
506 self - self.project_onto_normalized(rhs)
507 }
508
509 /// Returns a vector containing the nearest integer to a number for each element of `self`.
510 /// Round half-way cases away from 0.0.
511 #[inline]
round(self) -> Self512 pub fn round(self) -> Self {
513 Self {
514 x: self.x.round(),
515 y: self.y.round(),
516 z: self.z.round(),
517 }
518 }
519
520 /// Returns a vector containing the largest integer less than or equal to a number for each
521 /// element of `self`.
522 #[inline]
floor(self) -> Self523 pub fn floor(self) -> Self {
524 Self {
525 x: self.x.floor(),
526 y: self.y.floor(),
527 z: self.z.floor(),
528 }
529 }
530
531 /// Returns a vector containing the smallest integer greater than or equal to a number for
532 /// each element of `self`.
533 #[inline]
ceil(self) -> Self534 pub fn ceil(self) -> Self {
535 Self {
536 x: self.x.ceil(),
537 y: self.y.ceil(),
538 z: self.z.ceil(),
539 }
540 }
541
542 /// Returns a vector containing the fractional part of the vector, e.g. `self -
543 /// self.floor()`.
544 ///
545 /// Note that this is fast but not precise for large numbers.
546 #[inline]
fract(self) -> Self547 pub fn fract(self) -> Self {
548 self - self.floor()
549 }
550
551 /// Returns a vector containing `e^self` (the exponential function) for each element of
552 /// `self`.
553 #[inline]
exp(self) -> Self554 pub fn exp(self) -> Self {
555 Self::new(self.x.exp(), self.y.exp(), self.z.exp())
556 }
557
558 /// Returns a vector containing each element of `self` raised to the power of `n`.
559 #[inline]
powf(self, n: f32) -> Self560 pub fn powf(self, n: f32) -> Self {
561 Self::new(self.x.powf(n), self.y.powf(n), self.z.powf(n))
562 }
563
564 /// Returns a vector containing the reciprocal `1.0/n` of each element of `self`.
565 #[inline]
recip(self) -> Self566 pub fn recip(self) -> Self {
567 Self {
568 x: self.x.recip(),
569 y: self.y.recip(),
570 z: self.z.recip(),
571 }
572 }
573
574 /// Performs a linear interpolation between `self` and `rhs` based on the value `s`.
575 ///
576 /// When `s` is `0.0`, the result will be equal to `self`. When `s` is `1.0`, the result
577 /// will be equal to `rhs`. When `s` is outside of range `[0, 1]`, the result is linearly
578 /// extrapolated.
579 #[doc(alias = "mix")]
580 #[inline]
lerp(self, rhs: Self, s: f32) -> Self581 pub fn lerp(self, rhs: Self, s: f32) -> Self {
582 self + ((rhs - self) * s)
583 }
584
585 /// Returns true if the absolute difference of all elements between `self` and `rhs` is
586 /// less than or equal to `max_abs_diff`.
587 ///
588 /// This can be used to compare if two vectors contain similar elements. It works best when
589 /// comparing with a known value. The `max_abs_diff` that should be used used depends on
590 /// the values being compared against.
591 ///
592 /// For more see
593 /// [comparing floating point numbers](https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/).
594 #[inline]
abs_diff_eq(self, rhs: Self, max_abs_diff: f32) -> bool595 pub fn abs_diff_eq(self, rhs: Self, max_abs_diff: f32) -> bool {
596 self.sub(rhs).abs().cmple(Self::splat(max_abs_diff)).all()
597 }
598
599 /// Returns a vector with a length no less than `min` and no more than `max`
600 ///
601 /// # Panics
602 ///
603 /// Will panic if `min` is greater than `max` when `glam_assert` is enabled.
604 #[inline]
clamp_length(self, min: f32, max: f32) -> Self605 pub fn clamp_length(self, min: f32, max: f32) -> Self {
606 glam_assert!(min <= max);
607 let length_sq = self.length_squared();
608 if length_sq < min * min {
609 self * (length_sq.sqrt().recip() * min)
610 } else if length_sq > max * max {
611 self * (length_sq.sqrt().recip() * max)
612 } else {
613 self
614 }
615 }
616
617 /// Returns a vector with a length no more than `max`
clamp_length_max(self, max: f32) -> Self618 pub fn clamp_length_max(self, max: f32) -> Self {
619 let length_sq = self.length_squared();
620 if length_sq > max * max {
621 self * (length_sq.sqrt().recip() * max)
622 } else {
623 self
624 }
625 }
626
627 /// Returns a vector with a length no less than `min`
clamp_length_min(self, min: f32) -> Self628 pub fn clamp_length_min(self, min: f32) -> Self {
629 let length_sq = self.length_squared();
630 if length_sq < min * min {
631 self * (length_sq.sqrt().recip() * min)
632 } else {
633 self
634 }
635 }
636
637 /// Fused multiply-add. Computes `(self * a) + b` element-wise with only one rounding
638 /// error, yielding a more accurate result than an unfused multiply-add.
639 ///
640 /// Using `mul_add` *may* be more performant than an unfused multiply-add if the target
641 /// architecture has a dedicated fma CPU instruction. However, this is not always true,
642 /// and will be heavily dependant on designing algorithms with specific target hardware in
643 /// mind.
644 #[inline]
mul_add(self, a: Self, b: Self) -> Self645 pub fn mul_add(self, a: Self, b: Self) -> Self {
646 Self::new(
647 self.x.mul_add(a.x, b.x),
648 self.y.mul_add(a.y, b.y),
649 self.z.mul_add(a.z, b.z),
650 )
651 }
652
653 /// Returns the angle (in radians) between two vectors.
654 ///
655 /// The input vectors do not need to be unit length however they must be non-zero.
656 #[inline]
angle_between(self, rhs: Self) -> f32657 pub fn angle_between(self, rhs: Self) -> f32 {
658 use crate::FloatEx;
659 self.dot(rhs)
660 .div(self.length_squared().mul(rhs.length_squared()).sqrt())
661 .acos_approx()
662 }
663
664 /// Returns some vector that is orthogonal to the given one.
665 ///
666 /// The input vector must be finite and non-zero.
667 ///
668 /// The output vector is not necessarily unit-length.
669 /// For that use [`Self::any_orthonormal_vector`] instead.
670 #[inline]
any_orthogonal_vector(&self) -> Self671 pub fn any_orthogonal_vector(&self) -> Self {
672 // This can probably be optimized
673 if self.x.abs() > self.y.abs() {
674 Self::new(-self.z, 0.0, self.x) // self.cross(Self::Y)
675 } else {
676 Self::new(0.0, self.z, -self.y) // self.cross(Self::X)
677 }
678 }
679
680 /// Returns any unit-length vector that is orthogonal to the given one.
681 /// The input vector must be finite and non-zero.
682 ///
683 /// # Panics
684 ///
685 /// Will panic if `self` is not normalized when `glam_assert` is enabled.
686 #[inline]
any_orthonormal_vector(&self) -> Self687 pub fn any_orthonormal_vector(&self) -> Self {
688 glam_assert!(self.is_normalized());
689 // From https://graphics.pixar.com/library/OrthonormalB/paper.pdf
690 #[cfg(feature = "std")]
691 let sign = (1.0_f32).copysign(self.z);
692 #[cfg(not(feature = "std"))]
693 let sign = self.z.signum();
694 let a = -1.0 / (sign + self.z);
695 let b = self.x * self.y * a;
696 Self::new(b, sign + self.y * self.y * a, -self.y)
697 }
698
699 /// Given a unit-length vector return two other vectors that together form an orthonormal
700 /// basis. That is, all three vectors are orthogonal to each other and are normalized.
701 ///
702 /// # Panics
703 ///
704 /// Will panic if `self` is not normalized when `glam_assert` is enabled.
705 #[inline]
any_orthonormal_pair(&self) -> (Self, Self)706 pub fn any_orthonormal_pair(&self) -> (Self, Self) {
707 glam_assert!(self.is_normalized());
708 // From https://graphics.pixar.com/library/OrthonormalB/paper.pdf
709 #[cfg(feature = "std")]
710 let sign = (1.0_f32).copysign(self.z);
711 #[cfg(not(feature = "std"))]
712 let sign = self.z.signum();
713 let a = -1.0 / (sign + self.z);
714 let b = self.x * self.y * a;
715 (
716 Self::new(1.0 + sign * self.x * self.x * a, sign * b, -sign * self.x),
717 Self::new(b, sign + self.y * self.y * a, -self.y),
718 )
719 }
720
721 /// Casts all elements of `self` to `f64`.
722 #[inline]
as_dvec3(&self) -> crate::DVec3723 pub fn as_dvec3(&self) -> crate::DVec3 {
724 crate::DVec3::new(self.x as f64, self.y as f64, self.z as f64)
725 }
726
727 /// Casts all elements of `self` to `i32`.
728 #[inline]
as_ivec3(&self) -> crate::IVec3729 pub fn as_ivec3(&self) -> crate::IVec3 {
730 crate::IVec3::new(self.x as i32, self.y as i32, self.z as i32)
731 }
732
733 /// Casts all elements of `self` to `u32`.
734 #[inline]
as_uvec3(&self) -> crate::UVec3735 pub fn as_uvec3(&self) -> crate::UVec3 {
736 crate::UVec3::new(self.x as u32, self.y as u32, self.z as u32)
737 }
738 }
739
740 impl Default for Vec3 {
741 #[inline(always)]
default() -> Self742 fn default() -> Self {
743 Self::ZERO
744 }
745 }
746
747 impl Div<Vec3> for Vec3 {
748 type Output = Self;
749 #[inline]
div(self, rhs: Self) -> Self750 fn div(self, rhs: Self) -> Self {
751 Self {
752 x: self.x.div(rhs.x),
753 y: self.y.div(rhs.y),
754 z: self.z.div(rhs.z),
755 }
756 }
757 }
758
759 impl DivAssign<Vec3> for Vec3 {
760 #[inline]
div_assign(&mut self, rhs: Self)761 fn div_assign(&mut self, rhs: Self) {
762 self.x.div_assign(rhs.x);
763 self.y.div_assign(rhs.y);
764 self.z.div_assign(rhs.z);
765 }
766 }
767
768 impl Div<f32> for Vec3 {
769 type Output = Self;
770 #[inline]
div(self, rhs: f32) -> Self771 fn div(self, rhs: f32) -> Self {
772 Self {
773 x: self.x.div(rhs),
774 y: self.y.div(rhs),
775 z: self.z.div(rhs),
776 }
777 }
778 }
779
780 impl DivAssign<f32> for Vec3 {
781 #[inline]
div_assign(&mut self, rhs: f32)782 fn div_assign(&mut self, rhs: f32) {
783 self.x.div_assign(rhs);
784 self.y.div_assign(rhs);
785 self.z.div_assign(rhs);
786 }
787 }
788
789 impl Div<Vec3> for f32 {
790 type Output = Vec3;
791 #[inline]
div(self, rhs: Vec3) -> Vec3792 fn div(self, rhs: Vec3) -> Vec3 {
793 Vec3 {
794 x: self.div(rhs.x),
795 y: self.div(rhs.y),
796 z: self.div(rhs.z),
797 }
798 }
799 }
800
801 impl Mul<Vec3> for Vec3 {
802 type Output = Self;
803 #[inline]
mul(self, rhs: Self) -> Self804 fn mul(self, rhs: Self) -> Self {
805 Self {
806 x: self.x.mul(rhs.x),
807 y: self.y.mul(rhs.y),
808 z: self.z.mul(rhs.z),
809 }
810 }
811 }
812
813 impl MulAssign<Vec3> for Vec3 {
814 #[inline]
mul_assign(&mut self, rhs: Self)815 fn mul_assign(&mut self, rhs: Self) {
816 self.x.mul_assign(rhs.x);
817 self.y.mul_assign(rhs.y);
818 self.z.mul_assign(rhs.z);
819 }
820 }
821
822 impl Mul<f32> for Vec3 {
823 type Output = Self;
824 #[inline]
mul(self, rhs: f32) -> Self825 fn mul(self, rhs: f32) -> Self {
826 Self {
827 x: self.x.mul(rhs),
828 y: self.y.mul(rhs),
829 z: self.z.mul(rhs),
830 }
831 }
832 }
833
834 impl MulAssign<f32> for Vec3 {
835 #[inline]
mul_assign(&mut self, rhs: f32)836 fn mul_assign(&mut self, rhs: f32) {
837 self.x.mul_assign(rhs);
838 self.y.mul_assign(rhs);
839 self.z.mul_assign(rhs);
840 }
841 }
842
843 impl Mul<Vec3> for f32 {
844 type Output = Vec3;
845 #[inline]
mul(self, rhs: Vec3) -> Vec3846 fn mul(self, rhs: Vec3) -> Vec3 {
847 Vec3 {
848 x: self.mul(rhs.x),
849 y: self.mul(rhs.y),
850 z: self.mul(rhs.z),
851 }
852 }
853 }
854
855 impl Add<Vec3> for Vec3 {
856 type Output = Self;
857 #[inline]
add(self, rhs: Self) -> Self858 fn add(self, rhs: Self) -> Self {
859 Self {
860 x: self.x.add(rhs.x),
861 y: self.y.add(rhs.y),
862 z: self.z.add(rhs.z),
863 }
864 }
865 }
866
867 impl AddAssign<Vec3> for Vec3 {
868 #[inline]
add_assign(&mut self, rhs: Self)869 fn add_assign(&mut self, rhs: Self) {
870 self.x.add_assign(rhs.x);
871 self.y.add_assign(rhs.y);
872 self.z.add_assign(rhs.z);
873 }
874 }
875
876 impl Add<f32> for Vec3 {
877 type Output = Self;
878 #[inline]
add(self, rhs: f32) -> Self879 fn add(self, rhs: f32) -> Self {
880 Self {
881 x: self.x.add(rhs),
882 y: self.y.add(rhs),
883 z: self.z.add(rhs),
884 }
885 }
886 }
887
888 impl AddAssign<f32> for Vec3 {
889 #[inline]
add_assign(&mut self, rhs: f32)890 fn add_assign(&mut self, rhs: f32) {
891 self.x.add_assign(rhs);
892 self.y.add_assign(rhs);
893 self.z.add_assign(rhs);
894 }
895 }
896
897 impl Add<Vec3> for f32 {
898 type Output = Vec3;
899 #[inline]
add(self, rhs: Vec3) -> Vec3900 fn add(self, rhs: Vec3) -> Vec3 {
901 Vec3 {
902 x: self.add(rhs.x),
903 y: self.add(rhs.y),
904 z: self.add(rhs.z),
905 }
906 }
907 }
908
909 impl Sub<Vec3> for Vec3 {
910 type Output = Self;
911 #[inline]
sub(self, rhs: Self) -> Self912 fn sub(self, rhs: Self) -> Self {
913 Self {
914 x: self.x.sub(rhs.x),
915 y: self.y.sub(rhs.y),
916 z: self.z.sub(rhs.z),
917 }
918 }
919 }
920
921 impl SubAssign<Vec3> for Vec3 {
922 #[inline]
sub_assign(&mut self, rhs: Vec3)923 fn sub_assign(&mut self, rhs: Vec3) {
924 self.x.sub_assign(rhs.x);
925 self.y.sub_assign(rhs.y);
926 self.z.sub_assign(rhs.z);
927 }
928 }
929
930 impl Sub<f32> for Vec3 {
931 type Output = Self;
932 #[inline]
sub(self, rhs: f32) -> Self933 fn sub(self, rhs: f32) -> Self {
934 Self {
935 x: self.x.sub(rhs),
936 y: self.y.sub(rhs),
937 z: self.z.sub(rhs),
938 }
939 }
940 }
941
942 impl SubAssign<f32> for Vec3 {
943 #[inline]
sub_assign(&mut self, rhs: f32)944 fn sub_assign(&mut self, rhs: f32) {
945 self.x.sub_assign(rhs);
946 self.y.sub_assign(rhs);
947 self.z.sub_assign(rhs);
948 }
949 }
950
951 impl Sub<Vec3> for f32 {
952 type Output = Vec3;
953 #[inline]
sub(self, rhs: Vec3) -> Vec3954 fn sub(self, rhs: Vec3) -> Vec3 {
955 Vec3 {
956 x: self.sub(rhs.x),
957 y: self.sub(rhs.y),
958 z: self.sub(rhs.z),
959 }
960 }
961 }
962
963 impl Rem<Vec3> for Vec3 {
964 type Output = Self;
965 #[inline]
rem(self, rhs: Self) -> Self966 fn rem(self, rhs: Self) -> Self {
967 Self {
968 x: self.x.rem(rhs.x),
969 y: self.y.rem(rhs.y),
970 z: self.z.rem(rhs.z),
971 }
972 }
973 }
974
975 impl RemAssign<Vec3> for Vec3 {
976 #[inline]
rem_assign(&mut self, rhs: Self)977 fn rem_assign(&mut self, rhs: Self) {
978 self.x.rem_assign(rhs.x);
979 self.y.rem_assign(rhs.y);
980 self.z.rem_assign(rhs.z);
981 }
982 }
983
984 impl Rem<f32> for Vec3 {
985 type Output = Self;
986 #[inline]
rem(self, rhs: f32) -> Self987 fn rem(self, rhs: f32) -> Self {
988 Self {
989 x: self.x.rem(rhs),
990 y: self.y.rem(rhs),
991 z: self.z.rem(rhs),
992 }
993 }
994 }
995
996 impl RemAssign<f32> for Vec3 {
997 #[inline]
rem_assign(&mut self, rhs: f32)998 fn rem_assign(&mut self, rhs: f32) {
999 self.x.rem_assign(rhs);
1000 self.y.rem_assign(rhs);
1001 self.z.rem_assign(rhs);
1002 }
1003 }
1004
1005 impl Rem<Vec3> for f32 {
1006 type Output = Vec3;
1007 #[inline]
rem(self, rhs: Vec3) -> Vec31008 fn rem(self, rhs: Vec3) -> Vec3 {
1009 Vec3 {
1010 x: self.rem(rhs.x),
1011 y: self.rem(rhs.y),
1012 z: self.rem(rhs.z),
1013 }
1014 }
1015 }
1016
1017 #[cfg(not(target_arch = "spirv"))]
1018 impl AsRef<[f32; 3]> for Vec3 {
1019 #[inline]
as_ref(&self) -> &[f32; 3]1020 fn as_ref(&self) -> &[f32; 3] {
1021 unsafe { &*(self as *const Vec3 as *const [f32; 3]) }
1022 }
1023 }
1024
1025 #[cfg(not(target_arch = "spirv"))]
1026 impl AsMut<[f32; 3]> for Vec3 {
1027 #[inline]
as_mut(&mut self) -> &mut [f32; 3]1028 fn as_mut(&mut self) -> &mut [f32; 3] {
1029 unsafe { &mut *(self as *mut Vec3 as *mut [f32; 3]) }
1030 }
1031 }
1032
1033 impl Sum for Vec3 {
1034 #[inline]
sum<I>(iter: I) -> Self where I: Iterator<Item = Self>,1035 fn sum<I>(iter: I) -> Self
1036 where
1037 I: Iterator<Item = Self>,
1038 {
1039 iter.fold(Self::ZERO, Self::add)
1040 }
1041 }
1042
1043 impl<'a> Sum<&'a Self> for Vec3 {
1044 #[inline]
sum<I>(iter: I) -> Self where I: Iterator<Item = &'a Self>,1045 fn sum<I>(iter: I) -> Self
1046 where
1047 I: Iterator<Item = &'a Self>,
1048 {
1049 iter.fold(Self::ZERO, |a, &b| Self::add(a, b))
1050 }
1051 }
1052
1053 impl Product for Vec3 {
1054 #[inline]
product<I>(iter: I) -> Self where I: Iterator<Item = Self>,1055 fn product<I>(iter: I) -> Self
1056 where
1057 I: Iterator<Item = Self>,
1058 {
1059 iter.fold(Self::ONE, Self::mul)
1060 }
1061 }
1062
1063 impl<'a> Product<&'a Self> for Vec3 {
1064 #[inline]
product<I>(iter: I) -> Self where I: Iterator<Item = &'a Self>,1065 fn product<I>(iter: I) -> Self
1066 where
1067 I: Iterator<Item = &'a Self>,
1068 {
1069 iter.fold(Self::ONE, |a, &b| Self::mul(a, b))
1070 }
1071 }
1072
1073 impl Neg for Vec3 {
1074 type Output = Self;
1075 #[inline]
neg(self) -> Self1076 fn neg(self) -> Self {
1077 Self {
1078 x: self.x.neg(),
1079 y: self.y.neg(),
1080 z: self.z.neg(),
1081 }
1082 }
1083 }
1084
1085 impl Index<usize> for Vec3 {
1086 type Output = f32;
1087 #[inline]
index(&self, index: usize) -> &Self::Output1088 fn index(&self, index: usize) -> &Self::Output {
1089 match index {
1090 0 => &self.x,
1091 1 => &self.y,
1092 2 => &self.z,
1093 _ => panic!("index out of bounds"),
1094 }
1095 }
1096 }
1097
1098 impl IndexMut<usize> for Vec3 {
1099 #[inline]
index_mut(&mut self, index: usize) -> &mut Self::Output1100 fn index_mut(&mut self, index: usize) -> &mut Self::Output {
1101 match index {
1102 0 => &mut self.x,
1103 1 => &mut self.y,
1104 2 => &mut self.z,
1105 _ => panic!("index out of bounds"),
1106 }
1107 }
1108 }
1109
1110 #[cfg(not(target_arch = "spirv"))]
1111 impl fmt::Display for Vec3 {
fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result1112 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1113 write!(f, "[{}, {}, {}]", self.x, self.y, self.z)
1114 }
1115 }
1116
1117 #[cfg(not(target_arch = "spirv"))]
1118 impl fmt::Debug for Vec3 {
fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result1119 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1120 fmt.debug_tuple(stringify!(Vec3))
1121 .field(&self.x)
1122 .field(&self.y)
1123 .field(&self.z)
1124 .finish()
1125 }
1126 }
1127
1128 impl From<[f32; 3]> for Vec3 {
1129 #[inline]
from(a: [f32; 3]) -> Self1130 fn from(a: [f32; 3]) -> Self {
1131 Self::new(a[0], a[1], a[2])
1132 }
1133 }
1134
1135 impl From<Vec3> for [f32; 3] {
1136 #[inline]
from(v: Vec3) -> Self1137 fn from(v: Vec3) -> Self {
1138 [v.x, v.y, v.z]
1139 }
1140 }
1141
1142 impl From<(f32, f32, f32)> for Vec3 {
1143 #[inline]
from(t: (f32, f32, f32)) -> Self1144 fn from(t: (f32, f32, f32)) -> Self {
1145 Self::new(t.0, t.1, t.2)
1146 }
1147 }
1148
1149 impl From<Vec3> for (f32, f32, f32) {
1150 #[inline]
from(v: Vec3) -> Self1151 fn from(v: Vec3) -> Self {
1152 (v.x, v.y, v.z)
1153 }
1154 }
1155
1156 impl From<(Vec2, f32)> for Vec3 {
1157 #[inline]
from((v, z): (Vec2, f32)) -> Self1158 fn from((v, z): (Vec2, f32)) -> Self {
1159 Self::new(v.x, v.y, z)
1160 }
1161 }
1162