maths_rs/
vec.rs

1use std::ops::Index;
2use std::ops::IndexMut;
3use std::ops::Mul;
4use std::ops::MulAssign;
5use std::ops::Add;
6use std::ops::AddAssign;
7use std::ops::Sub;
8use std::ops::SubAssign;
9use std::ops::Div;
10use std::ops::DivAssign;
11use std::ops::Rem;
12use std::ops::RemAssign;
13use std::ops::Neg;
14use std::ops::Deref;
15use std::ops::DerefMut;
16
17use std::cmp::PartialEq;
18
19use std::fmt::Display;
20use std::fmt::Formatter;
21
22use crate::num::*;
23
24//
25// Vec Traits
26//
27
28/// generic vec trait to allow sized vectors to be treated generically
29pub trait VecN<T: Number>:
30    Base<T> + Dot<T> +
31    Index<usize, Output=T> + IndexMut<usize> +
32    Add<T, Output=Self> + Sub<T, Output=Self> +
33    Mul<T, Output=Self> + Div<T, Output=Self> {
34    /// returns the count of elements in the vector type
35    fn len() -> usize;
36    /// returns true if all elements in vector `a` are non-zero
37    fn all(a: Self) -> bool;
38    /// returns true if any element of the vector `a` is non-zero
39    fn any(a: Self) -> bool;
40    /// returns a vector initialised as a unit vector in the x-axis `[1, 0, 0, 0]`
41    fn unit_x() -> Self;
42    /// returns a vector initialised as a unit vector in the y-axis `[0, 1, 0, 0]`
43    fn unit_y() -> Self;
44    /// returns a vector initialised as a unit vector in the z-axis `[0, 0, 1, 0]` value will be truncated to 0 for vectors < 3 dimension
45    fn unit_z() -> Self;
46    /// returns a vector initialised as a unit vector in the w-axis `[0, 0, 0, 1]` value will be truncated to 0 for vectors < 4 dimension
47    fn unit_w() -> Self;
48    /// returns a vector initialised to red `[1, 0, 0, 1]`
49    fn red() -> Self;
50    /// returns a vector initialised to green `[0, 1, 0, 1]`
51    fn green() -> Self;
52    /// returns a vector initialised to blue `[0, 0, 1, 1]` value will be truncated to 0 for vectors < 3 dimension
53    fn blue() -> Self;
54    /// returns a vector initialised to cyan `[0, 1, 1, 1]` value will be truncated to green for vectors < 3 dimension
55    fn cyan() -> Self;
56    /// returns a vector initialised to magenta `[1, 0, 1, 1]` value will be truncated to red for vectors < 3 dimension
57    fn magenta() -> Self;
58    /// returns a vector initialised to yellow `[1, 1, 0, 0]`
59    fn yellow() -> Self;
60    /// returns a vector initialised to black (zero's)
61    fn black() -> Self;
62    /// returns a vector initialised to white (ones's)
63    fn white() -> Self;
64    /// returns a slice T of the vector
65    fn as_slice(&self) -> &[T];
66    /// returns a mutable slice T of the vector
67    fn as_mut_slice(&mut self) -> &mut [T];
68    /// returns a slice of bytes for the vector
69    fn as_u8_slice(&self) -> &[u8];
70    /// returns the largest scalar value component contained in the vector `a`
71    fn max_scalar(a: Self) -> T;
72    /// returns the smallest scalar value component contained in the vector `a`
73    fn min_scalar(a: Self) -> T;
74}
75
76/// trait for vectors of signed types to allow Neg
77pub trait SignedVecN<T: SignedNumber>: Neg<Output=Self> {
78    /// returns a vector initialised with -1
79    fn minus_one() -> Self;
80}
81
82/// trait for operations involve vector magnitude or dot product
83pub trait Magnitude<T: Float> {
84    /// returns scalar magnitude or length of vector `a`
85    fn length(a: Self) -> T;
86    /// returns scalar magnitude or length of vector `a`
87    fn mag(a: Self) -> T;
88    /// returns scalar magnitude or length of vector `a` squared to avoid using sqrt
89    fn mag2(a: Self) -> T;
90    /// returns a normalized unit vector of `a`
91    fn normalize(a: Self) -> Self;
92}
93
94/// operations to apply to n-dimensional vectors
95pub trait VecFloatOps<T: Float>: SignedVecN<T> + Magnitude<T> {
96    /// returns scalar distance between point `a` and `b` (magnitude of the vector between the 2 points)
97    fn distance(a: Self, b: Self) -> T;
98    /// returns scalar distance between point `a` and `b` (magnitude of the vector between the 2 points)
99    fn dist(a: Self, b: Self) -> T;
100    /// returns scalar squared distance between point `a` and `b` to avoid using sqrt
101    fn dist2(a: Self, b: Self) -> T;
102    /// returns a reflection vector using an incident ray `i` and a surface normal `n`
103    fn reflect(i: Self, n: Self) -> Self;
104    /// returns a refraction vector using an entering ray `i`, a surface normal `n`, and a refraction index `eta`
105    fn refract(i: Self, n: Self, eta: T) -> Self;
106    /// returns linear interpolation between `e0` and `e1`, `t` specifies the ratio to interpolate between the values, with component-wise `t`
107    fn vlerp(e0: Self, e1: Self, t: Self) -> Self;
108    /// returns vector with component wise hermite interpolation between `0-1`, with component-wise `t`
109    fn vsmoothstep(e0: Self, e1: Self, t: Self) -> Self;
110    /// returns vector `a` raised to component wise power `exp`
111    fn powfn(a: Self, exp: Self) -> Self;
112}
113
114/// trait for dot product
115pub trait Dot<T> {
116    /// vector dot-product
117    fn dot(a: Self, b: Self) -> T;
118}
119
120impl<T> Dot<T> for Vec2<T> where T: Number {
121    fn dot(a: Self, b: Self) -> T {
122        a.x * b.x + a.y * b.y
123    }
124}
125
126impl<T> Dot<T> for Vec3<T> where T: Number {
127    fn dot(a: Self, b: Self) -> T {
128        a.x * b.x + a.y * b.y + a.z * b.z
129    }
130}
131
132impl<T> Dot<T> for Vec4<T> where T: Number {
133    fn dot(a: Self, b: Self) -> T {
134        a.x * b.x + a.y * b.y + a.z * b.z + a.w * b.w
135    }
136}
137
138/// trait for cross product, this is implemented for Vec3
139pub trait Cross<T> {
140    /// vector cross-product
141    fn cross(a: Self, b: Self) -> Self;
142}
143
144impl<T> Cross<T> for Vec3<T> where T: Number {
145    fn cross(a: Self, b: Self) -> Self {
146        Vec3 {
147            x: (a.y * b.z) - (a.z * b.y),
148            y: (a.z * b.x) - (a.x * b.z),
149            z: (a.x * b.y) - (a.y * b.x),
150        }
151    }
152}
153
154/// trait for scalar and vector triple products
155pub trait Triple<T> {
156    /// scalar triple product
157    fn scalar_triple(a: Self, b: Self, c: Self) -> T;
158    /// vector triple product
159    fn vector_triple(a: Self, b: Self, c: Self) -> Self;
160}
161
162/// 3D triple products
163impl<T> Triple<T> for Vec3<T> where T: Number {
164    fn scalar_triple(a: Self, b: Self, c: Self) -> T {
165        a.x * (b.y * c.z - b.z * c.y) + a.y * (b.z * c.x - b.x * c.z) + a.z * (b.x * c.y - b.y * c.x)
166    }
167
168    fn vector_triple(a: Self, b: Self, c: Self) -> Self {
169        Self::cross(Self::cross(a, b), c)
170    }
171}
172
173/// 2D triple product specialisation, levearging z-axis
174impl<T> Triple<T> for Vec2<T> where T: Number + SignedNumber {
175    fn scalar_triple(_a: Self, b: Self, c: Self) -> T {
176        b.x * c.y - b.y * c.x
177    }
178
179    fn vector_triple(a: Self, b: Self, c: Self) -> Self {
180        let a3 = Vec3::<T>::new(a.x, a.y, T::zero());
181        let b3 = Vec3::<T>::new(b.x, b.y, T::zero());
182        let c3 = Vec3::<T>::new(c.x, c.y, T::zero());
183        let v3 = Vec3::<T>::cross(Vec3::<T>::cross(a3, b3), c3);
184        Self {
185            x: v3.x,
186            y: v3.y
187        }
188    }
189}
190
191/// trait for spherical interpolation, which is applicable with vec and quat
192pub trait Slerp<T: Float + FloatOps<T>> {
193    // spherically interpolate between edges `e0` and `e1` by percentage `t`
194    fn slerp(e0: Self, e1: Self, t: T) -> Self;
195}
196
197/// trait for normalized interpolation, which is applicable with vec and quat
198pub trait Nlerp<T: Float> {
199    // linearly interpolate between edges `e0` and `e1` by percentage `t` and return the normalized value
200    fn nlerp(e0: Self, e1: Self, t: T) -> Self;
201}
202
203//
204// Macro Implementation
205//
206
207/// macro to stamp out various n-dimensional vectors, all of their ops and functions
208macro_rules! vec_impl {
209    ($VecN:ident { $($field:ident, $field_index:expr),* }, $len:expr, $module:ident) => {
210
211        #[cfg_attr(feature="serde", derive(serde::Serialize, serde::Deserialize))]
212        #[cfg_attr(feature="hash", derive(Hash))]
213        #[derive(Debug, Copy, Clone)]
214        #[repr(C)]
215        pub struct $VecN<T> {
216            $(pub $field: T,)+
217        }
218
219        impl<T> $VecN<T> where T: Number {
220            /// construct a new vector from scalar values
221            pub fn new($($field: T,)+) -> $VecN<T> {
222                $VecN {
223                    $($field,)+
224                }
225            }
226        }
227
228        impl<T> VecN<T> for $VecN<T> where T: Number {
229            fn len() -> usize {
230                $len
231            }
232
233            fn all(a: Self) -> bool {
234                $(a.$field != T::zero() &&)+
235                true
236            }
237
238            fn any(a: Self) -> bool {
239                $(a.$field != T::zero() ||)+
240                false
241            }
242
243            fn max_scalar(a: Self) -> T {
244                let mut max = a[0];
245                for i in 1..Self::len() {
246                    if a[i] > max {
247                        max = a[i];
248                    }
249                }
250                max
251            }
252
253            fn min_scalar(a: Self) -> T {
254                let mut min = a[0];
255                for i in 1..Self::len() {
256                    if a[i] < min {
257                        min = a[i];
258                    }
259                }
260                min
261            }
262
263            fn unit_x() -> $VecN<T> {
264                let v = [T::one(), T::zero(), T::zero(), T::zero()];
265                Self {
266                    $($field: v[$field_index],)+
267                }
268            }
269
270            fn unit_y() -> $VecN<T> {
271                let v = [T::zero(), T::one(), T::zero(), T::zero()];
272                Self {
273                    $($field: v[$field_index],)+
274                }
275            }
276
277            fn unit_z() -> $VecN<T> {
278                let v = [T::zero(), T::zero(), T::one(), T::zero()];
279                Self {
280                    $($field: v[$field_index],)+
281                }
282            }
283
284            fn unit_w() -> $VecN<T> {
285                let v = [T::zero(), T::zero(), T::zero(), T::one()];
286                Self {
287                    $($field: v[$field_index],)+
288                }
289            }
290
291            fn red() -> $VecN<T> {
292                let v = [T::one(), T::zero(), T::zero(), T::one()];
293                Self {
294                    $($field: v[$field_index],)+
295                }
296            }
297
298            fn green() -> $VecN<T> {
299                let v = [T::zero(), T::one(), T::zero(), T::one()];
300                Self {
301                    $($field: v[$field_index],)+
302                }
303            }
304
305            fn blue() -> $VecN<T> {
306                let v = [T::zero(), T::zero(), T::one(), T::one()];
307                Self {
308                    $($field: v[$field_index],)+
309                }
310            }
311
312            fn cyan() -> $VecN<T> {
313                let v = [T::zero(), T::one(), T::one(), T::one()];
314                Self {
315                    $($field: v[$field_index],)+
316                }
317            }
318
319            fn magenta() -> $VecN<T> {
320                let v = [T::one(), T::zero(), T::one(), T::one()];
321                Self {
322                    $($field: v[$field_index],)+
323                }
324            }
325
326            fn yellow() -> $VecN<T> {
327                let v = [T::one(), T::one(), T::zero(), T::one()];
328                Self {
329                    $($field: v[$field_index],)+
330                }
331            }
332
333            fn black() -> $VecN<T> {
334                let v = [T::zero(), T::zero(), T::zero(), T::one()];
335                Self {
336                    $($field: v[$field_index],)+
337                }
338            }
339
340            fn white() -> $VecN<T> {
341                Self::one()
342            }
343
344            fn as_slice(&self) -> &[T] {
345                unsafe {
346                    std::slice::from_raw_parts(&self.x, $len)
347                }
348            }
349
350            fn as_mut_slice(&mut self) -> &mut [T] {
351                unsafe {
352                    std::slice::from_raw_parts_mut(&mut self.x, $len)
353                }
354            }
355
356            fn as_u8_slice(&self) -> &[u8] {
357                unsafe {
358                    std::slice::from_raw_parts((&self.x as *const T) as *const u8, std::mem::size_of::<$VecN<T>>())
359                }
360            }
361        }
362
363        impl<T> SignedVecN<T> for $VecN<T> where T: SignedNumber  {
364            fn minus_one() -> Self {
365                $VecN {
366                    $($field: T::minus_one(),)+
367                }
368            }
369        }
370
371        impl<T> IntegerOps<T> for $VecN<T> where T: Integer + IntegerOps<T> {
372            fn pow(a: Self, exp: u32) -> Self {
373                Self {
374                    $($field: T::pow(a.$field, exp),)+
375                }
376            }
377        }
378
379        impl<T> NumberOps<T> for $VecN<T> where T: Number + NumberOps<T> {
380            fn min(a: Self, b: Self) -> Self {
381                Self {
382                    $($field: T::min(a.$field, b.$field),)+
383                }
384            }
385
386            fn max(a: Self, b: Self) -> Self {
387                Self {
388                    $($field: T::max(a.$field, b.$field),)+
389                }
390            }
391
392            fn clamp(x: Self, min: Self, max: Self) -> Self {
393                Self {
394                    $($field: T::max(T::min(x.$field, max.$field), min.$field),)+
395                }
396            }
397
398            fn step(a: Self, b: Self) -> Self {
399                Self {
400                    $($field: T::step(a.$field, b.$field),)+
401                }
402            }
403        }
404
405        impl<T> SignedNumberOps<T> for $VecN<T> where T: SignedNumber + SignedNumberOps<T> {
406            fn signum(a: Self) -> Self {
407                Self {
408                    $($field: T::signum(a.$field),)+
409                }
410            }
411
412            fn abs(a: Self) -> Self {
413                Self {
414                    $($field: T::abs(a.$field),)+
415                }
416            }
417        }
418
419        impl<T> Magnitude<T> for $VecN<T> where T: Float + FloatOps<T> {
420            fn length(a: Self) -> T {
421                T::sqrt(Self::dot(a, a))
422            }
423
424            fn mag(a: Self) -> T {
425                T::sqrt(Self::dot(a, a))
426            }
427
428            fn mag2(a: Self) -> T {
429                Self::dot(a, a)
430            }
431
432            fn normalize(a: Self) -> Self {
433                let m = Self::mag(a);
434                a / m
435            }
436        }
437
438        impl<T> VecFloatOps<T> for $VecN<T> where T: Float + FloatOps<T> {
439            fn distance(a: Self, b: Self) -> T {
440                let c = a-b;
441                T::sqrt(Self::dot(c, c))
442            }
443
444            fn dist(a: Self, b: Self) -> T {
445                Self::distance(a, b)
446            }
447
448            fn dist2(a: Self, b: Self) -> T {
449                let c = a-b;
450                Self::dot(c, c)
451            }
452
453            fn reflect(i: Self, n: Self) -> Self {
454                // https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-reflect
455                (i - T::two()) * n * Self::dot(i, n)
456            }
457
458            fn refract(i: Self, n: Self, eta: T) -> Self {
459                // https://asawicki.info/news_1301_reflect_and_refract_functions.html
460                let n_dot_i = Self::dot(n, i);
461                let k = T::one() - eta * eta * (T::one() - n_dot_i * n_dot_i);
462                if k < T::zero() {
463                    Self::zero()
464                }
465                else {
466                    (i * eta) - n * ((n_dot_i + T::sqrt(k)) * eta)
467                }
468            }
469
470            fn vlerp(e0: Self, e1: Self, t: Self) -> Self {
471                Self {
472                    $($field: T::lerp(e0.$field, e1.$field, t.$field),)+
473                }
474            }
475
476            fn vsmoothstep(e0: Self, e1: Self, t: Self) -> Self {
477                Self {
478                    $($field: T::smoothstep(e0.$field, e1.$field, t.$field),)+
479                }
480            }
481
482            fn powfn(a: Self, exp: Self) -> Self {
483                Self {
484                    $($field: T::powf(a.$field, exp.$field),)+
485                }
486            }
487        }
488
489        impl<T> Slerp<T> for $VecN<T> where T: Float + FloatOps<T> + NumberOps<T> {
490            fn slerp(e0: Self, e1: Self, t: T) -> Self {
491                // https://blog.demofox.org/2016/02/19/normalized-vector-interpolation-tldr/
492                let dot = Self::dot(e0, e1);
493                let dot = T::clamp(dot, T::minus_one(), T::one());
494                let theta = T::acos(dot) * t;
495                let v = Self::normalize(e1 - e0 * dot);
496                ((e0 * T::cos(theta)) + (v * T::sin(theta)))
497            }
498        }
499
500        impl<T> Nlerp<T> for $VecN<T> where T: Float + FloatOps<T> + NumberOps<T> {
501            fn nlerp(e0: Self, e1: Self, t: T) -> Self {
502                Self::normalize( Self {
503                    $($field: T::lerp(e0.$field, e1.$field, t),)+
504                })
505            }
506        }
507
508        impl<T> Base<T> for $VecN<T> where T: Number {
509            fn zero() -> Self {
510                $VecN {
511                    $($field: T::zero(),)+
512                }
513            }
514
515            fn one() -> Self {
516                $VecN {
517                    $($field: T::one(),)+
518                }
519            }
520
521            fn two() -> Self {
522                $VecN {
523                    $($field: T::two(),)+
524                }
525            }
526
527            fn three() -> Self {
528                $VecN {
529                    $($field: T::four(),)+
530                }
531            }
532
533            fn four() -> Self {
534                $VecN {
535                    $($field: T::four(),)+
536                }
537            }
538
539            fn min_value() -> Self {
540                $VecN {
541                    $($field: T::min_value(),)+
542                }
543            }
544
545            fn max_value() -> Self {
546                $VecN {
547                    $($field: T::max_value(),)+
548                }
549            }
550        }
551
552        impl<T> Lerp<T> for $VecN<T> where T: Float + Lerp<T> {
553            fn lerp(e0: Self, e1: Self, t: T) -> Self {
554                Self {
555                    $($field: T::lerp(e0.$field, e1.$field, t),)+
556                }
557            }
558        }
559
560        impl<T> FloatOps<T> for $VecN<T> where T: Float + SignedNumberOps<T> + NumberOps<T> + FloatOps<T> {
561            fn point_five() -> Self {
562                $VecN {
563                    $($field: T::point_five(),)+
564                }
565            }
566
567            fn pi() -> Self {
568                $VecN {
569                    $($field: T::pi(),)+
570                }
571            }
572
573            fn two_pi() -> Self {
574                $VecN {
575                    $($field: T::two_pi(),)+
576                }
577            }
578
579            fn inv_pi() -> Self {
580                $VecN {
581                    $($field: T::inv_pi(),)+
582                }
583            }
584
585            fn phi() -> Self {
586                $VecN {
587                    $($field: T::phi(),)+
588                }
589            }
590
591            fn inv_phi() -> Self {
592                $VecN {
593                    $($field: T::inv_phi(),)+
594                }
595            }
596
597            fn tau() -> Self {
598                $VecN {
599                    $($field: T::tau(),)+
600                }
601            }
602
603            fn sqrt(a: Self) -> Self {
604                Self {
605                    $($field: T::sqrt(a.$field),)+
606                }
607            }
608
609            fn rsqrt(a: Self) -> Self {
610                Self {
611                    $($field: T::recip(T::sqrt(a.$field)),)+
612                }
613            }
614
615            fn recip(a: Self) -> Self {
616                Self {
617                    $($field: T::recip(a.$field),)+
618                }
619            }
620
621            fn powi(a: Self, exp: i32) -> Self {
622                Self {
623                    $($field: T::powi(a.$field, exp),)+
624                }
625            }
626
627            fn powf(a: Self, exp: T) -> Self {
628                Self {
629                    $($field: T::powf(a.$field, exp),)+
630                }
631            }
632
633            fn mad(m: Self, a: Self, b: Self) -> Self {
634                Self {
635                    $($field: T::mad(m.$field, a.$field, b.$field),)+
636                }
637            }
638
639            fn approx(a: Self, b: Self, eps: T) -> bool {
640                $(T::abs(a.$field - b.$field) < eps &&)+
641                true
642            }
643
644            fn floor(a: Self) -> Self {
645                Self {
646                    $($field: T::floor(a.$field),)+
647                }
648            }
649
650            fn ceil(a: Self) -> Self {
651                Self {
652                    $($field: T::ceil(a.$field),)+
653                }
654            }
655
656            fn copysign(a: Self, sign: T) -> Self {
657                Self {
658                    $($field: T::copysign(a.$field, sign),)+
659                }
660            }
661
662            fn smoothstep(e0: Self, e1: Self, t: T) -> Self {
663                Self {
664                    $($field: T::smoothstep(e0.$field, e1.$field, t),)+
665                }
666            }
667
668            fn round(a: Self) -> Self {
669                Self {
670                    $($field: T::round(a.$field),)+
671                }
672            }
673
674            fn is_nan(a: Self) -> Self {
675                Self {
676                    $($field: T::is_nan(a.$field),)+
677                }
678            }
679
680            fn is_infinite(a: Self) -> Self {
681                Self {
682                    $($field: T::is_infinite(a.$field),)+
683                }
684            }
685
686            fn is_finite(a: Self) -> Self {
687                Self {
688                    $($field: T::is_finite(a.$field),)+
689                }
690            }
691
692            fn saturate(x: Self) -> Self {
693                Self::clamp(x, Self::zero(), Self::one())
694            }
695
696            fn deg_to_rad(a: Self) -> Self {
697                Self {
698                    $($field: T::deg_to_rad(a.$field),)+
699                }
700            }
701
702            fn rad_to_deg(a: Self) -> Self {
703                Self {
704                    $($field: T::rad_to_deg(a.$field),)+
705                }
706            }
707
708            fn fmod(x: Self, y: Self) -> Self {
709                x % y
710            }
711
712            fn frac(v: Self) -> Self {
713                Self {
714                    $($field: T::frac(v.$field),)+
715                }
716            }
717
718            fn trunc(v: Self) -> Self {
719                Self {
720                    $($field: T::trunc(v.$field),)+
721                }
722            }
723
724            fn modf(v: Self) -> (Self, Self) {
725                (
726                    Self {
727                        $($field: T::frac(v.$field),)+
728                    },
729                    Self {
730                        $($field: T::trunc(v.$field),)+
731                    }
732                )
733            }
734
735            fn cos(v: Self) -> Self {
736                Self {
737                    $($field: T::cos(v.$field),)+
738                }
739            }
740
741            fn sin(v: Self) -> Self {
742                Self {
743                    $($field: T::sin(v.$field),)+
744                }
745            }
746
747            fn tan(v: Self) -> Self {
748                Self {
749                    $($field: T::tan(v.$field),)+
750                }
751            }
752
753            fn acos(v: Self) -> Self {
754                Self {
755                    $($field: T::acos(v.$field),)+
756                }
757            }
758
759            fn asin(v: Self) -> Self {
760                Self {
761                    $($field: T::asin(v.$field),)+
762                }
763            }
764
765            fn atan(v: Self) -> Self {
766                Self {
767                    $($field: T::atan(v.$field),)+
768                }
769            }
770
771            fn cosh(v: Self) -> Self {
772                Self {
773                    $($field: T::cosh(v.$field),)+
774                }
775            }
776
777            fn sinh(v: Self) -> Self {
778                Self {
779                    $($field: T::sinh(v.$field),)+
780                }
781            }
782
783            fn tanh(v: Self) -> Self {
784                Self {
785                    $($field: T::tanh(v.$field),)+
786                }
787            }
788
789            fn sin_cos(v: Self) -> (Self, Self) {
790                (
791                    Self {
792                        $($field: T::sin(v.$field),)+
793                    },
794                    Self {
795                        $($field: T::cos(v.$field),)+
796                    }
797                )
798            }
799
800            fn atan2(y: Self, x: Self) -> Self {
801                Self {
802                    $($field: T::atan2(y.$field, x.$field),)+
803                }
804            }
805
806            fn exp(v: Self) -> Self {
807                Self {
808                    $($field: T::exp(v.$field),)+
809                }
810            }
811
812            fn exp2(v: Self) -> Self {
813                Self {
814                    $($field: T::exp2(v.$field),)+
815                }
816            }
817
818            fn log2(v: Self) -> Self {
819                Self {
820                    $($field: T::log2(v.$field),)+
821                }
822            }
823
824            fn log10(v: Self) -> Self {
825                Self {
826                    $($field: T::log10(v.$field),)+
827                }
828            }
829
830            fn log(v: Self, base: T) -> Self {
831                Self {
832                    $($field: T::log(v.$field, base),)+
833                }
834            }
835        }
836
837        impl<T> Index<usize> for $VecN<T> {
838            type Output = T;
839            fn index(&self, i: usize) -> &Self::Output {
840                match i {
841                    $($field_index => &self.$field, )+
842                    _ => &self.x
843                }
844            }
845        }
846
847        impl<T> IndexMut<usize> for $VecN<T> {
848            fn index_mut(&mut self, i: usize) -> &mut T {
849                match i {
850                    $($field_index => &mut self.$field, )+
851                    _ => &mut self.x
852                }
853            }
854        }
855
856        /// displays like [10.0, 12.0, 13.0]
857        impl<T> Display for $VecN<T> where T: Display {
858            fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
859                let mut output = String::from("[");
860                $(
861                    output += &self.$field.to_string();
862                    if $field_index < $len-1 {
863                        output += &String::from(", ");
864                    }
865                )+
866                output += "]";
867                write!(f, "{}", output)
868            }
869        }
870
871        /// default to zero
872        impl<T> Default for $VecN<T> where T: Number {
873            fn default() -> Self {
874                Self::zero()
875            }
876        }
877
878        //
879        // ops
880        //
881
882        impl<T> Deref for $VecN<T> where T: Number {
883            type Target = [T];
884            fn deref(&self) -> &Self::Target {
885                self.as_slice()
886            }
887        }
888
889        impl<T> DerefMut for $VecN<T> where T: Number {
890            fn deref_mut(&mut self) -> &mut [T] {
891                self.as_mut_slice()
892            }
893        }
894
895        impl<T> Add<Self> for $VecN<T> where T: Number {
896            type Output = Self;
897            fn add(self, other: Self) -> Self {
898                Self {
899                    $($field: self.$field + other.$field,)+
900                }
901            }
902        }
903
904        impl<T> Add<T> for $VecN<T> where T: Number {
905            type Output = Self;
906            fn add(self, other: T) -> Self {
907                Self {
908                    $($field: self.$field + other,)+
909                }
910            }
911        }
912
913        // add refs
914        impl<T> Add<&Self> for $VecN<T> where T: Number {
915            type Output = Self;
916            fn add(self, other: &Self) -> Self {
917                self.add(*other)
918            }
919        }
920
921        impl<T> Add<$VecN<T>> for &$VecN<T> where T: Number {
922            type Output = $VecN<T>;
923            fn add(self, other: $VecN<T>) -> $VecN<T> {
924                *self + other
925            }
926        }
927
928        impl<T> Add<Self> for &$VecN<T> where T: Number {
929            type Output = $VecN<T>;
930            fn add(self, other: Self) -> $VecN<T> {
931                *self + other
932            }
933        }
934
935        impl<T> AddAssign<Self> for $VecN<T> where T: Number {
936            fn add_assign(&mut self, other: Self) {
937                $(self.$field += other.$field;)+
938            }
939        }
940
941        impl<T> AddAssign<T> for $VecN<T> where T: Number {
942            fn add_assign(&mut self, other: T) {
943                $(self.$field += other;)+
944            }
945        }
946
947        // add assign ref
948        impl<T> AddAssign<&Self> for $VecN<T> where T: Number {
949            fn add_assign(&mut self, other: &Self) {
950                $(self.$field += other.$field;)+
951            }
952        }
953
954        impl<T> Sub<Self> for $VecN<T> where T: Number {
955            type Output = Self;
956            fn sub(self, other: Self) -> Self {
957                Self {
958                    $($field: self.$field - other.$field,)+
959                }
960            }
961        }
962
963        impl<T> Sub<T> for $VecN<T> where T: Number {
964            type Output = Self;
965            fn sub(self, other: T) -> Self {
966                Self {
967                    $($field: self.$field - other,)+
968                }
969            }
970        }
971
972        // sub refs
973        impl<T> Sub<&Self> for $VecN<T> where T: Number {
974            type Output = Self;
975            fn sub(self, other: &Self) -> Self {
976                self.sub(*other)
977            }
978        }
979
980        impl<T> Sub<$VecN<T>> for &$VecN<T> where T: Number {
981            type Output = $VecN<T>;
982            fn sub(self, other: $VecN<T>) -> $VecN<T> {
983                *self - other
984            }
985        }
986
987        impl<T> Sub<Self> for &$VecN<T> where T: Number {
988            type Output = $VecN<T>;
989            fn sub(self, other: Self) -> $VecN<T> {
990                *self - other
991            }
992        }
993
994        impl<T> SubAssign<Self> for $VecN<T> where T: Number {
995            fn sub_assign(&mut self, other: Self) {
996                $(self.$field -= other.$field;)+
997            }
998        }
999
1000        impl<T> SubAssign<T> for $VecN<T> where T: Number {
1001            fn sub_assign(&mut self, other: T) {
1002                $(self.$field -= other;)+
1003            }
1004        }
1005
1006        // sub assign ref
1007        impl<T> SubAssign<&Self> for $VecN<T> where T: Number {
1008            fn sub_assign(&mut self, other: &Self) {
1009                $(self.$field -= other.$field;)+
1010            }
1011        }
1012
1013        impl<T> Mul<Self> for $VecN<T> where T: Number {
1014            type Output = Self;
1015            fn mul(self, other: Self) -> Self {
1016                Self {
1017                    $($field: self.$field * other.$field,)+
1018                }
1019            }
1020        }
1021
1022        impl<T> Mul<T> for $VecN<T> where T: Number {
1023            type Output = Self;
1024            fn mul(self, other: T) -> Self {
1025                Self {
1026                    $($field: self.$field * other,)+
1027                }
1028            }
1029        }
1030
1031        // mul refs
1032        impl<T> Mul<&Self> for $VecN<T> where T: Number {
1033            type Output = Self;
1034            fn mul(self, other: &Self) -> Self {
1035                self.mul(*other)
1036            }
1037        }
1038
1039        impl<T> Mul<$VecN<T>> for &$VecN<T> where T: Number {
1040            type Output = $VecN<T>;
1041            fn mul(self, other: $VecN<T>) -> $VecN<T> {
1042                *self * other
1043            }
1044        }
1045
1046        impl<T> Mul<Self> for &$VecN<T> where T: Number {
1047            type Output = $VecN<T>;
1048            fn mul(self, other: Self) -> $VecN<T> {
1049                *self * other
1050            }
1051        }
1052
1053        impl<T> MulAssign<Self> for $VecN<T> where T: Number {
1054            fn mul_assign(&mut self, other: Self) {
1055                $(self.$field *= other.$field;)+
1056            }
1057        }
1058
1059        impl<T> MulAssign<T> for $VecN<T> where T: Number {
1060            fn mul_assign(&mut self, other: T) {
1061                $(self.$field *= other;)+
1062            }
1063        }
1064
1065        // mul assign ref
1066        impl<T> MulAssign<&Self> for $VecN<T> where T: Number {
1067            fn mul_assign(&mut self, other: &Self) {
1068                $(self.$field *= other.$field;)+
1069            }
1070        }
1071
1072        impl<T> Div<Self> for $VecN<T> where T: Number {
1073            type Output = Self;
1074            fn div(self, other: Self) -> Self {
1075                Self {
1076                    $($field: self.$field / other.$field,)+
1077                }
1078            }
1079        }
1080
1081        impl<T> Div<T> for $VecN<T> where T: Number {
1082            type Output = Self;
1083            fn div(self, other: T) -> Self {
1084                Self {
1085                    $($field: self.$field / other,)+
1086                }
1087            }
1088        }
1089
1090        // div refs
1091        impl<T> Div<&Self> for $VecN<T> where T: Number {
1092            type Output = Self;
1093            fn div(self, other: &Self) -> Self {
1094                self.div(*other)
1095            }
1096        }
1097
1098        impl<T> Div<$VecN<T>> for &$VecN<T> where T: Number {
1099            type Output = $VecN<T>;
1100            fn div(self, other: $VecN<T>) -> $VecN<T> {
1101                *self / other
1102            }
1103        }
1104
1105        impl<T> Div<Self> for &$VecN<T> where T: Number {
1106            type Output = $VecN<T>;
1107            fn div(self, other: Self) -> $VecN<T> {
1108                *self / other
1109            }
1110        }
1111
1112        impl<T> DivAssign<Self> for $VecN<T> where T: Number {
1113            fn div_assign(&mut self, other: Self) {
1114                $(self.$field /= other.$field;)+
1115            }
1116        }
1117
1118        impl<T> DivAssign<T> for $VecN<T> where T: Number {
1119            fn div_assign(&mut self, other: T) {
1120                $(self.$field /= other;)+
1121            }
1122        }
1123
1124        // div assign ref
1125        impl<T> DivAssign<&Self> for $VecN<T> where T: Number {
1126            fn div_assign(&mut self, other: &Self) {
1127                $(self.$field /= other.$field;)+
1128            }
1129        }
1130
1131        impl<T> Rem<Self> for $VecN<T> where T: Number {
1132            type Output = Self;
1133            fn rem(self, other: Self) -> Self {
1134                Self {
1135                    $($field: self.$field % other.$field,)+
1136                }
1137            }
1138        }
1139
1140        impl<T> Rem<T> for $VecN<T> where T: Number {
1141            type Output = Self;
1142            fn rem(self, other: T) -> Self {
1143                Self {
1144                    $($field: self.$field % other,)+
1145                }
1146            }
1147        }
1148
1149        impl<T> RemAssign<Self> for $VecN<T> where T: Number {
1150            fn rem_assign(&mut self, other: Self) {
1151                $(self.$field %= other.$field;)+
1152            }
1153        }
1154
1155        impl<T> RemAssign<T> for $VecN<T> where T: Number {
1156            fn rem_assign(&mut self, other: T) {
1157                $(self.$field %= other;)+
1158            }
1159        }
1160
1161        impl<T> Neg for $VecN<T> where T: SignedNumber {
1162            type Output = Self;
1163            fn neg(self) -> Self::Output {
1164                Self {
1165                    $($field: -self.$field,)+
1166                }
1167            }
1168        }
1169
1170        impl<T> Eq for $VecN<T> where T: Eq  {}
1171        impl<T> PartialEq for $VecN<T> where T: PartialEq  {
1172            fn eq(&self, other: &Self) -> bool {
1173                $(self.$field == other.$field &&)+
1174                true
1175            }
1176        }
1177    }
1178}
1179
1180/// macro to stamp out various typed c-style constructors. ie. let v = vec3f(0.0, 1.0, 0.0);
1181macro_rules! vec_ctor {
1182    ($VecN:ident { $($field:ident),+ }, $ctor:ident, $splat:ident, $t:ident) => {
1183        pub fn $ctor($($field: $t,)+) -> $VecN<$t> {
1184            $VecN {
1185                $($field,)+
1186            }
1187        }
1188        pub fn $splat(v: $t) -> $VecN<$t> {
1189            $VecN {
1190                $($field: v,)+
1191            }
1192        }
1193    }
1194}
1195
1196/// macro to stamp out all arithmetic ops for lhs scalars
1197macro_rules! vec_scalar_lhs {
1198    ($VecN:ident { $($field:ident),+ }, $t:ident) => {
1199        impl Add<$VecN<$t>> for $t {
1200            type Output = $VecN<$t>;
1201            fn add(self, other: $VecN<$t>) -> $VecN<$t> {
1202                $VecN {
1203                    $($field: self + other.$field,)+
1204                }
1205            }
1206        }
1207
1208        impl Sub<$VecN<$t>> for $t {
1209            type Output = $VecN<$t>;
1210            fn sub(self, other: $VecN<$t>) -> $VecN<$t> {
1211                $VecN {
1212                    $($field: self - other.$field,)+
1213                }
1214            }
1215        }
1216
1217        impl Mul<$VecN<$t>> for $t {
1218            type Output = $VecN<$t>;
1219            fn mul(self, other: $VecN<$t>) -> $VecN<$t> {
1220                $VecN {
1221                    $($field: self * other.$field,)+
1222                }
1223            }
1224        }
1225
1226        impl Div<$VecN<$t>> for $t {
1227            type Output = $VecN<$t>;
1228            fn div(self, other: $VecN<$t>) -> $VecN<$t> {
1229                $VecN {
1230                    $($field: self / other.$field,)+
1231                }
1232            }
1233        }
1234
1235        impl Rem<$VecN<$t>> for $t {
1236            type Output = $VecN<$t>;
1237            fn rem(self, other: $VecN<$t>) -> $VecN<$t> {
1238                $VecN {
1239                    $($field: self % other.$field,)+
1240                }
1241            }
1242        }
1243    }
1244}
1245
1246//
1247// From
1248//
1249
1250/// constructs vec2 from scalar T splatting to x and y
1251impl<T> From<T> for Vec2<T> where T: Number {
1252    fn from(other: T) -> Vec2<T> {
1253        Vec2 {
1254            x: other,
1255            y: other,
1256        }
1257    }
1258}
1259
1260// constructs vec2 from tuple of 2 scalars x: .0, y: .1
1261impl<T> From<(T, T)> for Vec2<T> where T: Number {
1262    fn from(other: (T, T)) -> Vec2<T> {
1263        Vec2 {
1264            x: other.0,
1265            y: other.1,
1266        }
1267    }
1268}
1269
1270/// constructs vec2 from vec3 copying the x,y and truncating the z
1271impl<T> From<Vec3<T>> for Vec2<T> where T: Number {
1272    fn from(other: Vec3<T>) -> Vec2<T> {
1273        Vec2 {
1274            x: other.x,
1275            y: other.y,
1276        }
1277    }
1278}
1279
1280/// constructs vec2 from vec4 copying the x,y and truncating the z,w
1281impl<T> From<Vec4<T>> for Vec2<T> where T: Number {
1282    fn from(other: Vec4<T>) -> Vec2<T> {
1283        Vec2 {
1284            x: other.x,
1285            y: other.y,
1286        }
1287    }
1288}
1289
1290/// constructs vec3 from scalar T splatting to x,y,z
1291impl<T> From<T> for Vec3<T> where T: Number {
1292    fn from(other: T) -> Vec3<T> {
1293        Vec3 {
1294            x: other,
1295            y: other,
1296            z: other
1297        }
1298    }
1299}
1300
1301/// constructs vec3 from vec2 copying the x,y and zeroing the z
1302impl<T> From<Vec2<T>> for Vec3<T> where T: Number {
1303    fn from(other: Vec2<T>) -> Vec3<T> {
1304        Vec3 {
1305            x: other.x,
1306            y: other.y,
1307            z: T::zero()
1308        }
1309    }
1310}
1311
1312/// constructs vec3 from tuple of 3 scalars
1313impl<T> From<(T, T, T)> for Vec3<T> where T: Number {
1314    fn from(other: (T, T, T)) -> Vec3<T> {
1315        Vec3 {
1316            x: other.0,
1317            y: other.1,
1318            z: other.2
1319        }
1320    }
1321}
1322
1323/// construct from a tuple of vec2 into x,y and scalar into z
1324impl<T> From<(Vec2<T>, T)> for Vec3<T> where T: Number {
1325    fn from(other: (Vec2<T>, T)) -> Vec3<T> {
1326        Vec3 {
1327            x: other.0.x,
1328            y: other.0.y,
1329            z: other.1
1330        }
1331    }
1332}
1333
1334/// constructs vec3 from vec4 copying the x,y,z and truncating the w
1335impl<T> From<Vec4<T>> for Vec3<T> where T: Number {
1336    fn from(other: Vec4<T>) -> Vec3<T> {
1337        Vec3 {
1338            x: other.x,
1339            y: other.y,
1340            z: other.z,
1341        }
1342    }
1343}
1344
1345/// constructs vec4 from scalar T splatting to x,y,z,w
1346impl<T> From<T> for Vec4<T> where T: Number {
1347    fn from(other: T) -> Vec4<T> {
1348        Vec4 {
1349            x: other,
1350            y: other,
1351            z: other,
1352            w: other
1353        }
1354    }
1355}
1356
1357/// constructs vec4 from vec2 copying the x,y and zeroing the z,w
1358impl<T> From<Vec2<T>> for Vec4<T> where T: Number {
1359    fn from(other: Vec2<T>) -> Vec4<T> {
1360        Vec4 {
1361            x: other.x,
1362            y: other.y,
1363            z: T::zero(),
1364            w: T::zero()
1365        }
1366    }
1367}
1368
1369/// constructs vec4 from vec2 copying the x,y,z and zeroing the w
1370impl<T> From<Vec3<T>> for Vec4<T> where T: Number {
1371    fn from(other: Vec3<T>) -> Vec4<T> {
1372        Vec4 {
1373            x: other.x,
1374            y: other.y,
1375            z: other.z,
1376            w: T::zero()
1377        }
1378    }
1379}
1380
1381/// construct from a tuple of vec2 into x,y 2 scalars into z and w
1382impl<T> From<(Vec2<T>, T, T)> for Vec4<T> where T: Number {
1383    fn from(other: (Vec2<T>, T, T)) -> Vec4<T> {
1384        Vec4 {
1385            x: other.0.x,
1386            y: other.0.y,
1387            z: other.1,
1388            w: other.2
1389        }
1390    }
1391}
1392
1393/// construct from a tuple of vec2 into x,y and vec2 into z,w
1394impl<T> From<(Vec2<T>, Vec2<T>)> for Vec4<T> where T: Number {
1395    fn from(other: (Vec2<T>, Vec2<T>)) -> Vec4<T> {
1396        Vec4 {
1397            x: other.0.x,
1398            y: other.0.y,
1399            z: other.1.x,
1400            w: other.1.y
1401        }
1402    }
1403}
1404
1405/// construct from a tuple of vec3 into x,y,z and a scalar into w
1406impl<T> From<(Vec3<T>, T)> for Vec4<T> where T: Number {
1407    fn from(other: (Vec3<T>, T)) -> Vec4<T> {
1408        Vec4 {
1409            x: other.0.x,
1410            y: other.0.y,
1411            z: other.0.z,
1412            w: other.1
1413        }
1414    }
1415}
1416
1417/// constructs vec4 from tuple of 4 scalars
1418impl<T> From<(T, T, T, T)> for Vec4<T> where T: Number {
1419    fn from(other: (T, T, T, T)) -> Vec4<T> {
1420        Vec4 {
1421            x: other.0,
1422            y: other.1,
1423            z: other.2,
1424            w: other.3
1425        }
1426    }
1427}
1428
1429macro_rules! vec_cast {
1430    ($VecN:ident { $($field:ident),+ }, $t:ident, $u:ident) => {
1431        impl From<$VecN<$u>> for $VecN<$t> {
1432            fn from(other: $VecN<$u>) -> $VecN<$t> {
1433                $VecN {
1434                    $($field: other.$field as $t,)+
1435                }
1436            }
1437        }
1438
1439        impl From<$VecN<$t>> for $VecN<$u> {
1440            fn from(other: $VecN<$t>) -> $VecN<$u> {
1441                $VecN {
1442                    $($field: other.$field as $u,)+
1443                }
1444            }
1445        }
1446    }
1447}
1448
1449//
1450// Macro Decl
1451//
1452
1453vec_impl!(Vec2 { x, 0, y, 1 }, 2, v2);
1454vec_impl!(Vec3 { x, 0, y, 1, z, 2 }, 3, v3);
1455vec_impl!(Vec4 { x, 0, y, 1, z, 2, w, 3 }, 4, v4);
1456
1457#[cfg(feature = "lhs_scalar_vec_ops")]
1458vec_scalar_lhs!(Vec2 { x, y }, f32);
1459vec_scalar_lhs!(Vec3 { x, y, z }, f32);
1460vec_scalar_lhs!(Vec4 { x, y, z, w }, f32);
1461vec_scalar_lhs!(Vec2 { x, y }, f64);
1462vec_scalar_lhs!(Vec3 { x, y, z }, f64);
1463vec_scalar_lhs!(Vec4 { x, y, z, w }, f64);
1464vec_scalar_lhs!(Vec2 { x, y }, i32);
1465vec_scalar_lhs!(Vec3 { x, y, z }, i32);
1466vec_scalar_lhs!(Vec4 { x, y, z, w }, i32);
1467vec_scalar_lhs!(Vec2 { x, y }, u32);
1468vec_scalar_lhs!(Vec3 { x, y, z }, u32);
1469vec_scalar_lhs!(Vec4 { x, y, z, w }, u32);
1470
1471#[cfg(feature = "short_hand_constructors")]
1472vec_ctor!(Vec2 { x, y }, vec2f, splat2f, f32);
1473vec_ctor!(Vec3 { x, y, z }, vec3f, splat3f, f32);
1474vec_ctor!(Vec4 { x, y, z, w }, vec4f, splat4f, f32);
1475vec_ctor!(Vec2 { x, y }, vec2d, splat2d, f64);
1476vec_ctor!(Vec3 { x, y, z }, vec3d, splat3d, f64);
1477vec_ctor!(Vec4 { x, y, z, w }, vec4d, splat4d, f64);
1478vec_ctor!(Vec2 { x, y }, vec2i, splat2i, i32);
1479vec_ctor!(Vec3 { x, y, z }, vec3i, splat3i, i32);
1480vec_ctor!(Vec4 { x, y, z, w }, vec4i, splat4i, i32);
1481vec_ctor!(Vec2 { x, y }, vec2u, splat2u, u32);
1482vec_ctor!(Vec3 { x, y, z }, vec3u, splat3u, u32);
1483vec_ctor!(Vec4 { x, y, z, w }, vec4u, splat4u, u32);
1484
1485#[cfg(feature = "casts")]
1486vec_cast!(Vec2 { x, y }, f64, i32);
1487vec_cast!(Vec2 { x, y }, f64, u32);
1488vec_cast!(Vec2 { x, y }, f32, f64);
1489vec_cast!(Vec2 { x, y }, f32, i32);
1490vec_cast!(Vec2 { x, y }, f32, u32);
1491vec_cast!(Vec2 { x, y }, i32, u32);
1492vec_cast!(Vec3 {x, y, z}, f64, i32);
1493vec_cast!(Vec3 {x, y, z}, f64, u32);
1494vec_cast!(Vec3 {x, y, z}, f32, f64);
1495vec_cast!(Vec3 {x, y, z}, f32, i32);
1496vec_cast!(Vec3 {x, y, z}, f32, u32);
1497vec_cast!(Vec3 {x, y, z}, i32, u32);
1498vec_cast!(Vec4 {x, y, z, w}, f64, i32);
1499vec_cast!(Vec4 {x, y, z, w}, f64, u32);
1500vec_cast!(Vec4 {x, y, z, w}, f32, f64);
1501vec_cast!(Vec4 {x, y, z, w}, f32, i32);
1502vec_cast!(Vec4 {x, y, z, w}, f32, u32);
1503vec_cast!(Vec4 {x, y, z, w}, i32, u32);