Depth buffer store depth value and that determines if the fragment is in front or not. Likewise, the color buffer stores the color value of the fragment which is visible output.
With every pixel, it should be stated with color to display. When there are multiple items in a line of sight then the order of appearance in the screen is dependent on their presence in code. For example, there is a table on the floor and a laptop on that table. If you describe the table after the laptop in code, the table appears to be on top of the laptop and floor which is not intended for sure.
Depth testing rather uses the distance from the camera to find out what to appear or more precisely, what color to appear in pixel.
When a depth test is enabled, the graphics library checks for the depth value of the fragment with the depth buffer. Webgl performs an operation that returns true if the fragment can render and false if the fragment needs to be discarded. There are multiple options to choose the depth test but we don’t discuss this here. Just to say, the default comparison function is gl.LESS which means color closer to the camera is displayed for that pixel.
It is performed after the fragment shader and it is not enabled by default in Webgl so we need to enable it ourselves.
Syntax to enable:
If you are familiar with OpenGL, the above syntax does the same thing as this does in OpenGL:
While rendering, you have a buffer of pixels, and depth testing creates another buffer of the same number of entries but here the second buffer only holds depth i.e distance from the camera instead of color values. While rendering what happens is you go through all the entries and store fragments z-values in a depth buffer if it passes the test otherwise (which means if fragment fails the depth test) the fragment is discarded.
Remember that we need to clear the depth buffer before every frame using a clear function otherwise we will be stuck with the last frame. In WebGL, we have syntax as
We generally clear both color buffer and depth buffer before every frame and for that, we use this syntax which clears both the depth buffer and color buffer.
That’s it. Thanks for your time and for reading this.
Happy learning Happy coding. Take Care.0