Search code examples
copenglglslglm-math

Applying MVP transformation renders nothing OpenGL


I'm trying to apply MVP Transformation to a Square in OpenGL

But, it shows nothing.

If I remove the mvp from the Vertex Shader, The Square Gets Rendered

I'm using cglm as the math library, but there is no tag for it. So, I'm giving it the glm tag

I'm uploading a mat4 uniform to the Vertex Shader. I also tried uploading a vec3 as uniform to the shader and it worked. So, I feel like this is more of a calculation problem than a shader problem. But I can't seem to figure it out.

The Code

Creating and Uploading Matrix

// Model
mat4 model = {{1.0f}};
glm_translate(model, (vec3){5.0f, 5.0f, 0.0f});

// View Matrix
mat4 view = {{1.0f}};
glm_translate(view, (vec3){0.0f, 0.0f, 10.0f});

// Projection Matrix
mat4 projection;
glm_ortho(0.0f, WINDOW_WIDTH, 0.0f, WINDOW_HEIGHT, 0.001f, 1000.0f, projection);

// The MVP Matrix
mat4 mvp;
glm_mat4_mulN((mat4* []){&projection, &view, &model}, 3, mvp);

// Uploading the Matrix
glUniformMatrix4fv(glGetUniformLocation(shaderProgram, "mvp"), 1, GL_FALSE, (float*)mvp);

Vertex Shader

#version 330 core

layout (location = 0) in vec3 aPos;
layout (location = 1) in vec4 aColor;

uniform mat4 mvp;

out vec4 fColor;

void main()
{
    gl_Position = mvp * vec4(aPos, 1.0);
    // On removing the mvp, the square gets rendered
    // gl_Position = vec4(aPos, 1.0);
    fColor = aColor;
}

Solution

  • The OpenGL coordinate system is a right-handed system. In the view space, the x-axis points to the right and the y-axis points up. Since the z-axis is the cross product of the x-axis and the y-axis, it points out of the view. Projection transforms the viewing volume into a unique cube (NDC), mirroring the z-axis and converting the coordinate system from a right-handed system to a left-handed system. All geometry that is not in the viewing volume (clip space) will be clipped. Therefore, you must move the geometry along the negative z-axis between the near and far planes. e.g.:

    glm_translate(view, (vec3){0.0f, 0.0f, 10.0f});

    glm_translate(view, (vec3){0.0f, 0.0f, -10.0f});