简体   繁体   中英

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.

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.

Remember to check if you have C++11 or vert.data won't compile.

If you look at the std::vector doc you'll that std::vector::data() is tagged with C++11.

http://www.cplusplus.com/reference/vector/vector/data/

If you don't have C++11 you can do the following:

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(), &vert[0], GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);

Taking a reference to the first element of a vector gives you a pointer to the data itself.

I might be a bit late, but for anyone else who needs help on this, you have to obtain a pointer from the start of the data which can be done with &vert.front() or &vert[0]

So it should look something like this:

glBufferData(GL_ARRAY_BUFFER, vert.size() * sizeof(float), &vert.front(), GL_STATIC_DRAW);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM