Debian Codegraph @

third_party/rust/euclid/src/vector.rs

raw
1 // Copyright 2013 The Servo Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution.
3 //
4 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
5 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
7 // option. This file may not be copied, modified, or distributed
8 // except according to those terms.
9
10 use super::UnknownUnit;
11 use crate::approxeq::ApproxEq;
12 use crate::approxord::{max, min};
13 use crate::length::Length;
14 use crate::num::*;
15 use crate::point::{point2, point3, Point2D, Point3D};
16 use crate::scale::Scale;
17 use crate::size::{size2, size3, Size2D, Size3D};
18 use crate::transform2d::Transform2D;
19 use crate::transform3d::Transform3D;
20 use crate::trig::Trig;
21 use crate::Angle;
22 use core::cmp::{Eq, PartialEq};
23 use core::fmt;
24 use core::hash::Hash;
25 use core::iter::Sum;
26 use core::marker::PhantomData;
27 use core::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Sub, SubAssign};
28 #[cfg(feature = "mint")]
29 use mint;
30 use num_traits::real::Real;
31 use num_traits::{Float, NumCast, Signed};
32 #[cfg(feature = "serde")]
33 use serde;
34
35 #[cfg(feature = "bytemuck")]
36 use bytemuck::{Pod, Zeroable};
37
38 /// A 2d Vector tagged with a unit.
39 #[repr(C)]
40 pub struct Vector2D<T, U> {
41 /// The `x` (traditionally, horizontal) coordinate.
42 pub x: T,
43 /// The `y` (traditionally, vertical) coordinate.
44 pub y: T,
45 #[doc(hidden)]
46 pub _unit: PhantomData<U>,
47 }
48
49 mint_vec!(Vector2D[x, y] = Vector2);
50
51 impl<T: Copy, U> Copy for Vector2D<T, U> {}
52
53 impl<T: Clone, U> Clone for Vector2D<T, U> {
54 fn clone(&self) -> Self {
55 Vector2D {
56 x: self.x.clone(),
57 y: self.y.clone(),
58 _unit: PhantomData,
59 }
60 }
61 }
62
63 #[cfg(feature = "serde")]
64 impl<'de, T, U> serde::Deserialize<'de> for Vector2D<T, U>
65 where
66 T: serde::Deserialize<'de>,
67 {
68 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
69 where
70 D: serde::Deserializer<'de>,
71 {
72 let (x, y) = serde::Deserialize::deserialize(deserializer)?;
73 Ok(Vector2D {
74 x,
75 y,
76 _unit: PhantomData,
77 })
78 }
79 }
80
81 #[cfg(feature = "serde")]
82 impl<T, U> serde::Serialize for Vector2D<T, U>
83 where
84 T: serde::Serialize,
85 {
86 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
87 where
88 S: serde::Serializer,
89 {
90 (&self.x, &self.y).serialize(serializer)
91 }
92 }
93
94 #[cfg(feature = "arbitrary")]
95 impl<'a, T, U> arbitrary::Arbitrary<'a> for Vector2D<T, U>
96 where
97 T: arbitrary::Arbitrary<'a>,
98 {
99 fn arbitrary(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result<Self> {
100 let (x, y) = arbitrary::Arbitrary::arbitrary(u)?;
101 Ok(Vector2D {
102 x,
103 y,
104 _unit: PhantomData,
105 })
106 }
107 }
108
109 #[cfg(feature = "bytemuck")]
110 unsafe impl<T: Zeroable, U> Zeroable for Vector2D<T, U> {}
111
112 #[cfg(feature = "bytemuck")]
113 unsafe impl<T: Pod, U: 'static> Pod for Vector2D<T, U> {}
114
115 impl<T: Eq, U> Eq for Vector2D<T, U> {}
116
117 impl<T: PartialEq, U> PartialEq for Vector2D<T, U> {
118 fn eq(&self, other: &Self) -> bool {
119 self.x == other.x && self.y == other.y
120 }
121 }
122
123 impl<T: Hash, U> Hash for Vector2D<T, U> {
124 fn hash<H: core::hash::Hasher>(&self, h: &mut H) {
125 self.x.hash(h);
126 self.y.hash(h);
127 }
128 }
129
130 impl<T: Zero, U> Zero for Vector2D<T, U> {
131 /// Constructor, setting all components to zero.
132 #[inline]
133 fn zero() -> Self {
134 Vector2D::new(Zero::zero(), Zero::zero())
135 }
136 }
137
138 impl<T: fmt::Debug, U> fmt::Debug for Vector2D<T, U> {
139 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
140 f.debug_tuple("").field(&self.x).field(&self.y).finish()
141 }
142 }
143
144 impl<T: Default, U> Default for Vector2D<T, U> {
145 fn default() -> Self {
146 Vector2D::new(Default::default(), Default::default())
147 }
148 }
149
150 impl<T, U> Vector2D<T, U> {
151 /// Constructor, setting all components to zero.
152 #[inline]
153 pub fn zero() -> Self
154 where
155 T: Zero,
156 {
157 Vector2D::new(Zero::zero(), Zero::zero())
158 }
159
160 /// Constructor, setting all components to one.
161 #[inline]
162 pub fn one() -> Self
163 where
164 T: One,
165 {
166 Vector2D::new(One::one(), One::one())
167 }
168
169 /// Constructor taking scalar values directly.
170 #[inline]
171 pub const fn new(x: T, y: T) -> Self {
172 Vector2D {
173 x,
174 y,
175 _unit: PhantomData,
176 }
177 }
178
179 /// Constructor setting all components to the same value.
180 #[inline]
181 pub fn splat(v: T) -> Self
182 where
183 T: Clone,
184 {
185 Vector2D {
186 x: v.clone(),
187 y: v,
188 _unit: PhantomData,
189 }
190 }
191
192 /// Constructor taking angle and length
193 pub fn from_angle_and_length(angle: Angle<T>, length: T) -> Self
194 where
195 T: Trig + Mul<Output = T> + Copy,
196 {
197 vec2(length * angle.radians.cos(), length * angle.radians.sin())
198 }
199
200 /// Constructor taking properly Lengths instead of scalar values.
201 #[inline]
202 pub fn from_lengths(x: Length<T, U>, y: Length<T, U>) -> Self {
203 vec2(x.0, y.0)
204 }
205
206 /// Tag a unit-less value with units.
207 #[inline]
208 pub fn from_untyped(p: Vector2D<T, UnknownUnit>) -> Self {
209 vec2(p.x, p.y)
210 }
211
212 /// Apply the function `f` to each component of this vector.
213 ///
214 /// # Example
215 ///
216 /// This may be used to perform unusual arithmetic which is not already offered as methods.
217 ///
218 /// ```
219 /// use euclid::default::Vector2D;
220 ///
221 /// let p = Vector2D::<u32>::new(5, 11);
222 /// assert_eq!(p.map(|coord| coord.saturating_sub(10)), Vector2D::new(0, 1));
223 /// ```
224 #[inline]
225 pub fn map<V, F: FnMut(T) -> V>(self, mut f: F) -> Vector2D<V, U> {
226 vec2(f(self.x), f(self.y))
227 }
228
229 /// Apply the function `f` to each pair of components of this point and `rhs`.
230 ///
231 /// # Example
232 ///
233 /// This may be used to perform unusual arithmetic which is not already offered as methods.
234 ///
235 /// ```
236 /// use euclid::default::Vector2D;
237 ///
238 /// let a: Vector2D<u8> = Vector2D::new(50, 200);
239 /// let b: Vector2D<u8> = Vector2D::new(100, 100);
240 /// assert_eq!(a.zip(b, u8::saturating_add), Vector2D::new(150, 255));
241 /// ```
242 #[inline]
243 pub fn zip<V, F: FnMut(T, T) -> V>(self, rhs: Self, mut f: F) -> Vector2D<V, U> {
244 vec2(f(self.x, rhs.x), f(self.y, rhs.y))
245 }
246
247 /// Computes the vector with absolute values of each component.
248 ///
249 /// # Example
250 ///
251 /// ```rust
252 /// # use std::{i32, f32};
253 /// # use euclid::vec2;
254 /// enum U {}
255 ///
256 /// assert_eq!(vec2::<_, U>(-1, 2).abs(), vec2(1, 2));
257 ///
258 /// let vec = vec2::<_, U>(f32::NAN, -f32::MAX).abs();
259 /// assert!(vec.x.is_nan());
260 /// assert_eq!(vec.y, f32::MAX);
261 /// ```
262 ///
263 /// # Panics
264 ///
265 /// The behavior for each component follows the scalar type's implementation of
266 /// `num_traits::Signed::abs`.
267 pub fn abs(self) -> Self
268 where
269 T: Signed,
270 {
271 vec2(self.x.abs(), self.y.abs())
272 }
273
274 /// Dot product.
275 #[inline]
276 pub fn dot(self, other: Self) -> T
277 where
278 T: Add<Output = T> + Mul<Output = T>,
279 {
280 self.x * other.x + self.y * other.y
281 }
282
283 /// Returns the norm of the cross product [self.x, self.y, 0] x [other.x, other.y, 0].
284 #[inline]
285 pub fn cross(self, other: Self) -> T
286 where
287 T: Sub<Output = T> + Mul<Output = T>,
288 {
289 self.x * other.y - self.y * other.x
290 }
291
292 /// Returns the component-wise multiplication of the two vectors.
293 #[inline]
294 pub fn component_mul(self, other: Self) -> Self
295 where
296 T: Mul<Output = T>,
297 {
298 vec2(self.x * other.x, self.y * other.y)
299 }
300
301 /// Returns the component-wise division of the two vectors.
302 #[inline]
303 pub fn component_div(self, other: Self) -> Self
304 where
305 T: Div<Output = T>,
306 {
307 vec2(self.x / other.x, self.y / other.y)
308 }
309 }
310
311 impl<T: Copy, U> Vector2D<T, U> {
312 /// Create a 3d vector from this one, using the specified z value.
313 #[inline]
314 pub fn extend(self, z: T) -> Vector3D<T, U> {
315 vec3(self.x, self.y, z)
316 }
317
318 /// Cast this vector into a point.
319 ///
320 /// Equivalent to adding this vector to the origin.
321 #[inline]
322 pub fn to_point(self) -> Point2D<T, U> {
323 Point2D {
324 x: self.x,
325 y: self.y,
326 _unit: PhantomData,
327 }
328 }
329
330 /// Swap x and y.
331 #[inline]
332 pub fn yx(self) -> Self {
333 vec2(self.y, self.x)
334 }
335
336 /// Cast this vector into a size.
337 #[inline]
338 pub fn to_size(self) -> Size2D<T, U> {
339 size2(self.x, self.y)
340 }
341
342 /// Drop the units, preserving only the numeric value.
343 #[inline]
344 pub fn to_untyped(self) -> Vector2D<T, UnknownUnit> {
345 vec2(self.x, self.y)
346 }
347
348 /// Cast the unit.
349 #[inline]
350 pub fn cast_unit<V>(self) -> Vector2D<T, V> {
351 vec2(self.x, self.y)
352 }
353
354 /// Cast into an array with x and y.
355 #[inline]
356 pub fn to_array(self) -> [T; 2] {
357 [self.x, self.y]
358 }
359
360 /// Cast into a tuple with x and y.
361 #[inline]
362 pub fn to_tuple(self) -> (T, T) {
363 (self.x, self.y)
364 }
365
366 /// Convert into a 3d vector with `z` coordinate equals to `T::zero()`.
367 #[inline]
368 pub fn to_3d(self) -> Vector3D<T, U>
369 where
370 T: Zero,
371 {
372 vec3(self.x, self.y, Zero::zero())
373 }
374
375 /// Rounds each component to the nearest integer value.
376 ///
377 /// This behavior is preserved for negative values (unlike the basic cast).
378 ///
379 /// ```rust
380 /// # use euclid::vec2;
381 /// enum Mm {}
382 ///
383 /// assert_eq!(vec2::<_, Mm>(-0.1, -0.8).round(), vec2::<_, Mm>(0.0, -1.0))
384 /// ```
385 #[inline]
386 #[must_use]
387 pub fn round(self) -> Self
388 where
389 T: Round,
390 {
391 vec2(self.x.round(), self.y.round())
392 }
393
394 /// Rounds each component to the smallest integer equal or greater than the original value.
395 ///
396 /// This behavior is preserved for negative values (unlike the basic cast).
397 ///
398 /// ```rust
399 /// # use euclid::vec2;
400 /// enum Mm {}
401 ///
402 /// assert_eq!(vec2::<_, Mm>(-0.1, -0.8).ceil(), vec2::<_, Mm>(0.0, 0.0))
403 /// ```
404 #[inline]
405 #[must_use]
406 pub fn ceil(self) -> Self
407 where
408 T: Ceil,
409 {
410 vec2(self.x.ceil(), self.y.ceil())
411 }
412
413 /// Rounds each component to the biggest integer equal or lower than the original value.
414 ///
415 /// This behavior is preserved for negative values (unlike the basic cast).
416 ///
417 /// ```rust
418 /// # use euclid::vec2;
419 /// enum Mm {}
420 ///
421 /// assert_eq!(vec2::<_, Mm>(-0.1, -0.8).floor(), vec2::<_, Mm>(-1.0, -1.0))
422 /// ```
423 #[inline]
424 #[must_use]
425 pub fn floor(self) -> Self
426 where
427 T: Floor,
428 {
429 vec2(self.x.floor(), self.y.floor())
430 }
431
432 /// Returns the signed angle between this vector and the x axis.
433 /// Positive values counted counterclockwise, where 0 is `+x` axis, `PI/2`
434 /// is `+y` axis.
435 ///
436 /// The returned angle is between -PI and PI.
437 pub fn angle_from_x_axis(self) -> Angle<T>
438 where
439 T: Trig,
440 {
441 Angle::radians(Trig::fast_atan2(self.y, self.x))
442 }
443
444 /// Creates translation by this vector in vector units.
445 #[inline]
446 pub fn to_transform(self) -> Transform2D<T, U, U>
447 where
448 T: Zero + One,
449 {
450 Transform2D::translation(self.x, self.y)
451 }
452 }
453
454 impl<T, U> Vector2D<T, U>
455 where
456 T: Copy + Mul<T, Output = T> + Add<T, Output = T>,
457 {
458 /// Returns the vector's length squared.
459 #[inline]
460 pub fn square_length(self) -> T {
461 self.x * self.x + self.y * self.y
462 }
463
464 /// Returns this vector projected onto another one.
465 ///
466 /// Projecting onto a nil vector will cause a division by zero.
467 #[inline]
468 pub fn project_onto_vector(self, onto: Self) -> Self
469 where
470 T: Sub<T, Output = T> + Div<T, Output = T>,
471 {
472 onto * (self.dot(onto) / onto.square_length())
473 }
474
475 /// Returns the signed angle between this vector and another vector.
476 ///
477 /// The returned angle is between -PI and PI.
478 pub fn angle_to(self, other: Self) -> Angle<T>
479 where
480 T: Sub<Output = T> + Trig,
481 {
482 Angle::radians(Trig::fast_atan2(self.cross(other), self.dot(other)))
483 }
484 }
485
486 impl<T: Float, U> Vector2D<T, U> {
487 /// Return the normalized vector even if the length is larger than the max value of Float.
488 #[inline]
489 #[must_use]
490 pub fn robust_normalize(self) -> Self {
491 let length = self.length();
492 if length.is_infinite() {
493 let scaled = self / T::max_value();
494 scaled / scaled.length()
495 } else {
496 self / length
497 }
498 }
499
500 /// Returns true if all members are finite.
501 #[inline]
502 pub fn is_finite(self) -> bool {
503 self.x.is_finite() && self.y.is_finite()
504 }
505 }
506
507 impl<T: Real, U> Vector2D<T, U> {
508 /// Returns the vector length.
509 #[inline]
510 pub fn length(self) -> T {
511 self.square_length().sqrt()
512 }
513
514 /// Returns the vector with length of one unit.
515 #[inline]
516 #[must_use]
517 pub fn normalize(self) -> Self {
518 self / self.length()
519 }
520
521 /// Returns the vector with length of one unit.
522 ///
523 /// Unlike [`Vector2D::normalize`](#method.normalize), this returns None in the case that the
524 /// length of the vector is zero.
525 #[inline]
526 #[must_use]
527 pub fn try_normalize(self) -> Option<Self> {
528 let len = self.length();
529 if len == T::zero() {
530 None
531 } else {
532 Some(self / len)
533 }
534 }
535
536 /// Return this vector scaled to fit the provided length.
537 #[inline]
538 pub fn with_length(self, length: T) -> Self {
539 self.normalize() * length
540 }
541
542 /// Return this vector capped to a maximum length.
543 #[inline]
544 pub fn with_max_length(self, max_length: T) -> Self {
545 let square_length = self.square_length();
546 if square_length > max_length * max_length {
547 return self * (max_length / square_length.sqrt());
548 }
549
550 self
551 }
552
553 /// Return this vector with a minimum length applied.
554 #[inline]
555 pub fn with_min_length(self, min_length: T) -> Self {
556 let square_length = self.square_length();
557 if square_length < min_length * min_length {
558 return self * (min_length / square_length.sqrt());
559 }
560
561 self
562 }
563
564 /// Return this vector with minimum and maximum lengths applied.
565 #[inline]
566 pub fn clamp_length(self, min: T, max: T) -> Self {
567 debug_assert!(min <= max);
568 self.with_min_length(min).with_max_length(max)
569 }
570 }
571
572 impl<T, U> Vector2D<T, U>
573 where
574 T: Copy + One + Add<Output = T> + Sub<Output = T> + Mul<Output = T>,
575 {
576 /// Linearly interpolate each component between this vector and another vector.
577 ///
578 /// # Example
579 ///
580 /// ```rust
581 /// use euclid::vec2;
582 /// use euclid::default::Vector2D;
583 ///
584 /// let from: Vector2D<_> = vec2(0.0, 10.0);
585 /// let to: Vector2D<_> = vec2(8.0, -4.0);
586 ///
587 /// assert_eq!(from.lerp(to, -1.0), vec2(-8.0, 24.0));
588 /// assert_eq!(from.lerp(to, 0.0), vec2( 0.0, 10.0));
589 /// assert_eq!(from.lerp(to, 0.5), vec2( 4.0, 3.0));
590 /// assert_eq!(from.lerp(to, 1.0), vec2( 8.0, -4.0));
591 /// assert_eq!(from.lerp(to, 2.0), vec2(16.0, -18.0));
592 /// ```
593 #[inline]
594 pub fn lerp(self, other: Self, t: T) -> Self {
595 let one_t = T::one() - t;
596 self * one_t + other * t
597 }
598
599 /// Returns a reflection vector using an incident ray and a surface normal.
600 #[inline]
601 pub fn reflect(self, normal: Self) -> Self {
602 let two = T::one() + T::one();
603 self - normal * two * self.dot(normal)
604 }
605 }
606
607 impl<T: PartialOrd, U> Vector2D<T, U> {
608 /// Returns the vector each component of which are minimum of this vector and another.
609 #[inline]
610 pub fn min(self, other: Self) -> Self {
611 vec2(min(self.x, other.x), min(self.y, other.y))
612 }
613
614 /// Returns the vector each component of which are maximum of this vector and another.
615 #[inline]
616 pub fn max(self, other: Self) -> Self {
617 vec2(max(self.x, other.x), max(self.y, other.y))
618 }
619
620 /// Returns the vector each component of which is clamped by corresponding
621 /// components of `start` and `end`.
622 ///
623 /// Shortcut for `self.max(start).min(end)`.
624 #[inline]
625 pub fn clamp(self, start: Self, end: Self) -> Self
626 where
627 T: Copy,
628 {
629 self.max(start).min(end)
630 }
631
632 /// Returns vector with results of "greater than" operation on each component.
633 #[inline]
634 pub fn greater_than(self, other: Self) -> BoolVector2D {
635 BoolVector2D {
636 x: self.x > other.x,
637 y: self.y > other.y,
638 }
639 }
640
641 /// Returns vector with results of "lower than" operation on each component.
642 #[inline]
643 pub fn lower_than(self, other: Self) -> BoolVector2D {
644 BoolVector2D {
645 x: self.x < other.x,
646 y: self.y < other.y,
647 }
648 }
649 }
650
651 impl<T: PartialEq, U> Vector2D<T, U> {
652 /// Returns vector with results of "equal" operation on each component.
653 #[inline]
654 pub fn equal(self, other: Self) -> BoolVector2D {
655 BoolVector2D {
656 x: self.x == other.x,
657 y: self.y == other.y,
658 }
659 }
660
661 /// Returns vector with results of "not equal" operation on each component.
662 #[inline]
663 pub fn not_equal(self, other: Self) -> BoolVector2D {
664 BoolVector2D {
665 x: self.x != other.x,
666 y: self.y != other.y,
667 }
668 }
669 }
670
671 impl<T: NumCast + Copy, U> Vector2D<T, U> {
672 /// Cast from one numeric representation to another, preserving the units.
673 ///
674 /// When casting from floating vector to integer coordinates, the decimals are truncated
675 /// as one would expect from a simple cast, but this behavior does not always make sense
676 /// geometrically. Consider using `round()`, `ceil()` or `floor()` before casting.
677 #[inline]
678 pub fn cast<NewT: NumCast>(self) -> Vector2D<NewT, U> {
679 self.try_cast().unwrap()
680 }
681
682 /// Fallible cast from one numeric representation to another, preserving the units.
683 ///
684 /// When casting from floating vector to integer coordinates, the decimals are truncated
685 /// as one would expect from a simple cast, but this behavior does not always make sense
686 /// geometrically. Consider using `round()`, `ceil()` or `floor()` before casting.
687 pub fn try_cast<NewT: NumCast>(self) -> Option<Vector2D<NewT, U>> {
688 match (NumCast::from(self.x), NumCast::from(self.y)) {
689 (Some(x), Some(y)) => Some(Vector2D::new(x, y)),
690 _ => None,
691 }
692 }
693
694 // Convenience functions for common casts.
695
696 /// Cast into an `f32` vector.
697 #[inline]
698 pub fn to_f32(self) -> Vector2D<f32, U> {
699 self.cast()
700 }
701
702 /// Cast into an `f64` vector.
703 #[inline]
704 pub fn to_f64(self) -> Vector2D<f64, U> {
705 self.cast()
706 }
707
708 /// Cast into an `usize` vector, truncating decimals if any.
709 ///
710 /// When casting from floating vector vectors, it is worth considering whether
711 /// to `round()`, `ceil()` or `floor()` before the cast in order to obtain
712 /// the desired conversion behavior.
713 #[inline]
714 pub fn to_usize(self) -> Vector2D<usize, U> {
715 self.cast()
716 }
717
718 /// Cast into an `u32` vector, truncating decimals if any.
719 ///
720 /// When casting from floating vector vectors, it is worth considering whether
721 /// to `round()`, `ceil()` or `floor()` before the cast in order to obtain
722 /// the desired conversion behavior.
723 #[inline]
724 pub fn to_u32(self) -> Vector2D<u32, U> {
725 self.cast()
726 }
727
728 /// Cast into an i32 vector, truncating decimals if any.
729 ///
730 /// When casting from floating vector vectors, it is worth considering whether
731 /// to `round()`, `ceil()` or `floor()` before the cast in order to obtain
732 /// the desired conversion behavior.
733 #[inline]
734 pub fn to_i32(self) -> Vector2D<i32, U> {
735 self.cast()
736 }
737
738 /// Cast into an i64 vector, truncating decimals if any.
739 ///
740 /// When casting from floating vector vectors, it is worth considering whether
741 /// to `round()`, `ceil()` or `floor()` before the cast in order to obtain
742 /// the desired conversion behavior.
743 #[inline]
744 pub fn to_i64(self) -> Vector2D<i64, U> {
745 self.cast()
746 }
747 }
748
749 impl<T: Neg, U> Neg for Vector2D<T, U> {
750 type Output = Vector2D<T::Output, U>;
751
752 #[inline]
753 fn neg(self) -> Self::Output {
754 vec2(-self.x, -self.y)
755 }
756 }
757
758 impl<T: Add, U> Add for Vector2D<T, U> {
759 type Output = Vector2D<T::Output, U>;
760
761 #[inline]
762 fn add(self, other: Self) -> Self::Output {
763 Vector2D::new(self.x + other.x, self.y + other.y)
764 }
765 }
766
767 impl<T: Add + Copy, U> Add<&Self> for Vector2D<T, U> {
768 type Output = Vector2D<T::Output, U>;
769
770 #[inline]
771 fn add(self, other: &Self) -> Self::Output {
772 Vector2D::new(self.x + other.x, self.y + other.y)
773 }
774 }
775
776 impl<T: Add<Output = T> + Zero, U> Sum for Vector2D<T, U> {
777 fn sum<I: Iterator<Item = Self>>(iter: I) -> Self {
778 iter.fold(Self::zero(), Add::add)
779 }
780 }
781
782 impl<'a, T: 'a + Add<Output = T> + Copy + Zero, U: 'a> Sum<&'a Self> for Vector2D<T, U> {
783 fn sum<I: Iterator<Item = &'a Self>>(iter: I) -> Self {
784 iter.fold(Self::zero(), Add::add)
785 }
786 }
787
788 impl<T: Copy + Add<T, Output = T>, U> AddAssign for Vector2D<T, U> {
789 #[inline]
790 fn add_assign(&mut self, other: Self) {
791 *self = *self + other
792 }
793 }
794
795 impl<T: Sub, U> Sub for Vector2D<T, U> {
796 type Output = Vector2D<T::Output, U>;
797
798 #[inline]
799 fn sub(self, other: Self) -> Self::Output {
800 vec2(self.x - other.x, self.y - other.y)
801 }
802 }
803
804 impl<T: Copy + Sub<T, Output = T>, U> SubAssign<Vector2D<T, U>> for Vector2D<T, U> {
805 #[inline]
806 fn sub_assign(&mut self, other: Self) {
807 *self = *self - other
808 }
809 }
810
811 impl<T: Copy + Mul, U> Mul<T> for Vector2D<T, U> {
812 type Output = Vector2D<T::Output, U>;
813
814 #[inline]
815 fn mul(self, scale: T) -> Self::Output {
816 vec2(self.x * scale, self.y * scale)
817 }
818 }
819
820 impl<T: Copy + Mul<T, Output = T>, U> MulAssign<T> for Vector2D<T, U> {
821 #[inline]
822 fn mul_assign(&mut self, scale: T) {
823 *self = *self * scale
824 }
825 }
826
827 impl<T: Copy + Mul, U1, U2> Mul<Scale<T, U1, U2>> for Vector2D<T, U1> {
828 type Output = Vector2D<T::Output, U2>;
829
830 #[inline]
831 fn mul(self, scale: Scale<T, U1, U2>) -> Self::Output {
832 vec2(self.x * scale.0, self.y * scale.0)
833 }
834 }
835
836 impl<T: Copy + MulAssign, U> MulAssign<Scale<T, U, U>> for Vector2D<T, U> {
837 #[inline]
838 fn mul_assign(&mut self, scale: Scale<T, U, U>) {
839 self.x *= scale.0;
840 self.y *= scale.0;
841 }
842 }
843
844 impl<T: Copy + Div, U> Div<T> for Vector2D<T, U> {
845 type Output = Vector2D<T::Output, U>;
846
847 #[inline]
848 fn div(self, scale: T) -> Self::Output {
849 vec2(self.x / scale, self.y / scale)
850 }
851 }
852
853 impl<T: Copy + Div<T, Output = T>, U> DivAssign<T> for Vector2D<T, U> {
854 #[inline]
855 fn div_assign(&mut self, scale: T) {
856 *self = *self / scale
857 }
858 }
859
860 impl<T: Copy + Div, U1, U2> Div<Scale<T, U1, U2>> for Vector2D<T, U2> {
861 type Output = Vector2D<T::Output, U1>;
862
863 #[inline]
864 fn div(self, scale: Scale<T, U1, U2>) -> Self::Output {
865 vec2(self.x / scale.0, self.y / scale.0)
866 }
867 }
868
869 impl<T: Copy + DivAssign, U> DivAssign<Scale<T, U, U>> for Vector2D<T, U> {
870 #[inline]
871 fn div_assign(&mut self, scale: Scale<T, U, U>) {
872 self.x /= scale.0;
873 self.y /= scale.0;
874 }
875 }
876
877 impl<T: Round, U> Round for Vector2D<T, U> {
878 /// See [`Vector2D::round()`](#method.round)
879 #[inline]
880 fn round(self) -> Self {
881 self.round()
882 }
883 }
884
885 impl<T: Ceil, U> Ceil for Vector2D<T, U> {
886 /// See [`Vector2D::ceil()`](#method.ceil)
887 #[inline]
888 fn ceil(self) -> Self {
889 self.ceil()
890 }
891 }
892
893 impl<T: Floor, U> Floor for Vector2D<T, U> {
894 /// See [`Vector2D::floor()`](#method.floor)
895 #[inline]
896 fn floor(self) -> Self {
897 self.floor()
898 }
899 }
900
901 impl<T: ApproxEq<T>, U> ApproxEq<Vector2D<T, U>> for Vector2D<T, U> {
902 #[inline]
903 fn approx_epsilon() -> Self {
904 vec2(T::approx_epsilon(), T::approx_epsilon())
905 }
906
907 #[inline]
908 fn approx_eq_eps(&self, other: &Self, eps: &Self) -> bool {
909 self.x.approx_eq_eps(&other.x, &eps.x) && self.y.approx_eq_eps(&other.y, &eps.y)
910 }
911 }
912
913 impl<T, U> From<Vector2D<T, U>> for [T; 2] {
914 fn from(v: Vector2D<T, U>) -> Self {
915 [v.x, v.y]
916 }
917 }
918
919 impl<T, U> From<[T; 2]> for Vector2D<T, U> {
920 fn from([x, y]: [T; 2]) -> Self {
921 vec2(x, y)
922 }
923 }
924
925 impl<T, U> From<Vector2D<T, U>> for (T, T) {
926 fn from(v: Vector2D<T, U>) -> Self {
927 (v.x, v.y)
928 }
929 }
930
931 impl<T, U> From<(T, T)> for Vector2D<T, U> {
932 fn from(tuple: (T, T)) -> Self {
933 vec2(tuple.0, tuple.1)
934 }
935 }
936
937 impl<T, U> From<Size2D<T, U>> for Vector2D<T, U> {
938 fn from(s: Size2D<T, U>) -> Self {
939 vec2(s.width, s.height)
940 }
941 }
942
943 /// A 3d Vector tagged with a unit.
944 #[repr(C)]
945 pub struct Vector3D<T, U> {
946 /// The `x` (traditionally, horizontal) coordinate.
947 pub x: T,
948 /// The `y` (traditionally, vertical) coordinate.
949 pub y: T,
950 /// The `z` (traditionally, depth) coordinate.
951 pub z: T,
952 #[doc(hidden)]
953 pub _unit: PhantomData<U>,
954 }
955
956 mint_vec!(Vector3D[x, y, z] = Vector3);
957
958 impl<T: Copy, U> Copy for Vector3D<T, U> {}
959
960 impl<T: Clone, U> Clone for Vector3D<T, U> {
961 fn clone(&self) -> Self {
962 Vector3D {
963 x: self.x.clone(),
964 y: self.y.clone(),
965 z: self.z.clone(),
966 _unit: PhantomData,
967 }
968 }
969 }
970
971 #[cfg(feature = "serde")]
972 impl<'de, T, U> serde::Deserialize<'de> for Vector3D<T, U>
973 where
974 T: serde::Deserialize<'de>,
975 {
976 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
977 where
978 D: serde::Deserializer<'de>,
979 {
980 let (x, y, z) = serde::Deserialize::deserialize(deserializer)?;
981 Ok(Vector3D {
982 x,
983 y,
984 z,
985 _unit: PhantomData,
986 })
987 }
988 }
989
990 #[cfg(feature = "serde")]
991 impl<T, U> serde::Serialize for Vector3D<T, U>
992 where
993 T: serde::Serialize,
994 {
995 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
996 where
997 S: serde::Serializer,
998 {
999 (&self.x, &self.y, &self.z).serialize(serializer)
1000 }
1001 }
1002
1003 #[cfg(feature = "bytemuck")]
1004 unsafe impl<T: Zeroable, U> Zeroable for Vector3D<T, U> {}
1005
1006 #[cfg(feature = "bytemuck")]
1007 unsafe impl<T: Pod, U: 'static> Pod for Vector3D<T, U> {}
1008
1009 impl<T: Eq, U> Eq for Vector3D<T, U> {}
1010
1011 impl<T: PartialEq, U> PartialEq for Vector3D<T, U> {
1012 fn eq(&self, other: &Self) -> bool {
1013 self.x == other.x && self.y == other.y && self.z == other.z
1014 }
1015 }
1016
1017 impl<T: Hash, U> Hash for Vector3D<T, U> {
1018 fn hash<H: core::hash::Hasher>(&self, h: &mut H) {
1019 self.x.hash(h);
1020 self.y.hash(h);
1021 self.z.hash(h);
1022 }
1023 }
1024
1025 impl<T: Zero, U> Zero for Vector3D<T, U> {
1026 /// Constructor, setting all components to zero.
1027 #[inline]
1028 fn zero() -> Self {
1029 vec3(Zero::zero(), Zero::zero(), Zero::zero())
1030 }
1031 }
1032
1033 impl<T: fmt::Debug, U> fmt::Debug for Vector3D<T, U> {
1034 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1035 f.debug_tuple("")
1036 .field(&self.x)
1037 .field(&self.y)
1038 .field(&self.z)
1039 .finish()
1040 }
1041 }
1042
1043 impl<T: Default, U> Default for Vector3D<T, U> {
1044 fn default() -> Self {
1045 Vector3D::new(Default::default(), Default::default(), Default::default())
1046 }
1047 }
1048
1049 impl<T, U> Vector3D<T, U> {
1050 /// Constructor, setting all components to zero.
1051 #[inline]
1052 pub fn zero() -> Self
1053 where
1054 T: Zero,
1055 {
1056 vec3(Zero::zero(), Zero::zero(), Zero::zero())
1057 }
1058
1059 /// Constructor, setting all components to one.
1060 #[inline]
1061 pub fn one() -> Self
1062 where
1063 T: One,
1064 {
1065 vec3(One::one(), One::one(), One::one())
1066 }
1067
1068 /// Constructor taking scalar values directly.
1069 #[inline]
1070 pub const fn new(x: T, y: T, z: T) -> Self {
1071 Vector3D {
1072 x,
1073 y,
1074 z,
1075 _unit: PhantomData,
1076 }
1077 }
1078 /// Constructor setting all components to the same value.
1079 #[inline]
1080 pub fn splat(v: T) -> Self
1081 where
1082 T: Clone,
1083 {
1084 Vector3D {
1085 x: v.clone(),
1086 y: v.clone(),
1087 z: v,
1088 _unit: PhantomData,
1089 }
1090 }
1091
1092 /// Constructor taking properly Lengths instead of scalar values.
1093 #[inline]
1094 pub fn from_lengths(x: Length<T, U>, y: Length<T, U>, z: Length<T, U>) -> Vector3D<T, U> {
1095 vec3(x.0, y.0, z.0)
1096 }
1097
1098 /// Tag a unitless value with units.
1099 #[inline]
1100 pub fn from_untyped(p: Vector3D<T, UnknownUnit>) -> Self {
1101 vec3(p.x, p.y, p.z)
1102 }
1103
1104 /// Apply the function `f` to each component of this vector.
1105 ///
1106 /// # Example
1107 ///
1108 /// This may be used to perform unusual arithmetic which is not already offered as methods.
1109 ///
1110 /// ```
1111 /// use euclid::default::Vector3D;
1112 ///
1113 /// let p = Vector3D::<u32>::new(5, 11, 15);
1114 /// assert_eq!(p.map(|coord| coord.saturating_sub(10)), Vector3D::new(0, 1, 5));
1115 /// ```
1116 #[inline]
1117 pub fn map<V, F: FnMut(T) -> V>(self, mut f: F) -> Vector3D<V, U> {
1118 vec3(f(self.x), f(self.y), f(self.z))
1119 }
1120
1121 /// Apply the function `f` to each pair of components of this point and `rhs`.
1122 ///
1123 /// # Example
1124 ///
1125 /// This may be used to perform unusual arithmetic which is not already offered as methods.
1126 ///
1127 /// ```
1128 /// use euclid::default::Vector3D;
1129 ///
1130 /// let a: Vector3D<u8> = Vector3D::new(50, 200, 10);
1131 /// let b: Vector3D<u8> = Vector3D::new(100, 100, 0);
1132 /// assert_eq!(a.zip(b, u8::saturating_add), Vector3D::new(150, 255, 10));
1133 /// ```
1134 #[inline]
1135 pub fn zip<V, F: FnMut(T, T) -> V>(self, rhs: Self, mut f: F) -> Vector3D<V, U> {
1136 vec3(f(self.x, rhs.x), f(self.y, rhs.y), f(self.z, rhs.z))
1137 }
1138
1139 /// Computes the vector with absolute values of each component.
1140 ///
1141 /// # Example
1142 ///
1143 /// ```rust
1144 /// # use std::{i32, f32};
1145 /// # use euclid::vec3;
1146 /// enum U {}
1147 ///
1148 /// assert_eq!(vec3::<_, U>(-1, 0, 2).abs(), vec3(1, 0, 2));
1149 ///
1150 /// let vec = vec3::<_, U>(f32::NAN, 0.0, -f32::MAX).abs();
1151 /// assert!(vec.x.is_nan());
1152 /// assert_eq!(vec.y, 0.0);
1153 /// assert_eq!(vec.z, f32::MAX);
1154 /// ```
1155 ///
1156 /// # Panics
1157 ///
1158 /// The behavior for each component follows the scalar type's implementation of
1159 /// `num_traits::Signed::abs`.
1160 pub fn abs(self) -> Self
1161 where
1162 T: Signed,
1163 {
1164 vec3(self.x.abs(), self.y.abs(), self.z.abs())
1165 }
1166
1167 /// Dot product.
1168 #[inline]
1169 pub fn dot(self, other: Self) -> T
1170 where
1171 T: Add<Output = T> + Mul<Output = T>,
1172 {
1173 self.x * other.x + self.y * other.y + self.z * other.z
1174 }
1175 }
1176
1177 impl<T: Copy, U> Vector3D<T, U> {
1178 /// Cross product.
1179 #[inline]
1180 pub fn cross(self, other: Self) -> Self
1181 where
1182 T: Sub<Output = T> + Mul<Output = T>,
1183 {
1184 vec3(
1185 self.y * other.z - self.z * other.y,
1186 self.z * other.x - self.x * other.z,
1187 self.x * other.y - self.y * other.x,
1188 )
1189 }
1190
1191 /// Returns the component-wise multiplication of the two vectors.
1192 #[inline]
1193 pub fn component_mul(self, other: Self) -> Self
1194 where
1195 T: Mul<Output = T>,
1196 {
1197 vec3(self.x * other.x, self.y * other.y, self.z * other.z)
1198 }
1199
1200 /// Returns the component-wise division of the two vectors.
1201 #[inline]
1202 pub fn component_div(self, other: Self) -> Self
1203 where
1204 T: Div<Output = T>,
1205 {
1206 vec3(self.x / other.x, self.y / other.y, self.z / other.z)
1207 }
1208
1209 /// Cast this vector into a point.
1210 ///
1211 /// Equivalent to adding this vector to the origin.
1212 #[inline]
1213 pub fn to_point(self) -> Point3D<T, U> {
1214 point3(self.x, self.y, self.z)
1215 }
1216
1217 /// Returns a 2d vector using this vector's x and y coordinates
1218 #[inline]
1219 pub fn xy(self) -> Vector2D<T, U> {
1220 vec2(self.x, self.y)
1221 }
1222
1223 /// Returns a 2d vector using this vector's x and z coordinates
1224 #[inline]
1225 pub fn xz(self) -> Vector2D<T, U> {
1226 vec2(self.x, self.z)
1227 }
1228
1229 /// Returns a 2d vector using this vector's x and z coordinates
1230 #[inline]
1231 pub fn yz(self) -> Vector2D<T, U> {
1232 vec2(self.y, self.z)
1233 }
1234
1235 /// Cast into an array with x, y and z.
1236 #[inline]
1237 pub fn to_array(self) -> [T; 3] {
1238 [self.x, self.y, self.z]
1239 }
1240
1241 /// Cast into an array with x, y, z and 0.
1242 #[inline]
1243 pub fn to_array_4d(self) -> [T; 4]
1244 where
1245 T: Zero,
1246 {
1247 [self.x, self.y, self.z, Zero::zero()]
1248 }
1249
1250 /// Cast into a tuple with x, y and z.
1251 #[inline]
1252 pub fn to_tuple(self) -> (T, T, T) {
1253 (self.x, self.y, self.z)
1254 }
1255
1256 /// Cast into a tuple with x, y, z and 0.
1257 #[inline]
1258 pub fn to_tuple_4d(self) -> (T, T, T, T)
1259 where
1260 T: Zero,
1261 {
1262 (self.x, self.y, self.z, Zero::zero())
1263 }
1264
1265 /// Drop the units, preserving only the numeric value.
1266 #[inline]
1267 pub fn to_untyped(self) -> Vector3D<T, UnknownUnit> {
1268 vec3(self.x, self.y, self.z)
1269 }
1270
1271 /// Cast the unit.
1272 #[inline]
1273 pub fn cast_unit<V>(self) -> Vector3D<T, V> {
1274 vec3(self.x, self.y, self.z)
1275 }
1276
1277 /// Convert into a 2d vector.
1278 #[inline]
1279 pub fn to_2d(self) -> Vector2D<T, U> {
1280 self.xy()
1281 }
1282
1283 /// Rounds each component to the nearest integer value.
1284 ///
1285 /// This behavior is preserved for negative values (unlike the basic cast).
1286 ///
1287 /// ```rust
1288 /// # use euclid::vec3;
1289 /// enum Mm {}
1290 ///
1291 /// assert_eq!(vec3::<_, Mm>(-0.1, -0.8, 0.4).round(), vec3::<_, Mm>(0.0, -1.0, 0.0))
1292 /// ```
1293 #[inline]
1294 #[must_use]
1295 pub fn round(self) -> Self
1296 where
1297 T: Round,
1298 {
1299 vec3(self.x.round(), self.y.round(), self.z.round())
1300 }
1301
1302 /// Rounds each component to the smallest integer equal or greater than the original value.
1303 ///
1304 /// This behavior is preserved for negative values (unlike the basic cast).
1305 ///
1306 /// ```rust
1307 /// # use euclid::vec3;
1308 /// enum Mm {}
1309 ///
1310 /// assert_eq!(vec3::<_, Mm>(-0.1, -0.8, 0.4).ceil(), vec3::<_, Mm>(0.0, 0.0, 1.0))
1311 /// ```
1312 #[inline]
1313 #[must_use]
1314 pub fn ceil(self) -> Self
1315 where
1316 T: Ceil,
1317 {
1318 vec3(self.x.ceil(), self.y.ceil(), self.z.ceil())
1319 }
1320
1321 /// Rounds each component to the biggest integer equal or lower than the original value.
1322 ///
1323 /// This behavior is preserved for negative values (unlike the basic cast).
1324 ///
1325 /// ```rust
1326 /// # use euclid::vec3;
1327 /// enum Mm {}
1328 ///
1329 /// assert_eq!(vec3::<_, Mm>(-0.1, -0.8, 0.4).floor(), vec3::<_, Mm>(-1.0, -1.0, 0.0))
1330 /// ```
1331 #[inline]
1332 #[must_use]
1333 pub fn floor(self) -> Self
1334 where
1335 T: Floor,
1336 {
1337 vec3(self.x.floor(), self.y.floor(), self.z.floor())
1338 }
1339
1340 /// Creates translation by this vector in vector units
1341 #[inline]
1342 pub fn to_transform(self) -> Transform3D<T, U, U>
1343 where
1344 T: Zero + One,
1345 {
1346 Transform3D::translation(self.x, self.y, self.z)
1347 }
1348 }
1349
1350 impl<T, U> Vector3D<T, U>
1351 where
1352 T: Copy + Mul<T, Output = T> + Add<T, Output = T>,
1353 {
1354 /// Returns the vector's length squared.
1355 #[inline]
1356 pub fn square_length(self) -> T {
1357 self.x * self.x + self.y * self.y + self.z * self.z
1358 }
1359
1360 /// Returns this vector projected onto another one.
1361 ///
1362 /// Projecting onto a nil vector will cause a division by zero.
1363 #[inline]
1364 pub fn project_onto_vector(self, onto: Self) -> Self
1365 where
1366 T: Sub<T, Output = T> + Div<T, Output = T>,
1367 {
1368 onto * (self.dot(onto) / onto.square_length())
1369 }
1370 }
1371
1372 impl<T: Float, U> Vector3D<T, U> {
1373 /// Return the normalized vector even if the length is larger than the max value of Float.
1374 #[inline]
1375 #[must_use]
1376 pub fn robust_normalize(self) -> Self {
1377 let length = self.length();
1378 if length.is_infinite() {
1379 let scaled = self / T::max_value();
1380 scaled / scaled.length()
1381 } else {
1382 self / length
1383 }
1384 }
1385
1386 /// Returns true if all members are finite.
1387 #[inline]
1388 pub fn is_finite(self) -> bool {
1389 self.x.is_finite() && self.y.is_finite() && self.z.is_finite()
1390 }
1391 }
1392
1393 impl<T: Real, U> Vector3D<T, U> {
1394 /// Returns the positive angle between this vector and another vector.
1395 ///
1396 /// The returned angle is between 0 and PI.
1397 pub fn angle_to(self, other: Self) -> Angle<T>
1398 where
1399 T: Trig,
1400 {
1401 Angle::radians(Trig::fast_atan2(
1402 self.cross(other).length(),
1403 self.dot(other),
1404 ))
1405 }
1406
1407 /// Returns the vector length.
1408 #[inline]
1409 pub fn length(self) -> T {
1410 self.square_length().sqrt()
1411 }
1412
1413 /// Returns the vector with length of one unit
1414 #[inline]
1415 #[must_use]
1416 pub fn normalize(self) -> Self {
1417 self / self.length()
1418 }
1419
1420 /// Returns the vector with length of one unit.
1421 ///
1422 /// Unlike [`Vector2D::normalize`](#method.normalize), this returns None in the case that the
1423 /// length of the vector is zero.
1424 #[inline]
1425 #[must_use]
1426 pub fn try_normalize(self) -> Option<Self> {
1427 let len = self.length();
1428 if len == T::zero() {
1429 None
1430 } else {
1431 Some(self / len)
1432 }
1433 }
1434
1435 /// Return this vector capped to a maximum length.
1436 #[inline]
1437 pub fn with_max_length(self, max_length: T) -> Self {
1438 let square_length = self.square_length();
1439 if square_length > max_length * max_length {
1440 return self * (max_length / square_length.sqrt());
1441 }
1442
1443 self
1444 }
1445
1446 /// Return this vector with a minimum length applied.
1447 #[inline]
1448 pub fn with_min_length(self, min_length: T) -> Self {
1449 let square_length = self.square_length();
1450 if square_length < min_length * min_length {
1451 return self * (min_length / square_length.sqrt());
1452 }
1453
1454 self
1455 }
1456
1457 /// Return this vector with minimum and maximum lengths applied.
1458 #[inline]
1459 pub fn clamp_length(self, min: T, max: T) -> Self {
1460 debug_assert!(min <= max);
1461 self.with_min_length(min).with_max_length(max)
1462 }
1463 }
1464
1465 impl<T, U> Vector3D<T, U>
1466 where
1467 T: Copy + One + Add<Output = T> + Sub<Output = T> + Mul<Output = T>,
1468 {
1469 /// Linearly interpolate each component between this vector and another vector.
1470 ///
1471 /// # Example
1472 ///
1473 /// ```rust
1474 /// use euclid::vec3;
1475 /// use euclid::default::Vector3D;
1476 ///
1477 /// let from: Vector3D<_> = vec3(0.0, 10.0, -1.0);
1478 /// let to: Vector3D<_> = vec3(8.0, -4.0, 0.0);
1479 ///
1480 /// assert_eq!(from.lerp(to, -1.0), vec3(-8.0, 24.0, -2.0));
1481 /// assert_eq!(from.lerp(to, 0.0), vec3( 0.0, 10.0, -1.0));
1482 /// assert_eq!(from.lerp(to, 0.5), vec3( 4.0, 3.0, -0.5));
1483 /// assert_eq!(from.lerp(to, 1.0), vec3( 8.0, -4.0, 0.0));
1484 /// assert_eq!(from.lerp(to, 2.0), vec3(16.0, -18.0, 1.0));
1485 /// ```
1486 #[inline]
1487 pub fn lerp(self, other: Self, t: T) -> Self {
1488 let one_t = T::one() - t;
1489 self * one_t + other * t
1490 }
1491
1492 /// Returns a reflection vector using an incident ray and a surface normal.
1493 #[inline]
1494 pub fn reflect(self, normal: Self) -> Self {
1495 let two = T::one() + T::one();
1496 self - normal * two * self.dot(normal)
1497 }
1498 }
1499
1500 impl<T: PartialOrd, U> Vector3D<T, U> {
1501 /// Returns the vector each component of which are minimum of this vector and another.
1502 #[inline]
1503 pub fn min(self, other: Self) -> Self {
1504 vec3(
1505 min(self.x, other.x),
1506 min(self.y, other.y),
1507 min(self.z, other.z),
1508 )
1509 }
1510
1511 /// Returns the vector each component of which are maximum of this vector and another.
1512 #[inline]
1513 pub fn max(self, other: Self) -> Self {
1514 vec3(
1515 max(self.x, other.x),
1516 max(self.y, other.y),
1517 max(self.z, other.z),
1518 )
1519 }
1520
1521 /// Returns the vector each component of which is clamped by corresponding
1522 /// components of `start` and `end`.
1523 ///
1524 /// Shortcut for `self.max(start).min(end)`.
1525 #[inline]
1526 pub fn clamp(self, start: Self, end: Self) -> Self
1527 where
1528 T: Copy,
1529 {
1530 self.max(start).min(end)
1531 }
1532
1533 /// Returns vector with results of "greater than" operation on each component.
1534 #[inline]
1535 pub fn greater_than(self, other: Self) -> BoolVector3D {
1536 BoolVector3D {
1537 x: self.x > other.x,
1538 y: self.y > other.y,
1539 z: self.z > other.z,
1540 }
1541 }
1542
1543 /// Returns vector with results of "lower than" operation on each component.
1544 #[inline]
1545 pub fn lower_than(self, other: Self) -> BoolVector3D {
1546 BoolVector3D {
1547 x: self.x < other.x,
1548 y: self.y < other.y,
1549 z: self.z < other.z,
1550 }
1551 }
1552 }
1553
1554 impl<T: PartialEq, U> Vector3D<T, U> {
1555 /// Returns vector with results of "equal" operation on each component.
1556 #[inline]
1557 pub fn equal(self, other: Self) -> BoolVector3D {
1558 BoolVector3D {
1559 x: self.x == other.x,
1560 y: self.y == other.y,
1561 z: self.z == other.z,
1562 }
1563 }
1564
1565 /// Returns vector with results of "not equal" operation on each component.
1566 #[inline]
1567 pub fn not_equal(self, other: Self) -> BoolVector3D {
1568 BoolVector3D {
1569 x: self.x != other.x,
1570 y: self.y != other.y,
1571 z: self.z != other.z,
1572 }
1573 }
1574 }
1575
1576 impl<T: NumCast + Copy, U> Vector3D<T, U> {
1577 /// Cast from one numeric representation to another, preserving the units.
1578 ///
1579 /// When casting from floating vector to integer coordinates, the decimals are truncated
1580 /// as one would expect from a simple cast, but this behavior does not always make sense
1581 /// geometrically. Consider using `round()`, `ceil()` or `floor()` before casting.
1582 #[inline]
1583 pub fn cast<NewT: NumCast>(self) -> Vector3D<NewT, U> {
1584 self.try_cast().unwrap()
1585 }
1586
1587 /// Fallible cast from one numeric representation to another, preserving the units.
1588 ///
1589 /// When casting from floating vector to integer coordinates, the decimals are truncated
1590 /// as one would expect from a simple cast, but this behavior does not always make sense
1591 /// geometrically. Consider using `round()`, `ceil()` or `floor()` before casting.
1592 pub fn try_cast<NewT: NumCast>(self) -> Option<Vector3D<NewT, U>> {
1593 match (
1594 NumCast::from(self.x),
1595 NumCast::from(self.y),
1596 NumCast::from(self.z),
1597 ) {
1598 (Some(x), Some(y), Some(z)) => Some(vec3(x, y, z)),
1599 _ => None,
1600 }
1601 }
1602
1603 // Convenience functions for common casts.
1604
1605 /// Cast into an `f32` vector.
1606 #[inline]
1607 pub fn to_f32(self) -> Vector3D<f32, U> {
1608 self.cast()
1609 }
1610
1611 /// Cast into an `f64` vector.
1612 #[inline]
1613 pub fn to_f64(self) -> Vector3D<f64, U> {
1614 self.cast()
1615 }
1616
1617 /// Cast into an `usize` vector, truncating decimals if any.
1618 ///
1619 /// When casting from floating vector vectors, it is worth considering whether
1620 /// to `round()`, `ceil()` or `floor()` before the cast in order to obtain
1621 /// the desired conversion behavior.
1622 #[inline]
1623 pub fn to_usize(self) -> Vector3D<usize, U> {
1624 self.cast()
1625 }
1626
1627 /// Cast into an `u32` vector, truncating decimals if any.
1628 ///
1629 /// When casting from floating vector vectors, it is worth considering whether
1630 /// to `round()`, `ceil()` or `floor()` before the cast in order to obtain
1631 /// the desired conversion behavior.
1632 #[inline]
1633 pub fn to_u32(self) -> Vector3D<u32, U> {
1634 self.cast()
1635 }
1636
1637 /// Cast into an `i32` vector, truncating decimals if any.
1638 ///
1639 /// When casting from floating vector vectors, it is worth considering whether
1640 /// to `round()`, `ceil()` or `floor()` before the cast in order to obtain
1641 /// the desired conversion behavior.
1642 #[inline]
1643 pub fn to_i32(self) -> Vector3D<i32, U> {
1644 self.cast()
1645 }
1646
1647 /// Cast into an `i64` vector, truncating decimals if any.
1648 ///
1649 /// When casting from floating vector vectors, it is worth considering whether
1650 /// to `round()`, `ceil()` or `floor()` before the cast in order to obtain
1651 /// the desired conversion behavior.
1652 #[inline]
1653 pub fn to_i64(self) -> Vector3D<i64, U> {
1654 self.cast()
1655 }
1656 }
1657
1658 impl<T: Neg, U> Neg for Vector3D<T, U> {
1659 type Output = Vector3D<T::Output, U>;
1660
1661 #[inline]
1662 fn neg(self) -> Self::Output {
1663 vec3(-self.x, -self.y, -self.z)
1664 }
1665 }
1666
1667 impl<T: Add, U> Add for Vector3D<T, U> {
1668 type Output = Vector3D<T::Output, U>;
1669
1670 #[inline]
1671 fn add(self, other: Self) -> Self::Output {
1672 vec3(self.x + other.x, self.y + other.y, self.z + other.z)
1673 }
1674 }
1675
1676 impl<'a, T: 'a + Add + Copy, U: 'a> Add<&Self> for Vector3D<T, U> {
1677 type Output = Vector3D<T::Output, U>;
1678
1679 #[inline]
1680 fn add(self, other: &Self) -> Self::Output {
1681 vec3(self.x + other.x, self.y + other.y, self.z + other.z)
1682 }
1683 }
1684
1685 impl<T: Add<Output = T> + Zero, U> Sum for Vector3D<T, U> {
1686 fn sum<I: Iterator<Item = Self>>(iter: I) -> Self {
1687 iter.fold(Self::zero(), Add::add)
1688 }
1689 }
1690
1691 impl<'a, T: 'a + Add<Output = T> + Copy + Zero, U: 'a> Sum<&'a Self> for Vector3D<T, U> {
1692 fn sum<I: Iterator<Item = &'a Self>>(iter: I) -> Self {
1693 iter.fold(Self::zero(), Add::add)
1694 }
1695 }
1696
1697 impl<T: Copy + Add<T, Output = T>, U> AddAssign for Vector3D<T, U> {
1698 #[inline]
1699 fn add_assign(&mut self, other: Self) {
1700 *self = *self + other
1701 }
1702 }
1703
1704 impl<T: Sub, U> Sub for Vector3D<T, U> {
1705 type Output = Vector3D<T::Output, U>;
1706
1707 #[inline]
1708 fn sub(self, other: Self) -> Self::Output {
1709 vec3(self.x - other.x, self.y - other.y, self.z - other.z)
1710 }
1711 }
1712
1713 impl<T: Copy + Sub<T, Output = T>, U> SubAssign<Vector3D<T, U>> for Vector3D<T, U> {
1714 #[inline]
1715 fn sub_assign(&mut self, other: Self) {
1716 *self = *self - other
1717 }
1718 }
1719
1720 impl<T: Copy + Mul, U> Mul<T> for Vector3D<T, U> {
1721 type Output = Vector3D<T::Output, U>;
1722
1723 #[inline]
1724 fn mul(self, scale: T) -> Self::Output {
1725 vec3(self.x * scale, self.y * scale, self.z * scale)
1726 }
1727 }
1728
1729 impl<T: Copy + Mul<T, Output = T>, U> MulAssign<T> for Vector3D<T, U> {
1730 #[inline]
1731 fn mul_assign(&mut self, scale: T) {
1732 *self = *self * scale
1733 }
1734 }
1735
1736 impl<T: Copy + Mul, U1, U2> Mul<Scale<T, U1, U2>> for Vector3D<T, U1> {
1737 type Output = Vector3D<T::Output, U2>;
1738
1739 #[inline]
1740 fn mul(self, scale: Scale<T, U1, U2>) -> Self::Output {
1741 vec3(self.x * scale.0, self.y * scale.0, self.z * scale.0)
1742 }
1743 }
1744
1745 impl<T: Copy + MulAssign, U> MulAssign<Scale<T, U, U>> for Vector3D<T, U> {
1746 #[inline]
1747 fn mul_assign(&mut self, scale: Scale<T, U, U>) {
1748 self.x *= scale.0;
1749 self.y *= scale.0;
1750 self.z *= scale.0;
1751 }
1752 }
1753
1754 impl<T: Copy + Div, U> Div<T> for Vector3D<T, U> {
1755 type Output = Vector3D<T::Output, U>;
1756
1757 #[inline]
1758 fn div(self, scale: T) -> Self::Output {
1759 vec3(self.x / scale, self.y / scale, self.z / scale)
1760 }
1761 }
1762
1763 impl<T: Copy + Div<T, Output = T>, U> DivAssign<T> for Vector3D<T, U> {
1764 #[inline]
1765 fn div_assign(&mut self, scale: T) {
1766 *self = *self / scale
1767 }
1768 }
1769
1770 impl<T: Copy + Div, U1, U2> Div<Scale<T, U1, U2>> for Vector3D<T, U2> {
1771 type Output = Vector3D<T::Output, U1>;
1772
1773 #[inline]
1774 fn div(self, scale: Scale<T, U1, U2>) -> Self::Output {
1775 vec3(self.x / scale.0, self.y / scale.0, self.z / scale.0)
1776 }
1777 }
1778
1779 impl<T: Copy + DivAssign, U> DivAssign<Scale<T, U, U>> for Vector3D<T, U> {
1780 #[inline]
1781 fn div_assign(&mut self, scale: Scale<T, U, U>) {
1782 self.x /= scale.0;
1783 self.y /= scale.0;
1784 self.z /= scale.0;
1785 }
1786 }
1787
1788 impl<T: Round, U> Round for Vector3D<T, U> {
1789 /// See [`Vector3D::round()`](#method.round)
1790 #[inline]
1791 fn round(self) -> Self {
1792 self.round()
1793 }
1794 }
1795
1796 impl<T: Ceil, U> Ceil for Vector3D<T, U> {
1797 /// See [`Vector3D::ceil()`](#method.ceil)
1798 #[inline]
1799 fn ceil(self) -> Self {
1800 self.ceil()
1801 }
1802 }
1803
1804 impl<T: Floor, U> Floor for Vector3D<T, U> {
1805 /// See [`Vector3D::floor()`](#method.floor)
1806 #[inline]
1807 fn floor(self) -> Self {
1808 self.floor()
1809 }
1810 }
1811
1812 impl<T: ApproxEq<T>, U> ApproxEq<Vector3D<T, U>> for Vector3D<T, U> {
1813 #[inline]
1814 fn approx_epsilon() -> Self {
1815 vec3(
1816 T::approx_epsilon(),
1817 T::approx_epsilon(),
1818 T::approx_epsilon(),
1819 )
1820 }
1821
1822 #[inline]
1823 fn approx_eq_eps(&self, other: &Self, eps: &Self) -> bool {
1824 self.x.approx_eq_eps(&other.x, &eps.x)
1825 && self.y.approx_eq_eps(&other.y, &eps.y)
1826 && self.z.approx_eq_eps(&other.z, &eps.z)
1827 }
1828 }
1829
1830 impl<T, U> From<Vector3D<T, U>> for [T; 3] {
1831 fn from(v: Vector3D<T, U>) -> Self {
1832 [v.x, v.y, v.z]
1833 }
1834 }
1835
1836 impl<T, U> From<[T; 3]> for Vector3D<T, U> {
1837 fn from([x, y, z]: [T; 3]) -> Self {
1838 vec3(x, y, z)
1839 }
1840 }
1841
1842 impl<T, U> From<Vector3D<T, U>> for (T, T, T) {
1843 fn from(v: Vector3D<T, U>) -> Self {
1844 (v.x, v.y, v.z)
1845 }
1846 }
1847
1848 impl<T, U> From<(T, T, T)> for Vector3D<T, U> {
1849 fn from(tuple: (T, T, T)) -> Self {
1850 vec3(tuple.0, tuple.1, tuple.2)
1851 }
1852 }
1853
1854 /// A 2d vector of booleans, useful for component-wise logic operations.
1855 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
1856 pub struct BoolVector2D {
1857 pub x: bool,
1858 pub y: bool,
1859 }
1860
1861 /// A 3d vector of booleans, useful for component-wise logic operations.
1862 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
1863 pub struct BoolVector3D {
1864 pub x: bool,
1865 pub y: bool,
1866 pub z: bool,
1867 }
1868
1869 impl BoolVector2D {
1870 /// Returns `true` if all components are `true` and `false` otherwise.
1871 #[inline]
1872 pub fn all(self) -> bool {
1873 self.x && self.y
1874 }
1875
1876 /// Returns `true` if any component are `true` and `false` otherwise.
1877 #[inline]
1878 pub fn any(self) -> bool {
1879 self.x || self.y
1880 }
1881
1882 /// Returns `true` if all components are `false` and `false` otherwise. Negation of `any()`.
1883 #[inline]
1884 pub fn none(self) -> bool {
1885 !self.any()
1886 }
1887
1888 /// Returns new vector with by-component AND operation applied.
1889 #[inline]
1890 pub fn and(self, other: Self) -> Self {
1891 BoolVector2D {
1892 x: self.x && other.x,
1893 y: self.y && other.y,
1894 }
1895 }
1896
1897 /// Returns new vector with by-component OR operation applied.
1898 #[inline]
1899 pub fn or(self, other: Self) -> Self {
1900 BoolVector2D {
1901 x: self.x || other.x,
1902 y: self.y || other.y,
1903 }
1904 }
1905
1906 /// Returns new vector with results of negation operation on each component.
1907 #[inline]
1908 pub fn not(self) -> Self {
1909 BoolVector2D {
1910 x: !self.x,
1911 y: !self.y,
1912 }
1913 }
1914
1915 /// Returns point, each component of which or from `a`, or from `b` depending on truly value
1916 /// of corresponding vector component. `true` selects value from `a` and `false` from `b`.
1917 #[inline]
1918 pub fn select_point<T, U>(self, a: Point2D<T, U>, b: Point2D<T, U>) -> Point2D<T, U> {
1919 point2(
1920 if self.x { a.x } else { b.x },
1921 if self.y { a.y } else { b.y },
1922 )
1923 }
1924
1925 /// Returns vector, each component of which or from `a`, or from `b` depending on truly value
1926 /// of corresponding vector component. `true` selects value from `a` and `false` from `b`.
1927 #[inline]
1928 pub fn select_vector<T, U>(self, a: Vector2D<T, U>, b: Vector2D<T, U>) -> Vector2D<T, U> {
1929 vec2(
1930 if self.x { a.x } else { b.x },
1931 if self.y { a.y } else { b.y },
1932 )
1933 }
1934
1935 /// Returns size, each component of which or from `a`, or from `b` depending on truly value
1936 /// of corresponding vector component. `true` selects value from `a` and `false` from `b`.
1937 #[inline]
1938 pub fn select_size<T, U>(self, a: Size2D<T, U>, b: Size2D<T, U>) -> Size2D<T, U> {
1939 size2(
1940 if self.x { a.width } else { b.width },
1941 if self.y { a.height } else { b.height },
1942 )
1943 }
1944 }
1945
1946 impl BoolVector3D {
1947 /// Returns `true` if all components are `true` and `false` otherwise.
1948 #[inline]
1949 pub fn all(self) -> bool {
1950 self.x && self.y && self.z
1951 }
1952
1953 /// Returns `true` if any component are `true` and `false` otherwise.
1954 #[inline]
1955 pub fn any(self) -> bool {
1956 self.x || self.y || self.z
1957 }
1958
1959 /// Returns `true` if all components are `false` and `false` otherwise. Negation of `any()`.
1960 #[inline]
1961 pub fn none(self) -> bool {
1962 !self.any()
1963 }
1964
1965 /// Returns new vector with by-component AND operation applied.
1966 #[inline]
1967 pub fn and(self, other: Self) -> Self {
1968 BoolVector3D {
1969 x: self.x && other.x,
1970 y: self.y && other.y,
1971 z: self.z && other.z,
1972 }
1973 }
1974
1975 /// Returns new vector with by-component OR operation applied.
1976 #[inline]
1977 pub fn or(self, other: Self) -> Self {
1978 BoolVector3D {
1979 x: self.x || other.x,
1980 y: self.y || other.y,
1981 z: self.z || other.z,
1982 }
1983 }
1984
1985 /// Returns new vector with results of negation operation on each component.
1986 #[inline]
1987 pub fn not(self) -> Self {
1988 BoolVector3D {
1989 x: !self.x,
1990 y: !self.y,
1991 z: !self.z,
1992 }
1993 }
1994
1995 /// Returns point, each component of which or from `a`, or from `b` depending on truly value
1996 /// of corresponding vector component. `true` selects value from `a` and `false` from `b`.
1997 #[inline]
1998 pub fn select_point<T, U>(self, a: Point3D<T, U>, b: Point3D<T, U>) -> Point3D<T, U> {
1999 point3(
2000 if self.x { a.x } else { b.x },
2001 if self.y { a.y } else { b.y },
2002 if self.z { a.z } else { b.z },
2003 )
2004 }
2005
2006 /// Returns vector, each component of which or from `a`, or from `b` depending on truly value
2007 /// of corresponding vector component. `true` selects value from `a` and `false` from `b`.
2008 #[inline]
2009 pub fn select_vector<T, U>(self, a: Vector3D<T, U>, b: Vector3D<T, U>) -> Vector3D<T, U> {
2010 vec3(
2011 if self.x { a.x } else { b.x },
2012 if self.y { a.y } else { b.y },
2013 if self.z { a.z } else { b.z },
2014 )
2015 }
2016
2017 /// Returns size, each component of which or from `a`, or from `b` depending on truly value
2018 /// of corresponding vector component. `true` selects value from `a` and `false` from `b`.
2019 #[inline]
2020 #[must_use]
2021 pub fn select_size<T, U>(self, a: Size3D<T, U>, b: Size3D<T, U>) -> Size3D<T, U> {
2022 size3(
2023 if self.x { a.width } else { b.width },
2024 if self.y { a.height } else { b.height },
2025 if self.z { a.depth } else { b.depth },
2026 )
2027 }
2028
2029 /// Returns a 2d vector using this vector's x and y coordinates.
2030 #[inline]
2031 pub fn xy(self) -> BoolVector2D {
2032 BoolVector2D {
2033 x: self.x,
2034 y: self.y,
2035 }
2036 }
2037
2038 /// Returns a 2d vector using this vector's x and z coordinates.
2039 #[inline]
2040 pub fn xz(self) -> BoolVector2D {
2041 BoolVector2D {
2042 x: self.x,
2043 y: self.z,
2044 }
2045 }
2046
2047 /// Returns a 2d vector using this vector's y and z coordinates.
2048 #[inline]
2049 pub fn yz(self) -> BoolVector2D {
2050 BoolVector2D {
2051 x: self.y,
2052 y: self.z,
2053 }
2054 }
2055 }
2056
2057 /// Convenience constructor.
2058 #[inline]
2059 pub const fn vec2<T, U>(x: T, y: T) -> Vector2D<T, U> {
2060 Vector2D {
2061 x,
2062 y,
2063 _unit: PhantomData,
2064 }
2065 }
2066
2067 /// Convenience constructor.
2068 #[inline]
2069 pub const fn vec3<T, U>(x: T, y: T, z: T) -> Vector3D<T, U> {
2070 Vector3D {
2071 x,
2072 y,
2073 z,
2074 _unit: PhantomData,
2075 }
2076 }
2077
2078 /// Shorthand for `BoolVector2D { x, y }`.
2079 #[inline]
2080 pub const fn bvec2(x: bool, y: bool) -> BoolVector2D {
2081 BoolVector2D { x, y }
2082 }
2083
2084 /// Shorthand for `BoolVector3D { x, y, z }`.
2085 #[inline]
2086 pub const fn bvec3(x: bool, y: bool, z: bool) -> BoolVector3D {
2087 BoolVector3D { x, y, z }
2088 }
2089
2090 #[cfg(test)]
2091 mod vector2d {
2092 use crate::scale::Scale;
2093 use crate::{default, vec2};
2094
2095 #[cfg(feature = "mint")]
2096 use mint;
2097 type Vec2 = default::Vector2D<f32>;
2098
2099 #[test]
2100 pub fn test_scalar_mul() {
2101 let p1: Vec2 = vec2(3.0, 5.0);
2102
2103 let result = p1 * 5.0;
2104
2105 assert_eq!(result, Vec2::new(15.0, 25.0));
2106 }
2107
2108 #[test]
2109 pub fn test_dot() {
2110 let p1: Vec2 = vec2(2.0, 7.0);
2111 let p2: Vec2 = vec2(13.0, 11.0);
2112 assert_eq!(p1.dot(p2), 103.0);
2113 }
2114
2115 #[test]
2116 pub fn test_cross() {
2117 let p1: Vec2 = vec2(4.0, 7.0);
2118 let p2: Vec2 = vec2(13.0, 8.0);
2119 let r = p1.cross(p2);
2120 assert_eq!(r, -59.0);
2121 }
2122
2123 #[test]
2124 pub fn test_normalize() {
2125 use std::f32;
2126
2127 let p0: Vec2 = Vec2::zero();
2128 let p1: Vec2 = vec2(4.0, 0.0);
2129 let p2: Vec2 = vec2(3.0, -4.0);
2130 assert!(p0.normalize().x.is_nan() && p0.normalize().y.is_nan());
2131 assert_eq!(p1.normalize(), vec2(1.0, 0.0));
2132 assert_eq!(p2.normalize(), vec2(0.6, -0.8));
2133
2134 let p3: Vec2 = vec2(::std::f32::MAX, ::std::f32::MAX);
2135 assert_ne!(
2136 p3.normalize(),
2137 vec2(1.0 / 2.0f32.sqrt(), 1.0 / 2.0f32.sqrt())
2138 );
2139 assert_eq!(
2140 p3.robust_normalize(),
2141 vec2(1.0 / 2.0f32.sqrt(), 1.0 / 2.0f32.sqrt())
2142 );
2143
2144 let p4: Vec2 = Vec2::zero();
2145 assert!(p4.try_normalize().is_none());
2146 let p5: Vec2 = Vec2::new(f32::MIN_POSITIVE, f32::MIN_POSITIVE);
2147 assert!(p5.try_normalize().is_none());
2148
2149 let p6: Vec2 = vec2(4.0, 0.0);
2150 let p7: Vec2 = vec2(3.0, -4.0);
2151 assert_eq!(p6.try_normalize().unwrap(), vec2(1.0, 0.0));
2152 assert_eq!(p7.try_normalize().unwrap(), vec2(0.6, -0.8));
2153 }
2154
2155 #[test]
2156 pub fn test_min() {
2157 let p1: Vec2 = vec2(1.0, 3.0);
2158 let p2: Vec2 = vec2(2.0, 2.0);
2159
2160 let result = p1.min(p2);
2161
2162 assert_eq!(result, vec2(1.0, 2.0));
2163 }
2164
2165 #[test]
2166 pub fn test_max() {
2167 let p1: Vec2 = vec2(1.0, 3.0);
2168 let p2: Vec2 = vec2(2.0, 2.0);
2169
2170 let result = p1.max(p2);
2171
2172 assert_eq!(result, vec2(2.0, 3.0));
2173 }
2174
2175 #[test]
2176 pub fn test_angle_from_x_axis() {
2177 use crate::approxeq::ApproxEq;
2178 use core::f32::consts::FRAC_PI_2;
2179
2180 let right: Vec2 = vec2(10.0, 0.0);
2181 let down: Vec2 = vec2(0.0, 4.0);
2182 let up: Vec2 = vec2(0.0, -1.0);
2183
2184 assert!(right.angle_from_x_axis().get().approx_eq(&0.0));
2185 assert!(down.angle_from_x_axis().get().approx_eq(&FRAC_PI_2));
2186 assert!(up.angle_from_x_axis().get().approx_eq(&-FRAC_PI_2));
2187 }
2188
2189 #[test]
2190 pub fn test_angle_to() {
2191 use crate::approxeq::ApproxEq;
2192 use core::f32::consts::FRAC_PI_2;
2193
2194 let right: Vec2 = vec2(10.0, 0.0);
2195 let right2: Vec2 = vec2(1.0, 0.0);
2196 let up: Vec2 = vec2(0.0, -1.0);
2197 let up_left: Vec2 = vec2(-1.0, -1.0);
2198
2199 assert!(right.angle_to(right2).get().approx_eq(&0.0));
2200 assert!(right.angle_to(up).get().approx_eq(&-FRAC_PI_2));
2201 assert!(up.angle_to(right).get().approx_eq(&FRAC_PI_2));
2202 assert!(up_left
2203 .angle_to(up)
2204 .get()
2205 .approx_eq_eps(&(0.5 * FRAC_PI_2), &0.0005));
2206 }
2207
2208 #[test]
2209 pub fn test_with_max_length() {
2210 use crate::approxeq::ApproxEq;
2211
2212 let v1: Vec2 = vec2(0.5, 0.5);
2213 let v2: Vec2 = vec2(1.0, 0.0);
2214 let v3: Vec2 = vec2(0.1, 0.2);
2215 let v4: Vec2 = vec2(2.0, -2.0);
2216 let v5: Vec2 = vec2(1.0, 2.0);
2217 let v6: Vec2 = vec2(-1.0, 3.0);
2218
2219 assert_eq!(v1.with_max_length(1.0), v1);
2220 assert_eq!(v2.with_max_length(1.0), v2);
2221 assert_eq!(v3.with_max_length(1.0), v3);
2222 assert_eq!(v4.with_max_length(10.0), v4);
2223 assert_eq!(v5.with_max_length(10.0), v5);
2224 assert_eq!(v6.with_max_length(10.0), v6);
2225
2226 let v4_clamped = v4.with_max_length(1.0);
2227 assert!(v4_clamped.length().approx_eq(&1.0));
2228 assert!(v4_clamped.normalize().approx_eq(&v4.normalize()));
2229
2230 let v5_clamped = v5.with_max_length(1.5);
2231 assert!(v5_clamped.length().approx_eq(&1.5));
2232 assert!(v5_clamped.normalize().approx_eq(&v5.normalize()));
2233
2234 let v6_clamped = v6.with_max_length(2.5);
2235 assert!(v6_clamped.length().approx_eq(&2.5));
2236 assert!(v6_clamped.normalize().approx_eq(&v6.normalize()));
2237 }
2238
2239 #[test]
2240 pub fn test_project_onto_vector() {
2241 use crate::approxeq::ApproxEq;
2242
2243 let v1: Vec2 = vec2(1.0, 2.0);
2244 let x: Vec2 = vec2(1.0, 0.0);
2245 let y: Vec2 = vec2(0.0, 1.0);
2246
2247 assert!(v1.project_onto_vector(x).approx_eq(&vec2(1.0, 0.0)));
2248 assert!(v1.project_onto_vector(y).approx_eq(&vec2(0.0, 2.0)));
2249 assert!(v1.project_onto_vector(-x).approx_eq(&vec2(1.0, 0.0)));
2250 assert!(v1.project_onto_vector(x * 10.0).approx_eq(&vec2(1.0, 0.0)));
2251 assert!(v1.project_onto_vector(v1 * 2.0).approx_eq(&v1));
2252 assert!(v1.project_onto_vector(-v1).approx_eq(&v1));
2253 }
2254
2255 #[cfg(feature = "mint")]
2256 #[test]
2257 pub fn test_mint() {
2258 let v1 = Vec2::new(1.0, 3.0);
2259 let vm: mint::Vector2<_> = v1.into();
2260 let v2 = Vec2::from(vm);
2261
2262 assert_eq!(v1, v2);
2263 }
2264
2265 pub enum Mm {}
2266 pub enum Cm {}
2267
2268 pub type Vector2DMm<T> = super::Vector2D<T, Mm>;
2269 pub type Vector2DCm<T> = super::Vector2D<T, Cm>;
2270
2271 #[test]
2272 pub fn test_add() {
2273 let p1 = Vector2DMm::new(1.0, 2.0);
2274 let p2 = Vector2DMm::new(3.0, 4.0);
2275
2276 assert_eq!(p1 + p2, vec2(4.0, 6.0));
2277 assert_eq!(p1 + &p2, vec2(4.0, 6.0));
2278 }
2279
2280 #[test]
2281 pub fn test_sum() {
2282 let vecs = [
2283 Vector2DMm::new(1.0, 2.0),
2284 Vector2DMm::new(3.0, 4.0),
2285 Vector2DMm::new(5.0, 6.0),
2286 ];
2287 let sum = Vector2DMm::new(9.0, 12.0);
2288 assert_eq!(vecs.iter().sum::<Vector2DMm<_>>(), sum);
2289 }
2290
2291 #[test]
2292 pub fn test_add_assign() {
2293 let mut p1 = Vector2DMm::new(1.0, 2.0);
2294 p1 += vec2(3.0, 4.0);
2295
2296 assert_eq!(p1, vec2(4.0, 6.0));
2297 }
2298
2299 #[test]
2300 pub fn test_typed_scalar_mul() {
2301 let p1 = Vector2DMm::new(1.0, 2.0);
2302 let cm_per_mm = Scale::<f32, Mm, Cm>::new(0.1);
2303
2304 let result: Vector2DCm<f32> = p1 * cm_per_mm;
2305
2306 assert_eq!(result, vec2(0.1, 0.2));
2307 }
2308
2309 #[test]
2310 pub fn test_swizzling() {
2311 let p: default::Vector2D<i32> = vec2(1, 2);
2312 assert_eq!(p.yx(), vec2(2, 1));
2313 }
2314
2315 #[test]
2316 pub fn test_reflect() {
2317 use crate::approxeq::ApproxEq;
2318 let a: Vec2 = vec2(1.0, 3.0);
2319 let n1: Vec2 = vec2(0.0, -1.0);
2320 let n2: Vec2 = vec2(1.0, -1.0).normalize();
2321
2322 assert!(a.reflect(n1).approx_eq(&vec2(1.0, -3.0)));
2323 assert!(a.reflect(n2).approx_eq(&vec2(3.0, 1.0)));
2324 }
2325 }
2326
2327 #[cfg(test)]
2328 mod vector3d {
2329 use crate::scale::Scale;
2330 use crate::{default, vec2, vec3};
2331 #[cfg(feature = "mint")]
2332 use mint;
2333
2334 type Vec3 = default::Vector3D<f32>;
2335
2336 #[test]
2337 pub fn test_add() {
2338 let p1 = Vec3::new(1.0, 2.0, 3.0);
2339 let p2 = Vec3::new(4.0, 5.0, 6.0);
2340
2341 assert_eq!(p1 + p2, vec3(5.0, 7.0, 9.0));
2342 assert_eq!(p1 + &p2, vec3(5.0, 7.0, 9.0));
2343 }
2344
2345 #[test]
2346 pub fn test_sum() {
2347 let vecs = [
2348 Vec3::new(1.0, 2.0, 3.0),
2349 Vec3::new(4.0, 5.0, 6.0),
2350 Vec3::new(7.0, 8.0, 9.0),
2351 ];
2352 let sum = Vec3::new(12.0, 15.0, 18.0);
2353 assert_eq!(vecs.iter().sum::<Vec3>(), sum);
2354 }
2355
2356 #[test]
2357 pub fn test_dot() {
2358 let p1: Vec3 = vec3(7.0, 21.0, 32.0);
2359 let p2: Vec3 = vec3(43.0, 5.0, 16.0);
2360 assert_eq!(p1.dot(p2), 918.0);
2361 }
2362
2363 #[test]
2364 pub fn test_cross() {
2365 let p1: Vec3 = vec3(4.0, 7.0, 9.0);
2366 let p2: Vec3 = vec3(13.0, 8.0, 3.0);
2367 let p3 = p1.cross(p2);
2368 assert_eq!(p3, vec3(-51.0, 105.0, -59.0));
2369 }
2370
2371 #[test]
2372 pub fn test_normalize() {
2373 use std::f32;
2374
2375 let p0: Vec3 = Vec3::zero();
2376 let p1: Vec3 = vec3(0.0, -6.0, 0.0);
2377 let p2: Vec3 = vec3(1.0, 2.0, -2.0);
2378 assert!(
2379 p0.normalize().x.is_nan() && p0.normalize().y.is_nan() && p0.normalize().z.is_nan()
2380 );
2381 assert_eq!(p1.normalize(), vec3(0.0, -1.0, 0.0));
2382 assert_eq!(p2.normalize(), vec3(1.0 / 3.0, 2.0 / 3.0, -2.0 / 3.0));
2383
2384 let p3: Vec3 = vec3(::std::f32::MAX, ::std::f32::MAX, 0.0);
2385 assert_ne!(
2386 p3.normalize(),
2387 vec3(1.0 / 2.0f32.sqrt(), 1.0 / 2.0f32.sqrt(), 0.0)
2388 );
2389 assert_eq!(
2390 p3.robust_normalize(),
2391 vec3(1.0 / 2.0f32.sqrt(), 1.0 / 2.0f32.sqrt(), 0.0)
2392 );
2393
2394 let p4: Vec3 = Vec3::zero();
2395 assert!(p4.try_normalize().is_none());
2396 let p5: Vec3 = Vec3::new(f32::MIN_POSITIVE, f32::MIN_POSITIVE, f32::MIN_POSITIVE);
2397 assert!(p5.try_normalize().is_none());
2398
2399 let p6: Vec3 = vec3(4.0, 0.0, 3.0);
2400 let p7: Vec3 = vec3(3.0, -4.0, 0.0);
2401 assert_eq!(p6.try_normalize().unwrap(), vec3(0.8, 0.0, 0.6));
2402 assert_eq!(p7.try_normalize().unwrap(), vec3(0.6, -0.8, 0.0));
2403 }
2404
2405 #[test]
2406 pub fn test_min() {
2407 let p1: Vec3 = vec3(1.0, 3.0, 5.0);
2408 let p2: Vec3 = vec3(2.0, 2.0, -1.0);
2409
2410 let result = p1.min(p2);
2411
2412 assert_eq!(result, vec3(1.0, 2.0, -1.0));
2413 }
2414
2415 #[test]
2416 pub fn test_max() {
2417 let p1: Vec3 = vec3(1.0, 3.0, 5.0);
2418 let p2: Vec3 = vec3(2.0, 2.0, -1.0);
2419
2420 let result = p1.max(p2);
2421
2422 assert_eq!(result, vec3(2.0, 3.0, 5.0));
2423 }
2424
2425 #[test]
2426 pub fn test_clamp() {
2427 let p1: Vec3 = vec3(1.0, -1.0, 5.0);
2428 let p2: Vec3 = vec3(2.0, 5.0, 10.0);
2429 let p3: Vec3 = vec3(-1.0, 2.0, 20.0);
2430
2431 let result = p3.clamp(p1, p2);
2432
2433 assert_eq!(result, vec3(1.0, 2.0, 10.0));
2434 }
2435
2436 #[test]
2437 pub fn test_typed_scalar_mul() {
2438 enum Mm {}
2439 enum Cm {}
2440
2441 let p1 = super::Vector3D::<f32, Mm>::new(1.0, 2.0, 3.0);
2442 let cm_per_mm = Scale::<f32, Mm, Cm>::new(0.1);
2443
2444 let result: super::Vector3D<f32, Cm> = p1 * cm_per_mm;
2445
2446 assert_eq!(result, vec3(0.1, 0.2, 0.3));
2447 }
2448
2449 #[test]
2450 pub fn test_swizzling() {
2451 let p: Vec3 = vec3(1.0, 2.0, 3.0);
2452 assert_eq!(p.xy(), vec2(1.0, 2.0));
2453 assert_eq!(p.xz(), vec2(1.0, 3.0));
2454 assert_eq!(p.yz(), vec2(2.0, 3.0));
2455 }
2456
2457 #[cfg(feature = "mint")]
2458 #[test]
2459 pub fn test_mint() {
2460 let v1 = Vec3::new(1.0, 3.0, 5.0);
2461 let vm: mint::Vector3<_> = v1.into();
2462 let v2 = Vec3::from(vm);
2463
2464 assert_eq!(v1, v2);
2465 }
2466
2467 #[test]
2468 pub fn test_reflect() {
2469 use crate::approxeq::ApproxEq;
2470 let a: Vec3 = vec3(1.0, 3.0, 2.0);
2471 let n1: Vec3 = vec3(0.0, -1.0, 0.0);
2472 let n2: Vec3 = vec3(0.0, 1.0, 1.0).normalize();
2473
2474 assert!(a.reflect(n1).approx_eq(&vec3(1.0, -3.0, 2.0)));
2475 assert!(a.reflect(n2).approx_eq(&vec3(1.0, -2.0, -3.0)));
2476 }
2477
2478 #[test]
2479 pub fn test_angle_to() {
2480 use crate::approxeq::ApproxEq;
2481 use core::f32::consts::FRAC_PI_2;
2482
2483 let right: Vec3 = vec3(10.0, 0.0, 0.0);
2484 let right2: Vec3 = vec3(1.0, 0.0, 0.0);
2485 let up: Vec3 = vec3(0.0, -1.0, 0.0);
2486 let up_left: Vec3 = vec3(-1.0, -1.0, 0.0);
2487
2488 assert!(right.angle_to(right2).get().approx_eq(&0.0));
2489 assert!(right.angle_to(up).get().approx_eq(&FRAC_PI_2));
2490 assert!(up.angle_to(right).get().approx_eq(&FRAC_PI_2));
2491 assert!(up_left
2492 .angle_to(up)
2493 .get()
2494 .approx_eq_eps(&(0.5 * FRAC_PI_2), &0.0005));
2495 }
2496
2497 #[test]
2498 pub fn test_with_max_length() {
2499 use crate::approxeq::ApproxEq;
2500
2501 let v1: Vec3 = vec3(0.5, 0.5, 0.0);
2502 let v2: Vec3 = vec3(1.0, 0.0, 0.0);
2503 let v3: Vec3 = vec3(0.1, 0.2, 0.3);
2504 let v4: Vec3 = vec3(2.0, -2.0, 2.0);
2505 let v5: Vec3 = vec3(1.0, 2.0, -3.0);
2506 let v6: Vec3 = vec3(-1.0, 3.0, 2.0);
2507
2508 assert_eq!(v1.with_max_length(1.0), v1);
2509 assert_eq!(v2.with_max_length(1.0), v2);
2510 assert_eq!(v3.with_max_length(1.0), v3);
2511 assert_eq!(v4.with_max_length(10.0), v4);
2512 assert_eq!(v5.with_max_length(10.0), v5);
2513 assert_eq!(v6.with_max_length(10.0), v6);
2514
2515 let v4_clamped = v4.with_max_length(1.0);
2516 assert!(v4_clamped.length().approx_eq(&1.0));
2517 assert!(v4_clamped.normalize().approx_eq(&v4.normalize()));
2518
2519 let v5_clamped = v5.with_max_length(1.5);
2520 assert!(v5_clamped.length().approx_eq(&1.5));
2521 assert!(v5_clamped.normalize().approx_eq(&v5.normalize()));
2522
2523 let v6_clamped = v6.with_max_length(2.5);
2524 assert!(v6_clamped.length().approx_eq(&2.5));
2525 assert!(v6_clamped.normalize().approx_eq(&v6.normalize()));
2526 }
2527
2528 #[test]
2529 pub fn test_project_onto_vector() {
2530 use crate::approxeq::ApproxEq;
2531
2532 let v1: Vec3 = vec3(1.0, 2.0, 3.0);
2533 let x: Vec3 = vec3(1.0, 0.0, 0.0);
2534 let y: Vec3 = vec3(0.0, 1.0, 0.0);
2535 let z: Vec3 = vec3(0.0, 0.0, 1.0);
2536
2537 assert!(v1.project_onto_vector(x).approx_eq(&vec3(1.0, 0.0, 0.0)));
2538 assert!(v1.project_onto_vector(y).approx_eq(&vec3(0.0, 2.0, 0.0)));
2539 assert!(v1.project_onto_vector(z).approx_eq(&vec3(0.0, 0.0, 3.0)));
2540 assert!(v1.project_onto_vector(-x).approx_eq(&vec3(1.0, 0.0, 0.0)));
2541 assert!(v1
2542 .project_onto_vector(x * 10.0)
2543 .approx_eq(&vec3(1.0, 0.0, 0.0)));
2544 assert!(v1.project_onto_vector(v1 * 2.0).approx_eq(&v1));
2545 assert!(v1.project_onto_vector(-v1).approx_eq(&v1));
2546 }
2547 }
2548
2549 #[cfg(test)]
2550 mod bool_vector {
2551 use super::*;
2552 use crate::default;
2553 type Vec2 = default::Vector2D<f32>;
2554 type Vec3 = default::Vector3D<f32>;
2555
2556 #[test]
2557 fn test_bvec2() {
2558 assert_eq!(
2559 Vec2::new(1.0, 2.0).greater_than(Vec2::new(2.0, 1.0)),
2560 bvec2(false, true),
2561 );
2562
2563 assert_eq!(
2564 Vec2::new(1.0, 2.0).lower_than(Vec2::new(2.0, 1.0)),
2565 bvec2(true, false),
2566 );
2567
2568 assert_eq!(
2569 Vec2::new(1.0, 2.0).equal(Vec2::new(1.0, 3.0)),
2570 bvec2(true, false),
2571 );
2572
2573 assert_eq!(
2574 Vec2::new(1.0, 2.0).not_equal(Vec2::new(1.0, 3.0)),
2575 bvec2(false, true),
2576 );
2577
2578 assert!(bvec2(true, true).any());
2579 assert!(bvec2(false, true).any());
2580 assert!(bvec2(true, false).any());
2581 assert!(!bvec2(false, false).any());
2582 assert!(bvec2(false, false).none());
2583 assert!(bvec2(true, true).all());
2584 assert!(!bvec2(false, true).all());
2585 assert!(!bvec2(true, false).all());
2586 assert!(!bvec2(false, false).all());
2587
2588 assert_eq!(bvec2(true, false).not(), bvec2(false, true));
2589 assert_eq!(
2590 bvec2(true, false).and(bvec2(true, true)),
2591 bvec2(true, false)
2592 );
2593 assert_eq!(bvec2(true, false).or(bvec2(true, true)), bvec2(true, true));
2594
2595 assert_eq!(
2596 bvec2(true, false).select_vector(Vec2::new(1.0, 2.0), Vec2::new(3.0, 4.0)),
2597 Vec2::new(1.0, 4.0),
2598 );
2599 }
2600
2601 #[test]
2602 fn test_bvec3() {
2603 assert_eq!(
2604 Vec3::new(1.0, 2.0, 3.0).greater_than(Vec3::new(3.0, 2.0, 1.0)),
2605 bvec3(false, false, true),
2606 );
2607
2608 assert_eq!(
2609 Vec3::new(1.0, 2.0, 3.0).lower_than(Vec3::new(3.0, 2.0, 1.0)),
2610 bvec3(true, false, false),
2611 );
2612
2613 assert_eq!(
2614 Vec3::new(1.0, 2.0, 3.0).equal(Vec3::new(3.0, 2.0, 1.0)),
2615 bvec3(false, true, false),
2616 );
2617
2618 assert_eq!(
2619 Vec3::new(1.0, 2.0, 3.0).not_equal(Vec3::new(3.0, 2.0, 1.0)),
2620 bvec3(true, false, true),
2621 );
2622
2623 assert!(bvec3(true, true, false).any());
2624 assert!(bvec3(false, true, false).any());
2625 assert!(bvec3(true, false, false).any());
2626 assert!(!bvec3(false, false, false).any());
2627 assert!(bvec3(false, false, false).none());
2628 assert!(bvec3(true, true, true).all());
2629 assert!(!bvec3(false, true, false).all());
2630 assert!(!bvec3(true, false, false).all());
2631 assert!(!bvec3(false, false, false).all());
2632
2633 assert_eq!(bvec3(true, false, true).not(), bvec3(false, true, false));
2634 assert_eq!(
2635 bvec3(true, false, true).and(bvec3(true, true, false)),
2636 bvec3(true, false, false)
2637 );
2638 assert_eq!(
2639 bvec3(true, false, false).or(bvec3(true, true, false)),
2640 bvec3(true, true, false)
2641 );
2642
2643 assert_eq!(
2644 bvec3(true, false, true)
2645 .select_vector(Vec3::new(1.0, 2.0, 3.0), Vec3::new(4.0, 5.0, 6.0)),
2646 Vec3::new(1.0, 5.0, 3.0),
2647 );
2648 }
2649 }