minlin 0.4.0

Rust library with minimal linear algebra made to be as convinient as possible.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
use std::{
    cmp::Ordering,
    fmt::Display,
    mem,
    ops::{
        Add, AddAssign, Div, DivAssign, Index, IndexMut, Mul, MulAssign, Neg,
        Rem, RemAssign, Sub, SubAssign,
    },
};

use crate::{
    Checked, Float, Goniometric, IntoFloat, Isqrt, LargeType, MapExt,
    NormalLimits, Scale, Sqrt, Vec2, Zero,
};

/// Represents three dimensional vector. Can be also use as color or any
/// 3-tuple-like object where vector operations are benefit.
///
/// It is ment to be as convinient as possible to work with in many use cases.
#[derive(Debug, Copy, Clone, Default, PartialEq, Eq)]
pub struct Vec3<T = usize> {
    pub x: T,
    pub y: T,
    pub z: T,
}

impl<T> Vec3<T> {
    pub fn new(x: T, y: T, z: T) -> Self {
        Self { x, y, z }
    }

    /// Converts vector reference to vector of reference.
    pub fn as_ref(&self) -> Vec3<&T> {
        (&self.x, &self.y, &self.z).into()
    }

    /// Construct vector of mutable references to the components of the vector.
    pub fn as_mut(&mut self) -> Vec3<&mut T> {
        (&mut self.x, &mut self.y, &mut self.z).into()
    }

    /// Iterate over the three components.
    pub fn iter(&self) -> std::array::IntoIter<&T, 3> {
        let r: [_; 3] = self.as_ref().into();
        r.into_iter()
    }

    /// Get mutable iterator over the three components.
    pub fn iter_mut(&mut self) -> std::array::IntoIter<&mut T, 3> {
        let r: [_; 3] = self.as_mut().into();
        r.into_iter()
    }

    /// Get the red value. Alias to the first coordinate (x, [0]).
    pub fn r(&self) -> &T {
        &self.x
    }

    /// Get the green value. Alias to the second coordinate (y, [1]).
    pub fn g(&self) -> &T {
        &self.y
    }

    /// Get the blue value. Alias to the third coordinate (y, [2]).
    pub fn b(&self) -> &T {
        &self.z
    }

    /// Get the red value. Alias to the first coordinate (x, [0]).
    pub fn r_mut(&mut self) -> &mut T {
        &mut self.x
    }

    /// Get the green value. Alias to the second coordinate (y, [1]).
    pub fn g_mut(&mut self) -> &mut T {
        &mut self.y
    }

    /// Get the blue value. Alias to the third coordinate (y, [2]).
    pub fn b_mut(&mut self) -> &mut T {
        &mut self.z
    }

    /// Set the red value. Alias to the first coordinate (x, [0]).
    pub fn set_r(&mut self, r: T) {
        self.x = r;
    }

    /// Set the green value. Alias to the first coordinate (y, [1]).
    pub fn set_g(&mut self, g: T) {
        self.x = g;
    }

    /// Set the blue value. Alias to the first coordinate (z, [2]).
    pub fn set_b(&mut self, b: T) {
        self.x = b;
    }

    /// Calculate the dot product of two 3D vectors.
    pub fn dot<Right>(
        self,
        other: impl Into<Vec3<Right>>,
    ) -> <<T::Output as Add>::Output as Add<T::Output>>::Output
    where
        T: Mul<Right>,
        T::Output: Add,
        <T::Output as Add>::Output: Add<T::Output>,
    {
        let o = other.into();
        self.x * o.x + self.y * o.y + self.z * o.z
    }

    /// Calculate the square of the length of the vector.
    pub fn sq_len(
        &self,
    ) -> <<T::Output as Add>::Output as Add<T::Output>>::Output
    where
        T: Copy + Mul,
        T::Output: Add,
        <T::Output as Add>::Output: Add<T::Output>,
    {
        self.dot(*self)
    }

    /// Calculate the length of the vector.
    pub fn len(
        &self,
    ) -> <<<T::Output as Add>::Output as Add<T::Output>>::Output as Sqrt>::Output
    where
        T: Copy + Mul,
        T::Output: Add<T::Output>,
        <T::Output as Add>::Output: Add<T::Output>,
        <<T::Output as Add>::Output as Add<T::Output>>::Output: Sqrt,
    {
        self.sq_len().sqrt()
    }

    /// Calculate the integer length of the vector.
    pub fn ilen(
        &self,
    ) -> <<T::Output as Add>::Output as Add<T::Output>>::Output
    where
        T: Copy + Mul,
        T::Output: Add<T::Output>,
        <T::Output as Add>::Output: Add<T::Output>,
        <<T::Output as Add>::Output as Add<T::Output>>::Output: Isqrt,
    {
        self.sq_len().isqrt()
    }

