## Computing Vertex Normals of Heightfield

Sage
Posts: 1,066
Joined: 2004.07
Post: #1
I'm at it again! I'm using a recent article on GameDev.net to learn how to do my vertex normals and I'm wondering if someone can verify that what I'm doing is actually working correctly. It doesn't look too bad but I'm just making sure.

I can email the app but have no webspace as of now. Let me know if you'd like me to email it. You can customize the heightfield (as it is externally loaded at runtime).

Here's the normal computing code. Pretty simple. CRYVector is just my vector class. sNormal[][] is an array of vectors representing surface normals of triangles. vNormal[][] is an array of vectors representing actual vertex normals. height[][] is just an array of floats representing the height of the terrain at a given point on the heightfield. HEIGHTFIELD_STEP is a defined constant that represents how to step through and create the heightfield. It is set to 1. If I set it to 3, it only uses every third vertex. Kinda nifty if I want to dumb down the terrain. width and depth are the width and depth of the heightfield.

Code:
```CRYVector t1, t2, t3, t4, t5, t6;          for(x = 0; x <= width - (2 * HEIGHTFIELD_STEP); x+=HEIGHTFIELD_STEP)     {         for(y = 0; y <= depth - (2 * HEIGHTFIELD_STEP); y+=HEIGHTFIELD_STEP)         {             t1.x = x;             t1.y = height[x][y];             t1.z = y;                          t2.x = x + HEIGHTFIELD_STEP;             t2.y = height[x+HEIGHTFIELD_STEP][y];             t2.z = y;                          t3.x = x;             t3.y = height[x][y+HEIGHTFIELD_STEP];             t3.z = y + HEIGHTFIELD_STEP;                          t4 = t2 - t1;             t5 = t3 - t1;                          sNormal[x][y] = CRYCrossProduct(t4,t5);             sNormal[x][y].Normalize();         }     }               for(x = 0; x <= width - (2 * HEIGHTFIELD_STEP); x+=HEIGHTFIELD_STEP)     {         for(y = 0; y <= depth - (2 * HEIGHTFIELD_STEP); y+=HEIGHTFIELD_STEP)         {             t1 = sNormal[x][y];             t2 = sNormal[x+1][y];             t3 = sNormal[x+2][y];                          t4 = sNormal[x][y+1];             t5 = sNormal[x+1][y+1];             t6 = sNormal[x+2][y+1];                          vNormal[x][y] = ((t1 + t2 + t3 + t4 + t5 + t6) / 6);             vNormal[x][y].Normalize();         }     }```