I am trying to implement simple shadow mapping for a project i am working on. I can render the depth texture to the screen so i know it's there, the problem is when I sample the shadow map with the shadow texture coordinates it seems as if the coordinates are off.
Here is my light space matrix calculation
mat4x4 lightViewMatrix;
vec3 sun_pos = {SUN_OFFSET * the_sun->direction[0],
SUN_OFFSET * the_sun->direction[1],
SUN_OFFSET * the_sun->direction[2]};
mat4x4_look_at(lightViewMatrix,sun_pos,player->pos,up);
mat4x4_mul(lightSpaceMatrix,lightProjMatrix,lightViewMatrix);
I will tweak the values for the size and frustum of the shadow map, but for now i just want to draw shadows around the player position
the_sun->direction is a normalized vector so i multiply it by a constant to get the position.
player->pos is the camera position in world space
the light projection matrix is calculated like this:
mat4x4_ortho(lightProjMatrix,-SHADOW_FAR,SHADOW_FAR,-SHADOW_FAR,SHADOW_FAR,NEAR,SHADOW_FAR);
Shadow vertex shader:
uniform mat4 light_space_matrix;
void main()
{
gl_Position = light_space_matrix * transfMatrix * vec4(position, 1.0f);
}
Shadow fragment shader:
out float fragDepth;
void main()
{
fragDepth = gl_FragCoord.z;
}
I am using deferred rendering so i have all my world positions in the g_positions buffer
My shadow calculation in the deferred fragment shader:
float get_shadow_fac(vec4 light_space_pos)
{
vec3 shadow_coords = light_space_pos.xyz / light_space_pos.w;
shadow_coords = shadow_coords * 0.5 + 0.5;
float closest_depth = texture(shadow_map, shadow_coords.xy).r;
float current_depth = shadow_coords.z;
float shadow_fac = 1.0;
if(closest_depth < current_depth)
shadow_fac = 0.5;
return shadow_fac;
}
I call the function like this:
get_shadow_fac(light_space_matrix * vec4(position,1.0));
Where position is the value i got from sampling the g_position buffer
Here is my depth texture (i know it will produce low quality shadows but i just want to get it working for now):
sorry because of the compression , the black smudges are trees ... https://i.stack.imgur.com/T43aK.jpg
EDIT: Depth texture attachment:
glTexImage2D(GL_TEXTURE_2D, 0,GL_DEPTH_COMPONENT24,fbo->width,fbo->height,0,GL_DEPTH_COMPONENT,GL_FLOAT,NULL);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, fbo->depthTexture, 0);