I have a simple OpenGL application that i want to draw a cube, but it seems that the depth buffer is working somehow incorrectly. I am using SFML for windowin system and GLEW as the library.
The main looks like following: https://pastebin.com/tq5t0TJN
...code...
The mesh class looks like following: https://pastebin.com/YiWH8dWH
...code...
The loading functions looks like following: https://pastebin.com/vUNLn0gu - but they seem to work all correctly
...code...
Now I got a vertex shader: https://pastebin.com/EeP4RXHy
#version 330 core
layout (location = 0) in vec3 location_attrib;
layout (location = 1) in vec2 texcoord_attrib;
layout (location = 2) in vec3 normal_attrib;
out vec3 location;
out vec3 normal;
void main()
{
normal = normal_attrib;
gl_Position = vec4(location_attrib.x / 2, location_attrib.y / 2, location_attrib.z / 2, 1.0);
}
And a fragment shader: https://pastebin.com/E9krMFZq
#version 330 core
out vec4 gl_FragColor;
//out float gl_FragDepth ;
in vec3 location;
in vec3 normal;
void main()
{
vec3 normal_normalized = normalize(normal);
vec3 light_dir = vec3(0, -1, 0);
float light_amount = dot(normal_normalized, light_dir);
vec3 color = vec3(1.0f, 0.5f, 0.2f);
color = color * light_amount;
color = clamp(color, vec3(0,0,0), vec3(1,1,1));
color.r += 0.1;
color.g += 0.1;
color.b += 0.1;
//gl_FragColor = vec4(color.r, color.g, color.b , 1.0);
gl_FragDepth = location.z / 1000;
gl_FragColor = vec4(vec3(gl_FragCoord.z), 1.0);
}
But the image I get when doing it this way looks like so:
Can anybody tell what is the issue?
I tried to figure out what is wrong with the depth test, tried different combinations, but it all seems to not work.
The depth of the fragment is explicitly set in the fragment shader:
gl_FragDepth = location.z / 1000;
The depth buffer can represent values in the range [0.0, 1.0] and the accuracy of the depth buffer is limited. In your case the depth buffer has 24 bits (settings.depthBits = 24;
).
If the values are outside this range or if the difference between the values is so small that it cannot be represented with the accuracy of the depth buffer, then the depth test will not work correctly.
Anyway, the vertex shader does not write to the output variable location
. Hence location.z
is 0.0 for all fragments.
If you want to map the depth values to a subrange of [0.0, 1.0], then you can use glDepthRange
to specify a mapping.