Shader lighting and see-through faces


I’m trying to write my first shader, with a fixed directional light. The vertex and fragment shaders are as below:

Vertex Shader:

#version 330

uniform mat4 mvp;
uniform mat3 nmat;
uniform vec3 lightDir;
uniform vec4 ambient;

in vec3 coord3d;     
in vec3 v_color;  
in vec3 v_normal;    
out vec4 f_color;

void main(void) 
        float NdotL;
        gl_Position = mvp * vec4(coord3d, 1.0);

	f_normal = normalize(nmat * v_normal);

	NdotL = max(dot(f_normal, lightDir), 0.0);
	f_color = ambient * vec4(v_color,1.0);
	if (NdotL > 0.0)
		f_color += vec4(v_color, 1.0) * NdotL;

	f_color.a = 1.0;

Fragment Shader:

#version 330

in vec4 f_color;

void main(void) {
	gl_FragColor = f_color;

For nmat, I pass the model transform (converted to a mat3) so that normals and eye are all in world coordinates. With the above shaders, I’m trying to render a scene with two boxes but what I get is this (the light is directed in order to illuminate the top and right faces):


So you see what the problem is: the right face of the box is visible even though it’s behind the front face. Do you know why this happens and a possible way out of this problem?


Seems like you didn’t enable the depth test.


Hi Betrayal,

I’ve checked and the depth test is enabled.

Hmm, are you sure?

What library are you using to setup an OpenGL context?
Don’t forget to setup a number of bits != 0 for the depth buffer in context creation.

If this doesn’t help and nobody else is going to answer, just post the full code an i’ll try to search the error tomorrow.

Here is the code I use for initialization

int glWin::init(int argc, char* argv[], const char* title, int width, int height, glm::vec4& bgColor)
	m_bgColor = bgColor;
	glutInit(&argc, argv);
	glutInitContextVersion(2, 0);
	glutInitWindowSize(width, height);
	//glutCreateWindow("My first triangle");
	GLenum glew_status = glewInit();
	if (glew_status != GLEW_OK)
		fprintf(stderr, "Error: %s
", glewGetErrorString(glew_status));
		return EXIT_FAILURE;
	if (!GLEW_VERSION_2_0)
		fprintf(stderr, "Error: your graphic card does not support OpenGL 2.0
		return 1;

	return 1;

Well, can you please post the full code?

I fixed the problem. Actually the shader and the GL initialization was fine, I’ve just set up the vertices and indices incorrectly!