Question

I am trying to create my own quaternion class and I get weird results. Either the cube I am trying to rotate is flickering like crazy, or it is getting warped.

This is my code:

void Quaternion::AddRotation(vec4 v)
{
    Quaternion temp(v.x, v.y, v.z, v.w);
    *this = temp * (*this);
}

mat4   Quaternion::GenerateMatrix(Quaternion &q)
{
    q.Normalize();

    //Row order
    mat4 m( 1 - 2*q.y*q.y - 2*q.z*q.z, 2*q.x*q.y - 2*q.w*q.z, 2*q.x*q.z + 2*q.w*q.y, 0,
            2*q.x*q.y + 2*q.w*q.z, 1 - 2*q.x*q.x - 2*q.z*q.z, 2*q.y*q.z + 2*q.w*q.x, 0,
            2*q.x*q.z - 2*q.w*q.y, 2*q.y*q.z - 2*q.w*q.x, 1 - 2*q.x*q.x - 2*q.y*q.y, 0,
            0, 0, 0, 1);

    //Col order
    //  mat4 m( 1 - 2*q.y*q.y - 2*q.z*q.z,2*q.x*q.y + 2*q.w*q.z,2*q.x*q.z - 2*q.w*q.y,0,
    //          2*q.x*q.y - 2*q.w*q.z,1 - 2*q.x*q.x - 2*q.z*q.z,2*q.y*q.z - 2*q.w*q.x,0,
    //          2*q.x*q.z + 2*q.w*q.y,2*q.y*q.z + 2*q.w*q.x,1 - 2*q.x*q.x - 2*q.y*q.y,0,
    //          0,0,0,1);

    return m;
}

When I create the entity I give it a quaternion:

entity->Quat.AddRotation(vec4(1.0f, 1.0f, 0.0f, 45.f));

And each frame I try to rotate it additionally by a small amount:

for (int i = 0; i < Entities.size(); i++)
{
    if (Entities[i] != NULL)
    {
        Entities[i]->Quat.AddRotation(vec4(0.5f, 0.2f, 1.0f, 0.000005f));
        Entities[i]->DrawModel();
    }
    else
        break;
}

And finally this is how I draw each cube:

void Entity::DrawModel()
{
    glPushMatrix();

    //Rotation
    mat4 RotationMatrix;
    RotationMatrix = this->Quat.GenerateMatrix(this->Quat);

    //Position
    mat4 TranslationMatrix = glm::translate(mat4(1.0f), this->Pos);

    this->Trans = TranslationMatrix * RotationMatrix;

    glMultMatrixf(value_ptr(this->Trans));

    if (this->shape != NULL)
        this->shape->DrawShape();

    glPopMatrix();
}

EDIT: This is the tutorial I used to learn quaternions: http://www.cprogramming.com/tutorial/3d/quaternions.html

Was it helpful?

Solution

Without studying your rotation matrix to the end, there are two possible bugs I can think of. The first one is that your rotation matrix R is not orthogonal, i.e. the inverse of R is not equal to the transposed. This could cause warping of the object. The second place to hide a bug is inside the multiplication of your quaternions.

OTHER TIPS

There's a mistake in the rotation matrix. Try exchanging the element (2,3) with element (3,2).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top