關(guān)于四元數(shù)(Quaterion)
飄飄白云 2008-03-16
1843年,William Rowan Hamilton發(fā)明了四元數(shù),但直到1985年才有一個叫Ken Shoemake的人將四元數(shù)引入計算機圖形學(xué)處理領(lǐng)域。四元數(shù)在3D圖形學(xué)中主要用于旋轉(zhuǎn),骨骼動畫等。
簡單地來說,四元數(shù)描述了一次旋轉(zhuǎn):繞任意一個軸旋轉(zhuǎn)一個角度。四元數(shù)的定義形式:(w, x, y, z)。假如,繞軸向量v(_x,_y,_z)正向(右手旋轉(zhuǎn)法則)旋轉(zhuǎn)角度p,則對應(yīng)得四元數(shù)q為:
q = (cos(p/2), sin(p/2) * _x, sin(p/2) * _y, sin(p/2) * _z)
用四元數(shù)來表示旋轉(zhuǎn),不如用歐拉角(偏航/yaw,俯仰/pitch,橫滾/ roll)來表示直接,但是用歐拉角來處理旋轉(zhuǎn)有個不可回避的問題:萬向節(jié)死鎖。我們可以通過將歐拉角轉(zhuǎn)換到四元數(shù)來避免這個問題。在DirectX中提供了從歐拉角到四元數(shù),從四元數(shù)到矩陣(Direct3D用旋轉(zhuǎn)來實現(xiàn)旋轉(zhuǎn))的變換函數(shù)。下面參看:\Microsoft DirectX SDK\Include\d3dx9math.h的函數(shù)聲明
從四元數(shù)變換到軸與旋轉(zhuǎn)角
// Compute a quaternin's axis and angle of rotation. Expects unit quaternions.
void WINAPI D3DXQuaternionToAxisAngle
( CONST D3DXQUATERNION *pQ, D3DXVECTOR3 *pAxis, FLOAT *pAngle );
從旋轉(zhuǎn)矩陣構(gòu)造一個四元數(shù)
// Build a quaternion from a rotation matrix.
D3DXQUATERNION* WINAPI D3DXQuaternionRotationMatrix
( D3DXQUATERNION *pOut, CONST D3DXMATRIX *pM);
從一個軸與旋轉(zhuǎn)角構(gòu)造一個四元數(shù)
// Rotation about arbitrary axis.
D3DXQUATERNION* WINAPI D3DXQuaternionRotationAxis
( D3DXQUATERNION *pOut, CONST D3DXVECTOR3 *pV, FLOAT Angle );
從歐拉角構(gòu)造一個四元數(shù)
// Yaw around the Y axis, a pitch around the X axis,
// and a roll around the Z axis.
D3DXQUATERNION* WINAPI D3DXQuaternionRotationYawPitchRoll
( D3DXQUATERNION *pOut, FLOAT Yaw, FLOAT Pitch, FLOAT Roll );
下面我們來看看如何使用:若某物體要繞Y軸旋轉(zhuǎn)fYaw,繞X軸旋轉(zhuǎn)fPitch,繞Z軸旋轉(zhuǎn)fRoll,那么
對應(yīng)的旋轉(zhuǎn)矩陣matRot可以這么計算:
D3DXQUATERNION qR;
D3DXMATRIX matRot;
D3DXQuaternionRotationYawPitchRoll(&qR, fYaw, fPitch, fRoll);
D3DXMatrixRotationQuaternion(&matRot, &qR);
有關(guān)四元數(shù)更詳細的數(shù)學(xué)計算,轉(zhuǎn)換過程可以參考下面的鏈接:
http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/index.htm