Original Post
Hello,
I'm trying to add simple shading to my heightmaps, therefore I need normals, however it seems there's some problem with them. Issues are visible only when height difference is high (image). At first I thought normalize() is missing in pixel shader, but it's there. Possibly normal calculations are wrong, but I failed to find any mistakes. Maybe anyone knows what's wrong? Here's some relevant code:
Vertex & Pixel Shaders:
Normal Calculation:
Thank you in advance.
I'm trying to add simple shading to my heightmaps, therefore I need normals, however it seems there's some problem with them. Issues are visible only when height difference is high (image). At first I thought normalize() is missing in pixel shader, but it's there. Possibly normal calculations are wrong, but I failed to find any mistakes. Maybe anyone knows what's wrong? Here's some relevant code:
Vertex & Pixel Shaders:
VS_OUTPUT MainVS(VS_INPUT Input) {
VS_OUTPUT Output;
Output.Position = mul(float4(Input.Position, 1), WorldViewProj);
Output.Normal = Input.Normal;
Output.Tex0 = Input.Tex0;
return Output;
}
PS_OUTPUT MainPS(VS_OUTPUT Input) {
PS_OUTPUT Output;
Output.Color0 = float4(normalize(Input.Normal), 1);
return Output;
}Normal Calculation:
// triangle normals
MyEngine::Vector3 TriangleNormals[127][127][2];
for(uint8 x = 0; x < 127; x++) {
for(uint8 z = 0; z < 127; z++) {
MyEngine::Vector3 U1 = Vertices[z+1][x+1].Position - Vertices[z][x].Position;
MyEngine::Vector3 Y1 = Vertices[z][x+1].Position - Vertices[z][x].Position;
TriangleNormals[z][x][0] = U1.cross(Y1).normalized();
MyEngine::Vector3 U2 = Vertices[z+1][x].Position - Vertices[z][x].Position;
MyEngine::Vector3 Y2 = Vertices[z+1][x+1].Position - Vertices[z][x].Position;
TriangleNormals[z][x][1] = U2.cross(Y2).normalized();
}
}
// vertex normals, using macro to check for bounds
#define Q(i, j, x, z) \
if((x) >= 0 && (x) < 128 && (z) >= 0 && (z) < 128) { \
count += 2; \
Vertices[j].Normal += TriangleNormals[z][x][0] + TriangleNormals[z][x][1]; \
}
for(uint8 x = 0; x < 128; x++) {
for(uint8 z = 0; z < 128; z++) {
float count = 0;
Q(z, x, x, z);
Q(z, x, x-1, z);
Q(z, x, x, z-1);
Q(z, x, x-1, z-1);
Vertices[z][x].Normal /= count;
Vertices[z][x].Normal.normalize();
}
}Thank you in advance.