Search code examples
c++openglglm-math

How I can I get the mirror reflection of a glm::mat4?


So I'm using a shader to draw in OpenGL a 2D scene that so far looks like this

flipped scene

To get this image I have a camera that I use in the shader to multiply the coordinates of the vertex.

Camera code:

glm::mat4 projection =
  glm::perspective(glm::radians(45.0f), app.aspectRatio, 0.0f, 100.0f);
glm::vec3 camera = glm::vec3(0.0f, 0.0f, -2.0f);
glm::mat4 uCameraView = glm::translate(world.projection, world.camera);

Shader code:

#version 330 core

layout(location = 0) in vec2 vPosition;

layout(std140) uniform ubo
{
  mat4 uCameraView;
};

void main()
{
  gl_Position = uCameraView * vec4(vPosition.x, vPosition.y, 0.0f, 1.0f);
}

If I multiply by -1 vPosition.y in the shader I get the following image, which is the result I want

enter image description here

Could be possible to somehow apply this "mirror flip transformation" to the glm::mat4 uCameraView to avoid having to do this on every shader?


Solution

  • Mirror the y axis of the camera with glm::scale. The scale must be (1, -1, 1):

    glm::mat4 projection = 
        glm::perspective(glm::radians(45.0f), app.aspectRatio, 0.0f, 100.0f);
    
    glm::mat4 view = glm::translate(glm::mat4(1.0f), glm::vec3(0.0f, 0.0f, -2.0f));
    view = glm::scale(view, glm::vec3(1.0f, -1.0f, 1.0f));
    
    glm::mat4 uCameraView = projection * view;