|
|
某用程序生成了一片平面网格地形,运行后输出框没有错误提示.
地形顶点结构如下:
struct Vertex
{
Vertex(){}
Vertex(float x,float y,float z,float u,float v)
{
_x=x,_y=y,_z=z,_u=u,_v=v;
}
float _x,_y,_z;
float _u,_v;
static const DWORD FVF;
};
创建顶点缓冲区:
bool Terrain::computeVertices()
{
HRESULT hr = 0;
hr = m_pDevice->CreateVertexBuffer(_numVertices*sizeof(Vertex),D3DUSAGE_WRITEONLY,Vertex::FVF,D3DPOOL_MANAGED,&m_pVB,0);
if(FAILED(hr))
return false;
int startX = -_width/2;//set piont (0,0) the center of the terrain
int startZ = _depth/2;//地形起点Z坐标
int endX = _width/2;
int endZ = -_depth/2;//地形终点Z坐标
float uCoordIncrementSize = 1.0f/(float)_numCellsPerRow;//compute the increment size of texture coordinates 贴图U轴
float vCoordIncrementSize = 1.0f/(float)_numCellsPerCol;//from one vertex to the next
Vertex* v = 0;
m_pVB->Lock(0,0,(void**)&v,0);
int i = 0;
for(int z = startZ;z>=endZ;z-=_cellSpacing)//
{
int j = 0;
for(int x = startX;x<=endX;x+=_cellSpacing)
{
int index = i*_numVertsPerRow+j;//give every vertex its coordinate
v[index] = Vertex((float)x,(float)0,(float)z,(float)j*uCoordIncrementSize,(float)i*vCoordIncrementSize);
j++;
}
i++;
}
m_pVB->Unlock();
return true;
}
下面是索引缓冲:
bool Terrain::computeIndices()
{
HRESULT hr = 1;
hr = m_pDevice->CreateIndexBuffer(3*_numTriangles*sizeof(WORD),D3DUSAGE_WRITEONLY,D3DFMT_INDEX16,D3DPOOL_MANAGED,&m_pIB,0);//
if(FAILED(hr))
return false;
WORD* indices =0;
m_pIB->Lock(0,0,(void**)&indices,0);
int baseIndex = 0;
for(int i = 0;i<_numCellsPerCol;i++)
{
for(int j = 0;j<_numCellsPerRow;j++)//assign every vertex a number,weave tiangles
{
indices[baseIndex] = i*_numVertsPerRow+j;
indices[baseIndex+1] = i*_numVertsPerRow+j+1;
indices[baseIndex+2] = (i+1)*_numVertsPerRow+j;
indices[baseIndex+3] = (i+1)*_numVertsPerRow+j;
indices[baseIndex+4] = i*_numVertsPerRow+j+1;
indices[baseIndex+5] = (i+1)*_numVertsPerRow+j+1;
baseIndex +=6;
}
}
m_pIB->Unlock();
return true;
}
地形类中的渲染函数:
bool Terrain::Render()
{
m_pDevice->SetStreamSource( 0,m_pVB,0,sizeof(Vertex) );
m_pDevice->SetIndices( m_pIB );
m_pDevice->SetFVF(Vertex::FVF);
m_pDevice->DrawIndexedPrimitive(D3DPT_TRIANGLELIST,0,0,_numVertices,0,_numTriangles);
return true;
}
调用贴图的函数:
bool Terrain::createTexture()
{
HRESULT hr = 0;
hr = D3DXCreateTextureFromFile(m_pDevice,"Grass.bmp",&pTex);
if(FAILED(hr))
return false;
m_pDevice->SetTexture(0,pTex);
m_pDevice->SetSamplerState(0,D3DSAMP_MAGFILTER,D3DTEXF_LINEAR);
m_pDevice->SetSamplerState(0,D3DSAMP_MINFILTER,D3DTEXF_LINEAR);
m_pDevice->SetSamplerState(0,D3DSAMP_MIPFILTER,D3DTEXF_POINT);
return true;
}
这个函数在地形构造时被调用.
const DWORD Terrain::Vertex::FVF = D3DFVF_XYZ|D3DFVF_TEX1;//这句话写在主函数所在的文件中.
程序运行后只见地形网格不见贴图.什么原因?
恳请诸位指点.
|
|