常式一:XFile
該常式從bigship1.x檔案中載入資料。
該常式使用了下列全域變數:
ID3DXMesh* Mesh = 0;<br />std::vector<D3DMATERIAL9>Mtrls(0);<br />std::vector<IDirect3DTexture9*>Textures(0);
這裡我們用一個ID3DXMeshObject Storage Service從XFile中載入的網格資料。另外我們還用兩個向量分別儲存該網格的材質和紋理資料。
首先,實現我們的標準Setup函數。第一步是載入XFile檔案。
bool Setup()<br />{<br />HRESULT hr = 0;</p><p>//<br />//Load the XFile data.<br />//<br />ID3DXBuffer* adjBuffer = 0;<br />ID3DXBuffer* mtrlBuffer = 0;<br />DWORD numMtrls= 0;<br />hr = D3DXLoadMeshFromX(<br />"bigship1.x",<br />D3DXMESH_MANGED,<br />Device,<br />&adjBuffer,<br />&mtrlBuffer,<br />0,<br />&nummMtrls,<br />&Mesh);<br />if(FAILED(hr))<br />{<br />::MessageBox(0, "D3DXLoadMeshFromX() - FAILED", 0, 0);<br />return false;<br />}<br />}
載入XFile資料後,我們必須遍曆D3DXMATERIAL數組中的元素,並載入該網格所引用的紋理資料。
//<br />//Extract the materials, and load textures.<br />//<br />if(mtrlBuffer != 0 && numMtrls != 0)<br />{<br />D3DXMATERIAL* mtrls = (D3DXMATERIAL*)mtrlBuffer->GetBufferPointer();<br />for(int i=0; i<numMtrls; i++)<br />{<br />//the MatD3D property doesn't have an ambient value set<br />//when its loaded, so set it now:<br />mtrls[i].MatD3D.Ambient = mtrls[i].MatD3D.Diffuses;<br />//save the ith material<br />Mtrls.push_back(mtrls[i].MatD3D);<br />//check if the ith material has an associative texture<br />if(mtrls[i].pTextureFilename != 0)<br />{<br />//yes, load the texture for the ith subset<br />IDirect3DTexture9* tex = 0;<br />D3DXCreateTextureFromFile(<br />Device,<br />mtrls[i].pTextureFilename,<br />&tex);<br />//save the loaded texture<br />Textures.push_back(tex);<br />}<br />else<br />{<br />//no texture for the ith subset<br />Textures.push_back(0);<br />}<br />}<br />}<br />d3d::Release<ID3DXBuffer*>(mtrlBuffer);//done w/buffer<br />.<br />.//Snipped irrelevant code to this chapter(e.q., setting up lights,<br />.//view and projection matrices, etc.)<br />.<br />Return true;<br />)//end Setup()
在Display函數中,我們在每一幀映像中對網格做了稍微的旋轉,以使其呈現出旋轉的動畫效果。由於網格的各個子集已按0,1,2,...,n-1的順序標記(n為子集總數),整個網格的繪製通過一個簡單的迴圈即可輕鬆完成。