Codeblockz
Codeblockz

Reputation: 23

Invert Z-axis in Matrix4::Perspective

I'm making an OpenGL application in which I have the following code to setup the perspective matrix.

Matrix4 Matrix4::Perspective(float pL, float pR, float pB, float pT, float pN, float pF) {
    Matrix4 matrix;
    matrix[0] = 2 * pN / (pR - pL);
    matrix[5] = 2 * pN / (pT - pB);
    matrix[8] = (pR + pL) / (pR - pL);
    matrix[9] = (pT + pB) / (pT - pB);
    matrix[10] = -(pF + pN) / (pF - pN);
    matrix[11] = -1;
    matrix[14] = -(2 * pF * pN) / (pF - pN);
    matrix[15] = 0;
    return matrix;
}

As it stands when I manipulate the translation of the object, -Z moves it forward, +Z moves it backwards.

I came close to obtaining this behavior by switching matrix[11] and matrix[14] to:

matrix[11] = 1;
matrix[14] = (2 * pF * pN) / (pN - pF);

But the mesh becomes slightly deformed. (Probably hugely deformed on a more complex mesh.)

How would I manipulate this method to give me the desired result (invert z axis)?

pF = zFar pN = zNear

Upvotes: 0

Views: 1643

Answers (1)

derhass
derhass

Reputation: 45322

Conceptually, what you want invert z before the projection is applied, which will have the effect of mirroring the projection from -z to z. So what you conceptually have to do is calculating P * Scale(1,1,-1) = P * diag(1,1,-1,1). If you do the math, you will see that this just results in negating the third column of the projection matrix, so the correct matrix will be:

matrix[0] = 2 * pN / (pR - pL);
matrix[5] = 2 * pN / (pT - pB);
matrix[8] = -(pR + pL) / (pR - pL);
matrix[9] = -(pT + pB) / (pT - pB);
matrix[10] = (pF + pN) / (pF - pN);
matrix[11] = 1;
matrix[14] = -(2 * pF * pN) / (pF - pN);
matrix[15] = 0;

Negating matrix[14] like you did doesn't make the slightest sense, it just will move your near and far planes to elsewhere.

Upvotes: 3

Related Questions