Wrong shadow map coordinates


I need to calculates shadow map coordinates as we should do for shadow mapping, but here I don’t need it for shadow mapping.

As a test I wrote a shader that assign to each fragment its depth value stored in the shadow map. The problem is that the texture coordinates seem to be wrong. I see a part of shadow map projected on the mesh and it is translated from where it should be on the mesh.

So I think that I don’t computes correctly the texture coordinates for the shadow map…
I know that there is plenty of shadow mapping shader examples to which I could compare but each is different…so I think that I need a fresh eye to see where I did a beginner error:

This the vertex shader where I computes the shadow map coordinates:

varying vec2 depthTexCoords; // depth texture coordinates
varying vec4 lightVec;
void main()

	mat4 biasMatrix= mat4(0.5, 0.0, 0.0, 0.5,
						  0.0, 0.5, 0.0, 0.5,
						  0.0, 0.0, 0.5, 0.5,
						  0.0, 0.0, 0.0, 1.0);

	vec4 lightProj= gl_TextureMatrix[0] * gl_Vertex;   // lightProj are clipping coordinates 
													   // gl_TextureMatrix[0] = light projection matrix * light modelview matrix)
	lightProj= lightProj/lightProj.w;                  // now lightProj are normalized coordinates
	depthTexCoords= (biasMatrix * lightProj).xy;       // use the bias matrix to transform [-1 1]x[-1 1] to [0 1]x[0 1]
	lightVec= gl_LightSource[0].position - gl_Vertex;

	gl_Position= ftransform();


depthTexCoords coordinates are interpolated in the fragment shader and used to read the shadow map.

Thanks a lot.

Nobody see an error in my shader code?

It’s not a good idea to calculate the 2D texture coordinates in the vertex shader. You need to calculate at least 3 coordinates (s,t and q) for perspective correct texture mapping, the r component represents the depth of a fragment that can be used to compare against the value stored in the depth map. So you need to create all 4 texture coordinate components in the vertex shader and perform a projective texture lookup in the fragment shader.

Maybe this tutorial will get you on the right track.

Yes your are right, thank you, I have solved my problem.