Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
556 views
in Technique[技术] by (71.8m points)

c++ - VBOs with std::vector

I've written a model loader in C++ an OpenGL. I've used std::vectors to store my vertex data, but now I want to pass it to glBufferData(), however the data types are wildly different. I want to know if there's a way to convert between std::vector to the documented const GLvoid * for glBufferData().

Vertex type

typedef struct
{
    float x, y, z;
    float nx, ny, nz;
    float u, v;
}
Vertex;

vector<Vertex> vertices;

glBufferData() call

glBufferData(GL_ARRAY_BUFFER, vertices.size() * 3 * sizeof(float), vertices, GL_STATIC_DRAW);

I get the following (expected) error:

error: cannot convert ‘std::vector<Vertex>’ to ‘const GLvoid*’ in argument passing

How can I convert the vector to a type compatible with glBufferData()?

NB. I don't care about correct memory allocation at the moment; vertices.size() * 3 * sizeof(float) will most likely segfault, but I want to solve the type error first.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you have a std::vector<T> v, you may obtain a T* pointing to the start of the contiguous data (which is what OpenGL is after) with the expression &v[0].


In your case, this means passing a Vertex* to glBufferData:

glBufferData(
   GL_ARRAY_BUFFER,
   vertices.size() * sizeof(Vertex),
   &vertices[0],
   GL_STATIC_DRAW
);

Or like this, which is the same:

glBufferData(
   GL_ARRAY_BUFFER,
   vertices.size() * sizeof(Vertex),
   &vertices.front(),
   GL_STATIC_DRAW
);

You can rely on implicit conversion from Vertex* to void const* here; that should not pose a problem.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...