    /// Checked add of two vectors.
    ///
    /// Returns [`None`] if addition of any of the components fails.
    pub fn checked_add(self, other: impl Into<Vec3<T>>) -> Option<Vec3<T>>
    where
        T: Checked,
    {
        let o = other.into();
        Some(Self::new(
            self.x.checked_add(o.x)?,
            self.y.checked_add(o.y)?,
            self.z.checked_add(o.z)?,
        ))
    }

    /// Checked subtraction of two vectors.
    ///
    /// Returns [`None`] if subtraction of any of the components fails.
    pub fn checked_sub(self, other: impl Into<Vec3<T>>) -> Option<Vec3<T>>
    where
        T: Checked,
    {
        let o = other.into();
        Some(Self::new(
            self.x.checked_sub(o.x)?,
            self.y.checked_sub(o.y)?,
            self.z.checked_sub(o.z)?,
        ))
    }

    /// Checked componentwise multiplication of two vectors.
    ///
    /// Returns [`None`] if multiplication of any of the components fails.
    pub fn checked_cmul(self, other: impl Into<Vec3<T>>) -> Option<Vec3<T>>
    where
        T: Checked,
    {
        let o = other.into();
        Some(Self::new(
            self.x.checked_mul(o.x)?,
            self.y.checked_mul(o.y)?,
            self.z.checked_mul(o.z)?,
        ))
    }

    /// Sum all the components.
    pub fn sum(self) -> <T::Output as Add<T>>::Output
    where
        T: Add,
        T::Output: Add<T>,
    {
        self.x + self.y + self.z
    }

    /// Multiply all the components.
    pub fn prod(self) -> <T::Output as Mul<T>>::Output
    where
        T: Mul,
        T::Output: Mul<T>,
    {
        self.x * self.y * self.z
    }

    /// Checks if all the components are same.
    pub fn same(&self) -> bool
    where
        T: PartialEq,
    {
        self.x == self.y && self.x == self.z
    }

    /// Counts how many different values are in the components. Returns `1`,
    /// `2` or `3`.
    pub fn group_cnt(&self) -> usize
    where
        T: PartialEq,
    {
        if self.x == self.y {
            if self.x == self.z { 1 } else { 2 }
        } else if self.x == self.z || self.y == self.z {
            2
        } else {
            3
        }
    }

    /// Gets index to the largest of the components.
    pub fn max_idx(&self) -> usize
    where
        T: Ord,
    {
        if self.z > self.y {
            if self.z > self.x { 2 } else { 0 }
        } else if self.y > self.x {
            1
        } else {
            0
        }
    }

    /// Gets reference to the largest component.
    pub fn max(&self) -> &T
    where
        T: Ord,
    {
        &self[self.max_idx()]
    }

    /// Gets mutable reference to the largest component.
    pub fn max_mut(&mut self) -> &mut T
    where
        T: Ord,
    {
        let i = self.max_idx();
        &mut self[i]
    }

    /// Gets index to the smallest of the components.
    pub fn min_idx(&self) -> usize
    where
        T: Ord,
    {
        if self.z < self.y {
            if self.z < self.x { 2 } else { 0 }
        } else if self.y < self.x {
            1
        } else {
            0
        }
    }

    /// Gets reference to the smallest component.
    pub fn min(&self) -> &T
    where
        T: Ord,
    {
        &self[self.min_idx()]
    }

    /// Gets mutable reference to the smallest component.
    pub fn min_mut(&mut self) -> &mut T
    where
        T: Ord,
    {
        let i = self.min_idx();
        &mut self[i]
    }

    /// Gets index to the middle of the components.
    pub fn mid_idx(&self) -> usize
    where
        T: Ord,
    {
        if self.z < self.y {
            if self.z < self.x {
                if self.y < self.x { 1 } else { 0 }
            } else {
                2
            }
        } else if self.y < self.x {
            if self.z < self.x { 2 } else { 0 }
        } else {
            1
        }
    }

    /// Gets reference to the middle component.
    pub fn mid(&self) -> &T
    where
        T: Ord,
    {
        &self[self.mid_idx()]
    }

    /// Gets mutable reference to the middle component.
    pub fn mid_mut(&mut self) -> &mut T
    where
        T: Ord,
    {
        let i = self.mid_idx();
        &mut self[i]
    }

    /// Checks if all the components match the predicate.
    pub fn are_all(&self, mut f: impl FnMut(&T) -> bool) -> bool {
        f(&self.x) && f(&self.y) && f(&self.z)
    }

