使用着色器在 opengl 中绘制深度值 [英] draw the depth value in opengl using shaders
问题描述
我想在片段着色器中绘制深度缓冲区,我这样做:
I want to draw the depth buffer in the fragment shader, I do this:
顶点着色器:
varying vec4 position_;
gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;
position_ = gl_ModelViewProjectionMatrix * gl_Vertex;
片段着色器:
float depth = ((position_.z / position_.w) + 1.0) * 0.5;
gl_FragColor = vec4(depth, depth, depth, 1.0);
但是我打印的都是白色的,我做错了什么?
But all I print is white, what am I doing wrong?
推荐答案
你想在什么空间绘制深度?如果你想绘制窗口空间深度,你可以这样做:
In what space do you want to draw the depth? If you want to draw the window-space depth, you can do this:
gl_FragColor = vec4(gl_FragCoord.z);
然而,这不会特别有用,因为大多数数字将非常接近 1.0.只有非常接近的物体才可见.这是使用标准透视投影的深度缓冲区的深度值分布的性质.
However, this will not be particularly useful, since most of the numbers will be very close to 1.0. Only extremely close objects will be visible. This is the nature of the distribution of depth values for a depth buffer using a standard perspective projection.
或者,换句话说,这就是你变白的原因.
Or, to put it another way, that's why you're getting white.
如果您希望这些值在线性空间中,您需要执行以下操作:
If you want these values in a linear space, you will need to do something like the following:
float ndcDepth = ndcPos.z =
(2.0 * gl_FragCoord.z - gl_DepthRange.near - gl_DepthRange.far) /
(gl_DepthRange.far - gl_DepthRange.near);
float clipDepth = ndcDepth / gl_FragCoord.w;
gl_FragColor = vec4((clipDepth * 0.5) + 0.5);
这篇关于使用着色器在 opengl 中绘制深度值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!