Search code examples
javaopengllwjgl

View & Projection Matrices are not working


I am trying to implement MVP Matrices into my engine. My Model matrix is working fine but my View and Projection Matrices do not work. Here is the creation for both:

    public void calculateProjectionMatrix() {
        final float aspect = Display.getDisplayWidth() / Display.getDisplayHeight();
        final float y_scale = (float) ((1f / Math.tan(Math.toRadians(FOV / 2f))) * aspect);
        final float x_scale = y_scale / aspect;
        final float frustum_length = FAR_PLANE - NEAR_PLANE;

        proj.identity();
        proj._m00(x_scale);
        proj._m11(y_scale);
        proj._m22(-((FAR_PLANE + NEAR_PLANE) / frustum_length));
        proj._m23(-1);
        proj._m32(-((2 * NEAR_PLANE * FAR_PLANE) / frustum_length));
        proj._m33(0);
    }

    public void calculateViewMatrix() {
        view.identity();
        view.rotate((float) Math.toRadians(rot.x), Mathf.xRot);
        view.rotate((float) Math.toRadians(rot.y), Mathf.yRot);
        view.rotate((float) Math.toRadians(rot.z), Mathf.zRot);
        view.translate(new Vector3f(pos).mul(-1));
        System.out.println(view);
    }

The vertices i'm trying to render are: -0.5f, 0.5f, -1.0f, -0.5f, -0.5f, -1.0f, 0.5f, -0.5f, -1.0f, 0.5f, 0.5f, -1.0f

I Tested the view matrix before the upload to shader and it is correct.

This is how I render:

    ss.bind();
    glEnableVertexAttribArray(0);
    glEnableVertexAttribArray(1);
    glEnableVertexAttribArray(2);
    ss.loadViewProjection(cam);
    ss.loadModelMatrix(Mathf.transformation(new Vector3f(0, 0, 0), new Vector3f(), new Vector3f(1)));
    ss.connectTextureUnits();
    glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
    glDisableVertexAttribArray(0);
    glDisableVertexAttribArray(1);
    glDisableVertexAttribArray(2);
    ss.unbind();

Vertex Shader:

#version 330 core

layout(location = 0) in vec3 i_position;
layout(location = 1) in vec2 i_texCoord;
layout(location = 2) in vec3 i_normal;

out vec2 p_texCoord;

uniform mat4 u_proj;
uniform mat4 u_view;
uniform mat4 u_model;

void main() {
    gl_Position = u_proj * u_view * u_model * vec4(i_position, 1.0);
    p_texCoord = i_texCoord;
}

Solution

  • So I tried everything and found out that you should not initialise the uniform locations to 0. In the class that extends the ShaderProgram class, I had:

        private int l_TextureSampler = 0;
        private int l_ProjectionMatrix = 0;
        private int l_ViewMatrix = 0;
        private int l_ModelMatrix = 0;
    

    Changing it to this:

        private int l_TextureSampler;
        private int l_ProjectionMatrix;
        private int l_ViewMatrix;
        private int l_ModelMatrix;
    

    Worked for me.