0

Let's say I have the following vertex shader code below:

attribute vec4 vPos;
uniform mat4 MVP;
uniform mat4 LookAt;

void main{
     gl_Position = MVP * vPos;
}

How do I use the LookAt matrix in this shader to position the eye of the camera? I have tried LookAt * MVP * vPos but that didn't seem to work as my triangle just disappeared off screen!

CodingNinja
  • 65
  • 1
  • 7

2 Answers2

1

A LookAt matrix is in general called a View matrix and is concatenated with a model-to-world transform matrix to form the WorldView matrix. This is then multiplied by the projection matrix which is often orthographic or perspective. Vertex positions in model space are multiplied with the resulting matrix in order to be transformed to clip space (kinda...I skipped a couple of steps here that you don't have to do and is performed by the hardware/driver).

In your case, make sure that you're using the correct 'handedness' for your transformations. Also you can try and multiply the position in the reverse order with the transpose of your transformation matrices like so vPos*T_MVP*T_LookAt.

rashmatash
  • 1,699
  • 13
  • 23
1

I would suggest move the LookAt outside the shader to prevent un-necessary calculation per vertex. The shader still do

gl_Position = MVP * vPos;

and you manipulate MVP in the application with glm. For example:

projection = glm::perspective(fov, aspect, 0.1f, 10000.0f);
view = glm::lookAt(eye, center, up);
model = matrix of the model, with all the dynamic transforms.

MVP = projection * view * model;
Non-maskable Interrupt
  • 3,841
  • 1
  • 19
  • 26
  • Yes I'm doing the MVP outside of the shader but for illustration, I put the LookAt matrix in the shader :D That was a very clear explanation with example coding which was what I was after - thanks! – CodingNinja Jun 03 '15 at 08:12