I'm trying to create and texture a terrain mesh in DirectX11. I've managed to create the mesh itself, but I don't know how I should do the texturing. Let me start by explaining what I'm doing so far:
I have a vertex structure that looks like this:
struct Vertex
{
XMFLOAT3 position;
XMFLOAT4 color;
};
Then I create all the vertices for the terrain mesh:
for (int z = 0, index = 0; z < terrainHeight; ++z)
{
for (int x = 0; x < terrainWidth; ++x, ++index)
{
vertices[index].position = XMFLOAT3(x, 0.0f, z);
vertices[index].color = XMFLOAT3(1.0f, 1.0f, 1.0f, 1.0f);
}
}
Then I create all the triangles for the terrain mesh with indices:
for (int z = 0, index = 0; z < terrainHeight - 1; ++z)
{
for (int x = 0; x < terrainWidth - 1; ++x)
{
indices[index++] = (z ) * terrainWidth + (x );
indices[index++] = (z + 1) * terrainWidth + (x );
indices[index++] = (z + 1) * terrainWidth + (x + 1);
indices[index++] = (z ) * terrainWidth + (x );
indices[index++] = (z + 1) * terrainWidth + (x + 1);
indices[index++] = (z ) * terrainWidth + (x + 1);
}
}
With 256x256 vertices I get this result (rendering in wireframe):
I'd now like to change the color to a texture, so I change the Vertex structure to this:
struct Vertex
{
XMFLOAT3 position;
XMFLOAT2 texture; // Changed the color to a texture coordinate.
};
And this is where I get stuck. Since each vertex now have a texture coordinate (U, V) I'd like to set it up like this:
But each vertex can only hold one texture coordinate. As you can see, the 2 vertices between square A and B needs 2 different texture coordinates each in order to map it correctly. If I'd loop through each pair of triangles, then when I reach square B I'll overwrite the texture coordinates that was correct for square A.
So therefore I have some questions:
Am I doing this in the "right" way? How does modern games do it? Do they texture each square or the entire mesh?
If I'd like to texture each square, how can I solve this problem?