    /// Checks if any of the components match the predicate.
    pub fn is_any(&self, mut f: impl FnMut(&T) -> bool) -> bool {
        f(&self.x) || f(&self.y) || f(&self.z)
    }

    /// Checks if all the components don't match the predicate.
    pub fn is_none(&self, mut f: impl FnMut(&T) -> bool) -> bool {
        !f(&self.x) && !f(&self.y) && !f(&self.z)
    }

    /// Checks if at least one doesn't match the predicate.
    pub fn is_any_not(&self, mut f: impl FnMut(&T) -> bool) -> bool {
        !f(&self.x) || !f(&self.y) || !f(&self.z)
    }

    /// Counts how many components match the predicate.
    pub fn get_count(&self, mut f: impl FnMut(&T) -> bool) -> usize {
        f(&self.x) as usize + f(&self.y) as usize + f(&self.z) as usize
    }

    /// Identity.
    pub fn xyz(self) -> Self {
        self
    }

    /// Reorder the vector.
    pub fn xzy(self) -> Self {
        (self.x, self.z, self.y).into()
    }

    /// Reorder the vector.
    pub fn yxz(self) -> Self {
        (self.y, self.x, self.z).into()
    }

    /// Reorder the vector.
    pub fn yzx(self) -> Self {
        (self.y, self.z, self.x).into()
    }

    /// Reorder the vector.
    pub fn zxy(self) -> Self {
        (self.z, self.x, self.y).into()
    }

    /// Reorder the vector.
    pub fn zyx(self) -> Self {
        (self.z, self.y, self.x).into()
    }

    /// Split the vector.
    pub fn x_yz(self) -> (T, Vec2<T>) {
        (self.x, (self.y, self.z).into())
    }

    /// Split and reorder the vector.
    pub fn x_zy(self) -> (T, Vec2<T>) {
        (self.x, (self.z, self.y).into())
    }

    /// Split and reorder the vector.
    pub fn y_xz(self) -> (T, Vec2<T>) {
        (self.y, (self.x, self.z).into())
    }

    /// Split and reorder the vector.
    pub fn y_zx(self) -> (T, Vec2<T>) {
        (self.y, (self.z, self.x).into())
    }

    /// Split and reorder the vector.
    pub fn z_xy(self) -> (T, Vec2<T>) {
        (self.z, (self.x, self.y).into())
    }

    /// Split and reorder the vector.
    pub fn z_yx(self) -> (T, Vec2<T>) {
        (self.z, (self.y, self.x).into())
    }

    /// Split the vector.
    pub fn yz(self) -> Vec2<T> {
        (self.y, self.z).into()
    }

    /// Get two components of the vector.
    pub fn zy(self) -> Vec2<T> {
        (self.z, self.y).into()
    }

    /// Get two components of the vector.
    pub fn xz(self) -> (T, Vec2<T>) {
        (self.y, (self.x, self.z).into())
    }

    /// Get two components of the vector.
    pub fn zx(self) -> Vec2<T> {
        (self.z, self.x).into()
    }

    /// Get two components of the vector.
    pub fn xy(self) -> Vec2<T> {
        (self.x, self.y).into()
    }

    /// Get two components of the vector.
    pub fn yx(self) -> Vec2<T> {
        (self.y, self.x).into()
    }

    /// Creates sorted version of the vector.
    pub fn sorted(self) -> Self
    where
        T: Ord,
    {
        if self.z < self.y {
            if self.z < self.x {
                if self.y < self.x {
                    self.zyx()
                } else {
                    self.zxy()
                }
            } else {
                self.xzy()
            }
        } else if self.y < self.x {
            if self.z < self.x {
                self.yzx()
            } else {
                self.yxz()
            }
        } else {
            self.xyz()
        }
    }

    /// Sorts values in the vector.
    pub fn sort(&mut self)
    where
        T: Ord,
    {
        if self.z < self.y {
            if self.z < self.x {
                mem::swap(&mut self.z, &mut self.x);
                if self.y >= self.x {
                    mem::swap(&mut self.z, &mut self.y);
                }
            } else {
                mem::swap(&mut self.z, &mut self.y);
            }
        } else if self.y < self.x {
            mem::swap(&mut self.y, &mut self.x);
            if self.z < self.x {
                mem::swap(&mut self.z, &mut self.y);
            }
        }
    }

