Denis
Denis

Reputation: 758

Create dynamic array of objects for VBO

I am trying to create dynamic array of objects and then use it for VBO.

Vector3f Vertices[] = new Vector3f[size];
/* 
    initialization
*/

glGenBuffers(1, &VBO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(Vertices), Vertices, GL_STATIC_DRAW);

But i have the following error: initialization with '{...}' expected for aggregate object So, how can i do this? I suppose it must be possible.

Upvotes: 0

Views: 1743

Answers (2)

Brett Hale
Brett Hale

Reputation: 22318

My former comment: You want sizeof(Vector3f) * size rather than sizeof(Vertices), i.e., the size of the data in bytes, in your call to glBufferData.


1/. Use: Vector3f *vertices = new Vector3f[size];

vertices is a pointer a an array of Vector3f (with suitable padding between elements if required, given by sizeof(Vector3f). Each Vector3f element is constructed using Vector3f's default constructor.

2/. Consider managing your data with: std::vector<Vector3f> vertices (size); - so you can manage and operate on vector containers rather than managing pointers. Since std::vector data has contiguous access, you can use:

glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(Vector3f), vertices.data(), GL_STATIC_DRAW);

Should you change the size of the vertices (Vector3f) container, you let the std::vector<>::size() take care the number of elements.

Obviously, you don't need any explicit delete here. Once the Vector3f container passes out of scope, it's automatically destructed. Haven't even touched on all the advantage of generic functions that can operate on the container... merging, reversing, sorting ... just a few things you get for free.

Upvotes: 0

Vul
Vul

Reputation: 44

You may need to use std::vector or std::list in place of traditional C array.

Here is a reference

OpenGL: Using VBO with std::vector

Upvotes: 1

Related Questions