NeHe OpenGL Lesson48 - ArcBall Rotation (Mouse Rotation)
This sample provides us an ArcBall module that we could use to rotate object along the screen with mouse. The underneath idea is mapping a 2d screen position into a 3d sphere coordinate. A rotation Quat could be calculated out by two sphere coordinates (the start, end position). Then a rotation matrix created based on the quat.
This sample also provide some other useful technologies:
1) convert quat to a rotation matrix;
2) use OpenGL fucntion “glMultMatrixf(Transform.M);”to set up the model view matrix directly;
Mapping 2D Mouse Position into 3D Sphere Coordinate
At first we simply scale down the mouse coordinates from the range of [0...width), [0...height) to [-1...1], [1...-1] (Y flipped).
X = (MousePt.X / ((Width - 1) / 2)); Y = -(MousePt.Y / ((Height - 1) / 2));
Calculate the 3D Sphere coordinates:
length = (X * X) + (Y * Y); //If the point is mapped outside of the sphere... (length > radius squared) if (length > 1.0f) { GLfloat norm; //Compute a normalizing factor (radius / sqrt(length)) norm = 1.0f / FuncSqrt(length); //Return the "normalized" vector, a point on the sphere NewVec->s.X = TempPt.s.X * norm; NewVec->s.Y = TempPt.s.Y * norm; NewVec->s.Z = 0.0f; } else //Else it's on the inside { //Return a vector to a point mapped inside the sphere sqrt(radius squared - length) NewVec->s.X = TempPt.s.X; NewVec->s.Y = TempPt.s.Y; NewVec->s.Z = FuncSqrt(1.0f - length); }
The full source code could be found here.