    /// Get 3D position in 3D space with the size of self represented by 1D
    /// container from index into the 1D container.
    ///
    /// This is inverse opration to [`Self::idx_of_pos`].
    ///
    /// E.g. if we have [`Vec`] representing 3D space with dimesions given in
    /// this [`Vec3`], we can give index into the [`Vec`], and this will return
    /// position of that element within the 3D space of size given by this
    /// [`Vec3`].
    pub fn pos_of_idx<I, R>(self, i: I) -> Vec3<R>
    where
        T: Copy + Mul,
        T::Output: Copy,
        I: Copy + Div<T::Output, Output = R> + Rem<T::Output>,
        <I as Rem<T::Output>>::Output:
            Copy + Rem<T, Output = R> + Div<T, Output = R>,
    {
        let xy = self.x * self.y;
        let i2 = i % xy;
        (i2 % self.y, i2 / self.y, i / xy).into()
    }

    /// Get index corresponding to pos to 1D container that represents 3D space
    /// with size of this.
    ///
    /// This is inverse opration to [`Self::pos_of_idx`].
    ///
    /// E.g. if we have [`Vec`] representing 3D space with dimentions given in
    /// this [`Vec3`], we give position within the 3D space, and this will
    /// return index into the [`Vec`].
    #[allow(clippy::type_complexity)]
    pub fn idx_of_pos<R>(
        self,
        pos: impl Into<Vec3<R>>
    ) -> <<<<T as Mul>::Output as Mul<R>>::Output as Add<
            <T as Mul<R>>::Output>
        >::Output as Add<R>>::Output
    where
        T: Copy + Mul + Mul<R>,
        <T as Mul>::Output: Mul<R>,
        <<T as Mul>::Output as Mul<R>>::Output: Add<<T as Mul<R>>::Output>,
        <<<T as Mul>::Output as Mul<R>>::Output as Add<
            <T as Mul<R>>::Output
        >>::Output: Add<R>,
    {
        let p = pos.into();
        self.x * self.y * p.z + self.x * p.y + p.x
    }

    /// Calculate vector in 2D plane on which the x coordinate stays the same.
    ///
    /// The x coordinate will be the x coordinate in the new vector.
    pub fn plane_x(self) -> (T, <<T::Output as Add>::Output as Sqrt>::Output)
    where
        T: Copy + Mul<T>,
        T::Output: Add<T::Output>,
        <T::Output as Add>::Output: Sqrt,
    {
        (self.x, Vec2::new(self.y, self.z).len())
    }

    /// Calculate vector in 2D plane on which the x coordinate stays the same.
    ///
    /// The y coordinate will be the x coordinate in the new vector.
    pub fn plane_y(self) -> (T, <<T::Output as Add>::Output as Sqrt>::Output)
    where
        T: Copy + Mul<T>,
        T::Output: Add<T::Output>,
        <T::Output as Add>::Output: Sqrt,
    {
        (self.y, Vec2::new(self.z, self.x).len())
    }

    /// Calculate vector in 2D plane on which the x coordinate stays the same.
    ///
    /// The z coordinate will be the y coordinate in the new vector.
    pub fn plane_z(self) -> (T, <<T::Output as Add>::Output as Sqrt>::Output)
    where
        T: Copy + Mul<T>,
        T::Output: Add<T::Output>,
        <T::Output as Add>::Output: Sqrt,
    {
        (self.z, Vec2::new(self.x, self.y).len())
    }

    /// Calculate angle to the X axis.
    pub fn angle_x(self) -> <T as Goniometric>::Output
    where
        T: Copy + Mul + Goniometric,
        <T as Mul>::Output: Add<<T as Mul>::Output>,
        <<T as Mul>::Output as Add>::Output: Sqrt<Output = T>,
    {
        Vec2::from(self.plane_x()).angle()
    }

    /// Calculate angle to the Y axis.
    pub fn angle_y(self) -> <T as Goniometric>::Output
    where
        T: Copy + Mul + Goniometric,
        <T as Mul>::Output: Add<<T as Mul>::Output>,
        <<T as Mul>::Output as Add>::Output: Sqrt<Output = T>,
    {
        Vec2::from(self.plane_y()).angle()
    }

    /// Calculate angle to the Z axis.
    pub fn angle_z(self) -> <T as Goniometric>::Output
    where
        T: Copy + Mul + Goniometric,
        <T as Mul>::Output: Add<<T as Mul>::Output>,
        <<T as Mul>::Output as Add>::Output: Sqrt<Output = T>,
    {
        Vec2::from(self.plane_z()).angle()
    }

