几何着色器计算的线在相机移动时消失

Geometry shader calculated lines disappear on camera move

我使用几何着色器绘制顶点法线。一切都按预期显示,除了当我移动相机时,一些线条部分消失了。首先,我认为这是由于平截头体大小造成的,但我在场景中有其他物体比这个画得还好。

Before movement

After movement

如果有人能告诉我如何摆脱这种线条消失的影响,我将不胜感激。

下面是我的几何着色器的代码

#version 330 core


layout (triangles) in;
layout (line_strip, max_vertices = 6) out;

in Data{
    vec4 position;
    vec4 t_position;
    vec4 normal;
    vec2 texCoord;
    vec4 color;
    mat4 mvp;
    mat4 view;
    mat4 mv;
} received[];


out Data{
   vec4 color;
   vec2 uv;
   vec4 normal;
   vec2 texCoord;
   mat4 view;
} gdata;


const float MAGNITUDE = 1.5f;

void GenerateLine(int index) {
    const vec4 green = vec4(0.0f, 1.0f, 0.0f, 1.0f);
    const vec4 blue = vec4(0.0f, 0.0f, 1.0f, 1.0f);

    gl_Position = received[index].t_position;
    //gdata.color = received[index].color;
    gdata.color = green;
    EmitVertex();

    gl_Position = received[index].t_position + received[index].normal * MAGNITUDE;
    //gdata.color = received[index].color;
    gdata.color = blue;
    EmitVertex();

    EndPrimitive();
}

void main() {
    GenerateLine(0); // First vertex normal
    GenerateLine(1); // Second vertex normal
    GenerateLine(2); // Third vertex normal
}

顶点着色器

#version 330


layout(location = 0) in vec3 Position;
layout(location = 1) in vec2 TexCoord;
layout(location = 2) in vec3 Normal;

out Data{
    vec4 position;
    vec4 t_position;
    vec4 normal;
    vec2 texCoord;
    vec4 color;
    mat4 mvp;
    mat4 view;
    mat4 mv;
} vdata;

//MVP
uniform mat4 model;
uniform mat4 projection;
uniform mat4 view;

void main() {
    vdata.position = vec4(Position, 1.0f);
    vdata.normal = view * model * vec4(Normal, 0.0);
    vdata.texCoord = TexCoord;

    vdata.view = view;

    vec4 modelColor = vec4(0.8f, 0.8f, 0.8f, 1.0f);
    vdata.color = modelColor;

    vdata.mvp = projection * view * model;
    vdata.mv = view * model;
    vdata.t_position = vdata.mvp * vdata.position;

    gl_Position = vdata.t_position;
};

如果其他人遇到此问题,解决方案如下:

glm::perspective(45.0f, m_aspectRatio, m_zNear, m_zFar);

我最初的 m_zNear 等于 0.1,但当将其切换为 1.0 时,线条不再消失。我不完全确定为什么会这样。如果有人知道请分享。

你试过google zFar zNear 吗? Here you go.

或者至少尝试 google 神奇的帮助 glm::perspective(...) 功能?

参考 Illia 2016 年 5 月 18 日在 22:53

的回答

I originally had my m_zNear equal to 0.1 but when switched it to 1.0, the lines stopped disappearing. I am not completely sure why is that. If any one knows please share it

消失的线是关于深度缓冲区裁剪的。顶点在透视分割中是projected (multiplied with MVP-matrix) and then the vertex position is changed AFTER the projection in geometry shader (GS). These changes in GS causes the z-value to fall outside normalized device coordinates(NDC)。 zNear 值越大,投影的 z 值越小,因此它不会落在 NDC 之外。尽管如果 GS 中 MAGNITUDE 的值足够大,那么即使 zNear 更大,这些行也会被剪掉。解决此问题的一种方法是在 GS 中进行投影。