我希望获得实际的世界空间距离,我的实验感觉是:
(gl_FragCoord.z / gl_FragCoord.w)
这是世界空间中的深度?但我不太确定。
编辑 我刚刚在找到了我最初找到这段代码的地方。显然这是从相机到某个物体的实际深度?
我希望获得实际的世界空间距离,我的实验感觉是:
(gl_FragCoord.z / gl_FragCoord.w)
这是世界空间中的深度?但我不太确定。
编辑 我刚刚在找到了我最初找到这段代码的地方。显然这是从相机到某个物体的实际深度?
gl_FragCoord.w
为1/clip.w
,其中clip.w
是裁剪空间位置的W分量(即您写入gl_Position
的内容)。
gl_FragCoord.z
由以下过程生成,假设使用通常的变换:
clip.z = (projectionMatrix * cameraPosition).z
ndc.z = clip.z / clip.w
glDepthRange
近/远值 转换为窗口坐标。 win.z = ((dfar-dnear)/2) * ndc.z + (dfar+dnear)/2
。现在,使用默认的深度范围 near=0, far=1,我们可以用剪裁空间来定义 win.z
: (clip.z/clip.w)/2 + 0.5
。如果我们将其除以 gl_FragCoord.w
,那么就相当于乘以 clip.w
,从而得到:
(gl_FragCoord.z / gl_FragCoord.w) = clip.z/2 + clip.w/2 = (clip.z + clip.w) / 2
clip.z
代表相机空间Z分量的比例和偏移量。比例和偏移量由相机的近/远深度值定义。clip.w
在标准投影矩阵中再次表示相机空间Z的取反。因此,我们可以用这些术语重新定义我们的方程式:(gl_FragCoord.z / gl_FragCoord.w) = (A * cam.z + B -cam.z)/2 = (C * cam.z + D)
其中A
和B
表示基于近/远的偏移量和比例,C = (A - 1) / 2
和D = B / 2
。
因此,gl_FragCoord.z / gl_FragCoord.w
不是相机空间(或世界空间)到相机的距离。它也不是相机空间到相机的平面距离。但它是相机空间深度的线性变换。如果它们来自同一投影矩阵等,您可以将其用作比较两个深度值的方法。
实际上计算相机空间中的Z值,你需要从矩阵中传递相机的近/远距离 (OpenGL 已经给出了近/远范围) 并从中计算出 A
和 B
值,或者你需要使用投影矩阵的逆矩阵。另外,你也可以直接使用投影矩阵本身,因为片元着色器可以使用顶点着色器可用的相同 uniform 变量。你可以直接从该矩阵中选择 A
和 B
项。 A = projectionMatrix [2] [2]
,B = projectionMatrix [3] [2]
。
Available only in the fragment language, gl_FragDepth is an output variable that
is used to establish the depth value for the current fragment. If depth buffering
is enabled and no shader writes to gl_FragDepth, then the fixed function value
for depth will be used (this value is contained in the z component of
gl_FragCoord) otherwise, the value written to gl_FragDepth is used.
因此,除非在您的着色器中设置了其他值,否则gl_FragDepth
应该只是gl_FragCoord.z
。
gl_FragDepth
替换了我的方程中的gl_FragCoord.z
(用于生成线性雾)来检查你的答案,结果整个场景无论距离远近都变成了黑色。而当我保留原始的gl_FragCoord.z
时,我可以在一定距离后看到雾。 - Engineer作为
gl_FragCoord.w = 1.0 / gl_Position.w
float distanceToCamera = 1.0 / gl_FragCoord.w;