Search code examples
c++openglpointersstdvectorvbo

OpenGL: Using VBO with std::vector


I'm trying to load an object and use VBO and glDrawArrays() to render it. The problem is that a simple float pointer like float f[]={...} does not work in my case, because I passed the limit of values that this pointer can store. So my solution was to use a vector. And it's not working...

Here is my code:

unsigned int vbo;
vector<float*> vert;

...
vert.push_back(new float(i*size));
vert.push_back(new float(height*h));
vert.push_back(new float(j*size));
...

glGenBuffers(1, &vbo);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof(vert), &vert, GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);

and to render:

glBindBuffer(GL_ARRAY_BUFFER, vbo);
glEnableClientState(GL_VERTEX_ARRAY);
glVertexPointer(3, GL_FLOAT, 0, 0);
glDrawArrays(GL_TRIANGLE_STRIP, 0, 3);
glDisableClientState(GL_VERTEX_ARRAY);
glBindBuffer(GL_ARRAY_BUFFER, 0);

I'm having problem on the glBufferData() where the 3rd parameter is const GLvoid *data. I'm passing &vert but It's not working.


Solution

  • You want to do:

    unsigned int vbo;
    vector<float> vert;
    
    ...
    vert.push_back(i*size);
    vert.push_back(height*h);
    vert.push_back(j*size);
    ...
    
    glGenBuffers(1, &vbo);
    glBindBuffer(GL_ARRAY_BUFFER, vbo);
    glBufferData(GL_ARRAY_BUFFER, vert.size() * sizeof(float), vert.data(), GL_STATIC_DRAW);
    glBindBuffer(GL_ARRAY_BUFFER, 0);
    

    It is always good to read the documentation. Also, I would suggest you pick up a good C++ book, which probably would be a good way for you to avoid doing mistakes like these.