Debian Codegraph @

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

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