Game Development Reference
In-Depth Information
float Terrain::computeShade(int cellRow, int cellCol,
D3DXVECTOR3* directionToLight)
{
// get heights of three vertices on the quad
float heightA = getHeightmapEntry(cellRow, cellCol);
float heightB = getHeightmapEntry(cellRow, cellCol+1);
float heightC = getHeightmapEntry(cellRow+1, cellCol);
// build two vectors on the quad
D3DXVECTOR3 u(_cellSpacing, heightB - heightA, 0.0f);
D3DXVECTOR3 v(0.0f, heightC - heightA, -_cellSpacing);
// find the normal by taking the cross product of two
// vectors on the quad.
D3DXVECTOR3 n;
D3DXVec3Cross(&n, &u, &v);
D3DXVec3Normalize(&n, &n);
float cosine = D3DXVec3Dot(&n, directionToLight);
if(cosine < 0.0f)
cosine = 0.0f;
return cosine;
}
13.4.3 Shading the Terrain
Once we know how to shade a particular quad, we can shade all the
quads in the terrain. We simply iterate through each quad, compute the
shade value of that quad, and then scale the quad's corresponding texel
color by that shade. This darkens quads that receive less light. The fol-
lowing snippet of code shows the important part of the Terrain::
lightTerrain method:
DWORD* imageData = (DWORD*)lockedRect.pBits;
for(inti=0;i<textureDesc.Height; i++)
{
for(intj=0;j<textureDesc.Width; j++)
{
int index=i*lockedRect.Pitch/4+j;
// get current color of cell
D3DXCOLOR c( imageData[index] );
// shade current cell
c *= computeShade(i, j, lightDirection);;
// save shaded color
imageData[index] = (D3DCOLOR)c;
}
}
Search WWH ::




Custom Search