1 module gfm.math.matrix;
2 
3 import std.math,
4        std.typetuple,
5        std.traits,
6        std.string,
7        std.typecons,
8        std.conv;
9 
10 import gfm.math.vector,
11        gfm.math.shapes,
12        gfm.math.quaternion;
13 
14 /// Generic non-resizeable matrix with R rows and C columns.
15 /// Intended for 3D use (size 3x3 and 4x4).
16 /// Important: <b>Matrices here are in row-major order whereas OpenGL is column-major.</b>
17 /// Params:
18 ///   T = type of elements
19 ///   R = number of rows
20 ///   C = number of columns
21 struct Matrix(T, int R, int C)
22 {
23     public
24     {
25         static assert(R >= 1 && C >= 1);
26 
27         alias Vector!(T, C) row_t;
28         alias Vector!(T, R) column_t;
29 
30         enum bool isSquare = (R == C);
31 
32         // fields definition
33         union
34         {
35             T[C*R] v;        // all elements
36             row_t[R] rows;   // all rows
37             T[C][R] c;       // components
38         }
39 
40         @nogc this(U...)(U values) pure nothrow
41         {
42             static if ((U.length == C*R) && allSatisfy!(isTAssignable, U))
43             {
44                 // construct with components
45                 foreach(int i, x; values)
46                     v[i] = x;
47             }
48             else static if ((U.length == 1) && (isAssignable!(U[0])) && (!is(U[0] : Matrix)))
49             {
50                 // construct with assignment
51                 opAssign!(U[0])(values[0]);
52             }
53             else static assert(false, "cannot create a matrix from given arguments");
54         }
55 
56         /// Construct a matrix from columns.
57         @nogc static Matrix fromColumns(column_t[] columns) pure nothrow
58         {
59             assert(columns.length == C);
60             Matrix res;
61             for (int i = 0; i < R; ++i)
62                 for (int j = 0; j < C; ++j)
63                 {
64                    res.c[i][j] = columns[j][i];
65                 }
66             return res;
67         }
68 
69         /// Construct a matrix from rows.
70         @nogc static Matrix fromRows(row_t[] rows) pure nothrow
71         {
72             assert(rows.length == R);
73             Matrix res;
74             res.rows[] = rows[];
75             return res;
76         }
77 
78         /// Construct matrix with a scalar.
79         @nogc this(U)(T x) pure nothrow
80         {
81             for (int i = 0; i < _N; ++i)
82                 v[i] = x;
83         }
84 
85         /// Assign with a samey matrice.
86         @nogc ref Matrix opAssign(U : Matrix)(U x) pure nothrow
87         {
88             for (int i = 0; i < R * C; ++i)
89                 v[i] = x.v[i];
90             return this;
91         }
92 
93         /// Assign from other small matrices (same size, compatible type).
94         @nogc ref Matrix opAssign(U)(U x) pure nothrow
95             if (isMatrixInstantiation!U
96                 && is(U._T : _T)
97                 && (!is(U: Matrix))
98                 && (U._R == R) && (U._C == C))
99         {
100             for (int i = 0; i < R * C; ++i)
101                 v[i] = x.v[i];
102             return this;
103         }
104 
105         /// Assign with a static array of size R * C.
106         @nogc ref Matrix opAssign(U)(U x) pure nothrow
107             if ((isStaticArray!U)
108                 && is(typeof(x[0]) : T)
109                 && (U.length == R * C))
110         {
111             for (int i = 0; i < R * C; ++i)
112                 v[i] = x[i];
113             return this;
114         }
115 
116         /// Assign with a dynamic array of size R * C.
117         @nogc ref Matrix opAssign(U)(U x) pure nothrow
118             if ((isDynamicArray!U)
119                 && is(typeof(x[0]) : T))
120         {
121             assert(x.length == R * C);
122             for (int i = 0; i < R * C; ++i)
123                 v[i] = x[i];
124             return this;
125         }
126 
127         /// Return a pointer to content.
128         @nogc inout(T)* ptr() pure inout nothrow @property
129         {
130             return v.ptr;
131         }
132 
133         /// Returns: column j as a vector.
134         @nogc column_t column(int j) pure const nothrow
135         {
136             column_t res = void;
137             for (int i = 0; i < R; ++i)
138                 res.v[i] = c[i][j];
139             return res;
140         }
141 
142         /// Returns: row i as a vector.
143         @nogc row_t row(int i) pure const nothrow
144         {
145             return rows[i];
146         }
147 
148         /// Covnerts to pretty string.
149         string toString() const nothrow
150         {
151             try
152                 return format("%s", v);
153             catch (Exception e)
154                 assert(false); // should not happen since format is right
155         }
156 
157         /// Matrix * vector multiplication.
158         @nogc column_t opBinary(string op)(row_t x) pure const nothrow if (op == "*")
159         {
160             column_t res = void;
161             for (int i = 0; i < R; ++i)
162             {
163                 T sum = 0;
164                 for (int j = 0; j < C; ++j)
165                 {
166                     sum += c[i][j] * x.v[j];
167                 }
168                 res.v[i] = sum;
169             }
170             return res;
171         }
172 
173         /// Matrix * matrix multiplication.
174         @nogc auto opBinary(string op, U)(U x) pure const nothrow
175             if (isMatrixInstantiation!U && (U._R == C) && (op == "*"))
176         {
177             Matrix!(T, R, U._C) result = void;
178 
179             for (int i = 0; i < R; ++i)
180             {
181                 for (int j = 0; j < U._C; ++j)
182                 {
183                     T sum = 0;
184                     for (int k = 0; k < C; ++k)
185                         sum += c[i][k] * x.c[k][j];
186                     result.c[i][j] = sum;
187                 }
188             }
189             return result;
190         }
191 
192         /// Matrix add and substraction.
193         @nogc Matrix opBinary(string op, U)(U other) pure const nothrow
194             if (is(U : Matrix) && (op == "+" || op == "-"))
195         {
196             Matrix result = void;
197 
198             for (int i = 0; i < R; ++i)
199             {
200                 for (int j = 0; j < C; ++j)
201                 {
202                     mixin("result.c[i][j] = c[i][j] " ~ op ~ " other.c[i][j];");
203                 }
204             }
205             return result;
206         }
207 
208         /// Assignment operator with another samey matrix.
209         @nogc ref Matrix opOpAssign(string op, U)(U operand) pure nothrow if (is(U : Matrix))
210         {
211             mixin("Matrix result = this " ~ op ~ " operand;");
212             return opAssign!Matrix(result);
213         }
214 
215         /// Assignment operator with another samey matrix.
216         @nogc ref Matrix opOpAssign(string op, U)(U operand) pure nothrow if (isConvertible!U)
217         {
218             Matrix conv = operand;
219             return opOpAssign!op(conv);
220         }
221 
222         /// Cast to other matrix types.
223         /// If the size are different, the resulting matrix is truncated
224         /// and/or filled with identity coefficients.
225         @nogc U opCast(U)() pure const nothrow if (isMatrixInstantiation!U)
226         {
227             U res = U.identity();
228             enum minR = R < U._R ? R : U._R;
229             enum minC = C < U._C ? C : U._C;
230             for (int i = 0; i < minR; ++i)
231                 for (int j = 0; j < minC; ++j)
232                 {
233                     res.c[i][j] = cast(U._T)(c[i][j]);
234                 }
235             return res;
236         }
237 
238         @nogc bool opEquals(U)(U other) pure const nothrow if (is(U : Matrix))
239         {
240             for (int i = 0; i < R * C; ++i)
241                 if (v[i] != other.v[i])
242                     return false;
243             return true;
244         }
245 
246         @nogc bool opEquals(U)(U other) pure const nothrow
247             if ((isAssignable!U) && (!is(U: Matrix)))
248         {
249             Matrix conv = other;
250             return opEquals(conv);
251         }
252 
253         // +matrix, -matrix, ~matrix, !matrix
254         @nogc Matrix opUnary(string op)() pure const nothrow if (op == "+" || op == "-" || op == "~" || op == "!")
255         {
256             Matrix res = void;
257             for (int i = 0; i < N; ++i)
258                 mixin("res.v[i] = " ~ op ~ "v[i];");
259             return res;
260         }
261 
262         /// Convert 3x3 rotation matrix to quaternion.
263         /// See_also: 3D Math Primer for Graphics and Game Development.
264         @nogc U opCast(U)() pure const nothrow if (isQuaternionInstantiation!U
265                                                    && is(U._T : _T)
266                                                    && (_R == 3) && (_C == 3))
267         {
268             T fourXSquaredMinus1 = c[0][0] - c[1][1] - c[2][2];
269             T fourYSquaredMinus1 = c[1][1] - c[0][0] - c[2][2];
270             T fourZSquaredMinus1 = c[2][2] - c[0][0] - c[1][1];
271             T fourWSquaredMinus1 = c[0][0] + c[1][1] + c[2][2];
272 
273             int biggestIndex = 0;
274             T fourBiggestSquaredMinus1 = fourWSquaredMinus1;
275 
276             if(fourXSquaredMinus1 > fourBiggestSquaredMinus1)
277             {
278                 fourBiggestSquaredMinus1 = fourXSquaredMinus1;
279                 biggestIndex = 1;
280             }
281 
282             if(fourYSquaredMinus1 > fourBiggestSquaredMinus1)
283             {
284                 fourBiggestSquaredMinus1 = fourYSquaredMinus1;
285                 biggestIndex = 2;
286             }
287 
288             if(fourZSquaredMinus1 > fourBiggestSquaredMinus1)
289             {
290                 fourBiggestSquaredMinus1 = fourZSquaredMinus1;
291                 biggestIndex = 3;
292             }
293 
294             T biggestVal = sqrt(fourBiggestSquaredMinus1 + 1) / 2;
295             T mult = 1 / (biggestVal * 4);
296 
297             U quat;
298             switch(biggestIndex)
299             {
300                 case 1:
301                     quat.w = (c[1][2] - c[2][1]) * mult;
302                     quat.x = biggestVal;
303                     quat.y = (c[0][1] + c[1][0]) * mult;
304                     quat.z = (c[2][0] + c[0][2]) * mult;
305                     break;
306 
307                 case 2:
308                     quat.w = (c[2][0] - c[0][2]) * mult;
309                     quat.x = (c[0][1] + c[1][0]) * mult;
310                     quat.y = biggestVal;
311                     quat.z = (c[1][2] + c[2][1]) * mult;
312                     break;
313 
314                 case 3:
315                     quat.w = (c[0][1] - c[1][0]) * mult;
316                     quat.x = (c[2][0] + c[0][2]) * mult;
317                     quat.y = (c[1][2] + c[2][1]) * mult;
318                     quat.z = biggestVal;
319                     break;
320 
321                 default: // biggestIndex == 0
322                     quat.w = biggestVal;
323                     quat.x = (c[1][2] - c[2][1]) * mult;
324                     quat.y = (c[2][0] - c[0][2]) * mult;
325                     quat.z = (c[0][1] - c[1][0]) * mult;
326                     break;
327             }
328 
329             return quat;
330         }
331 
332         /// Converts a 4x4 rotation matrix to quaternion.
333         @nogc U opCast(U)() pure const nothrow if (isQuaternionInstantiation!U
334                                                    && is(U._T : _T)
335                                                    && (_R == 4) && (_C == 4))
336         {
337             auto m3 = cast(mat3!T)(this);
338             return cast(U)(m3);
339         }
340 
341         /// Matrix inversion is provided for 1x1, 2x2, 3x3 and 4x4 floating point matrices.
342 
343         static if (isSquare && isFloatingPoint!T && R == 1)
344         {
345             /// Returns: inverse of matrix.
346             @nogc Matrix inverse() pure const nothrow
347             {
348                 return Matrix( 1 / c[0][0]);
349             }
350         }
351 
352         static if (isSquare && isFloatingPoint!T && R == 2)
353         {
354             /// Returns: inverse of matrix.
355             @nogc Matrix inverse() pure const nothrow
356             {
357                 T invDet = 1 / (c[0][0] * c[1][1] - c[0][1] * c[1][0]);
358                 return Matrix( c[1][1] * invDet, -c[0][1] * invDet,
359                                    -c[1][0] * invDet,  c[0][0] * invDet);
360             }
361         }
362 
363         static if (isSquare && isFloatingPoint!T && R == 3)
364         {
365             /// Returns: inverse of matrix.
366             @nogc Matrix inverse() pure const nothrow
367             {
368                 T det = c[0][0] * (c[1][1] * c[2][2] - c[2][1] * c[1][2])
369                       - c[0][1] * (c[1][0] * c[2][2] - c[1][2] * c[2][0])
370                       + c[0][2] * (c[1][0] * c[2][1] - c[1][1] * c[2][0]);
371                 T invDet = 1 / det;
372 
373                 Matrix res = void;
374                 res.c[0][0] =  (c[1][1] * c[2][2] - c[2][1] * c[1][2]) * invDet;
375                 res.c[0][1] = -(c[0][1] * c[2][2] - c[0][2] * c[2][1]) * invDet;
376                 res.c[0][2] =  (c[0][1] * c[1][2] - c[0][2] * c[1][1]) * invDet;
377                 res.c[1][0] = -(c[1][0] * c[2][2] - c[1][2] * c[2][0]) * invDet;
378                 res.c[1][1] =  (c[0][0] * c[2][2] - c[0][2] * c[2][0]) * invDet;
379                 res.c[1][2] = -(c[0][0] * c[1][2] - c[1][0] * c[0][2]) * invDet;
380                 res.c[2][0] =  (c[1][0] * c[2][1] - c[2][0] * c[1][1]) * invDet;
381                 res.c[2][1] = -(c[0][0] * c[2][1] - c[2][0] * c[0][1]) * invDet;
382                 res.c[2][2] =  (c[0][0] * c[1][1] - c[1][0] * c[0][1]) * invDet;
383                 return res;
384             }
385         }
386 
387         static if (isSquare && isFloatingPoint!T && R == 4)
388         {
389             /// Returns: inverse of matrix.
390             @nogc Matrix inverse() pure const nothrow
391             {
392                 T det2_01_01 = c[0][0] * c[1][1] - c[0][1] * c[1][0];
393                 T det2_01_02 = c[0][0] * c[1][2] - c[0][2] * c[1][0];
394                 T det2_01_03 = c[0][0] * c[1][3] - c[0][3] * c[1][0];
395                 T det2_01_12 = c[0][1] * c[1][2] - c[0][2] * c[1][1];
396                 T det2_01_13 = c[0][1] * c[1][3] - c[0][3] * c[1][1];
397                 T det2_01_23 = c[0][2] * c[1][3] - c[0][3] * c[1][2];
398 
399                 T det3_201_012 = c[2][0] * det2_01_12 - c[2][1] * det2_01_02 + c[2][2] * det2_01_01;
400                 T det3_201_013 = c[2][0] * det2_01_13 - c[2][1] * det2_01_03 + c[2][3] * det2_01_01;
401                 T det3_201_023 = c[2][0] * det2_01_23 - c[2][2] * det2_01_03 + c[2][3] * det2_01_02;
402                 T det3_201_123 = c[2][1] * det2_01_23 - c[2][2] * det2_01_13 + c[2][3] * det2_01_12;
403 
404                 T det = - det3_201_123 * c[3][0] + det3_201_023 * c[3][1] - det3_201_013 * c[3][2] + det3_201_012 * c[3][3];
405                 T invDet = 1 / det;
406 
407                 T det2_03_01 = c[0][0] * c[3][1] - c[0][1] * c[3][0];
408                 T det2_03_02 = c[0][0] * c[3][2] - c[0][2] * c[3][0];
409                 T det2_03_03 = c[0][0] * c[3][3] - c[0][3] * c[3][0];
410                 T det2_03_12 = c[0][1] * c[3][2] - c[0][2] * c[3][1];
411                 T det2_03_13 = c[0][1] * c[3][3] - c[0][3] * c[3][1];
412                 T det2_03_23 = c[0][2] * c[3][3] - c[0][3] * c[3][2];
413                 T det2_13_01 = c[1][0] * c[3][1] - c[1][1] * c[3][0];
414                 T det2_13_02 = c[1][0] * c[3][2] - c[1][2] * c[3][0];
415                 T det2_13_03 = c[1][0] * c[3][3] - c[1][3] * c[3][0];
416                 T det2_13_12 = c[1][1] * c[3][2] - c[1][2] * c[3][1];
417                 T det2_13_13 = c[1][1] * c[3][3] - c[1][3] * c[3][1];
418                 T det2_13_23 = c[1][2] * c[3][3] - c[1][3] * c[3][2];
419 
420                 T det3_203_012 = c[2][0] * det2_03_12 - c[2][1] * det2_03_02 + c[2][2] * det2_03_01;
421                 T det3_203_013 = c[2][0] * det2_03_13 - c[2][1] * det2_03_03 + c[2][3] * det2_03_01;
422                 T det3_203_023 = c[2][0] * det2_03_23 - c[2][2] * det2_03_03 + c[2][3] * det2_03_02;
423                 T det3_203_123 = c[2][1] * det2_03_23 - c[2][2] * det2_03_13 + c[2][3] * det2_03_12;
424 
425                 T det3_213_012 = c[2][0] * det2_13_12 - c[2][1] * det2_13_02 + c[2][2] * det2_13_01;
426                 T det3_213_013 = c[2][0] * det2_13_13 - c[2][1] * det2_13_03 + c[2][3] * det2_13_01;
427                 T det3_213_023 = c[2][0] * det2_13_23 - c[2][2] * det2_13_03 + c[2][3] * det2_13_02;
428                 T det3_213_123 = c[2][1] * det2_13_23 - c[2][2] * det2_13_13 + c[2][3] * det2_13_12;
429 
430                 T det3_301_012 = c[3][0] * det2_01_12 - c[3][1] * det2_01_02 + c[3][2] * det2_01_01;
431                 T det3_301_013 = c[3][0] * det2_01_13 - c[3][1] * det2_01_03 + c[3][3] * det2_01_01;
432                 T det3_301_023 = c[3][0] * det2_01_23 - c[3][2] * det2_01_03 + c[3][3] * det2_01_02;
433                 T det3_301_123 = c[3][1] * det2_01_23 - c[3][2] * det2_01_13 + c[3][3] * det2_01_12;
434 
435                 Matrix res = void;
436                 res.c[0][0] = - det3_213_123 * invDet;
437                 res.c[1][0] = + det3_213_023 * invDet;
438                 res.c[2][0] = - det3_213_013 * invDet;
439                 res.c[3][0] = + det3_213_012 * invDet;
440 
441                 res.c[0][1] = + det3_203_123 * invDet;
442                 res.c[1][1] = - det3_203_023 * invDet;
443                 res.c[2][1] = + det3_203_013 * invDet;
444                 res.c[3][1] = - det3_203_012 * invDet;
445 
446                 res.c[0][2] = + det3_301_123 * invDet;
447                 res.c[1][2] = - det3_301_023 * invDet;
448                 res.c[2][2] = + det3_301_013 * invDet;
449                 res.c[3][2] = - det3_301_012 * invDet;
450 
451                 res.c[0][3] = - det3_201_123 * invDet;
452                 res.c[1][3] = + det3_201_023 * invDet;
453                 res.c[2][3] = - det3_201_013 * invDet;
454                 res.c[3][3] = + det3_201_012 * invDet;
455                 return res;
456             }
457         }
458 
459         /// Returns: transposed matrice.
460         @nogc Matrix!(T, C, R) transposed() pure const nothrow
461         {
462             Matrix!(T, C, R) res;
463             for (int i = 0; i < C; ++i)
464                 for (int j = 0; j < R; ++j)
465                     res.c[i][j] = c[j][i];
466             return res;
467         }
468 
469         static if (isSquare && R > 1)
470         {
471             /// In-place translate by (v, 1)
472             @nogc void translate(Vector!(T, R-1) v) pure nothrow
473             {
474                 for (int i = 0; i < R; ++i)
475                 {
476                     T dot = 0;
477                     for (int j = 0; j + 1 < C; ++j)
478                         dot += v.v[j] * c[i][j];
479 
480                     c[i][C-1] += dot;
481                 }
482             }
483 
484             /// Make a translation matrix.
485             @nogc static Matrix translation(Vector!(T, R-1) v) pure nothrow
486             {
487                 Matrix res = identity();
488                 for (int i = 0; i + 1 < R; ++i)
489                     res.c[i][C-1] += v.v[i];
490                 return res;
491             }
492 
493             /// In-place matrix scaling.
494             void scale(Vector!(T, R-1) v) pure nothrow
495             {
496                 for (int i = 0; i < R; ++i)
497                     for (int j = 0; j + 1 < C; ++j)
498                         c[i][j] *= v.v[j];
499             }
500 
501             /// Make a scaling matrix.
502             @nogc static Matrix scaling(Vector!(T, R-1) v) pure nothrow
503             {
504                 Matrix res = identity();
505                 for (int i = 0; i + 1 < R; ++i)
506                     res.c[i][i] = v.v[i];
507                 return res;
508             }
509         }
510 
511         // rotations are implemented for 3x3 and 4x4 matrices.
512         static if (isSquare && (R == 3 || R == 4) && isFloatingPoint!T)
513         {
514             @nogc public static Matrix rotateAxis(int i, int j)(T angle) pure nothrow
515             {
516                 Matrix res = identity();
517                 const T cosa = cos(angle);
518                 const T sina = sin(angle);
519                 res.c[i][i] = cosa;
520                 res.c[i][j] = -sina;
521                 res.c[j][i] = sina;
522                 res.c[j][j] = cosa;
523                 return res;
524             }
525 
526             /// Returns: rotation matrix along axis X
527             alias rotateAxis!(1, 2) rotateX;
528 
529             /// Returns: rotation matrix along axis Y
530             alias rotateAxis!(2, 0) rotateY;
531 
532             /// Returns: rotation matrix along axis Z
533             alias rotateAxis!(0, 1) rotateZ;
534 
535             /// Similar to the glRotate matrix, however the angle is expressed in radians
536             /// See_also: $(LINK http://www.cs.rutgers.edu/~decarlo/428/gl_man/rotate.html)
537             @nogc static Matrix rotation(T angle, vec3!T axis) pure nothrow
538             {
539                 Matrix res = identity();
540                 const T c = cos(angle);
541                 const oneMinusC = 1 - c;
542                 const T s = sin(angle);
543                 axis = axis.normalized();
544                 T x = axis.x,
545                   y = axis.y,
546                   z = axis.z;
547                 T xy = x * y,
548                   yz = y * z,
549                   xz = x * z;
550 
551                 res.c[0][0] = x * x * oneMinusC + c;
552                 res.c[0][1] = x * y * oneMinusC - z * s;
553                 res.c[0][2] = x * z * oneMinusC + y * s;
554                 res.c[1][0] = y * x * oneMinusC + z * s;
555                 res.c[1][1] = y * y * oneMinusC + c;
556                 res.c[1][2] = y * z * oneMinusC - x * s;
557                 res.c[2][0] = z * x * oneMinusC - y * s;
558                 res.c[2][1] = z * y * oneMinusC + x * s;
559                 res.c[2][2] = z * z * oneMinusC + c;
560                 return res;
561             }
562         }
563 
564         // 4x4 specific transformations for 3D usage
565         static if (isSquare && R == 4 && isFloatingPoint!T)
566         {
567             /// Returns: orthographic projection.
568             @nogc static Matrix orthographic(T left, T right, T bottom, T top, T near, T far) pure nothrow
569             {
570                 T dx = right - left,
571                   dy = top - bottom,
572                   dz = far - near;
573 
574                 T tx = -(right + left) / dx;
575                 T ty = -(top + bottom) / dy;
576                 T tz = -(far + near)   / dz;
577 
578                 return Matrix(2 / dx,   0,      0,    tx,
579                                 0,    2 / dy,   0,    ty,
580                                 0,      0,   -2 / dz, tz,
581                                 0,      0,      0,     1);
582             }
583 
584             /// Returns: perspective projection.
585             @nogc static Matrix perspective(T FOVInRadians, T aspect, T zNear, T zFar) pure nothrow
586             {
587                 T f = 1 / tan(FOVInRadians / 2);
588                 T d = 1 / (zNear - zFar);
589 
590                 return Matrix(f / aspect, 0,                  0,                    0,
591                                        0, f,                  0,                    0,
592                                        0, 0, (zFar + zNear) * d, 2 * d * zFar * zNear,
593                                        0, 0,                 -1,                    0);
594             }
595 
596             /// Returns: "lookAt" projection.
597             /// Thanks to vuaru for corrections.
598             @nogc static Matrix lookAt(vec3!T eye, vec3!T target, vec3!T up) pure nothrow
599             {
600                 vec3!T Z = (eye - target).normalized();
601                 vec3!T X = cross(-up, Z).normalized();
602                 vec3!T Y = cross(Z, -X);
603 
604                 return Matrix(-X.x,        -X.y,        -X.z,      dot(X, eye),
605                                Y.x,         Y.y,         Y.z,     -dot(Y, eye),
606                                Z.x,         Z.y,         Z.z,     -dot(Z, eye),
607                                0,           0,           0,        1);
608             }
609 
610             /// Extract frustum from a 4x4 matrice.
611             @nogc Frustum!T frustum() pure const nothrow
612             {
613                 auto left   = Plane!T(row(3) + row(0));
614                 auto right  = Plane!T(row(3) - row(0));
615                 auto top    = Plane!T(row(3) - row(1));
616                 auto bottom = Plane!T(row(3) + row(1));
617                 auto near   = Plane!T(row(3) + row(2));
618                 auto far    = Plane!T(row(3) - row(2));
619                 return Frustum!T(left, right, top, bottom, near, far);
620             }
621 
622         }
623     }
624 
625     package
626     {
627         alias T _T;
628         enum _R = R;
629         enum _C = C;
630     }
631 
632     private
633     {
634         template isAssignable(T)
635         {
636             enum bool isAssignable = std.traits.isAssignable!(Matrix, T);
637         }
638 
639         template isConvertible(T)
640         {
641             enum bool isConvertible = (!is(T : Matrix)) && isAssignable!T;
642         }
643 
644         template isTAssignable(U)
645         {
646             enum bool isTAssignable = std.traits.isAssignable!(T, U);
647         }
648 
649         template isRowConvertible(U)
650         {
651             enum bool isRowConvertible = is(U : row_t);
652         }
653 
654         template isColumnConvertible(U)
655         {
656             enum bool isColumnConvertible = is(U : column_t);
657         }
658     }
659 
660     public
661     {
662         /// Returns: an identity matrice.
663         /// Note: the identity matrix, while only meaningful for square matrices,
664         /// is also defined for non-square ones.
665         @nogc static Matrix identity() pure nothrow
666         {
667             Matrix res = void;
668             for (int i = 0; i < R; ++i)
669                 for (int j = 0; j < C; ++j)
670                     res.c[i][j] = (i == j) ? 1 : 0;
671             return res;
672         }
673 
674         /// Returns: a constant matrice.
675         @nogc static Matrix constant(U)(U x) pure nothrow
676         {
677             Matrix res = void;
678 
679             for (int i = 0; i < R * C; ++i)
680                 res.v[i] = cast(T)x;
681             return res;
682         }
683     }
684 }
685 
686 template isMatrixInstantiation(U)
687 {
688     private static void isMatrix(T, int R, int C)(Matrix!(T, R, C) x)
689     {
690     }
691 
692     enum bool isMatrixInstantiation = is(typeof(isMatrix(U.init)));
693 }
694 
695 // GLSL is a big inspiration here
696 // we defines types with more or less the same names
697 template mat2x2(T) { alias Matrix!(T, 2, 2) mat2x2; }
698 template mat3x3(T) { alias Matrix!(T, 3, 3) mat3x3; }
699 template mat4x4(T) { alias Matrix!(T, 4, 4) mat4x4; }
700 
701 // WARNING: in GLSL, first number is _columns_, second is rows
702 // It is the opposite here: first number is rows, second is columns
703 // With this convention mat2x3 * mat3x4 -> mat2x4.
704 template mat2x3(T) { alias Matrix!(T, 2, 3) mat2x3; }
705 template mat2x4(T) { alias Matrix!(T, 2, 4) mat2x4; }
706 template mat3x2(T) { alias Matrix!(T, 3, 2) mat3x2; }
707 template mat3x4(T) { alias Matrix!(T, 3, 4) mat3x4; }
708 template mat4x2(T) { alias Matrix!(T, 4, 2) mat4x2; }
709 template mat4x3(T) { alias Matrix!(T, 4, 3) mat4x3; }
710 
711 alias mat2x2 mat2;
712 alias mat3x3 mat3;  // shorter names for most common matrices
713 alias mat4x4 mat4;
714 
715 // Define a lot of type names
716 // Most useful are probably mat4f and mat4d
717 
718 alias mat2!byte   mat2b;
719 alias mat2!short  mat2s;
720 alias mat2!int    mat2i;
721 alias mat2!long   mat2l;
722 alias mat2!float  mat2f;
723 alias mat2!double mat2d;
724 
725 alias mat3!byte   mat3b;
726 alias mat3!short  mat3s;
727 alias mat3!int    mat3i;
728 alias mat3!long   mat3l;
729 alias mat3!float  mat3f;
730 alias mat3!double mat3d;
731 
732 alias mat4!byte   mat4b;
733 alias mat4!short  mat4s;
734 alias mat4!int    mat4i;
735 alias mat4!long   mat4l;
736 alias mat4!float  mat4f;
737 alias mat4!double mat4d;
738 
739 alias mat2x2!byte   mat2x2b;
740 alias mat2x2!short  mat2x2s;
741 alias mat2x2!int    mat2x2i;
742 alias mat2x2!long   mat2x2l;
743 alias mat2x2!float  mat2x2f;
744 alias mat2x2!double mat2x2d;
745 
746 alias mat2x3!byte   mat2x3b;
747 alias mat2x3!short  mat2x3s;
748 alias mat2x3!int    mat2x3i;
749 alias mat2x3!long   mat2x3l;
750 alias mat2x3!float  mat2x3f;
751 alias mat2x3!double mat2x3d;
752 
753 alias mat2x4!byte   mat2x4b;
754 alias mat2x4!short  mat2x4s;
755 alias mat2x4!int    mat2x4i;
756 alias mat2x4!long   mat2x4l;
757 alias mat2x4!float  mat2x4f;
758 alias mat2x4!double mat2x4d;
759 
760 alias mat3x2!byte   mat3x2b;
761 alias mat3x2!short  mat3x2s;
762 alias mat3x2!int    mat3x2i;
763 alias mat3x2!long   mat3x2l;
764 alias mat3x2!float  mat3x2f;
765 alias mat3x2!double mat3x2d;
766 
767 alias mat3x3!byte   mat3x3b;
768 alias mat3x3!short  mat3x3s;
769 alias mat3x3!int    mat3x3i;
770 alias mat3x3!long   mat3x3l;
771 alias mat3x3!float  mat3x3f;
772 alias mat3x3!double mat3x3d;
773 
774 alias mat3x4!byte   mat3x4b;
775 alias mat3x4!short  mat3x4s;
776 alias mat3x4!int    mat3x4i;
777 alias mat3x4!long   mat3x4l;
778 alias mat3x4!float  mat3x4f;
779 alias mat3x4!double mat3x4d;
780 
781 alias mat4x2!byte   mat4x2b;
782 alias mat4x2!short  mat4x2s;
783 alias mat4x2!int    mat4x2i;
784 alias mat4x2!long   mat4x2l;
785 alias mat4x2!float  mat4x2f;
786 alias mat4x2!double mat4x2d;
787 
788 alias mat4x3!byte   mat4x3b;
789 alias mat4x3!short  mat4x3s;
790 alias mat4x3!int    mat4x3i;
791 alias mat4x3!long   mat4x3l;
792 alias mat4x3!float  mat4x3f;
793 alias mat4x3!double mat4x3d;
794 
795 alias mat4x4!byte   mat4x4b;
796 alias mat4x4!short  mat4x4s;
797 alias mat4x4!int    mat4x4i;
798 alias mat4x4!long   mat4x4l;
799 alias mat4x4!float  mat4x4f;
800 alias mat4x4!double mat4x4d;
801 
802 unittest
803 {
804     mat2i x = mat2i(0, 1,
805                     2, 3);
806     assert(x.c[0][0] == 0 && x.c[0][1] == 1 && x.c[1][0] == 2 && x.c[1][1] == 3);
807 
808     vec2i[2] cols = [vec2i(0, 2), vec2i(1, 3)];
809     mat2i y = mat2i.fromColumns(cols[]);
810     assert(y.c[0][0] == 0 && y.c[0][1] == 1 && y.c[1][0] == 2 && y.c[1][1] == 3);
811     y = mat2i.fromRows(cols[]);
812     assert(y.c[0][0] == 0 && y.c[1][0] == 1 && y.c[0][1] == 2 && y.c[1][1] == 3);
813     y = y.transposed();
814 
815     assert(x == y);
816     x = [0, 1, 2, 3];
817     assert(x == y);
818 
819     mat2i z = x * y;
820     assert(z == mat2i([2, 3, 6, 11]));
821     vec2i vz = z * vec2i(2, -1);
822     assert(vz == vec2i(1, 1));
823 
824     mat2f a = z;
825     mat2d ad = a;
826     ad += a;
827     mat2f w = [4, 5, 6, 7];
828     z = cast(mat2i)w;
829     assert(w == z);
830 
831     {
832         mat2x3f A;
833         mat3x4f B;
834         mat2x4f C = A * B;
835     }
836 }