HamzaFarooq
HamzaFarooq

Reputation: 439

Get orientation of object in OpenTK C#

I used to rotate an object in multiple stages but cant figure out how to get the actual orientation (Eular angles) of object.

GL.Rotate(rotateCAx, new Vector3d(1, 0, 0));
GL.Rotate(rotateCAy, new Vector3d(0, 1, 0));
GL.Rotate(rotateCAz, new Vector3d(0, 0, 1));
GL.Rotate(xRot, new Vector3d(1, 0, 0));
GL.Rotate(yRot, new Vector3d(0, 1, 0));
GL.Rotate(zRot, new Vector3d(0, 0, 1));

What is the orientation of object now

Upvotes: 1

Views: 469

Answers (1)

Rabbid76
Rabbid76

Reputation: 210998

I recommend to change the order of the angles, when you apply them tho the current matrix:

GL.Rotate(rotateCAz, new Vector3d(1, 0, 0));
GL.Rotate(rotateCAy, new Vector3d(0, 1, 0));
GL.Rotate(rotateCAx, new Vector3d(0, 0, 1));
GL.Rotate(zRot, new Vector3d(1, 0, 0));
GL.Rotate(yRot, new Vector3d(0, 1, 0));
GL.Rotate(xRot, new Vector3d(0, 0, 1));

Either read back the current matrix from the GPU:

Matrix4 currentModelView;
GL.GetFloat(GetPName.ModelviewMatrix, out currentModelView);

or calculate a transformation matrix with the same rotations:

Matrix4 currentModelView = 
    Matrix4.CreateRotationX(xRot * (float)Math.PI / 180.0f) *
    Matrix4.CreateRotationY(yRot * (float)Math.PI / 180.0f) *
    Matrix4.CreateRotationZ(zRot * (float)Math.PI / 180.0f) * 
    Matrix4.CreateRotationX(rotateCAx * (float)Math.PI / 180.0f) *
    Matrix4.CreateRotationY(rotateCAy * (float)Math.PI / 180.0f) *
    Matrix4.CreateRotationZ(rotateCAz * (float)Math.PI / 180.0f);

Convert the rotation component of the Matrix4 to a Quaternion:

Quaternion q = currentModelView.ExtractRotation();

Compute the Pitch, yaw, and roll angles from the Quaternion. An algorithm fro that can be found at Maths - Conversion Quaternion to Euler. I've used the OpenGL Mathematics implementation for glm::pitch, glm::yaw and glm::roll:

const double epsi = 0.0001;
double y = 2.0 * (q.Y * q.Z + q.W * q.X);
double x = q.W * q.W - q.X * q.X - q.Y * q.Y + q.Z * q.Z;

double pitch = (Math.Abs(q.X) < epsi && Math.Abs(q.Y) < epsi) ? 2.0 * Math.Atan2(q.X, q.W) : Math.Atan2(y, x);
double yaw = Math.Asin(Math.Min(Math.Max(-2.0 * (q.X * q.Z - q.W * q.Y), -1.0), 1.0));
double roll = Math.Atan2(2.0 * (q.X * q.Y + q.W * q.Z), q.W * q.W + q.X * q.X - q.Y * q.Y - q.Z * q.Z);

The angles pitch, yaw and roll correspond to the current rotations around the x, y and z axis (in view space).

float rot_x = pitch * 180.0f / (float)Math.PI; 
float rot_y = yaw   * 180.0f / (float)Math.PI; 
float rot_z = roll  * 180.0f / (float)Math.PI;

Upvotes: 1

Related Questions