    /// Calculate polar coordinates with X being the polar axis.
    #[allow(clippy::type_complexity)]
    pub fn polar_x(
        self
    ) -> (
            <<<<T as Mul>::Output as Add>::Output as Add<
                <T as Mul>::Output>
            >::Output as Sqrt>::Output,
            <T as Goniometric>::Output,
            <T as Goniometric>::Output,
        )
    where
        T: Copy + Mul + Goniometric,
        <T as Mul>::Output: Add<<T as Mul>::Output>,
        <<T as Mul>::Output as Add>::Output:
            Add<<T as Mul>::Output> + Sqrt<Output = T>,
        <<<T as Mul>::Output as Add>::Output as Add<
            <T as Mul>::Output>
        >::Output: Sqrt,
    {
        (self.len(), self.angle_x(), self.yz().angle())
    }

    /// Calculate polar coordinates with Y being the polar axis.
    #[allow(clippy::type_complexity)]
    pub fn polar_y(
        self
    ) -> (
            <<<<T as Mul>::Output as Add>::Output as Add<
                <T as Mul>::Output>
            >::Output as Sqrt>::Output,
            <T as Goniometric>::Output,
            <T as Goniometric>::Output,
        )
    where
        T: Copy + Mul + Goniometric,
        <T as Mul>::Output: Add<<T as Mul>::Output>,
        <<T as Mul>::Output as Add>::Output:
            Add<<T as Mul>::Output> + Sqrt<Output = T>,
        <<<T as Mul>::Output as Add>::Output as Add<
            <T as Mul>::Output
        >>::Output: Sqrt,
    {
        (self.len(), self.angle_y(), self.zx().angle())
    }

    /// Calculate polar coordinates with Z being the polar axis.
    #[allow(clippy::type_complexity)]
    pub fn polar_z(
        self
    ) -> (
            <<<<T as Mul>::Output as Add>::Output as Add<
                <T as Mul>::Output>
            >::Output as Sqrt>::Output,
            <T as Goniometric>::Output,
            <T as Goniometric>::Output,
        )
    where
        T: Copy + Mul + Goniometric,
        <T as Mul>::Output: Add<<T as Mul>::Output>,
        <<T as Mul>::Output as Add>::Output:
            Add<<T as Mul>::Output> + Sqrt<Output = T>,
        <<<T as Mul>::Output as Add>::Output as Add<
            <T as Mul>::Output>
        >::Output: Sqrt,
    {
        (self.len(), self.angle_z(), self.xy().angle())
    }

    /// Get normalized version of the vector.
    #[allow(clippy::type_complexity)]
    pub fn normalized(
        self,
    ) -> Vec2<
        <T::Float as Div<
            <<<<T::Float as Mul>::Output as Add>::Output as Add<
                <T::Float as Mul>::Output,
            >>::Output as Sqrt>::Output,
        >>::Output,
    >
    where
        T: IntoFloat,
        T::Float: Copy + Mul,
        <T::Float as Mul>::Output: Add,
        <<T::Float as Mul>::Output as Add>::Output:
            Add<<T::Float as Mul>::Output>,
        <<<T::Float as Mul>::Output as Add>::Output as Add<
            <T::Float as Mul>::Output,
        >>::Output: Sqrt,
        <<<<T::Float as Mul>::Output as Add>::Output as Add<
            <T::Float as Mul>::Output,
        >>::Output as Sqrt>::Output: Copy,
        T::Float: Div<
            <<<<T::Float as Mul>::Output as Add>::Output as Add<
                <T::Float as Mul>::Output,
            >>::Output as Sqrt>::Output,
        >,
    {
        let v = self.map(|a| a.into_float());
        let len = v.len();
        (v.x / len, v.y / len).into()
    }

    /// Normalize the vector.
    pub fn normalize(&mut self)
    where
        T: Copy + Float + Mul,
        T::Output: Add,
        <T::Output as Add>::Output: Add<T::Output>,
        <<T::Output as Add>::Output as Add<T::Output>>::Output: Sqrt,
        <<<T::Output as Add>::Output as Add<
            T::Output
        >>::Output as Sqrt>::Output: Copy,
        T: DivAssign<<<<T::Output as Add>::Output as Add<
            T::Output
        >>::Output as Sqrt>::Output>,
    {
        *self /= self.len();
    }

    /// Creates vector from polar coodinate with polar axis X.
    pub fn from_polar_x<L, P, A>(length: L, polar: P, azimuth: A) -> Self
    where
        P: Copy + Goniometric,
        P::Output: Copy,
        A: Copy + Goniometric,
        L: Copy + Mul<P::Output, Output = T>,
        T: Mul<A::Output, Output = T>,
    {
        let ps = polar.sin();
        (
            length * polar.cos(),
            length * ps * azimuth.cos(),
            length * ps * azimuth.sin(),
        )
            .into()
    }

