c++opengldata-bindingvertex-buffervertex-array

C++ OpenGL, why isn't the vertex array binding the vertex buffer?


I'm pretty sure that the vertex array is not binding the vertex buffer because if I comment out the line where I unbind the vertex buffer it works perfectly fine, which suggests that the vertex array isn't binding the vertex buffer properly. Here is the code (there is some abstraction around the program and window but it isn't relevant to the question):

GLuint va;
glGenVertexArrays(1, &va);
glBindVertexArray(va);

GLuint vb;
glGenBuffers(1, &vb);
glBindBuffer(GL_ARRAY_BUFFER, vb);

glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, (2 + 3) * sizeof(float), nullptr);
glBindAttribLocation(program.id(), 0, "i_position");
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, (2 + 3) * sizeof(float), (const void*)(2 * sizeof(float)));
glBindAttribLocation(program.id(), 1, "i_color");

glBindVertexArray(0);
glBindBuffer(GL_ARRAY_BUFFER, 0); //< if this line is commented out it works perfectly fine

program.bind();

while(window->isOpen())
{
    glfwPollEvents();

    glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
    glClear(GL_COLOR_BUFFER_BIT);

    glBindVertexArray(va);
    glBufferData(GL_ARRAY_BUFFER, 3 * (2 + 3) * sizeof(float), vertexes, GL_DYNAMIC_DRAW);
    glDrawArrays(GL_TRIANGLES, 0, 3);

    window->update();
}

Does someone know what I am doing wrong?


Solution

  • A VAO doesn't store the buffer binding. It only stores which buffer is bound to which attribute. If you need the buffer binding itself (for example, for glBufferData), you have to bind the buffer yourself.

    Also note, that glBindAttribLocation has to be called before the program object get's linked.