Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculating lookat matrix using in vertex shader OpenGL 3.x

I followed this post to build the GluLookAt type matrix.

Calculating a LookAt matrix

            Method calculateLookAtMatrix(glm::vec3 eye, glm::vec3 center, glm::vec3 up)

    glm::vec3 zaxis = glm::normalize(center - eye);
    glm::vec3 xaxis = glm::normalize(glm::cross(up, zaxis));
    glm::vec3 yaxis = glm::cross(zaxis, xaxis);

    lookAtMatrix[0][0] = xaxis.x;
    lookAtMatrix[0][1] = yaxis.x;
    lookAtMatrix[0][2] = zaxis.x;

    lookAtMatrix[1][0] = xaxis.y;
    lookAtMatrix[1][1] = yaxis.y;
    lookAtMatrix[1][2] = zaxis.y;

    lookAtMatrix[2][0] = xaxis.z;
    lookAtMatrix[2][1] = yaxis.z;
    lookAtMatrix[2][2] = zaxis.z;

    lookAtMatrix[3][0] = glm::dot(xaxis, -eye);
    lookAtMatrix[3][1] = glm::dot(yaxis, -eye);
    lookAtMatrix[3][2] = glm::dot(zaxis, -eye);

    lookAtMatrix[3][3] = 1;

I calculate that CPU side and pass it in to the shader as a uniform in the same way as the perspective matrix.

The shader looks like this.

 gl_Position =   lookAtMatrix * position * perspectiveMatrix;

If pass in the lookAtMatrix as the identity matrix the scene is rendered correctly, however using the code above to set the matrix as ...

    eye(0.0f,0.0f,10.0f);
center(0.0f,0.0f,0.0f);
up(0.0f,0.0f,1.0f);

results in a blank scene. The scene is a grid 10x10 drawn on X/Y, I therefore would have been expecting a zoomed out view of the scene.

(I have played about with the rows and cols but I am 99.9% sure they are fine, as the perspective matrix is fine)

like image 286
Andrew Avatar asked Jan 31 '26 07:01

Andrew


1 Answers

gl_Position =   lookAtMatrix * position * perspectiveMatrix;

This is not correct. You want to transform your position by the lookAtMatrix, and then transform the result of that by the perspectiveMatrix.

When using column vector/column major vectors and matrices, you want to multiply a matrix and vector by placing the vector on the right hand side of the matrix.

So your multiplication should ultimately look like this:

gl_Position =   perspectiveMatrix * lookAtMatrix * position;

Having said that, I'm not sure why you had the position on the left in the first place, so I wonder if you're doing some matrix transposition somewhere in your pipeline. If this solution doesn't work you may need to show more code.

like image 124
Tim Avatar answered Feb 01 '26 22:02

Tim



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!