I'm trying to add normal mapping technique in my game, but I can't get correct results. It looks like everything is okay, but lighting is inverted, take a look at this picture:
http://s1.postimg.org/8g0lrdmcv/nmapping.png so as you can see the plane is lit not correctly, it is lit with ambient component where it should be lit with diffuse and specular component and vice versa. I tried various different codes for shaders, but none worked correctly. This is my vertex shader:
void main()
{
Position = vec3(ModelViewMatrix * vec4(VertexPosition, 1.0));
TexCoord = VertexTexCoord;
Normal = normalize(NormalMatrix * vec3(0.0, 1.0, 0.0));
vec3 T = normalize(NormalMatrix * vec3(1.0, 0.0, 0.0));
vec3 B = normalize(cross(Normal, T));
TBNMatrix = mat3(T, B, Normal);
gl_Position = MVPMatrix * vec4(VertexPosition, 1.0);
}
and fragment shader:
vec3 PhongShade(PointLight light, vec3 n, vec3 diffR)
{
vec3 lightDir = normalize(light.Position.xyz - Position);
vec3 viewDir = normalize(-Position);
float sDotN = max(dot(lightDir, n), 0.0);
vec3 ambient = light.Color * material.Ambient * diffR;
vec3 diffuse = light.Color * diffR * sDotN;
vec3 specular = vec3(0.0);
if(sDotN > 0.0){
vec3 r = reflect(-lightDir, n);
specular = light.Color * material.Specular * pow(max(dot(r, viewDir), 0.0), material.Shininess);
}
return ambient + diffuse + specular;
}
void main()
{
vec3 normal = texture2D(normalMap, TexCoord).rgb;
normal = normalize(normal * 2.0 - 1.0);
normal = normalize(TBNMatrix * normal);
vec3 lightColor = PhongShade(light, normal, texture2D(texture, TexCoord).rgb);
FragColor = vec4(lightColor, 1.0);
}
And I can't see where is my mistake.. Btw if I invert texture coordinates when loading model it works good, but I don't think that it's the proper way to fix it.