    /// Creates vector from polar coodinate with polar axis Y.
    pub fn from_polar_y<L, P, A>(length: L, polar: P, azimuth: A) -> Self
    where
        P: Copy + Goniometric,
        P::Output: Copy,
        A: Copy + Goniometric,
        L: Copy + Mul<P::Output, Output = T>,
        T: Mul<A::Output, Output = T>,
    {
        let ps = polar.sin();
        (
            length * ps * azimuth.sin(),
            length * polar.cos(),
            length * ps * azimuth.cos(),
        )
            .into()
    }

    /// Creates vector from polar coodinate with polar axis X.
    pub fn from_polar_z<L, P, A>(length: L, polar: P, azimuth: A) -> Self
    where
        P: Copy + Goniometric,
        P::Output: Copy,
        A: Copy + Goniometric,
        L: Copy + Mul<P::Output, Output = T>,
        T: Mul<A::Output, Output = T>,
    {
        let ps = polar.sin();
        (
            length * ps * azimuth.cos(),
            length * ps * azimuth.sin(),
            length * polar.cos(),
        )
            .into()
    }

    /// Scales the vector to different type. Floating point types are in range
    /// 0..=1 where integer types are in range MIN..=MAX.
    pub fn scale<S>(self) -> Vec3<S>
    where
        T: Scale<S>,
    {
        self.map(|a| a.scale())
    }

    /// Calculates the cross product of two vectors.
    pub fn cross<R>(
        self,
        other: impl Into<Vec3<R>>,
    ) -> Vec3<<T::Output as Sub>::Output>
    where
        T: Copy + Mul<R>,
        T::Output: Sub,
        R: Copy,
    {
        let Vec3 { x, y, z } = other.into();
        (
            self.y * z - self.z * y,
            self.z * x - self.x * z,
            self.x * y - self.y * x,
        )
            .into()
    }

    /// Creates RGB color for 332 format.
    pub fn from_332(c: u8) -> Self
    where
        u8: Scale<T>,
    {
        let mut r = c >> 5;
        r = (r << 5) | (r << 2) | (r >> 1);

        let mut g = (c >> 2) & 7;
        g = (g << 5) | (g << 2) | (g >> 1);

        let mut b = c & 3;
        b |= b << 2;
        b |= b << 4;

        Vec3::new(r, g, b).scale()
    }

    /// Converts this color to rgb 332 color.
    pub fn to_332(self) -> u8
    where
        T: Scale<u8>,
    {
        let (r, g, b) = self.scale().into();
        (r & 0b11100000) | ((g >> 3) & 0b11100) | (b >> 6)
    }

    /// Change the range of values from `ss..=se` to `ds..=de`.
    pub fn change_range(self, ss: T, se: T, ds: T, de: T) -> Vec3<T>
    where
        T: LargeType + Copy + Sub<Output = T>,
        T::Large: Add<Output = T::Large>
            + Sub<Output = T::Large>
            + Mul<Output = T::Large>
            + Div<Output = T::Large>,
    {
        self.map(|a| {
            T::from_large(
                (a.to_large() - ss.to_large()) * (de - ds).to_large()
                    / (se - ss).to_large()
                    + ds.to_large(),
            )
        })
    }

    /// Transform values from normal range to the given range.
    pub fn norm_to_range(self, s: T, e: T) -> Vec3<T>
    where
        T: LargeType + Copy + NormalLimits + Sub<Output = T>,
        T::Large: Add<Output = T::Large>
            + Sub<Output = T::Large>
            + Mul<Output = T::Large>
            + Div<Output = T::Large>,
    {
        self.change_range(T::NORM_MIN, T::NORM_MAX, s, e)
    }

    /// Transform values from the given range to normal range.
    pub fn to_norm_range(self, s: T, e: T) -> Vec3<T>
    where
        T: LargeType + Copy + NormalLimits + Sub<Output = T>,
        T::Large: Add<Output = T::Large>
            + Sub<Output = T::Large>
            + Mul<Output = T::Large>
            + Div<Output = T::Large>,
    {
        self.change_range(s, e, T::NORM_MIN, T::NORM_MAX)
    }

    /// Calculate the absolute value of each component.
    pub fn cabs(self) -> Vec3<T>
    where
        T: PartialOrd + Zero + Neg<Output = T>,
    {
        self.map(|a| if a < T::ZERO { -a } else { a })
    }
}

impl Vec3<bool> {
    /// Checks if all values are true.
    pub fn all(self) -> bool {
        self.x & self.y & self.z
    }

    /// Checks if any value is true.
    pub fn any(self) -> bool {
        self.x | self.y | self.z
    }

