Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OpenGL updating vertices array/buffer

When I first add some vertices to the buffer, these are the relevant functions I'm calling

    // Create and bind the object's Vertex Array Object:
    glGenVertexArrays(1, &_vao);
    glBindVertexArray(_vao);

    // Create and load vertex data into a Vertex Buffer Object:
    glGenBuffers(1, &_vbo);
    glBindBuffer(GL_ARRAY_BUFFER, _vbo);
    glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(float), &vertices[0], GL_STATIC_DRAW);

    // Tells OpenGL that there is vertex data in this buffer object and what form that vertex data takes:

    // Obtain attribute handles:
    _posAttrib = glGetAttribLocation(program, "position");
    glEnableVertexAttribArray(_posAttrib);
    glVertexAttribPointer(_posAttrib, // attribute handle
                          4,          // number of scalars per vertex
                          GL_FLOAT,   // scalar type
                          GL_FALSE,
                          0,
                          0);

    // Unbind vertex array:
    glBindVertexArray(0);

But later on in my program, I want to add some more vertices.

I do this by the following (within a separate function:

add_vertices(x,y); //adds the necessary vertices to the vector. 
glGenBuffers(1, &_vbo);
glBindBuffer(GL_ARRAY_BUFFER, _vbo);
glBufferData(GL_ARRAY_BUFFER, (TRIANGLE_AMOUNT+1)*4*_number_of_circles * sizeof(float), &vertices[0], GL_STATIC_DRAW);

Assuming the funky size in the 2nd argument of glBufferData is fine, am I missing anything? Are there any other OpenGL functions that need calling?

I'm not getting any errors, but when I'm trying to draw the extra shapes with the new vertices by looping over glDrawArrays with different subsets of the vertices, nothing happens. Only the first shape gets drawn.

I hope that this is semi-coherent...let me know if there's any info I haven't provided.

Cheers.

like image 932
James Adams Avatar asked Oct 30 '22 16:10

James Adams


1 Answers

In OpenGL, changing the buffers and exchanging the buffers data are two different things which require different actions to be taken afterwards:

Exchanging the data

In this case a previously generated vbo is required. To upload new data, it is only required to bind the buffer and to buffer new data:

glBindBuffer(GL_ARRAY_BUFFER, _vbo);
glBufferData(GL_ARRAY_BUFFER, (TRIANGLE_AMOUNT+1)*4*_number_of_circles * sizeof(float),
    &vertices[0], GL_STATIC_DRAW);

Creating a new buffer

In this case a new buffer is generated by glGenerateBuffers and (in addition to uploading the data) all VAO bindings have to be updated.

Sidenote: In the code shown above, you create a new buffer without deleting the previous buffer.

like image 199
BDL Avatar answered Nov 15 '22 05:11

BDL