Original Post
I followed a tutorial here on GameDev for calculating normals for heightfields. It works as far as creating surface normals, but somehow does not manage to smooth them out, though I have the code that is supposed to do it. Any trouble you see in the code?
normals = new SimVector[width * depth];
SimVector *sNormals = new SimVector[width * depth * 10];
int normalIndex = 0;
float height0, height1, height2;
SimVector normal1, normal2, normal3, normal4, normal5, normal6;
for(j = -1; j < depth; j++)
{
for(i = -1; i < width; i++)
{
if(!IsValidCoord(i, j) || !IsValidCoord(i + 1, j) ||
!IsValidCoord(i, j + 1) || !IsValidCoord(i + 1, j + 1))
{
normalIndex += 2;
continue;
}
height0 = GetHeight(i, j);
height1 = GetHeight(i, j + 1);
height2 = GetHeight(i + 1, j);
normal1.x = height0 - height2;
normal1.y = 1;
normal1.z = height0 - height1;
height0 = height2;
height2 = GetHeight(i + 1, j + 1);
normal2.x = height1 - height2;
normal2.y = 1;
normal2.z = height0 - height2;
SimStructs::Normalize(normal1);
SimStructs::Normalize(normal2);
sNormals[normalIndex++] = normal1;
sNormals[normalIndex++] = normal2;
}
}
int triIndex = 1;
int indexPlusOne = 2;
int indexPlusTwo = 3;
int vertIndex = 0;
int rowOffset = ((width + 1) * 2) - 1;
SimVector vertNormal;
for(j = 0; j < depth; j++)
{
for(i = 0; i < width; i++)
{
indexPlusOne = triIndex + 1;
indexPlusTwo = triIndex + 2;
normal1 = sNormals[triIndex];
normal2 = sNormals[indexPlusOne];
normal3 = sNormals[indexPlusTwo];
normal4 = sNormals[rowOffset + triIndex];
normal5 = sNormals[rowOffset + indexPlusOne];
normal6 = sNormals[rowOffset + indexPlusTwo];
vertNormal = normal1 + normal2 + normal3 + normal4 + normal5 + normal6;
vertNormal /= 6.0f;
SimStructs::Normalize(vertNormal);
normals[vertIndex] = vertNormal;
triIndex += 2;
vertIndex++;
}
triIndex += 2;
}
delete[] sNormals;
