Hi, I’ve writte a shader which write z fragment to a texture because if I attach a depthtexture to my FBO it doesn’t work :
const std::string vertexShader =
"#version 130
"
"out mat4 projMat;"
"void main () {"
"gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;"
"gl_TexCoord[0] = gl_TextureMatrix[0] * gl_MultiTexCoord0;"
"gl_FrontColor = gl_Color;"
"projMat = gl_ProjectionMatrix;"
"}";
const std::string depthGenFragShader =
"#version 130
"
“in mat4 projMat;”
“uniform sampler2D texture;”
“uniform float haveTexture;”
“void main () {”
“vec4 texel = texture2D(texture, gl_TexCoord[0].xy);”
“vec4 colors[2];”
“colors[1] = texel * gl_Color;”
“colors[0] = gl_Color;”
“bool b = (haveTexture > 0.9);”
“vec4 color = colors[int(b)];”
“float z = (gl_FragCoord.w != 1.f) ? (inverse(projMat) * vec4(0, 0, 0, gl_FragCoord.w)).w : gl_FragCoord.z;”
“gl_FragColor = vec4(0, 0, z, color.a);”
“}”;
I've written another shader that discard closest fragments.
const std::string frameBufferGenFragShader =
"#version 130
"
“uniform sampler2D depthBuffer;”
“uniform sampler2D texture;”
“uniform vec3 resolution;”
“uniform float haveTexture;”
“in mat4 projMat;”
“void main () {”
“vec2 position = ( gl_FragCoord.xy / resolution.xy );”
“float max_z = texture2D(depthBuffer, position).z;”
“vec4 texel = texture2D(texture, gl_TexCoord[0].xy);”
“vec4 colors[2];”
“colors[1] = texel * gl_Color;”
“colors[0] = gl_Color;”
“bool b = (haveTexture > 0.9);”
“vec4 color = colors[int(b)];”
“float z = (gl_FragCoord.w != 1.f) ? (inverse(projMat) * vec4(0, 0, 0, gl_FragCoord.w)).w : gl_FragCoord.z;”
“colors[1] = color;”
“colors[0] = vec4(0, 0, 0, 0);”
“b = (z < max_z);”
“gl_FragColor = colors[int(b)];”
“}”;
But it's not good some closest fragments are still written to the texture. What's gl_FragCoord.z, the z in window space (between 0 ans 1) or the result of the multiplication of the interpolated vertex by the modelViewProjectionMatrix ?
And it's seems there isn't enought space to write z in a GLRGBA8 text.
But I use exactly the same technique to test if a light fragment is behind an object or not and it works.