Search code examples
c++graphicsglslvulkanglm-math

GLM perspective matrix ruins rendering


I created a projection matrix for Vulkan renderer using GLM, but after multiplying it with vertex itself in vertex shader, nothing renders. I have defined GLM_FORCE_RADIANS and GLM_FORCE_DEPTH_ZERO_TO_ONE (to be fine, I tried without both of these, or without one of these). Also I tried to pass fovy param as degrees or radians, but it didn't help. In addition, I noticed that orthographic matrix works just fine! Here's my code of vertex shader, matrix creation itself and front face is CCW (if it can help), depth testing disabled (didn't implement that yet):

Projection matrix creation:

    glm::mat4 projection = glm::perspective(45.0f, 16.0f / 9.0f, 0.1f, 100.0f);
    glm::mat4 model = glm::mat4(1.0f);
    model = glm::rotate(model, (float)glfwGetTime() * 30, glm::vec3(0.0f, 0.0f, 1.0f));

Vertex Shader:

#version 460 core

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

layout(push_constant) uniform MVP {
   mat4 VP;
   mat4 Transform;
} matrices;

layout(location = 0) out vec4 Color;

void main()
{
   gl_Position = matrices.VP * matrices.Transform * vec4(aPos, 
   1.0f, 1.0f);
   Color = vec4(aColor, 1.0f);
}

The way I include GLM:

#define GLM_FORCE_RADIANS
#define GLM_FORCE_DEPTH_ZERO_TO_ONE
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>

Solution

  • I fixed it. The "problem" was that projection and perspective division maps the [-near, -far] range to [-1, 1], which lead to flipping Z coordinate. Meanwhile I had Z coordinate as 10.0f, it was actually behing the camera. Solution was setting up Z coordinate value as -10.0f, which will be flipped to 10.0f after projection.