meguli
meguli

Reputation: 1526

glDrawElements throws an exception without error code

I am trying to draw a simple triangle and set the buffers as follows;

triangle t;
point3f vertices[] = { t.p1(), t.p2(), t.p3() };
GLushort indices[] = { 0, 1, 2 };

gl_vertex_array vao{ 3 };
vao.bind_vertex_array();

gl_vertex_buffer position_vbo{ buffer_type::array_buf };
position_vbo.bind_vertex_buffer();
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), &vertices[0], 
             GL_STATIC_DRAW);
position_vbo.unbind_vertex_buffer();

gl_vertex_buffer index_vbo{ buffer_type::element_array_buf };
index_vbo.bind_vertex_buffer();
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), &indices[0], 
             GL_STATIC_DRAW);
index_vbo.unbind_vertex_buffer();

vao.unbind_vertex_array();

Setting up of buffers and VAOs are fine I think, I checked with glGetError at each stage and everything seems to be working. On my render function, I do the following:

glClearColor(0.4f, 0.3f, 0.6f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

o.vao.bind_vertex_array();
o.sp.use_program();

GLenum error = glGetError();
assert(error == GL_NO_ERROR);
//glDrawElements(GL_TRIANGLES, 3, GL_UNSIGNED_SHORT, 0);
glDrawArrays(GL_TRIANGLES, 0, 3);
error = glGetError();
assert(error == GL_NO_ERROR);

o.sp.unuse_program();
o.vao.unbind_vertex_array();

This rendering call with glDrawArrays works just fine but when I try to render with glDrawElements, I get an exception thrown. Moreover, this is hard exception. I can't go to the next line to see the error code. I didn't know that OpenGl calls could throw. I am stuck here. What might be the problem?

Here is a similar discussion

nvoglv32.dll throws the exception

Upvotes: 2

Views: 827

Answers (1)

BDL
BDL

Reputation: 22175

The problem lies in the VAO setup code. The index buffer gets unbound before the VAO is unbound:

index_vbo.unbind_vertex_buffer();
vao.unbind_vertex_array();

Since the VAO always stores the last state of the bound GL_ELEMENT_ARRAY_BUFFER, this is effectively unbinding the index buffer. The exception happens then because you try to read from a not bound index buffer. The solution should be to exchange these two lines and unbind the VAO first:

vao.unbind_vertex_array();
index_vbo.unbind_vertex_buffer();

As Nicol Bolas mentioned in the comments: You can actually leave away the unbinding of the element buffer completely. When the VAO gets unbound, there is no element buffer bound anymore.

Upvotes: 2

Related Questions