1 // Generated from vec.rs.tera template. Edit the template, not the generated file.
2
3 use crate::{f32::math, 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 /// Creates a 3-dimensional vector.
11 #[inline(always)]
12 #[must_use]
vec3(x: f32, y: f32, z: f32) -> Vec313 pub const fn vec3(x: f32, y: f32, z: f32) -> Vec3 {
14 Vec3::new(x, y, z)
15 }
16
17 /// A 3-dimensional vector.
18 #[derive(Clone, Copy, PartialEq)]
19 #[cfg_attr(not(target_arch = "spirv"), repr(C))]
20 #[cfg_attr(target_arch = "spirv", repr(simd))]
21 pub struct Vec3 {
22 pub x: f32,
23 pub y: f32,
24 pub z: f32,
25 }
26
27 impl Vec3 {
28 /// All zeroes.
29 pub const ZERO: Self = Self::splat(0.0);
30
31 /// All ones.
32 pub const ONE: Self = Self::splat(1.0);
33
34 /// All negative ones.
35 pub const NEG_ONE: Self = Self::splat(-1.0);
36
37 /// All `f32::MIN`.
38 pub const MIN: Self = Self::splat(f32::MIN);
39
40 /// All `f32::MAX`.
41 pub const MAX: Self = Self::splat(f32::MAX);
42
43 /// All `f32::NAN`.
44 pub const NAN: Self = Self::splat(f32::NAN);
45
46 /// All `f32::INFINITY`.
47 pub const INFINITY: Self = Self::splat(f32::INFINITY);
48
49 /// All `f32::NEG_INFINITY`.
50 pub const NEG_INFINITY: Self = Self::splat(f32::NEG_INFINITY);
51
52 /// A unit vector pointing along the positive X axis.
53 pub const X: Self = Self::new(1.0, 0.0, 0.0);
54
55 /// A unit vector pointing along the positive Y axis.
56 pub const Y: Self = Self::new(0.0, 1.0, 0.0);
57
58 /// A unit vector pointing along the positive Z axis.
59 pub const Z: Self = Self::new(0.0, 0.0, 1.0);
60
61 /// A unit vector pointing along the negative X axis.
62 pub const NEG_X: Self = Self::new(-1.0, 0.0, 0.0);
63
64 /// A unit vector pointing along the negative Y axis.
65 pub const NEG_Y: Self = Self::new(0.0, -1.0, 0.0);
66
67 /// A unit vector pointing along the negative Z axis.
68 pub const NEG_Z: Self = Self::new(0.0, 0.0, -1.0);
69
70 /// The unit axes.
71 pub const AXES: [Self; 3] = [Self::X, Self::Y, Self::Z];
72
73 /// Creates a new vector.
74 #[inline(always)]
75 #[must_use]
new(x: f32, y: f32, z: f32) -> Self76 pub const fn new(x: f32, y: f32, z: f32) -> Self {
77 Self { x, y, z }
78 }
79
80 /// Creates a vector with all elements set to `v`.
81 #[inline]
82 #[must_use]
splat(v: f32) -> Self83 pub const fn splat(v: f32) -> Self {
84 Self { x: v, y: v, z: v }
85 }
86
87 /// Creates a vector from the elements in `if_true` and `if_false`, selecting which to use
88 /// for each element of `self`.
89 ///
90 /// A true element in the mask uses the corresponding element from `if_true`, and false
91 /// uses the element from `if_false`.
92 #[inline]
93 #[must_use]
select(mask: BVec3, if_true: Self, if_false: Self) -> Self94 pub fn select(mask: BVec3, if_true: Self, if_false: Self) -> Self {
95 Self {
96 x: if mask.test(0) { if_true.x } else { if_false.x },
97 y: if mask.test(1) { if_true.y } else { if_false.y },
98 z: if mask.test(2) { if_true.z } else { if_false.z },
99 }
100 }
101
102 /// Creates a new vector from an array.
103 #[inline]
104 #[must_use]
from_array(a: [f32; 3]) -> Self105 pub const fn from_array(a: [f32; 3]) -> Self {
106 Self::new(a[0], a[1], a[2])
107 }
108
109 /// `[x, y, z]`
110 #[inline]
111 #[must_use]
to_array(&self) -> [f32; 3]112 pub const fn to_array(&self) -> [f32; 3] {
113 [self.x, self.y, self.z]
114 }
115
116 /// Creates a vector from the first 3 values in `slice`.
117 ///
118 /// # Panics
119 ///
120 /// Panics if `slice` is less than 3 elements long.
121 #[inline]
122 #[must_use]
from_slice(slice: &[f32]) -> Self123 pub const fn from_slice(slice: &[f32]) -> Self {
124 Self::new(slice[0], slice[1], slice[2])
125 }
126
127 /// Writes the elements of `self` to the first 3 elements in `slice`.
128 ///
129 /// # Panics
130 ///
131 /// Panics if `slice` is less than 3 elements long.
132 #[inline]
write_to_slice(self, slice: &mut [f32])133 pub fn write_to_slice(self, slice: &mut [f32]) {
134 slice[0] = self.x;
135 slice[1] = self.y;
136 slice[2] = self.z;
137 }
138
139 /// Internal method for creating a 3D vector from a 4D vector, discarding `w`.
140 #[allow(dead_code)]
141 #[inline]
142 #[must_use]
from_vec4(v: Vec4) -> Self143 pub(crate) fn from_vec4(v: Vec4) -> Self {
144 Self {
145 x: v.x,
146 y: v.y,
147 z: v.z,
148 }
149 }
150
151 /// Creates a 4D vector from `self` and the given `w` value.
152 #[inline]
153 #[must_use]
extend(self, w: f32) -> Vec4154 pub fn extend(self, w: f32) -> Vec4 {
155 Vec4::new(self.x, self.y, self.z, w)
156 }
157
158 /// Creates a 2D vector from the `x` and `y` elements of `self`, discarding `z`.
159 ///
160 /// Truncation may also be performed by using [`self.xy()`][crate::swizzles::Vec3Swizzles::xy()].
161 #[inline]
162 #[must_use]
truncate(self) -> Vec2163 pub fn truncate(self) -> Vec2 {
164 use crate::swizzles::Vec3Swizzles;
165 self.xy()
166 }
167
168 /// Computes the dot product of `self` and `rhs`.
169 #[inline]
170 #[must_use]
dot(self, rhs: Self) -> f32171 pub fn dot(self, rhs: Self) -> f32 {
172 (self.x * rhs.x) + (self.y * rhs.y) + (self.z * rhs.z)
173 }
174
175 /// Returns a vector where every component is the dot product of `self` and `rhs`.
176 #[inline]
177 #[must_use]
dot_into_vec(self, rhs: Self) -> Self178 pub fn dot_into_vec(self, rhs: Self) -> Self {
179 Self::splat(self.dot(rhs))
180 }
181
182 /// Computes the cross product of `self` and `rhs`.
183 #[inline]
184 #[must_use]
cross(self, rhs: Self) -> Self185 pub fn cross(self, rhs: Self) -> Self {
186 Self {
187 x: self.y * rhs.z - rhs.y * self.z,
188 y: self.z * rhs.x - rhs.z * self.x,
189 z: self.x * rhs.y - rhs.x * self.y,
190 }
191 }
192
193 /// Returns a vector containing the minimum values for each element of `self` and `rhs`.
194 ///
195 /// In other words this computes `[self.x.min(rhs.x), self.y.min(rhs.y), ..]`.
196 #[inline]
197 #[must_use]
min(self, rhs: Self) -> Self198 pub fn min(self, rhs: Self) -> Self {
199 Self {
200 x: self.x.min(rhs.x),
201 y: self.y.min(rhs.y),
202 z: self.z.min(rhs.z),
203 }
204 }
205
206 /// Returns a vector containing the maximum values for each element of `self` and `rhs`.
207 ///
208 /// In other words this computes `[self.x.max(rhs.x), self.y.max(rhs.y), ..]`.
209 #[inline]
210 #[must_use]
max(self, rhs: Self) -> Self211 pub fn max(self, rhs: Self) -> Self {
212 Self {
213 x: self.x.max(rhs.x),
214 y: self.y.max(rhs.y),
215 z: self.z.max(rhs.z),
216 }
217 }
218
219 /// Component-wise clamping of values, similar to [`f32::clamp`].
220 ///
221 /// Each element in `min` must be less-or-equal to the corresponding element in `max`.
222 ///
223 /// # Panics
224 ///
225 /// Will panic if `min` is greater than `max` when `glam_assert` is enabled.
226 #[inline]
227 #[must_use]
clamp(self, min: Self, max: Self) -> Self228 pub fn clamp(self, min: Self, max: Self) -> Self {
229 glam_assert!(min.cmple(max).all(), "clamp: expected min <= max");
230 self.max(min).min(max)
231 }
232
233 /// Returns the horizontal minimum of `self`.
234 ///
235 /// In other words this computes `min(x, y, ..)`.
236 #[inline]
237 #[must_use]
min_element(self) -> f32238 pub fn min_element(self) -> f32 {
239 self.x.min(self.y.min(self.z))
240 }
241
242 /// Returns the horizontal maximum of `self`.
243 ///
244 /// In other words this computes `max(x, y, ..)`.
245 #[inline]
246 #[must_use]
max_element(self) -> f32247 pub fn max_element(self) -> f32 {
248 self.x.max(self.y.max(self.z))
249 }
250
251 /// Returns a vector mask containing the result of a `==` comparison for each element of
252 /// `self` and `rhs`.
253 ///
254 /// In other words, this computes `[self.x == rhs.x, self.y == rhs.y, ..]` for all
255 /// elements.
256 #[inline]
257 #[must_use]
cmpeq(self, rhs: Self) -> BVec3258 pub fn cmpeq(self, rhs: Self) -> BVec3 {
259 BVec3::new(self.x.eq(&rhs.x), self.y.eq(&rhs.y), self.z.eq(&rhs.z))
260 }
261
262 /// Returns a vector mask containing the result of a `!=` comparison for each element of
263 /// `self` and `rhs`.
264 ///
265 /// In other words this computes `[self.x != rhs.x, self.y != rhs.y, ..]` for all
266 /// elements.
267 #[inline]
268 #[must_use]
cmpne(self, rhs: Self) -> BVec3269 pub fn cmpne(self, rhs: Self) -> BVec3 {
270 BVec3::new(self.x.ne(&rhs.x), self.y.ne(&rhs.y), self.z.ne(&rhs.z))
271 }
272
273 /// Returns a vector mask containing the result of a `>=` comparison for each element of
274 /// `self` and `rhs`.
275 ///
276 /// In other words this computes `[self.x >= rhs.x, self.y >= rhs.y, ..]` for all
277 /// elements.
278 #[inline]
279 #[must_use]
cmpge(self, rhs: Self) -> BVec3280 pub fn cmpge(self, rhs: Self) -> BVec3 {
281 BVec3::new(self.x.ge(&rhs.x), self.y.ge(&rhs.y), self.z.ge(&rhs.z))
282 }
283
284 /// Returns a vector mask containing the result of a `>` comparison for each element of
285 /// `self` and `rhs`.
286 ///
287 /// In other words this computes `[self.x > rhs.x, self.y > rhs.y, ..]` for all
288 /// elements.
289 #[inline]
290 #[must_use]
cmpgt(self, rhs: Self) -> BVec3291 pub fn cmpgt(self, rhs: Self) -> BVec3 {
292 BVec3::new(self.x.gt(&rhs.x), self.y.gt(&rhs.y), self.z.gt(&rhs.z))
293 }
294
295 /// Returns a vector mask containing the result of a `<=` comparison for each element of
296 /// `self` and `rhs`.
297 ///
298 /// In other words this computes `[self.x <= rhs.x, self.y <= rhs.y, ..]` for all
299 /// elements.
300 #[inline]
301 #[must_use]
cmple(self, rhs: Self) -> BVec3302 pub fn cmple(self, rhs: Self) -> BVec3 {
303 BVec3::new(self.x.le(&rhs.x), self.y.le(&rhs.y), self.z.le(&rhs.z))
304 }
305
306 /// Returns a vector mask containing the result of a `<` comparison for each element of
307 /// `self` and `rhs`.
308 ///
309 /// In other words this computes `[self.x < rhs.x, self.y < rhs.y, ..]` for all
310 /// elements.
311 #[inline]
312 #[must_use]
cmplt(self, rhs: Self) -> BVec3313 pub fn cmplt(self, rhs: Self) -> BVec3 {
314 BVec3::new(self.x.lt(&rhs.x), self.y.lt(&rhs.y), self.z.lt(&rhs.z))
315 }
316
317 /// Returns a vector containing the absolute value of each element of `self`.
318 #[inline]
319 #[must_use]
abs(self) -> Self320 pub fn abs(self) -> Self {
321 Self {
322 x: math::abs(self.x),
323 y: math::abs(self.y),
324 z: math::abs(self.z),
325 }
326 }
327
328 /// Returns a vector with elements representing the sign of `self`.
329 ///
330 /// - `1.0` if the number is positive, `+0.0` or `INFINITY`
331 /// - `-1.0` if the number is negative, `-0.0` or `NEG_INFINITY`
332 /// - `NAN` if the number is `NAN`
333 #[inline]
334 #[must_use]
signum(self) -> Self335 pub fn signum(self) -> Self {
336 Self {
337 x: math::signum(self.x),
338 y: math::signum(self.y),
339 z: math::signum(self.z),
340 }
341 }
342
343 /// Returns a vector with signs of `rhs` and the magnitudes of `self`.
344 #[inline]
345 #[must_use]
copysign(self, rhs: Self) -> Self346 pub fn copysign(self, rhs: Self) -> Self {
347 Self {
348 x: math::copysign(self.x, rhs.x),
349 y: math::copysign(self.y, rhs.y),
350 z: math::copysign(self.z, rhs.z),
351 }
352 }
353
354 /// Returns a bitmask with the lowest 3 bits set to the sign bits from the elements of `self`.
355 ///
356 /// A negative element results in a `1` bit and a positive element in a `0` bit. Element `x` goes
357 /// into the first lowest bit, element `y` into the second, etc.
358 #[inline]
359 #[must_use]
is_negative_bitmask(self) -> u32360 pub fn is_negative_bitmask(self) -> u32 {
361 (self.x.is_sign_negative() as u32)
362 | (self.y.is_sign_negative() as u32) << 1
363 | (self.z.is_sign_negative() as u32) << 2
364 }
365
366 /// Returns `true` if, and only if, all elements are finite. If any element is either
367 /// `NaN`, positive or negative infinity, this will return `false`.
368 #[inline]
369 #[must_use]
is_finite(self) -> bool370 pub fn is_finite(self) -> bool {
371 self.x.is_finite() && self.y.is_finite() && self.z.is_finite()
372 }
373
374 /// Returns `true` if any elements are `NaN`.
375 #[inline]
376 #[must_use]
is_nan(self) -> bool377 pub fn is_nan(self) -> bool {
378 self.x.is_nan() || self.y.is_nan() || self.z.is_nan()
379 }
380
381 /// Performs `is_nan` on each element of self, returning a vector mask of the results.
382 ///
383 /// In other words, this computes `[x.is_nan(), y.is_nan(), z.is_nan(), w.is_nan()]`.
384 #[inline]
385 #[must_use]
is_nan_mask(self) -> BVec3386 pub fn is_nan_mask(self) -> BVec3 {
387 BVec3::new(self.x.is_nan(), self.y.is_nan(), self.z.is_nan())
388 }
389
390 /// Computes the length of `self`.
391 #[doc(alias = "magnitude")]
392 #[inline]
393 #[must_use]
length(self) -> f32394 pub fn length(self) -> f32 {
395 math::sqrt(self.dot(self))
396 }
397
398 /// Computes the squared length of `self`.
399 ///
400 /// This is faster than `length()` as it avoids a square root operation.
401 #[doc(alias = "magnitude2")]
402 #[inline]
403 #[must_use]
length_squared(self) -> f32404 pub fn length_squared(self) -> f32 {
405 self.dot(self)
406 }
407
408 /// Computes `1.0 / length()`.
409 ///
410 /// For valid results, `self` must _not_ be of length zero.
411 #[inline]
412 #[must_use]
length_recip(self) -> f32413 pub fn length_recip(self) -> f32 {
414 self.length().recip()
415 }
416
417 /// Computes the Euclidean distance between two points in space.
418 #[inline]
419 #[must_use]
distance(self, rhs: Self) -> f32420 pub fn distance(self, rhs: Self) -> f32 {
421 (self - rhs).length()
422 }
423
424 /// Compute the squared euclidean distance between two points in space.
425 #[inline]
426 #[must_use]
distance_squared(self, rhs: Self) -> f32427 pub fn distance_squared(self, rhs: Self) -> f32 {
428 (self - rhs).length_squared()
429 }
430
431 /// Returns the element-wise quotient of [Euclidean division] of `self` by `rhs`.
432 #[inline]
433 #[must_use]
div_euclid(self, rhs: Self) -> Self434 pub fn div_euclid(self, rhs: Self) -> Self {
435 Self::new(
436 math::div_euclid(self.x, rhs.x),
437 math::div_euclid(self.y, rhs.y),
438 math::div_euclid(self.z, rhs.z),
439 )
440 }
441
442 /// Returns the element-wise remainder of [Euclidean division] of `self` by `rhs`.
443 ///
444 /// [Euclidean division]: f32::rem_euclid
445 #[inline]
446 #[must_use]
rem_euclid(self, rhs: Self) -> Self447 pub fn rem_euclid(self, rhs: Self) -> Self {
448 Self::new(
449 math::rem_euclid(self.x, rhs.x),
450 math::rem_euclid(self.y, rhs.y),
451 math::rem_euclid(self.z, rhs.z),
452 )
453 }
454
455 /// Returns `self` normalized to length 1.0.
456 ///
457 /// For valid results, `self` must _not_ be of length zero, nor very close to zero.
458 ///
459 /// See also [`Self::try_normalize()`] and [`Self::normalize_or_zero()`].
460 ///
461 /// Panics
462 ///
463 /// Will panic if `self` is zero length when `glam_assert` is enabled.
464 #[inline]
465 #[must_use]
normalize(self) -> Self466 pub fn normalize(self) -> Self {
467 #[allow(clippy::let_and_return)]
468 let normalized = self.mul(self.length_recip());
469 glam_assert!(normalized.is_finite());
470 normalized
471 }
472
473 /// Returns `self` normalized to length 1.0 if possible, else returns `None`.
474 ///
475 /// In particular, if the input is zero (or very close to zero), or non-finite,
476 /// the result of this operation will be `None`.
477 ///
478 /// See also [`Self::normalize_or_zero()`].
479 #[inline]
480 #[must_use]
try_normalize(self) -> Option<Self>481 pub fn try_normalize(self) -> Option<Self> {
482 let rcp = self.length_recip();
483 if rcp.is_finite() && rcp > 0.0 {
484 Some(self * rcp)
485 } else {
486 None
487 }
488 }
489
490 /// Returns `self` normalized to length 1.0 if possible, else returns zero.
491 ///
492 /// In particular, if the input is zero (or very close to zero), or non-finite,
493 /// the result of this operation will be zero.
494 ///
495 /// See also [`Self::try_normalize()`].
496 #[inline]
497 #[must_use]
normalize_or_zero(self) -> Self498 pub fn normalize_or_zero(self) -> Self {
499 let rcp = self.length_recip();
500 if rcp.is_finite() && rcp > 0.0 {
501 self * rcp
502 } else {
503 Self::ZERO
504 }
505 }
506
507 /// Returns whether `self` is length `1.0` or not.
508 ///
509 /// Uses a precision threshold of `1e-6`.
510 #[inline]
511 #[must_use]
is_normalized(self) -> bool512 pub fn is_normalized(self) -> bool {
513 // TODO: do something with epsilon
514 math::abs(self.length_squared() - 1.0) <= 1e-4
515 }
516
517 /// Returns the vector projection of `self` onto `rhs`.
518 ///
519 /// `rhs` must be of non-zero length.
520 ///
521 /// # Panics
522 ///
523 /// Will panic if `rhs` is zero length when `glam_assert` is enabled.
524 #[inline]
525 #[must_use]
project_onto(self, rhs: Self) -> Self526 pub fn project_onto(self, rhs: Self) -> Self {
527 let other_len_sq_rcp = rhs.dot(rhs).recip();
528 glam_assert!(other_len_sq_rcp.is_finite());
529 rhs * self.dot(rhs) * other_len_sq_rcp
530 }
531
532 /// Returns the vector rejection of `self` from `rhs`.
533 ///
534 /// The vector rejection is the vector perpendicular to the projection of `self` onto
535 /// `rhs`, in rhs words the result of `self - self.project_onto(rhs)`.
536 ///
537 /// `rhs` must be of non-zero length.
538 ///
539 /// # Panics
540 ///
541 /// Will panic if `rhs` has a length of zero when `glam_assert` is enabled.
542 #[inline]
543 #[must_use]
reject_from(self, rhs: Self) -> Self544 pub fn reject_from(self, rhs: Self) -> Self {
545 self - self.project_onto(rhs)
546 }
547
548 /// Returns the vector projection of `self` onto `rhs`.
549 ///
550 /// `rhs` must be normalized.
551 ///
552 /// # Panics
553 ///
554 /// Will panic if `rhs` is not normalized when `glam_assert` is enabled.
555 #[inline]
556 #[must_use]
project_onto_normalized(self, rhs: Self) -> Self557 pub fn project_onto_normalized(self, rhs: Self) -> Self {
558 glam_assert!(rhs.is_normalized());
559 rhs * self.dot(rhs)
560 }
561
562 /// Returns the vector rejection of `self` from `rhs`.
563 ///
564 /// The vector rejection is the vector perpendicular to the projection of `self` onto
565 /// `rhs`, in rhs words the result of `self - self.project_onto(rhs)`.
566 ///
567 /// `rhs` must be normalized.
568 ///
569 /// # Panics
570 ///
571 /// Will panic if `rhs` is not normalized when `glam_assert` is enabled.
572 #[inline]
573 #[must_use]
reject_from_normalized(self, rhs: Self) -> Self574 pub fn reject_from_normalized(self, rhs: Self) -> Self {
575 self - self.project_onto_normalized(rhs)
576 }
577
578 /// Returns a vector containing the nearest integer to a number for each element of `self`.
579 /// Round half-way cases away from 0.0.
580 #[inline]
581 #[must_use]
round(self) -> Self582 pub fn round(self) -> Self {
583 Self {
584 x: math::round(self.x),
585 y: math::round(self.y),
586 z: math::round(self.z),
587 }
588 }
589
590 /// Returns a vector containing the largest integer less than or equal to a number for each
591 /// element of `self`.
592 #[inline]
593 #[must_use]
floor(self) -> Self594 pub fn floor(self) -> Self {
595 Self {
596 x: math::floor(self.x),
597 y: math::floor(self.y),
598 z: math::floor(self.z),
599 }
600 }
601
602 /// Returns a vector containing the smallest integer greater than or equal to a number for
603 /// each element of `self`.
604 #[inline]
605 #[must_use]
ceil(self) -> Self606 pub fn ceil(self) -> Self {
607 Self {
608 x: math::ceil(self.x),
609 y: math::ceil(self.y),
610 z: math::ceil(self.z),
611 }
612 }
613
614 /// Returns a vector containing the integer part each element of `self`. This means numbers are
615 /// always truncated towards zero.
616 #[inline]
617 #[must_use]
trunc(self) -> Self618 pub fn trunc(self) -> Self {
619 Self {
620 x: math::trunc(self.x),
621 y: math::trunc(self.y),
622 z: math::trunc(self.z),
623 }
624 }
625
626 /// Returns a vector containing the fractional part of the vector, e.g. `self -
627 /// self.floor()`.
628 ///
629 /// Note that this is fast but not precise for large numbers.
630 #[inline]
631 #[must_use]
fract(self) -> Self632 pub fn fract(self) -> Self {
633 self - self.floor()
634 }
635
636 /// Returns a vector containing `e^self` (the exponential function) for each element of
637 /// `self`.
638 #[inline]
639 #[must_use]
exp(self) -> Self640 pub fn exp(self) -> Self {
641 Self::new(math::exp(self.x), math::exp(self.y), math::exp(self.z))
642 }
643
644 /// Returns a vector containing each element of `self` raised to the power of `n`.
645 #[inline]
646 #[must_use]
powf(self, n: f32) -> Self647 pub fn powf(self, n: f32) -> Self {
648 Self::new(
649 math::powf(self.x, n),
650 math::powf(self.y, n),
651 math::powf(self.z, n),
652 )
653 }
654
655 /// Returns a vector containing the reciprocal `1.0/n` of each element of `self`.
656 #[inline]
657 #[must_use]
recip(self) -> Self658 pub fn recip(self) -> Self {
659 Self {
660 x: 1.0 / self.x,
661 y: 1.0 / self.y,
662 z: 1.0 / self.z,
663 }
664 }
665
666 /// Performs a linear interpolation between `self` and `rhs` based on the value `s`.
667 ///
668 /// When `s` is `0.0`, the result will be equal to `self`. When `s` is `1.0`, the result
669 /// will be equal to `rhs`. When `s` is outside of range `[0, 1]`, the result is linearly
670 /// extrapolated.
671 #[doc(alias = "mix")]
672 #[inline]
673 #[must_use]
lerp(self, rhs: Self, s: f32) -> Self674 pub fn lerp(self, rhs: Self, s: f32) -> Self {
675 self + ((rhs - self) * s)
676 }
677
678 /// Returns true if the absolute difference of all elements between `self` and `rhs` is
679 /// less than or equal to `max_abs_diff`.
680 ///
681 /// This can be used to compare if two vectors contain similar elements. It works best when
682 /// comparing with a known value. The `max_abs_diff` that should be used used depends on
683 /// the values being compared against.
684 ///
685 /// For more see
686 /// [comparing floating point numbers](https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/).
687 #[inline]
688 #[must_use]
abs_diff_eq(self, rhs: Self, max_abs_diff: f32) -> bool689 pub fn abs_diff_eq(self, rhs: Self, max_abs_diff: f32) -> bool {
690 self.sub(rhs).abs().cmple(Self::splat(max_abs_diff)).all()
691 }
692
693 /// Returns a vector with a length no less than `min` and no more than `max`
694 ///
695 /// # Panics
696 ///
697 /// Will panic if `min` is greater than `max` when `glam_assert` is enabled.
698 #[inline]
699 #[must_use]
clamp_length(self, min: f32, max: f32) -> Self700 pub fn clamp_length(self, min: f32, max: f32) -> Self {
701 glam_assert!(min <= max);
702 let length_sq = self.length_squared();
703 if length_sq < min * min {
704 min * (self / math::sqrt(length_sq))
705 } else if length_sq > max * max {
706 max * (self / math::sqrt(length_sq))
707 } else {
708 self
709 }
710 }
711
712 /// Returns a vector with a length no more than `max`
713 #[inline]
714 #[must_use]
clamp_length_max(self, max: f32) -> Self715 pub fn clamp_length_max(self, max: f32) -> Self {
716 let length_sq = self.length_squared();
717 if length_sq > max * max {
718 max * (self / math::sqrt(length_sq))
719 } else {
720 self
721 }
722 }
723
724 /// Returns a vector with a length no less than `min`
725 #[inline]
726 #[must_use]
clamp_length_min(self, min: f32) -> Self727 pub fn clamp_length_min(self, min: f32) -> Self {
728 let length_sq = self.length_squared();
729 if length_sq < min * min {
730 min * (self / math::sqrt(length_sq))
731 } else {
732 self
733 }
734 }
735
736 /// Fused multiply-add. Computes `(self * a) + b` element-wise with only one rounding
737 /// error, yielding a more accurate result than an unfused multiply-add.
738 ///
739 /// Using `mul_add` *may* be more performant than an unfused multiply-add if the target
740 /// architecture has a dedicated fma CPU instruction. However, this is not always true,
741 /// and will be heavily dependant on designing algorithms with specific target hardware in
742 /// mind.
743 #[inline]
744 #[must_use]
mul_add(self, a: Self, b: Self) -> Self745 pub fn mul_add(self, a: Self, b: Self) -> Self {
746 Self::new(
747 math::mul_add(self.x, a.x, b.x),
748 math::mul_add(self.y, a.y, b.y),
749 math::mul_add(self.z, a.z, b.z),
750 )
751 }
752
753 /// Returns the angle (in radians) between two vectors.
754 ///
755 /// The inputs do not need to be unit vectors however they must be non-zero.
756 #[inline]
757 #[must_use]
angle_between(self, rhs: Self) -> f32758 pub fn angle_between(self, rhs: Self) -> f32 {
759 math::acos_approx(
760 self.dot(rhs)
761 .div(math::sqrt(self.length_squared().mul(rhs.length_squared()))),
762 )
763 }
764
765 /// Returns some vector that is orthogonal to the given one.
766 ///
767 /// The input vector must be finite and non-zero.
768 ///
769 /// The output vector is not necessarily unit length. For that use
770 /// [`Self::any_orthonormal_vector()`] instead.
771 #[inline]
772 #[must_use]
any_orthogonal_vector(&self) -> Self773 pub fn any_orthogonal_vector(&self) -> Self {
774 // This can probably be optimized
775 if math::abs(self.x) > math::abs(self.y) {
776 Self::new(-self.z, 0.0, self.x) // self.cross(Self::Y)
777 } else {
778 Self::new(0.0, self.z, -self.y) // self.cross(Self::X)
779 }
780 }
781
782 /// Returns any unit vector that is orthogonal to the given one.
783 ///
784 /// The input vector must be unit length.
785 ///
786 /// # Panics
787 ///
788 /// Will panic if `self` is not normalized when `glam_assert` is enabled.
789 #[inline]
790 #[must_use]
any_orthonormal_vector(&self) -> Self791 pub fn any_orthonormal_vector(&self) -> Self {
792 glam_assert!(self.is_normalized());
793 // From https://graphics.pixar.com/library/OrthonormalB/paper.pdf
794 let sign = math::signum(self.z);
795 let a = -1.0 / (sign + self.z);
796 let b = self.x * self.y * a;
797 Self::new(b, sign + self.y * self.y * a, -self.y)
798 }
799
800 /// Given a unit vector return two other vectors that together form an orthonormal
801 /// basis. That is, all three vectors are orthogonal to each other and are normalized.
802 ///
803 /// # Panics
804 ///
805 /// Will panic if `self` is not normalized when `glam_assert` is enabled.
806 #[inline]
807 #[must_use]
any_orthonormal_pair(&self) -> (Self, Self)808 pub fn any_orthonormal_pair(&self) -> (Self, Self) {
809 glam_assert!(self.is_normalized());
810 // From https://graphics.pixar.com/library/OrthonormalB/paper.pdf
811 let sign = math::signum(self.z);
812 let a = -1.0 / (sign + self.z);
813 let b = self.x * self.y * a;
814 (
815 Self::new(1.0 + sign * self.x * self.x * a, sign * b, -sign * self.x),
816 Self::new(b, sign + self.y * self.y * a, -self.y),
817 )
818 }
819
820 /// Casts all elements of `self` to `f64`.
821 #[inline]
822 #[must_use]
as_dvec3(&self) -> crate::DVec3823 pub fn as_dvec3(&self) -> crate::DVec3 {
824 crate::DVec3::new(self.x as f64, self.y as f64, self.z as f64)
825 }
826
827 /// Casts all elements of `self` to `i16`.
828 #[inline]
829 #[must_use]
as_i16vec3(&self) -> crate::I16Vec3830 pub fn as_i16vec3(&self) -> crate::I16Vec3 {
831 crate::I16Vec3::new(self.x as i16, self.y as i16, self.z as i16)
832 }
833
834 /// Casts all elements of `self` to `u16`.
835 #[inline]
836 #[must_use]
as_u16vec3(&self) -> crate::U16Vec3837 pub fn as_u16vec3(&self) -> crate::U16Vec3 {
838 crate::U16Vec3::new(self.x as u16, self.y as u16, self.z as u16)
839 }
840
841 /// Casts all elements of `self` to `i32`.
842 #[inline]
843 #[must_use]
as_ivec3(&self) -> crate::IVec3844 pub fn as_ivec3(&self) -> crate::IVec3 {
845 crate::IVec3::new(self.x as i32, self.y as i32, self.z as i32)
846 }
847
848 /// Casts all elements of `self` to `u32`.
849 #[inline]
850 #[must_use]
as_uvec3(&self) -> crate::UVec3851 pub fn as_uvec3(&self) -> crate::UVec3 {
852 crate::UVec3::new(self.x as u32, self.y as u32, self.z as u32)
853 }
854
855 /// Casts all elements of `self` to `i64`.
856 #[inline]
857 #[must_use]
as_i64vec3(&self) -> crate::I64Vec3858 pub fn as_i64vec3(&self) -> crate::I64Vec3 {
859 crate::I64Vec3::new(self.x as i64, self.y as i64, self.z as i64)
860 }
861
862 /// Casts all elements of `self` to `u64`.
863 #[inline]
864 #[must_use]
as_u64vec3(&self) -> crate::U64Vec3865 pub fn as_u64vec3(&self) -> crate::U64Vec3 {
866 crate::U64Vec3::new(self.x as u64, self.y as u64, self.z as u64)
867 }
868 }
869
870 impl Default for Vec3 {
871 #[inline(always)]
default() -> Self872 fn default() -> Self {
873 Self::ZERO
874 }
875 }
876
877 impl Div<Vec3> for Vec3 {
878 type Output = Self;
879 #[inline]
div(self, rhs: Self) -> Self880 fn div(self, rhs: Self) -> Self {
881 Self {
882 x: self.x.div(rhs.x),
883 y: self.y.div(rhs.y),
884 z: self.z.div(rhs.z),
885 }
886 }
887 }
888
889 impl DivAssign<Vec3> for Vec3 {
890 #[inline]
div_assign(&mut self, rhs: Self)891 fn div_assign(&mut self, rhs: Self) {
892 self.x.div_assign(rhs.x);
893 self.y.div_assign(rhs.y);
894 self.z.div_assign(rhs.z);
895 }
896 }
897
898 impl Div<f32> for Vec3 {
899 type Output = Self;
900 #[inline]
div(self, rhs: f32) -> Self901 fn div(self, rhs: f32) -> Self {
902 Self {
903 x: self.x.div(rhs),
904 y: self.y.div(rhs),
905 z: self.z.div(rhs),
906 }
907 }
908 }
909
910 impl DivAssign<f32> for Vec3 {
911 #[inline]
div_assign(&mut self, rhs: f32)912 fn div_assign(&mut self, rhs: f32) {
913 self.x.div_assign(rhs);
914 self.y.div_assign(rhs);
915 self.z.div_assign(rhs);
916 }
917 }
918
919 impl Div<Vec3> for f32 {
920 type Output = Vec3;
921 #[inline]
div(self, rhs: Vec3) -> Vec3922 fn div(self, rhs: Vec3) -> Vec3 {
923 Vec3 {
924 x: self.div(rhs.x),
925 y: self.div(rhs.y),
926 z: self.div(rhs.z),
927 }
928 }
929 }
930
931 impl Mul<Vec3> for Vec3 {
932 type Output = Self;
933 #[inline]
mul(self, rhs: Self) -> Self934 fn mul(self, rhs: Self) -> Self {
935 Self {
936 x: self.x.mul(rhs.x),
937 y: self.y.mul(rhs.y),
938 z: self.z.mul(rhs.z),
939 }
940 }
941 }
942
943 impl MulAssign<Vec3> for Vec3 {
944 #[inline]
mul_assign(&mut self, rhs: Self)945 fn mul_assign(&mut self, rhs: Self) {
946 self.x.mul_assign(rhs.x);
947 self.y.mul_assign(rhs.y);
948 self.z.mul_assign(rhs.z);
949 }
950 }
951
952 impl Mul<f32> for Vec3 {
953 type Output = Self;
954 #[inline]
mul(self, rhs: f32) -> Self955 fn mul(self, rhs: f32) -> Self {
956 Self {
957 x: self.x.mul(rhs),
958 y: self.y.mul(rhs),
959 z: self.z.mul(rhs),
960 }
961 }
962 }
963
964 impl MulAssign<f32> for Vec3 {
965 #[inline]
mul_assign(&mut self, rhs: f32)966 fn mul_assign(&mut self, rhs: f32) {
967 self.x.mul_assign(rhs);
968 self.y.mul_assign(rhs);
969 self.z.mul_assign(rhs);
970 }
971 }
972
973 impl Mul<Vec3> for f32 {
974 type Output = Vec3;
975 #[inline]
mul(self, rhs: Vec3) -> Vec3976 fn mul(self, rhs: Vec3) -> Vec3 {
977 Vec3 {
978 x: self.mul(rhs.x),
979 y: self.mul(rhs.y),
980 z: self.mul(rhs.z),
981 }
982 }
983 }
984
985 impl Add<Vec3> for Vec3 {
986 type Output = Self;
987 #[inline]
add(self, rhs: Self) -> Self988 fn add(self, rhs: Self) -> Self {
989 Self {
990 x: self.x.add(rhs.x),
991 y: self.y.add(rhs.y),
992 z: self.z.add(rhs.z),
993 }
994 }
995 }
996
997 impl AddAssign<Vec3> for Vec3 {
998 #[inline]
add_assign(&mut self, rhs: Self)999 fn add_assign(&mut self, rhs: Self) {
1000 self.x.add_assign(rhs.x);
1001 self.y.add_assign(rhs.y);
1002 self.z.add_assign(rhs.z);
1003 }
1004 }
1005
1006 impl Add<f32> for Vec3 {
1007 type Output = Self;
1008 #[inline]
add(self, rhs: f32) -> Self1009 fn add(self, rhs: f32) -> Self {
1010 Self {
1011 x: self.x.add(rhs),
1012 y: self.y.add(rhs),
1013 z: self.z.add(rhs),
1014 }
1015 }
1016 }
1017
1018 impl AddAssign<f32> for Vec3 {
1019 #[inline]
add_assign(&mut self, rhs: f32)1020 fn add_assign(&mut self, rhs: f32) {
1021 self.x.add_assign(rhs);
1022 self.y.add_assign(rhs);
1023 self.z.add_assign(rhs);
1024 }
1025 }
1026
1027 impl Add<Vec3> for f32 {
1028 type Output = Vec3;
1029 #[inline]
add(self, rhs: Vec3) -> Vec31030 fn add(self, rhs: Vec3) -> Vec3 {
1031 Vec3 {
1032 x: self.add(rhs.x),
1033 y: self.add(rhs.y),
1034 z: self.add(rhs.z),
1035 }
1036 }
1037 }
1038
1039 impl Sub<Vec3> for Vec3 {
1040 type Output = Self;
1041 #[inline]
sub(self, rhs: Self) -> Self1042 fn sub(self, rhs: Self) -> Self {
1043 Self {
1044 x: self.x.sub(rhs.x),
1045 y: self.y.sub(rhs.y),
1046 z: self.z.sub(rhs.z),
1047 }
1048 }
1049 }
1050
1051 impl SubAssign<Vec3> for Vec3 {
1052 #[inline]
sub_assign(&mut self, rhs: Vec3)1053 fn sub_assign(&mut self, rhs: Vec3) {
1054 self.x.sub_assign(rhs.x);
1055 self.y.sub_assign(rhs.y);
1056 self.z.sub_assign(rhs.z);
1057 }
1058 }
1059
1060 impl Sub<f32> for Vec3 {
1061 type Output = Self;
1062 #[inline]
sub(self, rhs: f32) -> Self1063 fn sub(self, rhs: f32) -> Self {
1064 Self {
1065 x: self.x.sub(rhs),
1066 y: self.y.sub(rhs),
1067 z: self.z.sub(rhs),
1068 }
1069 }
1070 }
1071
1072 impl SubAssign<f32> for Vec3 {
1073 #[inline]
sub_assign(&mut self, rhs: f32)1074 fn sub_assign(&mut self, rhs: f32) {
1075 self.x.sub_assign(rhs);
1076 self.y.sub_assign(rhs);
1077 self.z.sub_assign(rhs);
1078 }
1079 }
1080
1081 impl Sub<Vec3> for f32 {
1082 type Output = Vec3;
1083 #[inline]
sub(self, rhs: Vec3) -> Vec31084 fn sub(self, rhs: Vec3) -> Vec3 {
1085 Vec3 {
1086 x: self.sub(rhs.x),
1087 y: self.sub(rhs.y),
1088 z: self.sub(rhs.z),
1089 }
1090 }
1091 }
1092
1093 impl Rem<Vec3> for Vec3 {
1094 type Output = Self;
1095 #[inline]
rem(self, rhs: Self) -> Self1096 fn rem(self, rhs: Self) -> Self {
1097 Self {
1098 x: self.x.rem(rhs.x),
1099 y: self.y.rem(rhs.y),
1100 z: self.z.rem(rhs.z),
1101 }
1102 }
1103 }
1104
1105 impl RemAssign<Vec3> for Vec3 {
1106 #[inline]
rem_assign(&mut self, rhs: Self)1107 fn rem_assign(&mut self, rhs: Self) {
1108 self.x.rem_assign(rhs.x);
1109 self.y.rem_assign(rhs.y);
1110 self.z.rem_assign(rhs.z);
1111 }
1112 }
1113
1114 impl Rem<f32> for Vec3 {
1115 type Output = Self;
1116 #[inline]
rem(self, rhs: f32) -> Self1117 fn rem(self, rhs: f32) -> Self {
1118 Self {
1119 x: self.x.rem(rhs),
1120 y: self.y.rem(rhs),
1121 z: self.z.rem(rhs),
1122 }
1123 }
1124 }
1125
1126 impl RemAssign<f32> for Vec3 {
1127 #[inline]
rem_assign(&mut self, rhs: f32)1128 fn rem_assign(&mut self, rhs: f32) {
1129 self.x.rem_assign(rhs);
1130 self.y.rem_assign(rhs);
1131 self.z.rem_assign(rhs);
1132 }
1133 }
1134
1135 impl Rem<Vec3> for f32 {
1136 type Output = Vec3;
1137 #[inline]
rem(self, rhs: Vec3) -> Vec31138 fn rem(self, rhs: Vec3) -> Vec3 {
1139 Vec3 {
1140 x: self.rem(rhs.x),
1141 y: self.rem(rhs.y),
1142 z: self.rem(rhs.z),
1143 }
1144 }
1145 }
1146
1147 #[cfg(not(target_arch = "spirv"))]
1148 impl AsRef<[f32; 3]> for Vec3 {
1149 #[inline]
as_ref(&self) -> &[f32; 3]1150 fn as_ref(&self) -> &[f32; 3] {
1151 unsafe { &*(self as *const Vec3 as *const [f32; 3]) }
1152 }
1153 }
1154
1155 #[cfg(not(target_arch = "spirv"))]
1156 impl AsMut<[f32; 3]> for Vec3 {
1157 #[inline]
as_mut(&mut self) -> &mut [f32; 3]1158 fn as_mut(&mut self) -> &mut [f32; 3] {
1159 unsafe { &mut *(self as *mut Vec3 as *mut [f32; 3]) }
1160 }
1161 }
1162
1163 impl Sum for Vec3 {
1164 #[inline]
sum<I>(iter: I) -> Self where I: Iterator<Item = Self>,1165 fn sum<I>(iter: I) -> Self
1166 where
1167 I: Iterator<Item = Self>,
1168 {
1169 iter.fold(Self::ZERO, Self::add)
1170 }
1171 }
1172
1173 impl<'a> Sum<&'a Self> for Vec3 {
1174 #[inline]
sum<I>(iter: I) -> Self where I: Iterator<Item = &'a Self>,1175 fn sum<I>(iter: I) -> Self
1176 where
1177 I: Iterator<Item = &'a Self>,
1178 {
1179 iter.fold(Self::ZERO, |a, &b| Self::add(a, b))
1180 }
1181 }
1182
1183 impl Product for Vec3 {
1184 #[inline]
product<I>(iter: I) -> Self where I: Iterator<Item = Self>,1185 fn product<I>(iter: I) -> Self
1186 where
1187 I: Iterator<Item = Self>,
1188 {
1189 iter.fold(Self::ONE, Self::mul)
1190 }
1191 }
1192
1193 impl<'a> Product<&'a Self> for Vec3 {
1194 #[inline]
product<I>(iter: I) -> Self where I: Iterator<Item = &'a Self>,1195 fn product<I>(iter: I) -> Self
1196 where
1197 I: Iterator<Item = &'a Self>,
1198 {
1199 iter.fold(Self::ONE, |a, &b| Self::mul(a, b))
1200 }
1201 }
1202
1203 impl Neg for Vec3 {
1204 type Output = Self;
1205 #[inline]
neg(self) -> Self1206 fn neg(self) -> Self {
1207 Self {
1208 x: self.x.neg(),
1209 y: self.y.neg(),
1210 z: self.z.neg(),
1211 }
1212 }
1213 }
1214
1215 impl Index<usize> for Vec3 {
1216 type Output = f32;
1217 #[inline]
index(&self, index: usize) -> &Self::Output1218 fn index(&self, index: usize) -> &Self::Output {
1219 match index {
1220 0 => &self.x,
1221 1 => &self.y,
1222 2 => &self.z,
1223 _ => panic!("index out of bounds"),
1224 }
1225 }
1226 }
1227
1228 impl IndexMut<usize> for Vec3 {
1229 #[inline]
index_mut(&mut self, index: usize) -> &mut Self::Output1230 fn index_mut(&mut self, index: usize) -> &mut Self::Output {
1231 match index {
1232 0 => &mut self.x,
1233 1 => &mut self.y,
1234 2 => &mut self.z,
1235 _ => panic!("index out of bounds"),
1236 }
1237 }
1238 }
1239
1240 #[cfg(not(target_arch = "spirv"))]
1241 impl fmt::Display for Vec3 {
fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result1242 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1243 write!(f, "[{}, {}, {}]", self.x, self.y, self.z)
1244 }
1245 }
1246
1247 #[cfg(not(target_arch = "spirv"))]
1248 impl fmt::Debug for Vec3 {
fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result1249 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1250 fmt.debug_tuple(stringify!(Vec3))
1251 .field(&self.x)
1252 .field(&self.y)
1253 .field(&self.z)
1254 .finish()
1255 }
1256 }
1257
1258 impl From<[f32; 3]> for Vec3 {
1259 #[inline]
from(a: [f32; 3]) -> Self1260 fn from(a: [f32; 3]) -> Self {
1261 Self::new(a[0], a[1], a[2])
1262 }
1263 }
1264
1265 impl From<Vec3> for [f32; 3] {
1266 #[inline]
from(v: Vec3) -> Self1267 fn from(v: Vec3) -> Self {
1268 [v.x, v.y, v.z]
1269 }
1270 }
1271
1272 impl From<(f32, f32, f32)> for Vec3 {
1273 #[inline]
from(t: (f32, f32, f32)) -> Self1274 fn from(t: (f32, f32, f32)) -> Self {
1275 Self::new(t.0, t.1, t.2)
1276 }
1277 }
1278
1279 impl From<Vec3> for (f32, f32, f32) {
1280 #[inline]
from(v: Vec3) -> Self1281 fn from(v: Vec3) -> Self {
1282 (v.x, v.y, v.z)
1283 }
1284 }
1285
1286 impl From<(Vec2, f32)> for Vec3 {
1287 #[inline]
from((v, z): (Vec2, f32)) -> Self1288 fn from((v, z): (Vec2, f32)) -> Self {
1289 Self::new(v.x, v.y, z)
1290 }
1291 }
1292