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 2x2, 3x3 and 4x4 floating point matrices.
342 
343         static if (isSquare && isFloatingPoint!T && R == 2)
344         {
345             /// Returns: inverse of matrix.
346             @nogc Matrix inverse() pure const nothrow
347             {
348                 T invDet = 1 / (c[0][0] * c[1][1] - c[0][1] * c[1][0]);
349                 return Matrix( c[1][1] * invDet, -c[0][1] * invDet,
350                                    -c[1][0] * invDet,  c[0][0] * invDet);
351             }
352         }
353 
354         static if (isSquare && isFloatingPoint!T && R == 3)
355         {
356             /// Returns: inverse of matrix.
357             @nogc Matrix inverse() pure const nothrow
358             {
359                 T det = c[0][0] * (c[1][1] * c[2][2] - c[2][1] * c[1][2])
360                       - c[0][1] * (c[1][0] * c[2][2] - c[1][2] * c[2][0])
361                       + c[0][2] * (c[1][0] * c[2][1] - c[1][1] * c[2][0]);
362                 T invDet = 1 / det;
363 
364                 Matrix res = void;
365                 res.c[0][0] =  (c[1][1] * c[2][2] - c[2][1] * c[1][2]) * invDet;
366                 res.c[0][1] = -(c[0][1] * c[2][2] - c[0][2] * c[2][1]) * invDet;
367                 res.c[0][2] =  (c[0][1] * c[1][2] - c[0][2] * c[1][1]) * invDet;
368                 res.c[1][0] = -(c[1][0] * c[2][2] - c[1][2] * c[2][0]) * invDet;
369                 res.c[1][1] =  (c[0][0] * c[2][2] - c[0][2] * c[2][0]) * invDet;
370                 res.c[1][2] = -(c[0][0] * c[1][2] - c[1][0] * c[0][2]) * invDet;
371                 res.c[2][0] =  (c[1][0] * c[2][1] - c[2][0] * c[1][1]) * invDet;
372                 res.c[2][1] = -(c[0][0] * c[2][1] - c[2][0] * c[0][1]) * invDet;
373                 res.c[2][2] =  (c[0][0] * c[1][1] - c[1][0] * c[0][1]) * invDet;
374                 return res;
375             }
376         }
377 
378         static if (isSquare && isFloatingPoint!T && R == 4)
379         {
380             /// Returns: inverse of matrix.
381             @nogc Matrix inverse() pure const nothrow
382             {
383                 T det2_01_01 = c[0][0] * c[1][1] - c[0][1] * c[1][0];
384                 T det2_01_02 = c[0][0] * c[1][2] - c[0][2] * c[1][0];
385                 T det2_01_03 = c[0][0] * c[1][3] - c[0][3] * c[1][0];
386                 T det2_01_12 = c[0][1] * c[1][2] - c[0][2] * c[1][1];
387                 T det2_01_13 = c[0][1] * c[1][3] - c[0][3] * c[1][1];
388                 T det2_01_23 = c[0][2] * c[1][3] - c[0][3] * c[1][2];
389 
390                 T det3_201_012 = c[2][0] * det2_01_12 - c[2][1] * det2_01_02 + c[2][2] * det2_01_01;
391                 T det3_201_013 = c[2][0] * det2_01_13 - c[2][1] * det2_01_03 + c[2][3] * det2_01_01;
392                 T det3_201_023 = c[2][0] * det2_01_23 - c[2][2] * det2_01_03 + c[2][3] * det2_01_02;
393                 T det3_201_123 = c[2][1] * det2_01_23 - c[2][2] * det2_01_13 + c[2][3] * det2_01_12;
394 
395                 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];
396                 T invDet = 1 / det;
397 
398                 T det2_03_01 = c[0][0] * c[3][1] - c[0][1] * c[3][0];
399                 T det2_03_02 = c[0][0] * c[3][2] - c[0][2] * c[3][0];
400                 T det2_03_03 = c[0][0] * c[3][3] - c[0][3] * c[3][0];
401                 T det2_03_12 = c[0][1] * c[3][2] - c[0][2] * c[3][1];
402                 T det2_03_13 = c[0][1] * c[3][3] - c[0][3] * c[3][1];
403                 T det2_03_23 = c[0][2] * c[3][3] - c[0][3] * c[3][2];
404                 T det2_13_01 = c[1][0] * c[3][1] - c[1][1] * c[3][0];
405                 T det2_13_02 = c[1][0] * c[3][2] - c[1][2] * c[3][0];
406                 T det2_13_03 = c[1][0] * c[3][3] - c[1][3] * c[3][0];
407                 T det2_13_12 = c[1][1] * c[3][2] - c[1][2] * c[3][1];
408                 T det2_13_13 = c[1][1] * c[3][3] - c[1][3] * c[3][1];
409                 T det2_13_23 = c[1][2] * c[3][3] - c[1][3] * c[3][2];
410 
411                 T det3_203_012 = c[2][0] * det2_03_12 - c[2][1] * det2_03_02 + c[2][2] * det2_03_01;
412                 T det3_203_013 = c[2][0] * det2_03_13 - c[2][1] * det2_03_03 + c[2][3] * det2_03_01;
413                 T det3_203_023 = c[2][0] * det2_03_23 - c[2][2] * det2_03_03 + c[2][3] * det2_03_02;
414                 T det3_203_123 = c[2][1] * det2_03_23 - c[2][2] * det2_03_13 + c[2][3] * det2_03_12;
415 
416                 T det3_213_012 = c[2][0] * det2_13_12 - c[2][1] * det2_13_02 + c[2][2] * det2_13_01;
417                 T det3_213_013 = c[2][0] * det2_13_13 - c[2][1] * det2_13_03 + c[2][3] * det2_13_01;
418                 T det3_213_023 = c[2][0] * det2_13_23 - c[2][2] * det2_13_03 + c[2][3] * det2_13_02;
419                 T det3_213_123 = c[2][1] * det2_13_23 - c[2][2] * det2_13_13 + c[2][3] * det2_13_12;
420 
421                 T det3_301_012 = c[3][0] * det2_01_12 - c[3][1] * det2_01_02 + c[3][2] * det2_01_01;
422                 T det3_301_013 = c[3][0] * det2_01_13 - c[3][1] * det2_01_03 + c[3][3] * det2_01_01;
423                 T det3_301_023 = c[3][0] * det2_01_23 - c[3][2] * det2_01_03 + c[3][3] * det2_01_02;
424                 T det3_301_123 = c[3][1] * det2_01_23 - c[3][2] * det2_01_13 + c[3][3] * det2_01_12;
425 
426                 Matrix res = void;
427                 res.c[0][0] = - det3_213_123 * invDet;
428                 res.c[1][0] = + det3_213_023 * invDet;
429                 res.c[2][0] = - det3_213_013 * invDet;
430                 res.c[3][0] = + det3_213_012 * invDet;
431 
432                 res.c[0][1] = + det3_203_123 * invDet;
433                 res.c[1][1] = - det3_203_023 * invDet;
434                 res.c[2][1] = + det3_203_013 * invDet;
435                 res.c[3][1] = - det3_203_012 * invDet;
436 
437                 res.c[0][2] = + det3_301_123 * invDet;
438                 res.c[1][2] = - det3_301_023 * invDet;
439                 res.c[2][2] = + det3_301_013 * invDet;
440                 res.c[3][2] = - det3_301_012 * invDet;
441 
442                 res.c[0][3] = - det3_201_123 * invDet;
443                 res.c[1][3] = + det3_201_023 * invDet;
444                 res.c[2][3] = - det3_201_013 * invDet;
445                 res.c[3][3] = + det3_201_012 * invDet;
446                 return res;
447             }
448         }
449 
450         /// Returns: transposed matrice.
451         @nogc Matrix!(T, C, R) transposed() pure const nothrow
452         {
453             Matrix!(T, C, R) res;
454             for (int i = 0; i < C; ++i)
455                 for (int j = 0; j < R; ++j)
456                     res.c[i][j] = c[j][i];
457             return res;
458         }
459 
460         static if (isSquare && R > 1)
461         {
462             /// In-place translate by (v, 1)
463             @nogc void translate(Vector!(T, R-1) v) pure nothrow
464             {
465                 for (int i = 0; i < R; ++i)
466                 {
467                     T dot = 0;
468                     for (int j = 0; j + 1 < C; ++j)
469                         dot += v.v[j] * c[i][j];
470 
471                     c[i][C-1] += dot;
472                 }
473             }
474 
475             /// Make a translation matrix.
476             @nogc static Matrix translation(Vector!(T, R-1) v) pure nothrow
477             {
478                 Matrix res = identity();
479                 for (int i = 0; i + 1 < R; ++i)
480                     res.c[i][C-1] += v.v[i];
481                 return res;
482             }
483 
484             /// In-place matrix scaling.
485             void scale(Vector!(T, R-1) v) pure nothrow
486             {
487                 for (int i = 0; i < R; ++i)
488                     for (int j = 0; j + 1 < C; ++j)
489                         c[i][j] *= v.v[j];
490             }
491 
492             /// Make a scaling matrix.
493             @nogc static Matrix scaling(Vector!(T, R-1) v) pure nothrow
494             {
495                 Matrix res = identity();
496                 for (int i = 0; i + 1 < R; ++i)
497                     res.c[i][i] = v.v[i];
498                 return res;
499             }
500         }
501 
502         // rotations are implemented for 3x3 and 4x4 matrices.
503         static if (isSquare && (R == 3 || R == 4) && isFloatingPoint!T)
504         {
505             @nogc public static Matrix rotateAxis(int i, int j)(T angle) pure nothrow
506             {
507                 Matrix res = identity();
508                 const T cosa = cos(angle);
509                 const T sina = sin(angle);
510                 res.c[i][i] = cosa;
511                 res.c[i][j] = -sina;
512                 res.c[j][i] = sina;
513                 res.c[j][j] = cosa;
514                 return res;
515             }
516 
517             /// Returns: rotation matrix along axis X
518             alias rotateAxis!(1, 2) rotateX;
519 
520             /// Returns: rotation matrix along axis Y
521             alias rotateAxis!(2, 0) rotateY;
522 
523             /// Returns: rotation matrix along axis Z
524             alias rotateAxis!(0, 1) rotateZ;
525 
526             /// Similar to the glRotate matrix, however the angle is expressed in radians
527             /// See_also: $(LINK http://www.cs.rutgers.edu/~decarlo/428/gl_man/rotate.html)
528             @nogc static Matrix rotation(T angle, vec3!T axis) pure nothrow
529             {
530                 Matrix res = identity();
531                 const T c = cos(angle);
532                 const oneMinusC = 1 - c;
533                 const T s = sin(angle);
534                 axis = axis.normalized();
535                 T x = axis.x,
536                   y = axis.y,
537                   z = axis.z;
538                 T xy = x * y,
539                   yz = y * z,
540                   xz = x * z;
541 
542                 res.c[0][0] = x * x * oneMinusC + c;
543                 res.c[0][1] = x * y * oneMinusC - z * s;
544                 res.c[0][2] = x * z * oneMinusC + y * s;
545                 res.c[1][0] = y * x * oneMinusC + z * s;
546                 res.c[1][1] = y * y * oneMinusC + c;
547                 res.c[1][2] = y * z * oneMinusC - x * s;
548                 res.c[2][0] = z * x * oneMinusC - y * s;
549                 res.c[2][1] = z * y * oneMinusC + x * s;
550                 res.c[2][2] = z * z * oneMinusC + c;
551                 return res;
552             }
553         }
554 
555         // 4x4 specific transformations for 3D usage
556         static if (isSquare && R == 4 && isFloatingPoint!T)
557         {
558             /// Returns: orthographic projection.
559             @nogc static Matrix orthographic(T left, T right, T bottom, T top, T near, T far) pure nothrow
560             {
561                 T dx = right - left,
562                   dy = top - bottom,
563                   dz = far - near;
564 
565                 T tx = -(right + left) / dx;
566                 T ty = -(top + bottom) / dy;
567                 T tz = -(far + near)   / dz;
568 
569                 return Matrix(2 / dx,   0,      0,    tx,
570                                 0,    2 / dy,   0,    ty,
571                                 0,      0,   -2 / dz, tz,
572                                 0,      0,      0,     1);
573             }
574 
575             /// Returns: perspective projection.
576             @nogc static Matrix perspective(T FOVInRadians, T aspect, T zNear, T zFar) pure nothrow
577             {
578                 T f = 1 / tan(FOVInRadians / 2);
579                 T d = 1 / (zNear - zFar);
580 
581                 return Matrix(f / aspect, 0,                  0,                    0,
582                                        0, f,                  0,                    0,
583                                        0, 0, (zFar + zNear) * d, 2 * d * zFar * zNear,
584                                        0, 0,                 -1,                    0);
585             }
586 
587             /// Returns: "lookAt" projection.
588             /// Thanks to vuaru for corrections.
589             @nogc static Matrix lookAt(vec3!T eye, vec3!T target, vec3!T up) pure nothrow
590             {
591                 vec3!T Z = (eye - target).normalized();
592                 vec3!T X = cross(-up, Z).normalized();
593                 vec3!T Y = cross(Z, -X);
594 
595                 return Matrix(-X.x,        -X.y,        -X.z,      dot(X, eye),
596                                Y.x,         Y.y,         Y.z,     -dot(Y, eye),
597                                Z.x,         Z.y,         Z.z,     -dot(Z, eye),
598                                0,           0,           0,        1);
599             }
600 
601             /// Extract frustum from a 4x4 matrice.
602             @nogc Frustum!T frustum() pure const nothrow
603             {
604                 auto left   = Plane!T(row(3) + row(0));
605                 auto right  = Plane!T(row(3) - row(0));
606                 auto top    = Plane!T(row(3) - row(1));
607                 auto bottom = Plane!T(row(3) + row(1));
608                 auto near   = Plane!T(row(3) + row(2));
609                 auto far    = Plane!T(row(3) - row(2));
610                 return Frustum!T(left, right, top, bottom, near, far);
611             }
612 
613         }
614     }
615 
616     package
617     {
618         alias T _T;
619         enum _R = R;
620         enum _C = C;
621     }
622 
623     private
624     {
625         template isAssignable(T)
626         {
627             enum bool isAssignable = std.traits.isAssignable!(Matrix, T);
628         }
629 
630         template isConvertible(T)
631         {
632             enum bool isConvertible = (!is(T : Matrix)) && isAssignable!T;
633         }
634 
635         template isTAssignable(U)
636         {
637             enum bool isTAssignable = std.traits.isAssignable!(T, U);
638         }
639 
640         template isRowConvertible(U)
641         {
642             enum bool isRowConvertible = is(U : row_t);
643         }
644 
645         template isColumnConvertible(U)
646         {
647             enum bool isColumnConvertible = is(U : column_t);
648         }
649     }
650 
651     public
652     {
653         /// Returns: an identity matrice.
654         /// Note: the identity matrix, while only meaningful for square matrices,
655         /// is also defined for non-square ones.
656         @nogc static Matrix identity() pure nothrow
657         {
658             Matrix res = void;
659             for (int i = 0; i < R; ++i)
660                 for (int j = 0; j < C; ++j)
661                     res.c[i][j] = (i == j) ? 1 : 0;
662             return res;
663         }
664 
665         /// Returns: a constant matrice.
666         @nogc static Matrix constant(U)(U x) pure nothrow
667         {
668             Matrix res = void;
669 
670             for (int i = 0; i < R * C; ++i)
671                 res.v[i] = cast(T)x;
672             return res;
673         }
674     }
675 }
676 
677 template isMatrixInstantiation(U)
678 {
679     private static void isMatrix(T, int R, int C)(Matrix!(T, R, C) x)
680     {
681     }
682 
683     enum bool isMatrixInstantiation = is(typeof(isMatrix(U.init)));
684 }
685 
686 // GLSL is a big inspiration here
687 // we defines types with more or less the same names
688 template mat2x2(T) { alias Matrix!(T, 2, 2) mat2x2; }
689 template mat3x3(T) { alias Matrix!(T, 3, 3) mat3x3; }
690 template mat4x4(T) { alias Matrix!(T, 4, 4) mat4x4; }
691 
692 // WARNING: in GLSL, first number is _columns_, second is rows
693 // It is the opposite here: first number is rows, second is columns
694 // With this convention mat2x3 * mat3x4 -> mat2x4.
695 template mat2x3(T) { alias Matrix!(T, 2, 3) mat2x3; }
696 template mat2x4(T) { alias Matrix!(T, 2, 4) mat2x4; }
697 template mat3x2(T) { alias Matrix!(T, 3, 2) mat3x2; }
698 template mat3x4(T) { alias Matrix!(T, 3, 4) mat3x4; }
699 template mat4x2(T) { alias Matrix!(T, 4, 2) mat4x2; }
700 template mat4x3(T) { alias Matrix!(T, 4, 3) mat4x3; }
701 
702 alias mat2x2 mat2;
703 alias mat3x3 mat3;  // shorter names for most common matrices
704 alias mat4x4 mat4;
705 
706 private string definePostfixAliases(string type)
707 {
708     return "alias " ~ type ~ "!byte "   ~ type ~ "b;"
709          ~ "alias " ~ type ~ "!short "  ~ type ~ "s;"
710          ~ "alias " ~ type ~ "!int "    ~ type ~ "i;"
711          ~ "alias " ~ type ~ "!long "   ~ type ~ "l;"
712          ~ "alias " ~ type ~ "!float "  ~ type ~ "f;"
713          ~ "alias " ~ type ~ "!double " ~ type ~ "d;";
714 }
715 
716 // define a lot of type names
717 mixin(definePostfixAliases("mat2"));
718 mixin(definePostfixAliases("mat3"));
719 mixin(definePostfixAliases("mat4"));
720 mixin(definePostfixAliases("mat2x2"));
721 mixin(definePostfixAliases("mat2x3"));
722 mixin(definePostfixAliases("mat2x4"));
723 mixin(definePostfixAliases("mat3x2"));
724 mixin(definePostfixAliases("mat3x3"));
725 mixin(definePostfixAliases("mat3x4"));
726 mixin(definePostfixAliases("mat4x2"));
727 mixin(definePostfixAliases("mat4x3"));
728 mixin(definePostfixAliases("mat4x4"));
729 
730 unittest
731 {
732     mat2i x = mat2i(0, 1,
733                     2, 3);
734     assert(x.c[0][0] == 0 && x.c[0][1] == 1 && x.c[1][0] == 2 && x.c[1][1] == 3);
735 
736     vec2i[2] cols = [vec2i(0, 2), vec2i(1, 3)];
737     mat2i y = mat2i.fromColumns(cols[]);
738     assert(y.c[0][0] == 0 && y.c[0][1] == 1 && y.c[1][0] == 2 && y.c[1][1] == 3);
739     y = mat2i.fromRows(cols[]);
740     assert(y.c[0][0] == 0 && y.c[1][0] == 1 && y.c[0][1] == 2 && y.c[1][1] == 3);
741     y = y.transposed();
742 
743     assert(x == y);
744     x = [0, 1, 2, 3];
745     assert(x == y);
746 
747     mat2i z = x * y;
748     assert(z == mat2i([2, 3, 6, 11]));
749     vec2i vz = z * vec2i(2, -1);
750     assert(vz == vec2i(1, 1));
751 
752     mat2f a = z;
753     mat2d ad = a;
754     ad += a;
755     mat2f w = [4, 5, 6, 7];
756     z = cast(mat2i)w;
757     assert(w == z);
758 
759     {
760         mat2x3f A;
761         mat3x4f B;
762         mat2x4f C = A * B;
763     }
764 }