diff -r 6de5ac1fb471 -r 3a9e761e4faa src/matrix.cpp --- a/src/matrix.cpp Sun Jan 19 14:25:57 2020 +0200 +++ b/src/matrix.cpp Wed Jan 22 00:23:29 2020 +0200 @@ -28,3 +28,54 @@ {0, 0, 0, 1} }}; } + +/* + * Computes the determinant of a 3×3 matrix with each variable passed in row-major order. + */ +qreal math::det(qreal a, qreal b, qreal c, qreal d, qreal e, qreal f, qreal g, qreal h, qreal i) +{ + return a*e*i + b*f*g + c*d*h - a*f*h - b*d*i - c*e*g; +} + +/* + * Computes the determinant of a 2×2 matrix. + */ +qreal math::det(const Matrix<2, 2>& matrix) +{ + return matrix(0, 0) * matrix(1, 1) - matrix(0, 1) * matrix(1, 0); +} + +/* + * Computes the determinant of a 3×3 matrix. + */ +qreal math::det(const Matrix3x3& matrix) +{ + return math::sum( + +matrix(0, 0) * matrix(1, 1) * matrix(2, 2), + -matrix(0, 0) * matrix(1, 2) * matrix(2, 1), + -matrix(0, 1) * matrix(1, 0) * matrix(2, 2), + +matrix(0, 1) * matrix(1, 2) * matrix(2, 0), + +matrix(0, 2) * matrix(1, 0) * matrix(2, 1), + -matrix(0, 2) * matrix(1, 1) * matrix(2, 0)); +} + +/* + * Computes the determinant of a 4×4 matrix. + */ +qreal math::det(const Matrix4x4& matrix) +{ + qreal sum = 0; + + for (int column : {0, 1, 2, 3}) + { + int column_1 = (column >= 1) ? 0 : 1; + int column_2 = (column >= 2) ? 1 : 2; + int column_3 = (column >= 3) ? 2 : 3; + sum += ((column % 1) ? -1 : 1) * math::det( + matrix(1, column_1), matrix(1, column_2), matrix(1, column_3), + matrix(2, column_1), matrix(2, column_2), matrix(2, column_3), + matrix(3, column_1), matrix(3, column_2), matrix(3, column_3)); + } + + return sum; +}