Drawing lines with shader

Hello,

I’m trying to draw cube with lines which connects every single vertex on 3D space.
and I want lines that are actually visible to user to be drawn on the screen.

[Expected]

I can easily draw cube and lines separately with glBegin() / glEnd()

[Actual]

[Vertex Shader]

#version 450 core
layout (location = 0) in vec3 aPos;
out vec4 aColor;
uniform mat4 projection;
uniform mat4 view;
uniform mat4 model;
uniform vec4 color;

void main() {
    aColor = color;
    gl_Position = projection * view * model * vec4(aPos, 1.0);
}

[Fragment Shader]

#version 450 core
in vec4 aColor;
out vec4 FragColor;

void main() {
    FragColor = aColor;
}

[Drawing codes]

glBindVertexArray(VAO);
glDrawArrays(GL_TRIANGLES, 0, 36); // draw cube
glBindVertexArray(0);

Is there any guidelines which can help me to achieve my goal with shader?

Thanks,

Did you turn off depth testing when you’re rendering lines, so that the triangles don’t block them from view?

IOW, depth-testing needs to be enabled to remove the hidden lines.

You might try glDepthFunc(GL_LEQUAL). The default is GL_LESS, which will discard fragments whose depth value is equal to that in the depth buffer.

But that may not be enough. Because of the differences in rasterisation, the fragments generated by the lines won’t have the same depth as those generated by the triangles. The fragments generated by triangles will have the depth calculated by sampling the plane equation at the fragment centre. Those generated by lines will be calculated by sampling the line equation at the closest point to the fragment centre.

To deal with that, use glEnable(GL_POLYGON_OFFSET_LINE) and glPolygonOffset to make the lines have slightly lower depth values. You’ll need to experiment regarding the parameters, as the required offset will depend upon the near and far plane distances used to construct the projection matrix and also upon the distance from the viewpoint.

1 Like

Thank you so much!! :slight_smile:
Problem has been resolved!! :+1: