Your terrain grid should be the same size as your heightmap.
The following then can be used:
I highly recommend you place this into a quadtree and pass the constraints of each node of the tree to a similar CreateVertices() function which will create the vertices and compute the bounding volume for the patch. This will create patches of terrain. At render time you simply traverse the quadtree and do a frustrum cull down the tree. Here are the rules.
void CTerrain::PrepareTerrain(int iCellSize)
//Create vertex buffer
HRESULT hr=m_pDevice->CreateVertexBuffer(m_iNumVerts * sizeof(TerrainVertex),
::MessageBox(0,"Failed to create vertex buffer",0,0);
//Create index buffer
hr=m_pDevice->CreateIndexBuffer(m_iNumIndices * sizeof(WORD),
::MessageBox(0,"Failed to create index buffer",0,0);
void CTerrain::CreateVertices(TerrainVertex *pVerts)
for (int z=iStartZ;z>=iEndZ;z-=m_iCellSize)
for (int x=iStartX;x<=iEndX;x+=m_iCellSize)
//Detail texture coords
void CTerrain::CreateIndices(WORD *pIndices)
for (int i=0;i<m_iNumCellsPerCol;i++)
for (int j=0;j<m_iNumCellsPerRow;j++)
- If the bounding volume of the patch is out, all it's children are also out and do not need to be checked. This patch and all of it's children are not rendered.
- If the bounding volume of the patch is partially in, you must check it's children. If one of the children's bounding volume is out, then all of it's children are also out. Render only the patches that are in or partially in. At this point you may choose to also render the patches that are partially in. It will take more time for you to code an algo to split the meshes along the frustum than it will for the graphic card to simply cull those triangles that are out.
- If the bounding volume of the patch is completely in, then all of it's children are also completely in. Therefore you do NOT check the children and you simply render the entire patch and all of it's children.
This is an extremely fast process and rendered terrain with no LOD on my GeForce 3 64MB card at a whopping 90 FPS (good for that card) with over 3 million vertices in the grid. A quadtree structure may look like this:
The parent node is so you can easily traverse the tree from anywhere in the tree. It does not have to be included for this to work as you will always be drilling down the tree and never up during rendering. I use it for other items in my system.
CTerrain *pUL; //Upper left
CTerrain *pUR; //Upper right
CTerrain *pLL; //Lower left
CTerrain *pLR; //Lower right
CBoundingVolume *pBounds; //Bounding volume for this patch
If you want to implement terrain LOD I recommend talking to Perspective as I do not yet have a working implementation.