How can I get view direction from the OpenGL ModelView Matrix?

AAB picture AAB · Mar 29, 2013 · Viewed 12.4k times · Source

I am writing a volume render program that constantly adjusts some plane geometry so it always faces the camera. The plane geometry rotates whenever the camera rotates in order to appear as if it doesn't move--relative to everything else in the scene. (I use the camera's viewing direction as a normal vector to these plane geometries.)

Currently I am manually storing a custom rotation vector ('rotations') and applying its affects as follows in the render function:

gl2.glRotated(rotations.y, 1.0, 0.0, 0.0);
gl2.glRotated(rotations.x, 0.0, 1.0, 0.0);

Then later on I get the viewing direction by rotating the initial view direction (0,0,-1) around the x and y axes with the values from rotation. This is done in the following manner. The final viewing direction is stored in 'view':

     public Vec3f getViewingAngle(){
        //first rotate the viewing POINT
        //then find the vector from there to the center
        Vec3f view=new Vec3f(0,0,-1);
        float newZ=0;
        float ratio=(float) (Math.PI/180);
        float vA=(float) (-1f*rotations.y*(ratio));
        float hA=(float) (-1f*rotations.x)*ratio;

        //rotate about the x axis first
        float newY=(float) (view.y*Math.cos(vA)-view.z*Math.sin(vA));
        newZ=(float) (view.y*Math.sin(vA)+view.z*Math.cos(vA));
        view=new Vec3f(view.x,newY,newZ);

        //rotate about Y axis
        float newX=(float) (view.z*Math.sin(hA)+view.x*Math.cos(hA));
        newZ=(float) (view.z*Math.cos(hA)-view.x*Math.sin(hA));
        view=new Vec3f(newX,view.y,newZ);
        view=new Vec3f(view.x*-1f,view.y*-1f,view.z*-1f);

        //return the finalized normal viewing direction
        view=Vec3f.normalized(view);
        return view;
}

Now I am moving this program to a larger project wherein the camera rotation is handled by a 3rd party graphics library. I have no rotations vector. Is there some way I can get my view direction vector from:

GLfloat matrix[16]; 
glGetFloatv (GL_MODELVIEW_MATRIX, matrix);

I am looking at this for reference http://3dengine.org/Modelview_matrix but I still don't get how to come up with the view direction. Can someone explain to me if it is possible and how it works?

Answer

Michaelangel007 picture Michaelangel007 · Nov 4, 2014

You'll want to look at this picture @ http://db-in.com/images/local_vectors.jpg http://db-in.com/images/local_vectors.jpg

The Direction-of-Flight ( DOF) is the 3rd row.

GLfloat matrix[16]; 
glGetFloatv( GL_MODELVIEW_MATRIX, matrix );

float DOF[3];
DOF[0] = matrix[  2 ]; // x
DOF[1] = matrix[  6 ]; // y
DOF[2] = matrix[ 10 ]; // z

Reference: