I'm using THREE.js with shader. I'm trying to get the zbuffer information.
Vertex shader:
// switch on high precision floats
#ifdef GL_ES
precision highp float;
#endif
void main()
{
gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
}
Fragment shader:
#ifdef GL_ES
precision highp float;
#endif
void main()
{
gl_FragColor = vec4(gl_FragCoord.x, gl_FragCoord.y, gl_FragCoord.z, 1.0);
}
There are objects with different position in the scene, thus the values in zbuffer should vary.
It's strange that gl_FragCoord.x
, gl_FragCoord.y
and gl_FragCoord.z
seems to be 1.0
for all fragments, while gl_FragCoord.w
seems to vary for different fragments.
If I use gl_FragCoord.w
:
#ifdef GL_ES
precision highp float;
#endif
void main()
{
float zbuffer = gl_FragCoord.w * 500.0;
gl_FragColor = vec4(zbuffer, zbuffer, zbuffer, 1.0);
}
It seems to be the zbuffer image:
So why would gl_FragCoord.w
be representing depth information while gl_FragCoord.z
is always 1.0
for all fragments?
gl_FragCoord
is in window space. And window space is in pixel coordinates of the window. So virtually all of your fragments are going to have values > 1.0. And since you're almost certainly not rendering to a floating-point framebuffer, your colors will be clamped to the [0, 1] range.
gl_FragCoord.z
is probably not 1.0, but it may be close enough to it, depending on your depth range and how far the objects are from the camera. If you want to get a real idea of the depth, you need to linearize it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With