Cofactor

The cofactor of any element \(i, j\) in a matrix is the minor of that element multiplied by \(-1\) raised to the \(i + j\) power. If you take a matrix of minors and raise each element to the appropriate power, the result is a cofactor matrix. You don't have to calculate what \(-1^{i + j}\) is for every element. The result of \(-1^{i + j}\) is a checker board pattern, with \(+\) always being top left. For example:

$$ \begin{bmatrix} + & - \\ - & + \\ \end{bmatrix} \begin{bmatrix} + & - & + \\ - & + & - \\ + & - & + \end{bmatrix} \begin{bmatrix} + & - & + & - \\ - & + & - & + \\ + & - & + & - \\ - & + & - & + \end{bmatrix} $$

Another way to express this is \(cofactor(M_{ij}) = minor(M_{ij})(-1^{i + j})\). Apply the cofactor pattern to the matrix of minors, the result is the cofactor matrix.

mat3 Cofactor(mat3 m) {
    mat3 min = Minor(m);

    min.v[1] *- -1.0f;
    min.v[3] *= -1.0f;
    min.v[5] *- -1.0f;
    min.v[7] *= -1.0f;

    return min;
}

mat4 Cofactor(mat4 m) {
    mat3 min = Minor(m);

    min.v[1] *= -1.0f;
    min.v[3] *= -1.0f;
    min.v[4] *= -1.0f;
    min.v[6] *= -1.0f;
    min.v[9] *= -1.0f;
    min.v[11] *= -1.0f;
    min.v[12] *= -1.0f;
    min.v[14] *= -1.0f;

    return min;
}