Search code examples
openglmatrixglslfrustum

Applying perspective with GLSL matrix


I am not quite sure what is missing, but I loaded a uniform matrix into a vertex shader and when the matrix was:

GLfloat translation[4][4] = {
    {1.0, 0.0, 0.0, 0.0},
    {0.0, 1.0, 0.0, 0.0},
    {0.0, 0.0, 1.0, 0.0},
    {0.0, 0.2, 0.0, 1.0}};

or so, I seemed to be able to translate vertices just fine, depending on which values I chose to change. However, when swapping this same uniform matrix to apply projection, the image would not appear. I tried several matrices, such as:

GLfloat frustum[4][4] = {
    {((2.0*frusZNear)/(frusRight - frusLeft)), 0.0, 0.0, 0.0},
    {0.0, ((2.0*frusZNear)/(frusTop - frusBottom)), 0.0 , 0.0},
    {((frusRight + frusLeft)/(frusRight-frusLeft)), ((frusTop + frusBottom) / (frusTop - frusBottom)), (-(frusZFar + frusZNear)/(frusZFar - frusZNear)), (-1.0)},
    {0.0, 0.0, ((-2.0*frusZFar*frusZNear)/(frusZFar-frusZNear)), 0.0}
};

and values, such as:

const GLfloat frusLeft = -3.0;
const GLfloat frusRight = 3.0;
const GLfloat frusBottom = -3.0;
const GLfloat frusTop = 3.0;
const GLfloat frusZNear = 5.0;
const GLfloat frusZFar = 10.0;

The vertex shader, which seemed to apply translation just fine:

gl_Position = frustum * vPosition;

Any help appreciated.


Solution

  • The code for calculating the perspective/frustum matrix looks correct to me. This sets up a perspective matrix that assumes that your eye point is at the origin, and you're looking down the negative z-axis. The near and far values specify the range of distances along the negative z-axis that are within the view volume.

    Therefore, with near/far values of 5.0/10.0, the range of z-values that are within your view volume will be from -5.0 to -10.0.

    If your geometry is currently drawn around the origin, use a translation by something like (0.0, 0.0, -7.0) as your view matrix. This needs to be applied before the projection matrix.

    You can either combine the view and projection matrices, or pass them separately into your vertex shader. With a separate view matrix, containing the translation above, your shader code could then look like this:

    uniform mat4 viewMat;
    ...
    gl_Position = frustum * viewMat * vPosition;