OpenGl rotate custom implementation

半腔热情 提交于 2019-12-11 20:28:27

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/20002810/opengl-rotate-custom-implementation

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!