Search code examples
copenglglm-math

Error changing view perspective in OpenGL


I'm trying to change the perspective of my square in OpenGL but when I put some vectors to multiply with my position's vector the image disappears and don't know if I changed the perspective enough to make it disappear from the screen or it is a rendering problem which I think that is more probable

Vertex Shader:

#version 330 core

layout (location = 0) in vec3 position;
layout (location = 1) in vec3 aColor;
layout (location = 2) in vec2 aTex;

out vec3 color;

out vec2 texCoord;

//uniform float scale;

uniform mat4 model;
uniform mat4 view;
uniform mat4 proj;

void main()
{
    gl_Position = proj * view * model * vec4(position, 1.0);
    color = aColor;
    texCoord = aTex;
}

Fragment Shader:

#version 330 core

out vec4 FragColor;

in vec3 color;

in vec2 texCoord;

uniform sampler2D tex0;

void main()
{
 FragColor = texture(tex0, texCoord);
}

Part of the program with the implementation:

while (true)
  {
    if (SDL_PollEvent(&windowEvent))
    {
      if (SDL_QUIT == windowEvent.type)
      {
        break;
      }
    }
    //Cor do background
    glClearColor(0.05f, 0.57f, 0.38f, 1.0f);
    //Limpa o buffer e o atribui uma nova cor
    glClear(GL_COLOR_BUFFER_BIT);
    //Ativa o Programa Shader designado
    shaderProgram.Activate(shaderProgram);

    mat4 model = {1.f};
    mat4 view = {1.f};
    mat4 proj = {1.f};

    glm_translate(view, (vec3){0.f, -0.5f, -2.f});
    glm_perspective(glm_rad(45.f), (float)(SCREEN_WIDTH / SCREEN_HEIGHT), 0.1f, 100.f, proj);
    int modelLoc = glGetUniformLocation(shaderProgram.id, "model");
    glUniformMatrix4fv(modelLoc, 1, GL_FALSE, (float *)model);
    int viewLoc = glGetUniformLocation(shaderProgram.id, "view");
    glUniformMatrix4fv(viewLoc, 1, GL_FALSE, (float *)view);
    int projLoc = glGetUniformLocation(shaderProgram.id, "proj");
    glUniformMatrix4fv(projLoc, 1, GL_FALSE, (float *)proj);

    //Atribui um valor uniforme podendo aumentar ou reduzir o objeto renderizado
    glUniform1f(uniID, 0.5);
    //Liga a textura para aparecer na renderização
    imagem.Bind(imagem);
    //Vincula o VAO ao OpenGL para ser usado
    vao1.Bind(vao1);
    //Desenha o elemento
    glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
    glEnd();
    //update the window
    SDL_GL_SwapWindow(window);
  }

Solution

  • If you are using is C++ and glm, then glm::mat4 model(1.0f); constructs an identity matrix.

    If you are using cglm then mat4 model = {1.f}; does not initialize an identity matrix. mat4 is a structure, but not a class with a constructor.

    You have to use glm_mat4_identity:

    mat4 model = {1.f}; mat4 view = {1.f}; mat4 proj = {1.f};

    mat4 model, view, proj;
    glm_mat4_identity(model); 
    glm_mat4_identity(view);
    glm_mat4_identity(proj);