Search code examples
openglbufferopengl-3vao

How do OpenGL buffers relate to the VAO?


I'm currently learning OpenGL, but I'm having some problems understanding how the different buffers relate to the VAO. In my following code, I'm creating one VAO and two buffers (VBO for the vertex positions and EBO for the vertex order). At this point, if I understood it correctly, there is no connection between the VAO, VBO and EBO. I basically just created one VAO and two buffers. Now with glBindVertexArray and glBindBuffer I tell the OpenGL state machine my currently used VAO and assign my created buffers to a specific buffer type. With glBufferData I then load my data into the buffers. As I understand it, the VAO is still empty at this point and only gets data loaded into with the glVertexAttribPointer function. Now, OpenGL interprets the Data from GL_ELEMENT_ARRAY_BUFFER and loads them into the VAO at index 0. With glEnableVertexAttribArray(0) I then specify that the data at index 0 from my VAO (the vertex positions) should be used in the rendering process.

unsigned int VAO, VBO, EBO;
glGenVertexArrays(1, &VAO);
glGenBuffers(1, &VBO);
glGenBuffers(1, &EBO);

glBindVertexArray(VAO);

glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
    
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);

glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), 0);
glEnableVertexAttribArray(0);

In my main loop, I specify a shader for my triangles, bind a VAO for rendering and then draw the elements followed by swapping the front and back buffers.

glUseProgram(shader);
glBindVertexArray(VAO);
glDrawElements(GL_TRIANGLES, 9, GL_UNSIGNED_INT, 0);
glfwSwapBuffers(window);

But how exactly does OpenGL know the order from the vertices? I have only uploaded the vertex position data into my VAO, but not the order(element) data. Does glVertexAttribPointer perhaps take into account the currently bound data from the GL_ELEMENT_ARRAY_BUFFER when loading data into the VAO? What am I missing here?


Solution

  • Now, OpenGL interprets the Data from GL_ELEMENT_ARRAY_BUFFER and loads them into the VAO at index 0.

    No. Well sort of, but not in the way you seem to be describing it.

    Most buffer binding points bind a buffer to the OpenGL context. The GL_ELEMENT_ARRAY_BUFFER binding point is different. It attaches the buffer to the VAO that itself is bound to the context. That is, the act of calling glBindBuffer(GL_ELEMENT_ARRAY_BUFFER) itself is what creates an association between the VAO and the index buffer. This association has nothing to do with glVertexAttribPointer.

    This also means that if you don't have a VAO bound to the context, you cannot bind anything to GL_ELEMENT_ARRAY_BUFFER.