Questions about glCullFace and gl_Fragcoord.z


I have questions about glCullFace and gl_Fragcoord.z.

First, when I turn on and off glCullFace, the depth value from shader stage does not make sense to me.

This is the scene


This is when the cullface is off


This is when culling is on.


void DeferredRenderer::ShadowPass(Entity * gLight, const Scene * scene)
  if (auto shadowBuffer = mRenderTarget[ShadowBuffer])
    glViewport(0, 0, shadowBuffer->GetBuffer().mWidth, shadowBuffer->GetBuffer().mHeight);
    auto shadowShader = this->mOwnerSystem->GetSubManager<ShaderManager>("Static_ESM");
    assert(shadowShader != nullptr);
    for (auto drawable : scene->mDrawableList)
  else DEBUG_PRINT("No shadow buffer");

Second, what is the difference between gl_Fragcoord.z and depth value?

Can gl_Fragcoord.z represent depth value in depth buffer?

This is from gl_Fragcoord.z


This is from depth buffer


This is how I created color buffer and depth buffer

  mRenderTarget.insert(std::make_pair(ShadowBuffer, new RenderTarget()));
  mRenderTarget[ShadowBuffer]->AddColorBuffer(mShadowSize.x, mShadowSize.y,
  mRenderTarget[ShadowBuffer]->AddDepthBuffer(mShadowSize.x, mShadowSize.y);

This is the fragment stage.

in float oClipZ;

uniform float uExpConstant;

out float oGShadow;

void main()
  float depthValue = oClipZ * gl_FragCoord.w * 0.5f + 0.5f;
  oGShadow = exp(depthValue * uExpConstant);
  oGShadow = depthValue; 
  oGShadow = gl_FragCoord.z; // gl_FragCoord.z is same with depthValue that I calculated because gl_FragCoord.z = clip.Z / clip.W

They’re the same. So if and only if the fragment depth is written to the depth buffer (render target has depth buffer, fragment passes depth/stencil/etc. tests, depth write is on, etc.) and your fragment shader does not write to gl_FragDepth, then the gl_FragCoord.z value would be written.

First, when I turn on and off glCullFace, the depth value from shader stage does not make sense to me.

This apparently isn’t your depth buffer but some color buffer (**)? You’re going to need to look deeper. Compare actual depth buffer values between the cullface ON and cullface OFF cases specifically. Assuming they look the same, then look at how you’re computing those color images.

(**) The reason I say this is because these two confusing images are named cullOn and cullOff. Yet below, you have one named cullOnDepth, which is presumably a depth image (and looks completely respectable by the way), implying the former two images are not depth images.

Also, before you dig deeper, ensure that the model you’re trying to draw with cullface ON actually has the faces oriented so that it renders properly with cullface ON. Otherwise, you’re going to have to 1) fix the model, or 2) render it with cullface OFF.