How would I create a line (possibly colored) with shaders? I'm using programmable pipeline and I'm a beginner with openGL. I can't find an example on how to draw lines with shaders.. I suppose I have to load a VAO (vertices array object) into the shader, but then what? What functions should I use and how?
To draw a line strip with N segments, 6*(N-1) vertices have tpo be processed. We have to create an "empty" Vertex Array Object (without any vertex attribute specification): glGenVertexArrays(1, &vao); glBindVertexArray(vao); And to draw 2*(N-1) triangle ( 6*(N-1) vertices):
Shaders use GLSL (OpenGL Shading Language), a special OpenGL Shading Language with syntax similar to C. GLSL is executed directly by the graphics pipeline. There are several kinds of shaders, but two are commonly used to create graphics on the web: Vertex Shaders and Fragment (Pixel) Shaders.
First, set use the shaderprogram. Then draw lines using glDrawArrays (or Elements if your data is indexed) with mode=GL_LINES or one of the other line drawing modes.
Here's a code example for 2D lines with different color in each end. If shading mode is set to smooth, OpenGL will interpolate the colors along the line.
struct LineSegment_t
{
float x1, y1;
float r1,g1,b1,a1;
float x2, y2;
float r2,g2,b2,a2;
};
int num_verts = lines.size()*2;
glBindVertexArray( line_vao ); // setup for the layout of LineSegment_t
glBindBuffer(GL_ARRAY_BUFFER, LineBufferObject);
glBufferData(GL_ARRAY_BUFFER, sizeof(LineSegment_t)/2 * num_verts, &lines[0], GL_DYNAMIC_DRAW);
glDrawArrays(GL_LINES, 0, num_verts );
If you need more flexibility, you can draw lines using triangles by creating a rectangle (4 points) from the line endpoints. In 2D you can create the 4 points by translating the endpoints using the line normal / perpendicular (-y,x) by the desired line with. In 3D you need to make sure the triangles are aligned to the camera as in billboarding.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With