color buffer stores all the fragment colors: the visual output. The depth-buffer stores depth value per fragment and has the same width and height as the color buffer. depth testing determines if a fragment is in front.
When depth testing is enabled, OpenGL tests the depth value of a fragment against the content of the depth buffer. OpenGL performs a depth test and if this test passes, the fragment is rendered(comment: the color buffer is updated with the new color vector) and the depth buffer is updated with the new depth value. If the depth test fails, the fragment is discarded(comment: The depth-buffer and the color buffer remain unchanged).
Depth testing is done in screen space. The screen space coordinates relate directly to the viewport defined by glViewport function and can be accessed via GLSL’s built-in gl_FragCoord variable in the fragment shader. The x and y components of gl_FragCoord represent the fragment’s screen-space coordinates (with (0,0) being the bottom-left corner), The z component of gl_FragCoord contains the depth value of the fragment. This z value is the value that is compared to the depth buffer’s content.
Depth testing is disabled by default so to enable depth testing we need to enable it with the GL_DEPTH_TEST option:
glEnable(GL_DEPTH_TEST);
Once enabled, OpenGL automatically stores fragments their z-values in the depth buffer if they passed the depth test and discards fragments if they failed the depth test accordingly. If you have depth testing enabled you should also clear the depth buffer before each frame using GL_DEPTH_BUFFER_BIT; otherwise you’re stuck with the depth values from last frame:
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
OpenGL allows us to modify the comparison operators it uses for the depth test. This allows us to control when OpenGL should pass or discard fragments and when to update the depth buffer. We can set the comparison operator (or depth function) by calling glDepthFunc:
glDepthFunc(GL_LESS);
The function accepts several comparison operators that are listed in the table below:
By default the depth function GL_LESS is used that discards all the fragments that have a depth value higher than or equal to the current depth buffer’s value.