Debian Codegraph @

debian/missing-sources/glam-0.28.0/src/f32/coresimd/vec3a.rs

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