Search code examples
c++openglglm-mathopengl-compat

How to use a glm::mat4 in a glRotatef


In modern OpenGL I would translate, rotate, scale, etc. like this:

m_cart.orientation = glm::mat4(glm::mat3(m_cart.T, m_cart.N, m_cart.B));

modelViewMatrixStack.Push();
    modelViewMatrixStack.Translate(m_cart.position);
    modelViewMatrixStack *= m_cart.orientation;
    modelViewMatrixStack.Scale(0.01f);
    m_cart.Render();
modelViewMatrixStack.Pop();

But now for reasons outside my control I have to use some old OpenGL and I've changed the code to something like this:

glPushMatrix();
    glTranslatef(m_cart.position.x, m_cart.position.y, m_cart.position.z);
    glScalef(0.01f, 0.01f, 0.01f);
    m_cart.Render();
glPopMatrix();

Above is pretty much equivalent but I can't figure out how I can apply the rotation using the glm::mat4. glRotatef wants an angle and floats for xyz. I've looked at `glm::decompose´ to get those out of the 4x4matrix but it's not very clear.

Is it possible?


Solution

  • You can't set an arbitrary orientation with a single glRotate. you would need up to 3 rotations.
    But it is not necessary to rotate the matrix, since you know the final orientation matrix already. Instead of calculating the parameters for glRotate you can use glMultMatrix which can directly multiply the m_cart.orientation matrix to the matrix stack:

    m_cart.orientation = glm::mat4(glm::mat3(m_cart.T, m_cart.N, m_cart.B));
    
    glPushMatrix();
        glTranslatef(m_cart.position.x, m_cart.position.y, m_cart.position.z);
        glMultMatrixf(glm::value_ptr(m_cart.orientation)); 
        glScalef(0.01f, 0.01f, 0.01f);
        m_cart.Render();
    glPopMatrix();