forked from cemyuksel/cyCodeBase
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cyMatrix.h
2427 lines (2143 loc) · 133 KB
/
cyMatrix.h
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
// cyCodeBase by Cem Yuksel
// [www.cemyuksel.com]
//-------------------------------------------------------------------------------
//! \file cyMatrix.h
//! \author Cem Yuksel
//!
//! \brief 2x2, 3x3, 3x4, and 4x4 matrix classes
//!
//-------------------------------------------------------------------------------
//
// Copyright (c) 2016, Cem Yuksel <[email protected]>
// All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
//-------------------------------------------------------------------------------
#ifndef _CY_MATRIX_H_INCLUDED_
#define _CY_MATRIX_H_INCLUDED_
//-------------------------------------------------------------------------------
#include "cyVector.h"
//-------------------------------------------------------------------------------
namespace cy {
//-------------------------------------------------------------------------------
// Forward declarations
//! \cond HIDDEN_SYMBOLS
template <typename T> class Matrix3;
template <typename T> class Matrix34;
template <typename T> class Matrix4;
//! \endcond
//-------------------------------------------------------------------------------
#define _CY_VEC_DEFAULT_ERROR_TOLERANCE 0.0001
//-------------------------------------------------------------------------------
// The macros below help the MSVC compiler with auto-vectorization
#define _CY_FORi(start,end,loop) _CY_IVDEP_FOR ( int i=(start); i<(end); ++i ) { loop; }
#define _CY_FORi0(end,loop) _CY_FORi(0,end,loop)
#define _CY_FOR_4i(loop) _CY_FORi0(4,loop)
#define _CY_FOR_8i(loop) _CY_FOR_4i(loop) _CY_FORi(4,8,loop)
#define _CY_FOR_9i(loop) _CY_FOR_8i(loop) { int i=8; loop; }
#define _CY_FOR_12i(loop) _CY_FOR_8i(loop) _CY_FORi( 8,12,loop)
#define _CY_FOR_16i(loop) _CY_FOR_12i(loop) _CY_FORi(12,16,loop)
//-------------------------------------------------------------------------------
//! 2x2 matrix class.
//!
//! Its data stores 4-value array of column-major matrix elements.
//! You can use Matrix2 with Vec2<T> to transform 2D points.
template <typename T>
class Matrix2
{
CY_NODISCARD friend Matrix2 operator * ( T value, Matrix2 const &right ) { Matrix2 r; _CY_FOR_4i( r.cell[i] = value * right.cell[i] ); return r; } //!< multiply matrix by a value
CY_NODISCARD friend Matrix2 operator + ( T value, Matrix2 const &right ) { return Matrix2(value+right.cell[0], right.cell[2], right.cell[1],value+right.cell[3]); } //!< add a value times identity matrix to a matrix
CY_NODISCARD friend Matrix2 operator - ( T value, Matrix2 const &right ) { return Matrix2(value-right.cell[0],-right.cell[2],-right.cell[1],value-right.cell[3]); } //!< subtract matrix from a value times identity matrix
CY_NODISCARD friend Matrix2 Inverse( Matrix2 const &m ) { return m.GetInverse(); } //!< return the inverse of the matrix
public:
//! Elements of the matrix are column-major: \n
//! | 0 2 | \n
//! | 1 3 | \n
#ifdef __cpp_unrestricted_unions
union {
T cell[4];
Vec2<T> column[2]; // column vectors
};
#else
T cell[4];
#endif
//////////////////////////////////////////////////////////////////////////
//!@name Constructors
Matrix2() CY_CLASS_FUNCTION_DEFAULT //!< Default constructor
template <typename TT> explicit Matrix2<T>( const Matrix2<TT> &matrix ) { MemConvert(cell,matrix.cell,4); } //!< Copy constructor for different types
explicit Matrix2( T const * restrict values ) { Set(values); } //!< Initialize the matrix using an array of 4 values
explicit Matrix2( T v ) { SetScale(v); } //!< Initialize the matrix as identity scaled by v
explicit Matrix2( Vec2<T> const &x, Vec2<T> const &y ) { Set(x,y); } //!< Initialize the matrix using two vectors as columns
explicit Matrix2( Matrix3 <T> const &m );
explicit Matrix2( Matrix34<T> const &m );
explicit Matrix2( Matrix4 <T> const &m );
//! Constructor using row-major order for initialization
Matrix2( T c00, T c01,
T c10, T c11 )
{
cell[0] = c00; cell[2] = c01;
cell[1] = c10; cell[3] = c11;
}
//////////////////////////////////////////////////////////////////////////
//!@name Set & Get Methods
void Zero () { MemClear(cell,4); } //!< Set all the values as zero
bool IsZero () const { return Column(0).IsZero () && Column(1).IsZero (); } //!< Returns true if the matrix is exactly zero
bool IsFinite() const { return Column(0).IsFinite() && Column(1).IsFinite(); } //!< Returns true if all components are finite real numbers.
void Get( T * restrict values ) { MemCopy(values,cell,4); } //!< Copies the matrix cell to the given values array of size 4
void Set( T const * restrict values ) { MemCopy(cell,values,4); } //!< Set Matrix using an array of 4 values
void Set( Vec2<T> const &x, Vec2<T> const &y ) { x.Get(cell); y.Get(cell+2); } //!< Set Matrix using two vectors as columns
void SetIdentity() { SetScale(T(1)); } //!< Converts the matrix to an identity matrix
void SetTensorProduct( Vec2<T> const &v0, Vec2<T> const &v1 ) //!< Sets the matrix as the tensor product (outer product) of two vectors
{
_CY_IVDEP_FOR ( int i=0; i<2; ++i ) cell[ i] = v0[i] * v1.x;
_CY_IVDEP_FOR ( int i=0; i<2; ++i ) cell[2+i] = v0[i] * v1.y;
}
//////////////////////////////////////////////////////////////////////////
//!@name Affine transformations
//! Sets a uniform scale matrix
void SetScale( T uniformScale ) { SetScale(uniformScale,uniformScale); }
//! Sets a scale matrix
void SetScale( T scaleX, T scaleY ) { cell[0]=scaleX; cell[1]=0; cell[2]=0; cell[3]=scaleY;}
//! Sets a scale matrix
void SetScale( Vec2<T> const &scale ) { SetScale(scale.x,scale.y); }
//! Set a rotation matrix by angle
void SetRotation( T angle ) { SetRotation( std::sin(angle), std::cos(angle) ); }
//! Set a rotation matrix by cos and sin of angle
void SetRotation( T sinAngle, T cosAngle ) { cell[0]=cosAngle; cell[1]=-sinAngle; cell[2]=sinAngle; cell[3]=cosAngle; }
//! Sets a Cartesian coordinate frame using the given x direction. x must be a unit vector.
void SetCartesianFrameX( Vec2<T> const &x ) { Set( x, x.GetPerpendicular() ); }
//! Sets a Cartesian coordinate frame using the given y direction. y must be a unit vector.
void SetCartesianFrameY( Vec2<T> const &y ) { Set( -y.GetPerpendicular(), y ); }
//////////////////////////////////////////////////////////////////////////
//!@name Set Row, Column, or Diagonal
void SetRow ( int ri, T x, T y ) { cell[ri]=x; cell[ri+2]=y; } //!< Sets a row of the matrix
void SetRow ( int ri, Vec2<T> const &v ) { SetRow(ri,v.x,v.y); } //!< Sets a row of the matrix
void SetColumn ( int ci, T x, T y ) { Column(ci).Set(x,y); } //!< Sets a column of the matrix
void SetColumn ( int ci, Vec2<T> const &v ) { Column(ci)=v; } //!< Sets a column of the matrix
void SetDiagonal( T xx, T yy ) { cell[0]=xx; cell[3]=yy; } //!< Sets the diagonal values of the matrix
void SetDiagonal( Vec2<T> const &p ) { SetDiagonal( p.x, p.y ); } //!< Sets the diagonal values of the matrix
void SetDiagonal( T const * restrict values ) { SetDiagonal(values[0],values[1]); } //!< Sets the diagonal values of the matrix
//////////////////////////////////////////////////////////////////////////
//!@name Get Row, Column, or Diagonal
#ifdef __cpp_unrestricted_unions
CY_NODISCARD Vec2<T> * Columns() { return column; }
CY_NODISCARD Vec2<T> const * Columns() const { return column; }
CY_NODISCARD Vec2<T> & Column ( int ci ) { return column[ci]; }
CY_NODISCARD Vec2<T> const & Column ( int ci ) const { return column[ci]; }
#else
CY_NODISCARD Vec2<T> * Columns() { return ((Vec2<T>*)cell); }
CY_NODISCARD Vec2<T> const * Columns() const { return ((Vec2<T>*)cell); }
CY_NODISCARD Vec2<T> & Column ( int ci ) { return Columns()[ci]; }
CY_NODISCARD Vec2<T> const & Column ( int ci ) const { return Columns()[ci]; }
#endif
CY_NODISCARD Vec2<T> GetRow ( int ri ) const { return Vec2<T>( cell[ri], cell[ri+2] ); } //!< Returns a row of the matrix
CY_NODISCARD Vec2<T> GetDiagonal() const { return Vec2<T>( cell[0], cell[3] ); } //!< Returns the diagonal of the matrix
CY_NODISCARD Matrix2 GetRotation() const { Matrix2 s, r; GetComponents(s,r); return r; } //!< Returns the rotation portion of the transformation
//! Returns the scale portion of the transformation.
//! The returned matrix is symmetric, but not necessarily diagonal, and it can include non-uniform scale.
CY_NODISCARD Matrix2 GetScale() const
{
Matrix2 trns = GetTranspose();
Matrix2 u2 = *this * trns;
Vec2<T> v0, v1;
u2.GetEigenvectors( v0, v1 );
Matrix2 v(v0,v1);
Matrix2 vt = v.GetTranspose();
Matrix2 d2 = vt * (*this) * v; // the result is a diagonal matrix
Vec2<T> diag = d2.GetDiagonal();
Matrix2 d;
d.SetScale(diag);
return v * d * vt;
}
//! Returns the average scale factor
CY_NODISCARD T GetAvrgScale() const
{
T det = cell[0]*cell[3]-cell[2]*cell[1];
T s = Sqrt( std::abs(det) );
return det >= 0 ? s : -s;
}
void GetComponents( Matrix2<T> &scale, Matrix2<T> &rotation ) const { scale = GetScale(); rotation = *this * scale.GetInverse(); } //!< Returns separate transformation components
//////////////////////////////////////////////////////////////////////////
//!@name Comparison Operators
CY_NODISCARD bool operator == ( Matrix2 const &right ) const { _CY_FOR_4i( if ( cell[i] != right.cell[i] ) return false ); return true; } //!< compare equal
CY_NODISCARD bool operator != ( Matrix2 const &right ) const { _CY_FOR_4i( if ( cell[i] != right.cell[i] ) return true ); return false; } //!< compare not equal
//////////////////////////////////////////////////////////////////////////
//!@name Access Operators
CY_NODISCARD T& operator () ( int ri, int ci ) { assert( ri>=0 && ri<2 && ci>=0 && ci<2 ); return cell[ ci*2 + ri ]; } //!< subscript operator
CY_NODISCARD T const & operator () ( int ri, int ci ) const { assert( ri>=0 && ri<2 && ci>=0 && ci<2 ); return cell[ ci*2 + ri ]; } //!< constant subscript operator
CY_NODISCARD T& operator [] ( int i ) { assert( i>=0 && i<4 ); return cell[i]; } //!< subscript operator
CY_NODISCARD T const & operator [] ( int i ) const { assert( i>=0 && i<4 ); return cell[i]; } //!< constant subscript operator
//////////////////////////////////////////////////////////////////////////
//!@name Unary and Binary Operators
// Unary operators
CY_NODISCARD Matrix2 operator - () const { Matrix2 r; _CY_FOR_4i( r.cell[i] = -cell[i] ); return r; } //!< negative matrix
// Binary operators
CY_NODISCARD Matrix2 operator * ( T const value ) const { Matrix2 r; _CY_FOR_4i( r.cell[i] = cell[i] * value ); return r; } //!< multiply matrix by a value
CY_NODISCARD Matrix2 operator / ( T const value ) const { Matrix2 r; _CY_FOR_4i( r.cell[i] = cell[i] / value ); return r; } //!< divide matrix by a value
CY_NODISCARD Matrix2 operator + ( Matrix2 const &right ) const { Matrix2 r; _CY_FOR_4i( r.cell[i] = cell[i] + right.cell[i] ); return r; } //!< add two Matrices
CY_NODISCARD Matrix2 operator - ( Matrix2 const &right ) const { Matrix2 r; _CY_FOR_4i( r.cell[i] = cell[i] - right.cell[i] ); return r; } //!< subtract one Matrix2 from another
CY_NODISCARD Matrix2 operator * ( Matrix2 const &right ) const //!< multiply a matrix with another
{
Matrix2 r;
r[0] = cell[0] * right.cell[0] + cell[2] * right.cell[1];
r[1] = cell[1] * right.cell[0] + cell[3] * right.cell[1];
r[2] = cell[0] * right.cell[2] + cell[2] * right.cell[3];
r[3] = cell[1] * right.cell[2] + cell[3] * right.cell[3];
return r;
}
CY_NODISCARD Vec2<T> operator * ( Vec2<T> const &p ) const { return Vec2<T>( p.x*cell[0] + p.y*cell[2], p.x*cell[1] + p.y*cell[3] ); }
CY_NODISCARD Matrix2 operator + ( T value ) const { Matrix2 r=*this; r.cell[0]+=value; r.cell[3]+=value; return r; } //!< add a value times identity matrix
CY_NODISCARD Matrix2 operator - ( T value ) const { Matrix2 r=*this; r.cell[0]-=value; r.cell[3]-=value; return r; } //!< subtract a value times identity matrix
//////////////////////////////////////////////////////////////////////////
//!@name Assignment Operators
Matrix2 const & operator += ( Matrix2 const &right ) { _CY_FOR_4i( cell[i] += right.cell[i] ); return *this; } //!< add two Matrices modify this
Matrix2 const & operator -= ( Matrix2 const &right ) { _CY_FOR_4i( cell[i] -= right.cell[i] ); return *this; } //!< subtract one Matrix2 from another matrix and modify this matrix
Matrix2 const & operator *= ( Matrix2 const &right ) { *this = operator*(right); return *this; } //!< multiply a matrix with another matrix and modify this matrix
Matrix2 const & operator *= ( T const value ) { _CY_FOR_4i( cell[i] *= value ); return *this; } //!< multiply a matrix with a value modify this matrix
Matrix2 const & operator /= ( T const value ) { _CY_FOR_4i( cell[i] /= value ); return *this; } //!< divide the matrix by a value modify the this matrix
Matrix2 const & operator += ( T const value ) { cell[0]+=value; cell[3]+=value; return *this; } //!< add a value times identity matrix
Matrix2 const & operator -= ( T const value ) { cell[0]-=value; cell[3]-=value; return *this; } //!< subtract a value times identity matrix
//////////////////////////////////////////////////////////////////////////
//!@name Other Methods
void Transpose() { T tmp=cell[0]; cell[0]=cell[3]; cell[3]=tmp; } //!< Transpose this matrix
CY_NODISCARD Matrix2 GetTranspose() const //!< Returns the transpose of this matrix
{
Matrix2 m;
m.cell[0] = cell[0]; m.cell[1] = cell[2];
m.cell[2] = cell[1]; m.cell[3] = cell[3];
return m;
}
//! Multiply the give vector with the transpose of the matrix
CY_NODISCARD Vec2<T> TransposeMult( Vec2<T> const &p ) const { return Vec2<T>( p.x*cell[0] + p.y*cell[1], p.x*cell[2] + p.y*cell[3] ); }
CY_NODISCARD Matrix2 TransposeMult( Matrix2 const & right ) const //!< Multiply a matrix by the transpose of this one (i.e. this^T * right).
{
Matrix2 r;
r[0] = cell[0] * right.cell[0] + cell[1] * right.cell[1];
r[1] = cell[2] * right.cell[0] + cell[3] * right.cell[1];
r[2] = cell[0] * right.cell[2] + cell[1] * right.cell[3];
r[3] = cell[2] * right.cell[2] + cell[3] * right.cell[3];
return r;
}
CY_NODISCARD Matrix2 MultTranspose( Matrix2 const & right ) const //!< Multiply the transpose of a matrix by this one (i.e. this * right^T).
{
Matrix2 r;
r[0] = cell[0] * right.cell[0] + cell[2] * right.cell[2];
r[1] = cell[1] * right.cell[0] + cell[3] * right.cell[2];
r[2] = cell[0] * right.cell[1] + cell[2] * right.cell[3];
r[3] = cell[1] * right.cell[1] + cell[3] * right.cell[3];
return r;
}
CY_NODISCARD Matrix2 TransposeMultSelf() const { return TransposeMult(*this); } //!< Multiply the transpose of this matrix with itself (i.e. this^T * this).
CY_NODISCARD Matrix2 MultSelfTranspose() const { return MultTranspose(*this); } //!< Multiply the matrix with its transpose (i.e. this * this^T).
CY_NODISCARD T GetTrace() const { return cell[0] + cell[3]; } //!< return the Trace of this matrix
CY_NODISCARD T GetDeterminant() const { return cell[0]*cell[3]-cell[2]*cell[1]; } //!< Get the determinant of this matrix
void Invert() //!< Invert this matrix
{
T det = GetDeterminant();
T cell3 = cell[0] / det;
cell[0] = cell[3] / det;
cell[1] = -cell[1] / det;
cell[2] = -cell[2] / det;
cell[3] = cell3;
}
CY_NODISCARD Matrix2 GetInverse() const //!< Get the inverse of this matrix
{
T det = GetDeterminant();
Matrix2 inv;
inv.cell[0] = cell[3] / det;
inv.cell[1] = -cell[1] / det;
inv.cell[2] = -cell[2] / det;
inv.cell[3] = cell[0] / det;
return inv;
}
//! Removes the scale component of the matrix by normalizing each column.
//! The resulting matrix can contain shear, if it originally contained non-uniform scale and rotation.
void Normalize() { Column(0).Normalize(); Column(1).Normalize(); }
//! Orthogonalizes the matrix and removes the scale component, preserving the x direction
void OrthogonalizeX()
{
Column(0).Normalize();
Column(1) -= Column(0) * (Column(1) % Column(0));
Column(1).Normalize();
}
//! Orthogonalizes the matrix and removes the scale component, preserving the y direction
void OrthogonalizeY()
{
Column(1).Normalize();
Column(0) -= Column(1) * (Column(0) % Column(1));
Column(0).Normalize();
}
//! Returns if the matrix is identity within the given error tollerance.
bool IsIdentity( T tollerance=T(_CY_VEC_DEFAULT_ERROR_TOLERANCE) ) const { return std::abs(cell[0] - T(1)) < tollerance && std::abs(cell[1]) < tollerance && std::abs(cell[2]) < tollerance && std::abs(cell[3] - T(1)) < tollerance; }
//! Returns if the matrix is symmetric within the given error tollerance.
bool IsSymmetric( T tollerance=T(_CY_VEC_DEFAULT_ERROR_TOLERANCE) ) const { return std::abs(cell[0] - cell[2]) < tollerance; }
//! Returns if the matrix is diagonal.
bool IsDiagonal( T tollerance=T(_CY_VEC_DEFAULT_ERROR_TOLERANCE) ) const { return std::abs(cell[1]) + std::abs(cell[2]) < tollerance*2; }
//! Returns the eigenvalues of the matrix.
//! The eigenvalues are ordered, such that the first one is larger.
CY_NODISCARD Vec2<T> GetEigenvalues() const
{
T t = GetTrace();
T d = GetDeterminant();
T a = t*t*T(0.25) - d;
T s = SqrtSafe<T>(a);
Vec2<T> lambda;
lambda.x = t * T(0.5) + s;
lambda.y = t * T(0.5) - s;
return lambda;
}
//! Returns the eigenvalues and sets the given vectors as the eigenvectors of the matrix.
//! The eigenvalues are ordered, such that the first one is larger.
//! The given tollerance is used for checking whether the eigenvalues are the same.
Vec2<T> GetEigenvectors( Vec2<T> &evec0, Vec2<T> &evec1, T tollerance=T(_CY_VEC_DEFAULT_ERROR_TOLERANCE) ) const
{
Vec2<T> lambda = GetEigenvalues();
if ( std::abs(lambda.x - lambda.y) < tollerance ) {
evec0 = Column(0);
evec1 = Column(1);
} else {
Matrix2 v0( cell[0]-lambda.y, cell[1], cell[2], cell[3]-lambda.y );
Matrix2 v1( cell[0]-lambda.x, cell[1], cell[2], cell[3]-lambda.x );
evec0 = v0.Column(0) + v0.Column(1);
evec1 = v1.Column(0) + v1.Column(1);
}
return lambda;
}
//! Singular value decomposition (SVD).
//! Returns the SVD of the matrix, where U and V are orthogonal matrices and
//! S is the diagonal elements of a diagonal matrix (including zeros),
//! such that this matrix A = U S V^T.
void SingularValueDecomposition( Matrix2<T> &U, Vec2<T> &S, Matrix2<T> &V )
{
Matrix2 AAT = MultSelfTranspose();
Vec2<T> lambda = AAT.GetEigenvectors( U.Column(0), U.Column(1) );
S = (lambda.Abs()).Sqrt();
U.Normalize();
Matrix2 ATA = TransposeMultSelf();
AAT.GetEigenvectors( V.Column(0), V.Column(1) );
V.Normalize();
}
//////////////////////////////////////////////////////////////////////////
//!@name Static Methods
//! Returns an identity matrix
CY_NODISCARD static Matrix2 Identity() { T c[] = { 1,0, 0,1 }; return Matrix2(c); }
//! Returns a rotation matrix by angle in radians
CY_NODISCARD static Matrix2 Rotation( T angle ) { Matrix2 m; m.SetRotation(angle); return m; }
//! Returns a rotation matrix by cos and sin of the rotation angle
CY_NODISCARD static Matrix2 Rotation( T cosAngle, T sinAngle ) { Matrix2 m; m.SetRotation(cosAngle,sinAngle); return m; }
//! Returns a uniform scale matrix
CY_NODISCARD static Matrix2 Scale( T uniformScale ) { Matrix2 m; m.SetScale(uniformScale); return m; }
//! Returns a scale matrix
CY_NODISCARD static Matrix2 Scale( T scaleX, T scaleY ) { Matrix2 m; m.SetScale(scaleX,scaleY); return m; }
//! Returns a scale matrix
CY_NODISCARD static Matrix2 Scale( Vec2<T> const &scale ) { Matrix2 m; m.SetScale(scale); return m; }
//! Returns the tensor product (outer product) matrix of two vectors
CY_NODISCARD static Matrix2 TensorProduct( Vec2<T> const &v0, Vec2<T> const &v1 ) { Matrix2 m; m.SetTensorProduct(v0,v1); return m; }
//////////////////////////////////////////////////////////////////////////
};
//-------------------------------------------------------------------------------
#ifdef CY_NONVECTORIZED_MATRIX3
# define _CY_INIT_MATRIX3_VECTORIZATION const int N = 3; T const *cell_6 = cell + 6;
#else
# define _CY_INIT_MATRIX3_VECTORIZATION const int N = 4; T cell_6[4] = { cell[6], cell[7], cell[8], cell[8] };
#endif
//-------------------------------------------------------------------------------
//! 3x3 matrix class.
//!
//! Its data stores 9-value array of column-major matrix elements.
//! You can use Matrix3 with Vec3<T> to transform 3D points.
template <typename T>
class Matrix3
{
CY_NODISCARD friend Matrix3 operator * ( T value, Matrix3 const &right ) { Matrix3 r; _CY_FOR_9i( r.cell[i] = value * right.cell[i] ); return r; } //!< multiply matrix by a value
CY_NODISCARD friend Matrix3 operator + ( T value, Matrix3 const &right ) { Matrix3 r= right; r.cell[0]+=value; r.cell[4]+=value; r.cell[8]+=value; return r; } //!< add a value times identity matrix to a matrix
CY_NODISCARD friend Matrix3 operator - ( T value, Matrix3 const &right ) { Matrix3 r=-right; r.cell[0]+=value; r.cell[4]+=value; r.cell[8]+=value; return r; } //!< subtract a matrix from a value times identity matrix
CY_NODISCARD friend Matrix3 Inverse( Matrix3 const &m ) { return m.GetInverse(); } //!< return the inverse of the matrix
public:
//! Elements of the matrix are column-major: \n
//! | 0 3 6 | \n
//! | 1 4 7 | \n
//! | 2 5 8 | \n
#ifdef __cpp_unrestricted_unions
union {
T cell[9];
Vec3<T> column[3]; // column vectors
};
#else
T cell[9];
#endif
//////////////////////////////////////////////////////////////////////////
//!@name Constructors
Matrix3() CY_CLASS_FUNCTION_DEFAULT //!< Default constructor
template <typename TT> explicit Matrix3<T>( Matrix3<TT> const &matrix ) { MemConvert(cell,matrix.cell,9); } //!< Copy constructor for different types
explicit Matrix3( T const * restrict values ) { Set(values); } //!< Initialize the matrix using an array of 9 values
explicit Matrix3( T v ) { SetScale(v); } //!< Initialize the matrix as identity scaled by v
explicit Matrix3( Vec3<T> const &x, Vec3<T> const &y, Vec3<T> const &z ) { Set(x,y,z); } //!< Initialize the matrix using x,y,z vectors as columns
explicit Matrix3( Matrix2 <T> const &m ) { Column(0).Set(m.Column(0),0); Column(1).Set(m.Column(1),0); Column(2).Set(0,0,1); }
explicit Matrix3( Matrix34<T> const &m );
explicit Matrix3( Matrix4 <T> const &m );
//! Constructor using row-major order for initialization
Matrix3( T c00, T c01, T c02,
T c10, T c11, T c12,
T c20, T c21, T c22 )
{
cell[0] = c00; cell[3] = c01; cell[6] = c02;
cell[1] = c10; cell[4] = c11; cell[7] = c12;
cell[2] = c20; cell[5] = c21; cell[8] = c22;
}
//////////////////////////////////////////////////////////////////////////
//!@name Set & Get Methods
void Zero () { MemClear(cell,9); } //!< Set all the values as zero
bool IsZero () const { return Column(0).IsZero () && Column(1).IsZero () && Column(2).IsZero (); } //!< Returns true if the matrix is exactly zero
bool IsFinite() const { return Column(0).IsFinite() && Column(1).IsFinite() && Column(2).IsFinite(); } //!< Returns true if all components are finite real numbers.
void Get( T * restrict values ) { MemCopy(values,cell,9); } //!< Copies the matrix cell to the given values array of size 9
void Set( T const * restrict values ) { MemCopy(cell,values,9); } //!< Set matrix using an array of 9 values
void Set( Vec3<T> const &x, Vec3<T> const &y, Vec3<T> const &z ) { Column(0)=x; Column(1)=y; Column(2)=z; } //!< Set matrix using x,y,z vectors as columns
void SetIdentity() { SetScale(T(1)); } //!< Converts the matrix to an identity matrix
void SetTensorProduct( Vec3<T> const &v0, Vec3<T> const &v1 ) //!< Sets the matrix as the tensor product (outer product) of two vectors
{
_CY_IVDEP_FOR ( int i=0; i<3; ++i ) cell[ i] = v0[i] * v1.x;
_CY_IVDEP_FOR ( int i=0; i<3; ++i ) cell[3+i] = v0[i] * v1.y;
_CY_IVDEP_FOR ( int i=0; i<3; ++i ) cell[6+i] = v0[i] * v1.z;
}
//! Matrix representation of the cross product ( a x b)
void SetCrossProd( Vec3<T> const &p ) { cell[0]=T(0); cell[1]=p.z; cell[2]=-p.y; cell[3]=-p.z; cell[4]=T(0); cell[5]=p.x; cell[6]=p.y; cell[7]=-p.x; cell[8]=T(0); }
//////////////////////////////////////////////////////////////////////////
//!@name Affine transformations
//! Sets a uniform scale matrix
void SetScale( T uniformScale ) { SetScale(uniformScale,uniformScale,uniformScale); }
//! Sets a scale matrix
void SetScale( T scaleX, T scaleY, T scaleZ )
{
cell[0] = scaleX; cell[1] = 0; cell[2]=0;
cell[3] = 0; cell[4] = scaleY; cell[5]=0;
cell[6] = 0; cell[7] = 0; cell[8]=scaleZ;
}
//! Sets a scale matrix
void SetScale( Vec3<T> const &scale ) { SetScale(scale.x,scale.y,scale.z); }
//! Set as rotation matrix around x axis
void SetRotationX( T angle ) { SetRotationX( std::sin(angle), std::cos(angle) ); }
//! Set as rotation matrix around x axis by cos and sin of angle
void SetRotationX( T sinAngle, T cosAngle )
{
cell[0] = T(1); cell[1] = T(0); cell[2] = T(0);
cell[3] = T(0); cell[4] = cosAngle; cell[5] = sinAngle;
cell[6] = T(0); cell[7] = -sinAngle; cell[8] = cosAngle;
}
//! Set as rotation matrix around y axis
void SetRotationY( T angle ) { SetRotationY( std::sin(angle), std::cos(angle) ); }
//! Set as rotation matrix around y axis by cos and sin of angle
void SetRotationY( T sinAngle, T cosAngle )
{
cell[0] = cosAngle; cell[1] = T(0); cell[2] = -sinAngle;
cell[3] = T(0); cell[4] = T(1); cell[5] = T(0);
cell[6] = sinAngle; cell[7] = T(0); cell[8] = cosAngle;
}
//! Set as rotation matrix around z axis
void SetRotationZ( T angle ) { SetRotationZ( std::sin(angle), std::cos(angle) ); }
//! Set as rotation matrix around z axis by cos and sin of angle
void SetRotationZ( T sinAngle, T cosAngle )
{
cell[0] = cosAngle; cell[1] = sinAngle; cell[2] = T(0);
cell[3] = -sinAngle; cell[4] = cosAngle; cell[5] = T(0);
cell[6] = T(0); cell[7] = T(0); cell[8] = T(1);
}
//! Set as rotation matrix around x, y, and then z axes ( Rz * Ry * Rx )
void SetRotationXYZ( T angleX, T angleY, T angleZ )
{
T sx = std::sin(angleX);
T cx = std::cos(angleX);
T sy = std::sin(angleY);
T cy = std::cos(angleY);
T sz = std::sin(angleZ);
T cz = std::cos(angleZ);
cell[0] = cy*cz; cell[1] = cy*sz; cell[2] =-sy;
cell[3] = cz*sx*sy - cx*sz; cell[4] = cx*cz + sx*sy*sz; cell[5] = cy*sx;
cell[6] = cx*cz*sy + sx*sz; cell[7] =-cz*sx + cx*sy*sz; cell[8] = cx*cy;
}
//! Set as rotation matrix around z, y, and then x axes ( Rx * Ry * Rz )
void SetRotationZYX( T angleX, T angleY, T angleZ )
{
T sx = std::sin(angleX);
T cx = std::cos(angleX);
T sy = std::sin(angleY);
T cy = std::cos(angleY);
T sz = std::sin(angleZ);
T cz = std::cos(angleZ);
cell[0] = cy*cz; cell[1] = cx*sz + sx*sy*cz; cell[2] = sx*sz - cx*sy*cz;
cell[3] = -cy*sz; cell[4] = cx*cz - sx*sy*sz; cell[5] = sx*cz + cx*sy*sz;
cell[6] = sy; cell[7] = -sx*cy; cell[8] = cx*cy;
}
//! Set a rotation matrix about the given axis by angle
void SetRotation( Vec3<T> const &axis, T angle ) { SetRotation(axis,std::sin(angle),std::cos(angle)); }
//! Set a rotation matrix about the given axis by cos and sin of angle
void SetRotation( Vec3<T> const &axis, T sinAngle, T cosAngle )
{
T t = T(1) - cosAngle;
Vec3<T> a = t * axis;
T txy = a.x * axis.y;
T txz = a.x * axis.z;
T tyz = a.y * axis.z;
Vec3<T> s = sinAngle * axis;
cell[ 0] = a.x * axis.x + cosAngle; cell[ 1] = txy + s.z; cell[ 2] = txz - s.y;
cell[ 3] = txy - s.z; cell[ 4] = a.y * axis.y + cosAngle; cell[ 5] = tyz + s.x;
cell[ 6] = txz + s.y; cell[ 7] = tyz - s.x; cell[ 8] = a.z * axis.z + cosAngle;
}
//! Set a rotation matrix that sets [from] unit vector to [to] unit vector
void SetRotation( Vec3<T> const &from, Vec3<T> const &to )
{
assert( from.IsFinite() && to.IsUnit() );
Vec3<T> axis = from.Cross(to);
T s = axis.Length();
if ( s < T(0.000001) ) SetIdentity();
else {
T c = from.Dot(to);
SetRotation(axis/s, s, c);
}
}
//! Set view matrix using position, target and approximate up vector
void SetView( Vec3<T> const &target, Vec3<T> const &up )
{
Vec3<T> f = target;
f.Normalize();
Vec3<T> s = f.Cross(up);
s.Normalize();
Vec3<T> u = s.Cross(f);
cell[0] = s.x; cell[1] = u.x; cell[2] = -f.x;
cell[3] = s.y; cell[4] = u.y; cell[5] = -f.y;
cell[6] = s.z; cell[7] = u.z; cell[8] = -f.z;
}
//! Sets a Cartesian coordinate frame using the given x direction and an approximate y direction. x must be a unit vector.
void SetCartesianFrameXY( Vec3<T> const &x, Vec3<T> const &y_approx ) { Vec3<T> z = x.Cross(y_approx); z.Normalize(); Vec3<T> y=z.Cross(x); Set(x,y,z); }
//! Sets a Cartesian coordinate frame using the given x direction and an approximate z direction. x must be a unit vector.
void SetCartesianFrameXZ( Vec3<T> const &x, Vec3<T> const &z_approx ) { Vec3<T> y = z_approx.Cross(x); y.Normalize(); Vec3<T> z=x.Cross(y); Set(x,y,z); }
//! Sets a Cartesian coordinate frame using the given y direction and an approximate x direction. y must be a unit vector.
void SetCartesianFrameYX( Vec3<T> const &y, Vec3<T> const &x_approx ) { Vec3<T> z = x_approx.Cross(y); z.Normalize(); Vec3<T> x=y.Cross(z); Set(x,y,z); }
//! Sets a Cartesian coordinate frame using the given y direction and an approximate z direction. y must be a unit vector.
void SetCartesianFrameYZ( Vec3<T> const &y, Vec3<T> const &z_approx ) { Vec3<T> x = y.Cross(z_approx); x.Normalize(); Vec3<T> z=x.Cross(y); Set(x,y,z); }
//! Sets a Cartesian coordinate frame using the given z direction and an approximate x direction. z must be a unit vector.
void SetCartesianFrameZX( Vec3<T> const &z, Vec3<T> const &x_approx ) { Vec3<T> y = z.Cross(x_approx); y.Normalize(); Vec3<T> x=y.Cross(z); Set(x,y,z); }
//! Sets a Cartesian coordinate frame using the given z direction and an approximate y direction. z must be a unit vector.
void SetCartesianFrameZY( Vec3<T> const &z, Vec3<T> const &y_approx ) { Vec3<T> x = y_approx.Cross(z); x.Normalize(); Vec3<T> y=z.Cross(x); Set(x,y,z); }
//////////////////////////////////////////////////////////////////////////
//!@name Set Row, Column, or Diagonal
void SetRow ( int ri, T x, T y, T z ) { cell[ri]=x; cell[ri+3]=y; cell[ri+6]=z; } //!< Sets a row of the matrix
void SetRow ( int ri, Vec3<T> const &v ) { SetRow(ri,v.x,v.y,v.z); } //!< Sets a row of the matrix
void SetColumn ( int ci, T x, T y, T z ) { Column(ci).Set(x,y,z); } //!< Sets a column of the matrix
void SetColumn ( int ci, Vec3<T> const &v ) { Column(ci)=v; } //!< Sets a column of the matrix
void SetDiagonal( T xx, T yy, T zz ) { cell[0]=xx; cell[4]=yy; cell[8]=zz; } //!< Sets the diagonal values of the matrix
void SetDiagonal( Vec3<T> const &p ) { SetDiagonal( p.x, p.y, p.z ); } //!< Sets the diagonal values of the matrix
void SetDiagonal( T const * restrict values ) { SetDiagonal(values[0],values[1],values[2]); } //!< Sets the diagonal values of the matrix
//////////////////////////////////////////////////////////////////////////
//!@name Get Row, Column, or Diagonal
#ifdef __cpp_unrestricted_unions
CY_NODISCARD Vec3<T> * Columns() { return column; }
CY_NODISCARD Vec3<T> const * Columns() const { return column; }
CY_NODISCARD Vec3<T> & Column ( int ci ) { return column[ci]; }
CY_NODISCARD Vec3<T> const & Column ( int ci ) const { return column[ci]; }
#else
CY_NODISCARD Vec3<T> * Columns() { return ((Vec3<T>*)cell); }
CY_NODISCARD Vec3<T> const * Columns() const { return ((Vec3<T>*)cell); }
CY_NODISCARD Vec3<T> & Column ( int ci ) { return Columns()[ci]; }
CY_NODISCARD Vec3<T> const & Column ( int ci ) const { return Columns()[ci]; }
#endif
CY_NODISCARD Vec3<T> GetRow ( int ri ) const { return Vec3<T>( cell[ri], cell[ri+3], cell[ri+6] ); } //!< Returns a row of the matrix
CY_NODISCARD Vec3<T> GetDiagonal() const { return Vec3<T>( cell[0], cell[4], cell[8] ); } //!< Returns the diagonal of the matrix
CY_NODISCARD Matrix3 GetRotation() const { Matrix3 s, r; GetComponents(s,r); return r; } //!< Returns the rotation portion of the transformation
//! Returns the scale portion of the transformation.
//! The returned matrix is symmetric, but not necessarily diagonal, and it can include non-uniform scale.
CY_NODISCARD Matrix3 GetScale() const
{
Matrix3 trns = GetTranspose();
Matrix3 u2 = *this * trns;
Vec3<T> v0, v1, v2;
u2.GetEigenvectors( v0, v1, v2 );
Matrix3 v(v0,v1,v2);
Matrix3 vt = v.GetTranspose();
Matrix3 d2 = vt * (*this) * v; // the result is a diagonal matrix
Vec3<T> diag = d2.GetDiagonal();
Matrix3 d;
d.SetScale(diag);
return v * d * vt;
}
//! Returns the average scale factor
CY_NODISCARD T GetAvrgScale() const
{
T det = cell[0] * ( cell[4] * cell[8] - cell[5] * cell[7] ) +
cell[1] * ( cell[5] * cell[6] - cell[3] * cell[8] ) +
cell[2] * ( cell[3] * cell[7] - cell[4] * cell[6] );
T s = std::pow( std::abs(det), T(1)/T(3) );
return det >= 0 ? s : -s;
}
void GetComponents( Matrix3<T> &scale, Matrix3<T> &rotation ) const { scale = GetScale(); rotation = *this * scale.GetInverse(); } //!< Returns separate transformation components
//////////////////////////////////////////////////////////////////////////
//!@name Get Sub-matrix cell
CY_NODISCARD Matrix2<T> GetSubMatrix2() const { Matrix2<T> m; MemCopy(m.cell,cell,2); MemCopy(m.cell+2,cell+3,2); return m; } //!< Returns the 2x2 portion of the matrix
//////////////////////////////////////////////////////////////////////////
//!@name Comparison Operators
CY_NODISCARD bool operator == ( Matrix3 const &right ) const { _CY_FOR_9i( if ( cell[i] != right.cell[i] ) return false ); return true; } //!< compare equal
CY_NODISCARD bool operator != ( Matrix3 const &right ) const { _CY_FOR_9i( if ( cell[i] != right.cell[i] ) return true ); return false; } //!< compare not equal
//////////////////////////////////////////////////////////////////////////
//!@name Access Operators
CY_NODISCARD T& operator () ( int ri, int ci ) { assert( ri>=0 && ri<3 && ci>=0 && ci<3 ); return cell[ ci*3 + ri ]; } //!< subscript operator
CY_NODISCARD T const & operator () ( int ri, int ci ) const { assert( ri>=0 && ri<3 && ci>=0 && ci<3 ); return cell[ ci*3 + ri ]; } //!< constant subscript operator
CY_NODISCARD T& operator [] ( int i ) { assert( i>=0 && i<9 ); return cell[i]; } //!< subscript operator
CY_NODISCARD T const & operator [] ( int i ) const { assert( i>=0 && i<9 ); return cell[i]; } //!< constant subscript operator
//////////////////////////////////////////////////////////////////////////
//!@name Unary and Binary Operators
// Unary operators
CY_NODISCARD Matrix3 operator - () const { Matrix3 r; _CY_FOR_9i( r.cell[i] = -cell[i] ); return r; } //!< negative matrix
// Binary operators
CY_NODISCARD Matrix3 operator * ( T const value ) const { Matrix3 r; _CY_FOR_9i( r.cell[i] = cell[i] * value ); return r; } //!< multiply matrix by a value
CY_NODISCARD Matrix3 operator / ( T const value ) const { Matrix3 r; _CY_FOR_9i( r.cell[i] = cell[i] / value ); return r; } //!< divide matrix by a value
CY_NODISCARD Matrix3 operator + ( Matrix3 const &right ) const { Matrix3 r; _CY_FOR_9i( r.cell[i] = cell[i] + right.cell[i] ); return r; } //!< add two Matrices
CY_NODISCARD Matrix3 operator - ( Matrix3 const &right ) const { Matrix3 r; _CY_FOR_9i( r.cell[i] = cell[i] - right.cell[i] ); return r; } //!< subtract one Matrix3 from another
CY_NODISCARD Matrix3 operator * ( Matrix3 const &right ) const //!< multiply a matrix with another
{
_CY_INIT_MATRIX3_VECTORIZATION;
Matrix3 rm;
for ( int i=0; i<9; i+=3 ) {
T a[4], b[4], c[4], d[4], r[4];
_CY_IVDEP_FOR ( int j=0; j<N; ++j ) a[j] = cell[ j] * right.cell[i ];
_CY_IVDEP_FOR ( int j=0; j<N; ++j ) b[j] = cell[3+j] * right.cell[i+1];
_CY_IVDEP_FOR ( int j=0; j<N; ++j ) c[j] = cell_6[j] * right.cell[i+2];
_CY_IVDEP_FOR ( int j=0; j<N; ++j ) d[j] = a[j] + b[j];
_CY_IVDEP_FOR ( int j=0; j<N; ++j ) r[j] = d[j] + c[j];
MemCopy( rm.cell+i, r, 3 );
}
return rm;
}
CY_NODISCARD Vec3<T> operator * ( Vec3<T> const &p ) const
{
_CY_INIT_MATRIX3_VECTORIZATION;
//return Vec3<T>( p.x*cell[0] + p.y*cell[3] + p.z*cell[6],
// p.x*cell[1] + p.y*cell[4] + p.z*cell[7],
// p.x*cell[2] + p.y*cell[5] + p.z*cell[8] );
T a[4], b[4], c[4], d[4], r[4];
_CY_IVDEP_FOR ( int i=0; i<N; ++i ) a[i] = p[0] * cell[ i];
_CY_IVDEP_FOR ( int i=0; i<N; ++i ) b[i] = p[1] * cell[3+i];
_CY_IVDEP_FOR ( int i=0; i<N; ++i ) c[i] = p[2] * cell_6[i];
_CY_IVDEP_FOR ( int i=0; i<N; ++i ) d[i] = a[i] + b[i];
_CY_IVDEP_FOR ( int i=0; i<N; ++i ) r[i] = d[i] + c[i];
return Vec3<T>(r);
}
CY_NODISCARD Matrix3 operator + ( T value ) const { Matrix3 r=*this; r.cell[0]+=value; r.cell[4]+=value; r.cell[8]+=value; return r; } //!< add a value times identity matrix
CY_NODISCARD Matrix3 operator - ( T value ) const { Matrix3 r=*this; r.cell[0]-=value; r.cell[4]-=value; r.cell[8]-=value; return r; } //!< subtract a value times identity matrix
//////////////////////////////////////////////////////////////////////////
//!@name Assignment Operators
Matrix3 const & operator *= ( Matrix3 const &right ) { *this = operator*(right); return *this; } //!< multiply a matrix with another matrix and modify this matrix
Matrix3 const & operator += ( Matrix3 const &right ) { _CY_FOR_9i( cell[i] += right.cell[i] ); return *this; } //!< add two Matrices modify this
Matrix3 const & operator -= ( Matrix3 const &right ) { _CY_FOR_9i( cell[i] -= right.cell[i] ); return *this; } //!< subtract one Matrix3 from another matrix and modify this matrix
Matrix3 const & operator *= ( T const value ) { _CY_FOR_9i( cell[i] *= value ); return *this; } //!< multiply a matrix with a value modify this matrix
Matrix3 const & operator /= ( T const value ) { _CY_FOR_9i( cell[i] /= value ); return *this; } //!< divide the matrix by a value modify the this matrix
Matrix3 const & operator += ( T const value ) { cell[0]+=value; cell[4]+=value; cell[8]+=value; return *this; } //!< add a value times identity matrix
Matrix3 const & operator -= ( T const value ) { cell[0]-=value; cell[4]-=value; cell[8]-=value; return *this; } //!< subtract a value times identity matrix
//////////////////////////////////////////////////////////////////////////
//!@name Other Methods
//! Adds a diagonal matrix to this matrix and returns the result.
CY_NODISCARD Matrix3 AddDiagonal( T xx, T yy, T zz ) const
{
Matrix3 m;
m.cell[0] = cell[0] + xx;
m.cell[1] = cell[1];
m.cell[2] = cell[2];
m.cell[3] = cell[3];
m.cell[4] = cell[4] + yy;
m.cell[5] = cell[5];
m.cell[6] = cell[6];
m.cell[7] = cell[7];
m.cell[8] = cell[8] + zz;
return m;
}
CY_NODISCARD Matrix3 AddDiagonal( Vec3<T> const &diag ) const { return AddDiagonal(diag.x,diag.y,diag.z); } //!< Adds a diagonal matrix to this matrix and returns the result.
CY_NODISCARD Matrix3 AddIdentity( T scale=T(1) ) const { return AddDiagonal( scale, scale, scale ); } //!< Adds a scaled identity matrix to this matrix and returns the result.
void Transpose() //!< Transpose this matrix
{
for ( int i = 1; i < 3; ++i ) {
for ( int j = 0; j < i; j++) {
T temp = cell[i * 3 + j];
cell[i * 3 + j] = cell[j * 3 + i];
cell[j * 3 + i] = temp;
}
}
}
CY_NODISCARD Matrix3 GetTranspose() const //!< Return the transpose of this matrix
{
Matrix3 m;
m.cell[0] = cell[0]; m.cell[1] = cell[3]; m.cell[2] = cell[6];
m.cell[3] = cell[1]; m.cell[4] = cell[4]; m.cell[5] = cell[7];
m.cell[6] = cell[2]; m.cell[7] = cell[5]; m.cell[8] = cell[8];
return m;
}
//! Multiply the give vector with the transpose of the matrix
CY_NODISCARD Vec3<T> TransposeMult( Vec3<T> const &p ) const
{
return Vec3<T>( p.x*cell[0] + p.y*cell[1] + p.z*cell[2],
p.x*cell[3] + p.y*cell[4] + p.z*cell[5],
p.x*cell[6] + p.y*cell[7] + p.z*cell[8] );
}
CY_NODISCARD Matrix3 TransposeMult( Matrix3 const & right ) const //!< Multiply a matrix by the transpose of this one (i.e. this^T * right).
{
Matrix3 r;
for ( int i=0, k=0; i<3; ++i ) {
for ( int j=0; j<3; ++j, ++k ) {
r.cell[k] = Column(j).Dot( right.Column(i) );
}
}
return r;
}
CY_NODISCARD Matrix3 MultTranspose( Matrix3 const & right ) const //!< Multiply the transpose of a matrix by this one (i.e. this * right^T).
{
_CY_INIT_MATRIX3_VECTORIZATION;
Matrix3 rm;
for ( int i=0; i<3; ++i ) {
T a[4], b[4], c[4], d[4], r[4];
_CY_IVDEP_FOR ( int j=0; j<N; ++j ) a[j] = cell[ j] * right.cell[i ];
_CY_IVDEP_FOR ( int j=0; j<N; ++j ) b[j] = cell[3+j] * right.cell[i+3];
_CY_IVDEP_FOR ( int j=0; j<N; ++j ) c[j] = cell_6[j] * right.cell[i+6];
_CY_IVDEP_FOR ( int j=0; j<N; ++j ) d[j] = a[j] + b[j];
_CY_IVDEP_FOR ( int j=0; j<N; ++j ) r[j] = d[j] + c[j];
MemCopy( rm.cell+i, r, 3 );
}
return rm;
}
CY_NODISCARD Matrix3 TransposeMultSelf() const { return TransposeMult(*this); } //!< Multiply the transpose of this matrix with itself (i.e. this^T * this).
CY_NODISCARD Matrix3 MultSelfTranspose() const { return MultTranspose(*this); } //!< Multiply the matrix with its transpose (i.e. this * this^T).
CY_NODISCARD T GetTrace() const { return cell[0]+cell[4]+cell[8]; }
CY_NODISCARD T GetDeterminant() const { //!< Get the determinant of this matrix
// 0 (4 8 - 5 7) + 1 (5 6 - 3 8) + 2 (3 7 - 4 6)
return cell[0] * ( cell[4] * cell[8] - cell[5] * cell[7] ) +
cell[1] * ( cell[5] * cell[6] - cell[3] * cell[8] ) +
cell[2] * ( cell[3] * cell[7] - cell[4] * cell[6] );
}
void Invert() { *this = GetInverse(); } //!< Invert this matrix
CY_NODISCARD Matrix3 GetInverse() const //!< Get the inverse of this matrix
{
// ( 4 8 - 5 7 5 6 - 3 8 3 7 - 4 6 )
// ( 2 7 - 1 8 0 8 - 2 6 1 6 - 0 7 ) / det
// ( 1 5 - 2 4 2 3 - 0 5 0 4 - 1 3 )
Matrix3 inverse;
inverse.cell[0] = (cell[4]*cell[8] - cell[5]*cell[7]);
inverse.cell[1] = (cell[2]*cell[7] - cell[1]*cell[8]);
inverse.cell[2] = (cell[1]*cell[5] - cell[2]*cell[4]);
inverse.cell[3] = (cell[5]*cell[6] - cell[3]*cell[8]);
inverse.cell[4] = (cell[0]*cell[8] - cell[2]*cell[6]);
inverse.cell[5] = (cell[2]*cell[3] - cell[0]*cell[5]);
inverse.cell[6] = (cell[3]*cell[7] - cell[4]*cell[6]);
inverse.cell[7] = (cell[1]*cell[6] - cell[0]*cell[7]);
inverse.cell[8] = (cell[0]*cell[4] - cell[1]*cell[3]);
T det = cell[0] * inverse.cell[0] + cell[1] * inverse.cell[3] + cell[2] * inverse.cell[6];
return inverse / det;
}
//! Removes the scale component of the matrix by normalizing each column.
//! The resulting matrix can contain shear, if it originally contained non-uniform scale and rotation.
void Normalize() { Column(0).Normalize(); Column(1).Normalize(); Column(2).Normalize(); }
//! Orthogonalizes the matrix and removes the scale component, preserving the x direction
void OrthogonalizeX()
{
Column(0).Normalize();
Column(1) -= Column(0) * (Column(1) % Column(0));
Column(1).Normalize();
Column(2) -= Column(0) * (Column(2) % Column(0));
Column(2) -= Column(1) * (Column(2) % Column(1));
Column(2).Normalize();
}
//! Orthogonalizes the matrix and removes the scale component, preserving the y direction
void OrthogonalizeY()
{
Column(1).Normalize();
Column(0) -= Column(1) * (Column(0) % Column(1));
Column(0).Normalize();
Column(2) -= Column(1) * (Column(2) % Column(1));
Column(2) -= Column(0) * (Column(2) % Column(0));
Column(2).Normalize();
}
//! Orthogonalizes the matrix and removes the scale component, preserving the z direction
void OrthogonalizeZ()
{
Column(2).Normalize();
Column(0) -= Column(2) * (Column(0) % Column(2));
Column(0).Normalize();
Column(1) -= Column(2) * (Column(1) % Column(2));
Column(1) -= Column(0) * (Column(1) % Column(0));
Column(1).Normalize();
}
//! Returns if the matrix is identity within the given error tollerance.
bool IsIdentity( T tollerance=T(_CY_VEC_DEFAULT_ERROR_TOLERANCE) ) const
{
return std::abs(cell[0]-T(1)) < tollerance && std::abs(cell[1]) < tollerance && std::abs(cell[2]) < tollerance &&
std::abs(cell[3]) < tollerance && std::abs(cell[4]-T(1)) < tollerance && std::abs(cell[5]) < tollerance &&
std::abs(cell[6]) < tollerance && std::abs(cell[7]) < tollerance && std::abs(cell[8]-T(1)) < tollerance;
}
//! Returns if the matrix is symmetric within the given error tollerance.
bool IsSymmetric( T tollerance=T(_CY_VEC_DEFAULT_ERROR_TOLERANCE) ) const { return std::abs(cell[1] - cell[3]) < tollerance && std::abs(cell[2] - cell[6]) < tollerance && std::abs(cell[5] - cell[7]) < tollerance; }
//! Returns if the matrix is diagonal.
bool IsDiagonal( T tollerance=T(_CY_VEC_DEFAULT_ERROR_TOLERANCE) ) const { return std::abs(cell[1]) + std::abs(cell[2]) + std::abs(cell[3]) + std::abs(cell[5]) + std::abs(cell[6]) + std::abs(cell[7]) < tollerance*6; }
//! Returns the eigenvalues of the matrix.
//! The eigenvalues are ordered, such that the first one is the largest.
//! The given tollerance value is used for checking whether the matrix is diagonal.
CY_NODISCARD Vec3<T> GetEigenvalues( T tollerance=T(_CY_VEC_DEFAULT_ERROR_TOLERANCE) ) const
{
Vec3<T> lambda;
if ( IsDiagonal(tollerance) ) {
lambda = GetDiagonal(); // diagonal matrix, so the eigenvalues are the same as the diagonal elements.
} else {
T q = GetTrace() / 3;
Matrix3 m = AddIdentity(-q);
Matrix3 m2 = m * m;
T p = Sqrt( m2.GetTrace() / T(6) );
Matrix3 B = m / p;
T d_2 = B.GetDeterminant() * T(0.5);
T a = d_2 < T(-1) ? Pi<T>()/3 : ( d_2 > T(1) ? T(0) : ACosSafe<T>(d_2)/3 ); // only guaranteed to work for symmetric matrices
Vec3<T> b;
b.x = 2*std::cos( a );
b.y = 2*std::cos( a + Pi<T>()*(T(2)/T(3)) );
b.z = 2*std::cos( a + Pi<T>()*(T(4)/T(3)) );
lambda = b*p + q;
}
return lambda;
}
//! Returns the eigenvalues and sets the given vector as the eigenvectors of the matrix.
//! The eigenvalues are ordered, such that the first one is the largest.
//! The given tollerance is used for checking whether the eigenvalues are the same.
Vec3<T> GetEigenvectors( Vec3<T> &evec0, Vec3<T> &evec1, Vec3<T> &evec2, T tollerance=T(_CY_VEC_DEFAULT_ERROR_TOLERANCE) ) const
{
static auto setVectors = [&]( Vec3<T> &e0, Vec3<T> &e1, Vec3<T> &e2, Matrix3 const &v20, Matrix3 const &v12, Matrix3 const &v01 ) {
int i = 0;
Matrix3 v2 = v20 * v12;
e2 = v2.Column(0) + v2.Column(1) + v2.Column(2);
if ( (e2 ^ v01.Column(0)).LengthSquared() < tollerance ) {
e0 = v01.Column(1);
e1 = v01.Column(2);
} else {
e0 = v01.Column(0);
e1 = v01.Column( ( (e2 ^ v01.Column(1)).LengthSquared() < tollerance ) ? 2 : 1 );
}
};
Vec3<T> lambda = GetEigenvalues(tollerance);
bool same01 = std::abs(lambda.x - lambda.y) < tollerance;
bool same12 = std::abs(lambda.y - lambda.z) < tollerance;
bool same02 = std::abs(lambda.x - lambda.z) < tollerance;
if ( same01 & same12 ) {
// All eigenvalues are the same, so, assuming that the matrix is normal, it must be scaled identity.
evec0 = Column(0);
evec1 = Column(1);
evec2 = Column(2);
} else {
Matrix3 v12 = AddIdentity( -lambda.x );
Matrix3 v20 = AddIdentity( -lambda.y );
Matrix3 v01 = AddIdentity( -lambda.z );
char same = char(same01) | char(same12)*char(2) | char(same02)*char(3); // only one of them can be true here
switch (same) {
default: case 0: {
Matrix3 v0 = v01 * v20;
Matrix3 v1 = v12 * v01;
Matrix3 v2 = v20 * v12;
evec0 = v0.Column(0) + v0.Column(1) + v0.Column(2);
evec1 = v1.Column(0) + v1.Column(1) + v1.Column(2);
evec2 = v2.Column(0) + v2.Column(1) + v2.Column(2);
}
break;
case 1: setVectors( evec0, evec1, evec2, v20, v12, v01 ); break;
case 2: setVectors( evec1, evec2, evec0, v01, v20, v12 ); break;
case 3: setVectors( evec0, evec2, evec1, v12, v01, v20 ); break;
}
}
return lambda;
}
//! Singular value decomposition (SVD)
//! Returns the SVD of the matrix, where U and V are orthogonal matrices and
//! S is the diagonal elements of a diagonal matrix (including zeros),
//! such that this matrix A = U S V^T.
//! The given tollerance is used for checking whether the eigenvalues are the same.
void SingularValueDecomposition( Matrix3<T> &U, Vec3<T> &S, Matrix3<T> &V, T tollerance=T(_CY_VEC_DEFAULT_ERROR_TOLERANCE) )