Search code examples
c++openglcoordinate-transformation

Opengl rotation doesn't work


I try understand opengl, but I have many simple problems... I try rotate my object and I'm doing this:

glBindVertexArray(VAOs[1]);
glBindTexture(GL_TEXTURE_2D, texture1);
glActiveTexture(GL_TEXTURE1);
glUniform1i(glGetUniformLocation(theProgram.get_programID(), "Texture1"), 1);

glMatrixMode(GL_MODELVIEW_MATRIX);
glPushMatrix();
glRotatef(10.0f, 0.0f, 0.0f, -0.1f);
glDrawElements(GL_TRIANGLES, _countof(tableIndices2), GL_UNSIGNED_INT, 0);
glPopMatrix();

And my object is still in the same position. What is wrong?


Solution

  • Functions like glRotate are part of the See Fixed Function Pipeline which is deprecated. This functions do not affect the vertices which are processed by a shader program.

    See Khronos wiki - Legacy OpenGL:

    In 2008, version 3.0 of the OpenGL specification was released. With this revision, the Fixed Function Pipeline as well as most of the related OpenGL functions and constants were declared deprecated. These deprecated elements and concepts are now commonly referred to as legacy OpenGL. ...

    See Khronos wiki - Fixed Function Pipeline:

    OpenGL 3.0 was the last revision of the specification which fully supported both fixed and programmable functionality. Even so, most hardware since the OpenGL 2.0 generation lacked the actual fixed-function hardware. Instead, fixed-function processes are emulated with shaders built by the system. ...


    In modern OpenGL you have to do this stuff by yourself.

    If you switch from Fixed Function Pipeline to today's OpenGL (in C++), then I recommend to use a library like glm OpenGL Mathematics for the matrix operations.

    First you have to create a vertex shader with a matrix uniform and you have to do the multiplivation of the vertex coordinate and the model matrix in the vertex shader:

    in vec3 vert_pos;
    
    uniform mat4 model_matrix;
    
    void main()
    {
        gl_Position = model * vec4(vert_pos.xyz, 1.0);
    }
    

    Of course you can declare further matrices like projection matrix and view matrix:

    in vec3 vert_pos;
    
    uniform mat4 model;
    uniform mat4 view;
    uniform mat4 projection;
    
    void main()
    {
        gl_Position = projection * view * model * vec4(vert_pos.xyz, 1.0);
    }
    

    In the c++ code you have to set set up the matrix and you have to set the matrix uniform:

    #include <glm/glm.hpp>
    #include <glm/gtc/matrix_transform.hpp> // glm::rotate
    #include <glm/gtc/type_ptr.hpp>         // glm::value_ptr
    
    
    glm::mat4 modelMat = glm::rotate(
        glm::mat4(1.0f),
        glm::radians(10.0f),
        glm::vec3(0.0f, 0.0f, -1.0f) );
    
    GLint model_loc = glGetUniformLocation(theProgram.get_programID(), "model");
    
    glUniformMatrix4fv(model_loc, 1, GL_FALSE, glm::value_ptr(modelMat)); 
    

    See also the documentation of the glm matrix transformations.