I'm wondering if there is a method to get depth for each sample in fragment-shader. I have tried GL_ARB_sample_shading
extension, which can give sample ID and sub-pixel coordinate but I haven't found any route for depth. I have tried gl_FragCoord
, but it's a constant among all samples within a pixel, giving something like (?.5,?.5,?,?).
It is supposed that depth is calculated and tested for each sample in MSAA. My question is whether it's available in a fragment-shader.
I want to discard fragments out of a depth range defined by two depth maps. That's why I need depth for each sample to perform correct per-sample discard. My depth maps are also generated with MSAA and I use GL_ARB_texture_multisample
extension to fetch multi-sampled depth in fragment-shader.
Here's sample code but I have no idea how to implement getSampleDepth
.
#version 430
#extension GL_ARB_sample_shading:enable
#extension GL_ARB_texture_multisample:enable
uniform sampler2DMS tex;
out vec4 vFragColor;
float getSampleDepth(int idx){
//TODO: I have no idea how to get depth for each sample
}
void main(void){
ivec2 icoord = ivec2(gl_FragCoord.xy);
int id = gl_SampleID;
if(getSampleDepth(id) < texelFetch(tex,icoord,id).x)
discard;
vFragColor = vec4(1.f);
// It seems sample can be correctly discarded
// Keeping part of samples leads to dim color
// if(gl_SampleID < 2)
// discard;
}
If you want the current fragment's depth, just use gl_FragCoord.z
. This is just as true of per-sample shading as for regular rendering.
If you're getting the same value for gl_FragCoord
, it would be because you have not successfully provoked per-sample shading somehow. Or a driver bug. One possible workaround might be to explicitly activate per-sample shading by glEnable(GL_SAMPLE_SHADING)
and glMinSampleShading(1.0f)
.