使用四元数的OpenGL旋转不起作用

使用四元数的OpenGL旋转不起作用,opengl,math,rotation,transformation,quaternions,Opengl,Math,Rotation,Transformation,Quaternions,我正在尝试使用四元数使立方体绕固定轴旋转。以下是我使用四元数生成的代码: glMatrixMode( GL_MODELVIEW_MATRIX ); Quaternion rot1; Quaternion rot2; rot1.FromAxis(Vector3(1.0,0.0,0.0),angleY); rot2.FromAxis(Vector3(0.0,1.0,0.0),angleX); ro

我正在尝试使用四元数使立方体绕固定轴旋转。以下是我使用四元数生成的代码:

            glMatrixMode( GL_MODELVIEW_MATRIX );
        Quaternion rot1;
        Quaternion rot2;
        rot1.FromAxis(Vector3(1.0,0.0,0.0),angleY);
        rot2.FromAxis(Vector3(0.0,1.0,0.0),angleX);
        rot1.normalise();
        rot2.normalise();
        QAccumulative = QAccumulative * rot1;
        QAccumulative = QAccumulative * rot2;


        Matrix4 mat;
        mat = QAccumulative.getMatrix();

        angleY = 0;
        angleX = 0;
        glMultMatrixf(mat.get());
你认为我的代码不正确吗,我的立方体看起来是无限大的,相比之下没有这张代码

编辑:

在得到一些帮助后,结果证明规范化QAcc使其具有标识性,但规范化rot1和rot2使QAcc不稳定,以下是我的规范化方法:

      void Quaternion::normalise()
{
    // Don't normalize if we don't have to
    float mag2 = w * w + x * x + y * y + z * z;
    if (fabs(mag2) > TOLERANCE && fabs(mag2 - 1.0f) > TOLERANCE) {
        float mag = sqrt(mag2);
        w /= mag;
        x /= mag;
        y /= mag;
        z /= mag;
    }
}
编辑:

这是我的FromAxis代码:

void Quaternion::FromAxis(const Vector3 &v, float angle)
{
    float sinAngle;
    angle *= 0.5f;
    Vector3 vn(v);
    vn.normalize();

    sinAngle = sin(angle);

    x = (vn.x * sinAngle);
    y = (vn.y * sinAngle);
    z = (vn.z * sinAngle);
    w = cos(angle);
}

我确实在规范化向量而没有检查它们,添加一个容差阈值解决了我的问题


谢谢大家的帮助。

QAccumulative是如何声明和初始化的?如果以后要覆盖标识,将mat设置为标识真的有用吗?QAccumulative的声明方式如下:QAccumulative.FromAxis(Vector3(0.0,0.0,0.0),0);我认为初始化它很重要(这是一个习惯),但正如你所说,我正在覆盖它,所以它没有用处。那么这不应该是错误。你可以尝试用rot四元数的标准化来代替QAccumulative的标准化,但这不会改变任何事情,四元数的标准并不是那么不稳定。这实际上解决了部分问题,我的立方体已恢复到正常大小,但在应用旋转时不会旋转:D.它在此更改之前确实移动了。这可能是由于
angleY=0;角x=0