Search code examples
openglglrotate

OpenGl rotate custom implementation


I'm trying to code my custom implementation of Opengl glRotatef(angle,x,y,z) function. I wrote the rotation matrix, but when I try to use it, the effect is not the same as the original function. Here is my code;

void mglRotate(float angle, float x, float y, float z)
{
    float angle_rad = angle * (PI/180.0f);

    float c = cos(angle_rad);
    float s = sin(angle_rad);
    float t = 1 - c;

    float m[16] = {
            c+x*x*t,y*x*t+z*s,z*x*t-y*s,0,
            x*y*t-z*s,c+y*y*t,z*y*t+x*s,0,
            x*z*t+y*s,y*z*t-x*s,z*z*t+c,0,
            0,0,0,1
    };

    glMultMatrixf(m);
}

Where is my mistake?


Solution

  • There is a library glm, that does exactly the same thing as old openGL functions. You can compare your implementation with implementation in glm and figure it out :)

    template <typename T> 
    GLM_FUNC_QUALIFIER detail::tmat4x4<T> rotate
    (
        detail::tmat4x4<T> const & m,
        T const & angle, 
        detail::tvec3<T> const & v
    )
    {
        T a = radians(angle);
        T c = cos(a);
        T s = sin(a);
    
        detail::tvec3<T> axis = normalize(v);
    
        detail::tvec3<T> temp = (T(1) - c) * axis;
    
        detail::tmat4x4<T> Rotate(detail::tmat4x4<T>::null);
        Rotate[0][0] = c + temp[0] * axis[0];
        Rotate[0][1] = 0 + temp[0] * axis[1] + s * axis[2];
        Rotate[0][2] = 0 + temp[0] * axis[2] - s * axis[1];
    
        Rotate[1][0] = 0 + temp[1] * axis[0] - s * axis[2];
        Rotate[1][1] = c + temp[1] * axis[1];
        Rotate[1][2] = 0 + temp[1] * axis[2] + s * axis[0];
    
        Rotate[2][0] = 0 + temp[2] * axis[0] + s * axis[1];
        Rotate[2][1] = 0 + temp[2] * axis[1] - s * axis[0];
        Rotate[2][2] = c + temp[2] * axis[2];
    
        detail::tmat4x4<T> Result(detail::tmat4x4<T>::null);
        Result[0] = m[0] * Rotate[0][0] + m[1] * Rotate[0][1] + m[2] * Rotate[0][2];
        Result[1] = m[0] * Rotate[1][0] + m[1] * Rotate[1][1] + m[2] * Rotate[1][2];
        Result[2] = m[0] * Rotate[2][0] + m[1] * Rotate[2][1] + m[2] * Rotate[2][2];
        Result[3] = m[3];
        return Result;
    }
    

    The one thing that seems wrong to me in your code is that you don't normalize the axis.