Search code examples
c++openglglslglm-math

Unexpected behaviour when scaling projection matrix in OpenGL


Here is my vertex shader:

#version 330 core
layout (location = 0) in vec3 vertexPos;

uniform mat4 viewMatrix_;
uniform mat4 projectionMatrix_;
uniform mat4 modelMatrix_;
void main()
{
    gl_Position = projectionMatrix_*viewMatrix_*modelMatrix_*vec4(vertexPos, 1.0);
}

I am trying to scale my points by scaling the model matrix as multiples of the identity. Ie,

glm::mat4 model = glm::mat4(1.0f)*scale;
shaderProgram_->SetUniformMat4("modelMatrix_", model);

But I seem to get no change at all. If I add a uniform float and multiply the vertex vector position by the scale, then I get my desired effect.

If the scale is 0, the vertices disappear as expected.

Why is this?


Solution

  • glm::mat4 model = glm::mat4(1.0f)*scale does not result in a valid scaling matrix. A valid scaling matrix would contain the scaling value on the first three elements of the diagonal, but have a value of 1.0 in the last diagonal element, e.g.:

    s 0 0 0
    0 s 0 0
    0 0 s 0
    0 0 0 1
    

    while your code produces a matrix where all diagonal elements are set to the scaling factor, e.g.:

    s 0 0 0
    0 s 0 0
    0 0 s 0
    0 0 0 s <-- check here
    

    The reason why you then don't see much of a difference is that now also the w value gets scaled, which means that the whole operation cancels out after the perspective divide.

    If you need a scaling matrix, I highly recommend to use

    glm::scale(glm::mat4(1.0f), glm::vec3(scale, scale, scale));