    /// Checks if no value is true.
    pub fn none(self) -> bool {
        !self.any()
    }

    /// Checks if at least one value is not true.
    pub fn not_all(self) -> bool {
        !self.all()
    }

    /// Counts the number of true values.
    pub fn count(self) -> usize {
        self.map(|a| a as usize).sum()
    }
}

impl<T> Vec3<&T> {
    /// Clones the components.
    pub fn cloned(self) -> Vec3<T>
    where
        T: Clone,
    {
        self.map(|a| a.clone())
    }

    /// Copies the components.
    pub fn copied(self) -> Vec3<T>
    where
        T: Copy,
    {
        self.map(|a| *a)
    }
}

impl<T: Zero> Vec3<T> {
    /// 3D vectors with all components set to zero.
    pub const ZERO: Vec3<T> = Vec3 {
        x: T::ZERO,
        y: T::ZERO,
        z: T::ZERO,
    };
}

impl<T> From<(T, T, T)> for Vec3<T> {
    fn from((x, y, z): (T, T, T)) -> Self {
        Self { x, y, z }
    }
}

impl<T> From<[T; 3]> for Vec3<T> {
    fn from([x, y, z]: [T; 3]) -> Self {
        Self { x, y, z }
    }
}

impl<T> From<Vec3<T>> for (T, T, T) {
    fn from(value: Vec3<T>) -> Self {
        (value.x, value.y, value.z)
    }
}

impl<T> From<Vec3<T>> for [T; 3] {
    fn from(value: Vec3<T>) -> Self {
        [value.x, value.y, value.z]
    }
}

impl<T> From<(Vec2<T>, T)> for Vec3<T> {
    fn from((Vec2 { x, y }, z): (Vec2<T>, T)) -> Self {
        Vec3 { x, y, z }
    }
}

impl<T> From<((T, T), T)> for Vec3<T> {
    fn from(((x, y), z): ((T, T), T)) -> Self {
        Vec3 { x, y, z }
    }
}

impl<T> From<([T; 2], T)> for Vec3<T> {
    fn from(([x, y], z): ([T; 2], T)) -> Self {
        Vec3 { x, y, z }
    }
}

impl<T> From<(T, Vec2<T>)> for Vec3<T> {
    fn from((x, Vec2 { x: y, y: z }): (T, Vec2<T>)) -> Self {
        Vec3 { x, y, z }
    }
}

impl<T> From<(T, (T, T))> for Vec3<T> {
    fn from((x, (y, z)): (T, (T, T))) -> Self {
        Vec3 { x, y, z }
    }
}

impl<T> From<(T, [T; 2])> for Vec3<T> {
    fn from((x, [y, z]): (T, [T; 2])) -> Self {
        Vec3 { x, y, z }
    }
}

impl<T> Index<usize> for Vec3<T> {
    type Output = T;

    fn index(&self, index: usize) -> &Self::Output {
        match index {
            0 => &self.x,
            1 => &self.y,
            2 => &self.z,
            _ => panic!("Inxe `{index}` is out of bounds for Vec3."),
        }
    }
}

impl<T> IndexMut<usize> for Vec3<T> {
    fn index_mut(&mut self, index: usize) -> &mut Self::Output {
        match index {
            0 => &mut self.x,
            1 => &mut self.y,
            2 => &mut self.z,
            _ => panic!("Inxe `{index}` is out of bounds for Vec3."),
        }
    }
}

impl<Left, Right> PartialEq<(Right, Right, Right)> for Vec3<Left>
where
    Left: PartialEq<Right>,
{
    fn eq(&self, (x, y, z): &(Right, Right, Right)) -> bool {
        self.x == *x && self.y == *y && self.z == *z
    }
}

impl<Left, Right> PartialEq<[Right; 3]> for Vec3<Left>
where
    Left: PartialEq<Right>,
{
    fn eq(&self, [x, y, z]: &[Right; 3]) -> bool {
        self.x == *x && self.y == *y && self.z == *z
    }
}

impl<T: Display> Display for Vec3<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "[{}, {}, {}]", self.x, self.y, self.z)
    }
}

impl<T> IntoIterator for Vec3<T> {
    type Item = T;
    type IntoIter = std::array::IntoIter<T, 3>;

    fn into_iter(self) -> Self::IntoIter {
        let r: [_; 3] = self.into();
        r.into_iter()
    }
}

impl<'a, T> IntoIterator for &'a Vec3<T> {
    type Item = &'a T;
    type IntoIter = std::array::IntoIter<&'a T, 3>;

    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}

impl<'a, T> IntoIterator for &'a mut Vec3<T> {
    type Item = &'a mut T;
    type IntoIter = std::array::IntoIter<&'a mut T, 3>;

