I have simple scene that involves a rotating cube and a directional (diffuse) light source, but I don't seem to get the lighting math right.
I load the vertices and normals from the obj file from this tutorial:
Some of my application code:
glm::mat4 modelview = ...
glm::mat4 projection = glm::perspective(60.0f, 16.0f/9.0f, 0.1f, 100.0f);
glm::mat4 MVP = projection * modelview;
glm::mat3 NormalMatrix = glm::transpose(glm::inverse(glm::mat3(modelview)));
glUniformMatrix4fv(MVP_location, 1, GL_FALSE, &MVP[0][0]);
glUniformMatrix3fv(NormalMatrix_location, 1, GL_FALSE, &NormalMatrix[0][0]);
glDrawArrays(GL_TRIANGLES, 0, 36);
Vertex shader:
#version 430
in vec3 position;
in vec3 in_normal;
uniform mat4 MVP;
uniform mat3 NormalMatrix;
out vec3 Normal;
out vec4 Color;
void main()
{
gl_Position = MVP * vec4(position, 1.0);
Color = vec4(clamp(position, 0.0, 1.0), 1.0); //based on vertex position
Normal = normalize(NormalMatrix * in_normal);
}
Fragment shader:
#version 430
const vec3 Ambient = vec3(0.15, 0.15, 0.15);
const vec3 LightDirection = normalize(vec3(1.0, 0.0, 1.0));
const vec3 LightColor = vec3(1.0, 1.0, 1.0);
const float Shininess = 20.0;
const float Strength = 5.0;
in vec3 Normal;
in vec4 Color;
out vec4 FragColor;
void main()
{
FragColor = Color;
float diffuse = max(0.0, dot(Normal, LightDirection));
vec3 scatteredLight = Ambient + LightColor * diffuse;
vec3 rgb = min(FragColor.rgb * scatteredLight, vec3(1.0));
FragColor = vec4(rgb, Color.a);
}
This is what I get: my fail
Any idea what am I doing wrong?
normal
is in view-space, whileLightDirection
is in world-space. - dari