Hence the C# code below for Managed DirectX will allow us to look at a rotation matrix and get back to one set of YawPitchRoll angles that would give rise to it. The DirectX Matrix structure exposes elements called Mij (e.g. M32, M21 etc.) where the first digit is the row, and the second the column (remember "Rock Cakes" for row followed by column). This being maths there are gotcha's - when the cosine of the pitch angle gets small, (for a pitch of 90-ish degrees, say) numerically things go bananas, so you can take an arbitrary decision about the yaw angle (here I've set it to zero) and deduce a roll. This is okay except where numerical consistency is important (flying jet fighters. guiding satellites and so on) where you can't just swizzle your object in space to make the sums work. If you're looking for the "proper" way to do this, I can recommend a piece I stumbled on called The Right Way to Calculate Stuff by Don Hatch. If you want the code and layout for the XYZ equivalent, holler - I'll be interested to see whether anyone out there got this far before sleep overwhelmed them.
static public void DecomposeRollPitchYawZXYMatrix(Matrix mx, out double xPitch, out double yYaw, out double zRoll)
{
xPitch = Math.Asin(-mx.M32);
double threshold = 0.001; // Hardcoded constant - burn him, he's a witch
double test = Math.Cos(xPitch);
if(test > threshold) {
zRoll = Math.Atan2(mx.M12, mx.M22);
yYaw = Math.Atan2(mx.M31, mx.M33);
}
else {
zRoll = Math.Atan2(-mx.M21, mx.M11);
yYaw = 0.0;
Thanks for your patience, O blogosphere - will try to be less turgid in future.