Drawing lines with glDrawElements

Hi everyone,

I’ve just started learning OpenGL over the last couple of days and am currently trying to draw a grid. For my testing purposes however I’m attempting to draw a single line. I should also mention I’m trying to do it with a VBO.

So creating my buffers & shader:

std::vector<glm::vec3> vertices;
std::vector<GLuint> indices;
GLuint vbo, indexBuffer;
// Add Vertices
vertices.push_back(glm::vec3(0.0f, 0.0f, 0.0f));
vertices.push_back(glm::vec3(5.0f, 0.0f, 0.0f));
// Add indicies

// Create buffers
glGenBuffers(1, &vbo);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof(glm::vec3) * vertices.size(), &vertices[0], GL_STATIC_DRAW);

glGenBuffers(1, &indexBuffer);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBuffer);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(GLuint) * indices.size(), &indices[0], GL_STATIC_DRAW);

// Create shader
Shader gridShader = Shader();
gridShader.loadShaders("shaders/shdr_grid.vert", "shaders/shdr_grid.frag");

Then in my render loop my code for drawing is:

gridShader.setUniform("view", view);
gridShader.setUniform("projection", projection);

glBindBuffer(GL_ARRAY_BUFFER, vbo);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0);

glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBuffer);
glDrawElements(GL_LINES, indices.size(), GL_UNSIGNED_INT, 0);


The view and projection matrix are confirmed correct when displaying models.

Now shader time :slight_smile:


#version 330

uniform mat4 projection;
uniform mat4 view;

layout (location = 0) in vec3 pos;

void main(void) 
	gl_Position = projection * view * vec4(pos, 1.0);


#version 330

out vec4 outColor;

void main(void) {
	outColor = vec4(1.0, 1.0, 1.0, 1.0);

I figured I didn’t need a model matrix if the grid was never going to transform (which it isn’t), as I’d just be passing in an identity matrix.

Thanks in advance!

You could use a geometry shader, which is a lot more flexible and versatile. Since in openGL, we are already using shaders, learning of the geometry shader is a bonus. https://learnopengl.com/Advanced-OpenGL/Geometry-Shader
By the way, that’s a good source for learning openGL.

A geometry shader isn’t much use here. Also, they’re slow (mostly because they de-duplicate all of the vertices, which drastically increases memory pressure).