Home
29 December 2006 @ 04:43 pm
Eigen example: the OpenGL camera problem  
It looks like Eigen 1.0 will be out in 2006 as promised. For this occasion, I have fixed a small example program. Since the beginning, one of the primary goals of Eigen has been to provide the math functionality that is useful in OpenGL apps. And one of the most common problems when writing OpenGL apps is, how to let the user freely move the camera around? Representing the camera orientation by 3 angles just doesn't work, and leads to the gimbal lock problem. So the best solution is to represent the camera position and orientation by a 4x4 matrix and pass it directly to OpenGL. The question is then, how to generate this matrix from the user input? This is where Eigen comes into play. Here is the GLWidget::mouseMoveEvent() function from the Eigen example program:
void GLWidget::mouseMoveEvent( QMouseEvent *event )
{
    QPoint delta = event->pos() - m_lastPos;
    m_lastPos = event->pos();
    if( event->buttons() & Qt::LeftButton )
    {
        m_cameraMatrix.prerotate3( - delta.x() * ROTATION_SPEED, AXIS_Y );
        m_cameraMatrix.prerotate3( - delta.y() * ROTATION_SPEED, AXIS_X );
    }
    if( event->buttons() & Qt::RightButton )
    {
        m_cameraMatrix.prerotate3( - delta.x() * ROTATION_SPEED, AXIS_Z );
        m_cameraMatrix.pretranslate( delta.y() * TRANSLATION_SPEED * AXIS_Z );
    }
    if( event->buttons() & ( Qt::LeftButton | Qt::RightButton ) )
        update();
}

This lets the user rotate around by drag & drop with the left mouse button, and tilt and move forwards/backwards by drag & drop with the right mouse button. Then the paintGL function looks like
void GLWidget::paintGL()
{
    glLoadMatrixd( m_cameraMatrix.array() );
    drawScene();
}

Obligatory screenshot: