public void CalculateNormals()
{
Vector3 p0, p1, p2, p3, fn1, fn2;
// Initialize Vertex Normals to ZERO
for ( int i = 0; i < cmplx + 1; i++ )
{
for ( int j = 0; j < cmplx + 1; j++ )
{
vNorms[ i, j ] = Vector3.Zero;
}
}
// Calculate Normal for each Face, and add it to the normal for each Vertex
for ( int i = 0; i < cmplx; i++ )
{
for ( int j = 0; j < cmplx; j++ )
{
// Define 4-points of this grid square (top-left, top-right, bottom-left, bottom-right)
p0 = vBuf[ i, j ];
p1 = vBuf[ i, j + 1 ];
p2 = vBuf[ i + 1, j ];
p3 = vBuf[ i + 1, j + 1 ];
// Calc Face Normals for both Triangles of each grid square
fn1 = ( (Vector3)( p2 - p0 ) ).Cross( p1 - p0 );
fn2 = ( (Vector3)( p1 - p3 ) ).Cross( p2 - p3 );
// Add Face Normals to the adjacent Vertex Normals
vNorms[ i, j ] += fn1; // top left
vNorms[ i, j + 1 ] += ( fn1 + fn2 ); // top right (adjacent to both triangles)
vNorms[ i + 1, j ] += ( fn1 + fn2 ); // bottom left (adjacent to both triangles)
vNorms[ i + 1, j + 1 ] += fn2; // bottom right
}
}
// Normalize the Vertex normals, and write it to the Normal Buffer
for ( int i = 0; i <= cmplx; i++ )
{
for ( int j = 0; j <= cmplx; j++ )
{
vNorms[ i, j ].Normalize();
}
}
normVBuf.WriteData( 0, normVBuf.Size, vNorms, true );
}