Depth Test

From OpenGL Wiki
Jump to navigation Jump to search

The Depth Test is a per-sample processing operation performed after the Fragment Shader (and sometimes before). The Fragment's output depth value may be tested against the depth of the sample being written to. If the test fails, the fragment is discarded. If the test passes, the depth buffer will be updated with the fragment's output depth, unless a subsequent per-sample operation prevents it (such as turning off depth writes).

Depth buffer[edit]

In order to use the depth test, the current Framebuffer must have a depth buffer. A depth buffer is an image that uses a depth image format. The Default Framebuffer may have a depth buffer, and user-defined framebuffers can attach depth formatted images (either depth/stencil or depth-only) to the GL_DEPTH_ATTACHMENT attachment point.

If the current framebuffer has no depth buffer, then the depth test behaves as if it is always disabled.

Fragment depth value[edit]

Every Fragment has a depth value. This value is either computed by the Fragment Shader (if it writes to gl_FragDepth) or is the window-space Z coordinate computed as the output of the Vertex Post-Processing steps.

Depth test[edit]

To enable depth testing, call glEnable with GL_DEPTH_TEST. When rendering to a framebuffer that has no depth buffer, depth testing always behaves as though the test is disabled.

When depth testing is disabled, writes to the depth buffer are also disabled.

When depth testing is active, the depth value from the fragment is compared to the depth value from the matching sample currently in the framebuffer. Let us call the fragment's depth N, while the framebuffer's depth P. The conditional test is of the form (N FUNC P), where FUNC is specified by this function:

void glDepthFunc(GLenum func​);

The func​ may be one of the following:

Enum Test Enum Test
GL_NEVER Always fails. GL_ALWAYS Always passes
GL_LESS < GL_LEQUAL
GL_GREATER > GL_GEQUAL
GL_EQUAL = GL_NOTEQUAL

Early test[edit]

The depth test can take place before the Fragment Shader executes. It can only do this if the FS does not discard the fragment and does not modify gl_FragDepth. This is done as an optimization.

Early testing can also be enforced (with OpenGL 4.2 or ARB_shader_image_load_store). If it is enforced, then the fragment shader's modifications to gl_FragDepth will be ignored, and if the FS discards the fragment, the depth will still be written (unless the current Write Mask prevents it).

See also[edit]