世界轉型 (Direct3D 9)
世界轉型的討論介紹基本概念,並提供如何設定世界轉型的詳細數據。
什麼是世界轉型?
世界轉換會將座標從模型空間變更,其中頂點是相對於模型本機原點定義的,而世界空間是相對於場景中所有物件通用的原點所定義的。 從本質上講,世界將模型轉化為世界:因此其名稱。 下圖顯示世界座標系統與模型本機座標系統之間的關聯性。
世界轉換可以包含翻譯、旋轉和縮放的任何組合。
設定世界矩陣
如同任何其他轉換,將一系列矩陣串連成包含其效果總和的單一矩陣,以建立世界轉換。 在最簡單的案例中,當模型位於世界原點,且其本機座標軸與世界空間相同時,世界矩陣就是識別矩陣。 更常見的是,世界矩陣是將轉譯成世界空間的組合,而且可能需要一或多個旋轉來視需要轉譯模型。
下列範例會從以 C++ 撰寫的虛構 3D 模型類別,使用 D3DX 公用程式連結庫中所包含的協助程式函式,建立包含三個旋轉的世界矩陣,以設定模型的方向,以及轉譯,以相對於其在世界空間中的位置進行重新置放。
/*
* For the purposes of this example, the following variables
* are assumed to be valid and initialized.
*
* The m_xPos, m_yPos, m_zPos variables contain the model's
* location in world coordinates.
*
* The m_fPitch, m_fYaw, and m_fRoll variables are floats that
* contain the model's orientation in terms of pitch, yaw, and roll
* angles, in radians.
*/
void C3DModel::MakeWorldMatrix( D3DXMATRIX* pMatWorld )
{
D3DXMATRIX MatTemp; // Temp matrix for rotations.
D3DXMATRIX MatRot; // Final rotation matrix, applied to
// pMatWorld.
// Using the left-to-right order of matrix concatenation,
// apply the translation to the object's world position
// before applying the rotations.
D3DXMatrixTranslation(pMatWorld, m_xPos, m_yPos, m_zPos);
D3DXMatrixIdentity(&MatRot);
// Now, apply the orientation variables to the world matrix
if(m_fPitch || m_fYaw || m_fRoll) {
// Produce and combine the rotation matrices.
D3DXMatrixRotationX(&MatTemp, m_fPitch); // Pitch
D3DXMatrixMultiply(&MatRot, &MatRot, &MatTemp);
D3DXMatrixRotationY(&MatTemp, m_fYaw); // Yaw
D3DXMatrixMultiply(&MatRot, &MatRot, &MatTemp);
D3DXMatrixRotationZ(&MatTemp, m_fRoll); // Roll
D3DXMatrixMultiply(&MatRot, &MatRot, &MatTemp);
// Apply the rotation matrices to complete the world matrix.
D3DXMatrixMultiply(pMatWorld, &MatRot, pMatWorld);
}
}
準備世界矩陣之後,請呼叫 IDirect3DDevice9::SetTransform 方法來設定它,並指定第一個參數的 D3DTS_WORLD 巨集。
注意
Direct3D 會使用您設定為設定數個內部數據結構的世界和檢視矩陣。 每次設定新的世界或檢視矩陣時,系統會重新計算相關聯的內部結構。 例如,設定這些矩陣時,每個畫面的計算耗時數千次。 您可以將世界和檢視矩陣串連到您設定為世界矩陣的世界檢視矩陣,然後將檢視矩陣設定為身分識別,以將所需的計算數目降到最低。 保留個別世界和檢視矩陣的快取複本,以便您可以視需要修改、串連及重設世界矩陣。 為了清楚起見,本檔 Direct3D 範例很少採用此優化。
相關主題