我正在尝试将一个球渲染成冒牌者,但是在计算球面上点的深度值时遇到了问题。
当我围绕冒牌者球和与球相交的“真实”立方体移动相机时,您可以看到发生了什么。 你可以看到,当我移动相机时,深度值不一致,有些立方体的部分应该在球体内,但根据相机位置的不同,会弹出和弹入球体。
这是伪装球体的顶点着色器和片段着色器。 顶点着色器:
我按照 这个例子 进行了深度值的计算。
我传递给着色器的模型矩阵是一个单位矩阵,因此它不会影响操作。
非常感谢您的帮助!!
当我围绕冒牌者球和与球相交的“真实”立方体移动相机时,您可以看到发生了什么。 你可以看到,当我移动相机时,深度值不一致,有些立方体的部分应该在球体内,但根据相机位置的不同,会弹出和弹入球体。
这是伪装球体的顶点着色器和片段着色器。 顶点着色器:
#version 450 core
uniform mat4 model;
uniform mat4 view;
uniform mat4 projection;
out vec2 coords;
void main()
{
switch (gl_VertexID)
{
case 0:
coords = vec2(-1.0f, -1.0f);
break;
case 1:
coords = vec2(-1.0f, +1.0f);
break;
case 2:
coords = vec2(+1.0f, -1.0f);
break;
case 3:
coords = vec2(+1.0f, +1.0f);
break;
}
// right & up axes camera space
vec3 right = vec3(view[0][0], view[1][0], view[2][0]);
vec3 up = vec3(view[0][1], view[1][1], view[2][1]);
vec3 center = vec3(0.0f);
float radius = 1.0f;
// vertex position
vec3 position = radius * vec3(coords, 0.0f);
position = right * position.x + up * position.y;
mat4 MVP = projection * view * model;
gl_Position = MVP * vec4(center + position, 1.0f);
}
片元着色器 :
#version 450 core
uniform mat4 model;
uniform mat4 view;
uniform mat4 projection;
in vec2 coords;
out vec4 pixel;
void main()
{
float d = dot(coords, coords);
if (d > 1.0f)
{
discard;
}
float z = sqrt(1.0f - d);
vec3 normal = vec3(coords, z);
normal = mat3(transpose((view * model))) * normal;
vec3 center = vec3(0.0f);
float radius = 1.0f;
vec3 position = center + radius * normal;
mat4 MVP = projection * view * model;
// gl_DepthRange.diff value is the far value minus the near value
vec4 clipPos = MVP * vec4(position, 1.0f);
float ndcDepth = clipPos.z / clipPos.w;
gl_FragDepth = ((gl_DepthRange.diff * ndcDepth) + gl_DepthRange.near + gl_DepthRange.far) * 0.5f;
pixel = vec4((normal + 1.0f) * 0.5f, 1.0f);
}
我按照 这个例子 进行了深度值的计算。
我传递给着色器的模型矩阵是一个单位矩阵,因此它不会影响操作。
非常感谢您的帮助!!
glClipControl()
吗? - Michael Kenzelgl_FragDepth = (ndcDepth + 1.0f) * 0.5f;
,它仅将剪裁空间中的深度值从范围[-1, +1]映射到范围[0, 1]。我认为代码几乎是正确的,但缺少了一些东西,特别是当物体之间的深度值很接近时。如果您有任何其他想法或认为检查代码的其他部分可能有用,请告诉我!非常感谢! - Arctic Pi