1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
| HRESULT InitGeometry() { HRESULT hr;
LPD3DXBUFFER pD3DXMtrlBuffer; //存储网格模型材质的缓存对象
//从磁盘文件加载网格模型 V_RETURN(D3DXLoadMeshFromX(L"plane.x", D3DXMESH_MANAGED, g_pd3dDevice, NULL, &pD3DXMtrlBuffer, NULL, &g_dwNumMaterials, &g_pMesh));
//从网格模型中提取材质属性和纹理文件名 D3DXMATERIAL* d3dxMaterials = (D3DXMATERIAL*)pD3DXMtrlBuffer->GetBufferPointer(); g_pMeshMaterials = new D3DMATERIAL9[g_dwNumMaterials];
if (g_pMeshMaterials == NULL) return E_OUTOFMEMORY;
g_pMeshTextures = new LPDIRECT3DTEXTURE9[g_dwNumMaterials]; if (g_pMeshTextures == NULL) return E_OUTOFMEMORY;
//逐块提取网格模型材质属性和纹理文件名 for (DWORD i = 0; i < g_dwNumMaterials; i++) { //材料属性 g_pMeshMaterials[i] = d3dxMaterials[i].MatD3D;
//设置模型材料的环境光反射系数, 因为模型材料本身没有设置环境光反射系数 g_pMeshMaterials[i].Ambient = g_pMeshMaterials[i].Diffuse;
g_pMeshTextures[i] = NULL; if (d3dxMaterials[i].pTextureFilename != NULL && strlen(d3dxMaterials[i].pTextureFilename) > 0) { //获取纹理文件名 WCHAR filename[256]; RemovePathFromFileName(d3dxMaterials[i].pTextureFilename, filename);
//创建纹理 if (FAILED(D3DXCreateTextureFromFile(g_pd3dDevice, filename, &g_pMeshTextures[i]))) { MessageBox(NULL, L"没有找到纹理文件!", L"FileMesh", MB_OK); } } }
//释放在加载模型文件时创建的保存模型材质和纹理数据的缓存对象 pD3DXMtrlBuffer->Release();
//为网格模型计算法线信息 if (!(g_pMesh->GetFVF() & D3DFVF_NORMAL)) { //克隆网格模型 LPD3DXMESH pTempMesh = NULL; g_pMesh->CloneMeshFVF(D3DXMESH_MANAGED, g_pMesh->GetFVF() | D3DFVF_NORMAL, g_pd3dDevice, &pTempMesh);
//为网格模型计算法线 D3DXComputeNormals(pTempMesh, NULL);
//释放原来的网格模型对象, 并保存新网格模型 g_pMesh->Release(); g_pMesh = pTempMesh; }
return S_OK; }
|