    fn into_iter(self) -> Self::IntoIter {
        self.iter_mut()
    }
}

impl<T: Neg> Neg for Vec3<T> {
    type Output = Vec3<T::Output>;

    fn neg(self) -> Self::Output {
        self.map(|x| -x)
    }
}

impl<T: PartialOrd> PartialOrd for Vec3<T> {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        match (
            self.x.partial_cmp(&other.x)?,
            self.y.partial_cmp(&other.y)?,
            self.z.partial_cmp(&other.z)?,
        ) {
            (Ordering::Equal, Ordering::Equal, Ordering::Equal) => {
                Some(Ordering::Equal)
            }
            (
                Ordering::Less | Ordering::Equal,
                Ordering::Less | Ordering::Equal,
                Ordering::Less | Ordering::Equal,
            ) => Some(Ordering::Less),
            (
                Ordering::Greater | Ordering::Equal,
                Ordering::Greater | Ordering::Equal,
                Ordering::Greater | Ordering::Equal,
            ) => Some(Ordering::Greater),
            _ => None,
        }
    }
}

macro_rules! op_single {
    ($op:ident, $fn:ident) => {
        impl<Left, Right> $op<Right> for Vec3<Left>
        where
            Left: $op<Right>,
            Right: Copy,
        {
            type Output = Vec3<Left::Output>;

            fn $fn(self, rhs: Right) -> Self::Output {
                self.map(|x| x.$fn(rhs))
            }
        }
    };
}

macro_rules! op_assign_single {
    ($op:ident, $fn:ident) => {
        impl<Left, Right> $op<Right> for Vec3<Left>
        where
            Left: $op<Right>,
            Right: Copy,
        {
            fn $fn(&mut self, rhs: Right) {
                self.x.$fn(rhs);
                self.y.$fn(rhs);
                self.z.$fn(rhs);
            }
        }
    };
}

macro_rules! op_triple {
    ($op:ident, $fn:ident) => {
        impl<Left, Right> $op<Vec3<Right>> for Vec3<Left>
        where
            Left: $op<Right>,
        {
            type Output = Vec3<Left::Output>;

            fn $fn(self, rhs: Vec3<Right>) -> Self::Output {
                (self.x.$fn(rhs.x), self.y.$fn(rhs.y), self.z.$fn(rhs.z))
                    .into()
            }
        }

        impl<Left, Right> $op<(Right, Right, Right)> for Vec3<Left>
        where
            Left: $op<Right>,
        {
            type Output = Vec3<Left::Output>;

            fn $fn(self, (x, y, z): (Right, Right, Right)) -> Self::Output {
                (self.x.$fn(x), self.y.$fn(y), self.z.$fn(z)).into()
            }
        }

        impl<Left, Right> $op<[Right; 3]> for Vec3<Left>
        where
            Left: $op<Right>,
        {
            type Output = Vec3<Left::Output>;

            fn $fn(self, [x, y, z]: [Right; 3]) -> Self::Output {
                (self.x.$fn(x), self.y.$fn(y), self.z.$fn(z)).into()
            }
        }
    };
}

macro_rules! op_assign_triple {
    ($op:ident, $fn:ident) => {
        impl<Left, Right> $op<Vec3<Right>> for Vec3<Left>
        where
            Left: $op<Right>,
        {
            fn $fn(&mut self, rhs: Vec3<Right>) {
                self.x.$fn(rhs.x);
                self.y.$fn(rhs.y);
                self.z.$fn(rhs.z);
            }
        }

        impl<Left, Right> $op<(Right, Right, Right)> for Vec3<Left>
        where
            Left: $op<Right>,
        {
            fn $fn(&mut self, (x, y, z): (Right, Right, Right)) {
                self.x.$fn(x);
                self.y.$fn(y);
                self.z.$fn(z);
            }
        }

        impl<Left, Right> $op<[Right; 3]> for Vec3<Left>
        where
            Left: $op<Right>,
        {
            fn $fn(&mut self, [x, y, z]: [Right; 3]) {
                self.x.$fn(x);
                self.y.$fn(y);
                self.z.$fn(z);
            }
        }
    };
}

op_single!(Mul, mul);
op_assign_single!(MulAssign, mul_assign);

op_single!(Div, div);
op_assign_single!(DivAssign, div_assign);

op_single!(Rem, rem);
op_assign_single!(RemAssign, rem_assign);

op_triple!(Add, add);
op_assign_triple!(AddAssign, add_assign);

op_triple!(Sub, sub);
op_assign_triple!(SubAssign, sub_assign);