Question

I am making a class and one of the values it has are all the vertices it is made up of(Its a 3d program). I want to have a default array of vertices as well(Because vertices are quite big to enter) and the way I want to do this is to define the vertices array:

    Entity::vertices[] = {
        { -0.5f, 0.5f, 0.0f, { 0.0f, 0.0f, 0.0f, 0.0f } },
        { 0.5f, 0.5f, 0.0f, { 0.0f, 0.0f, 0.0f, 0.0f } },
        { 0.5f, -0.5f, 0.0f, { 0.0f, 0.0f, 0.0f, 0.0f } },
        { 0.5f, -0.5f, 0.0f, { 0.0f, 0.0f, 0.0f, 0.0f } },
        { -0.5f, -0.5f, 0.0f, { 0.0f, 0.0f, 0.0f, 0.0f } },
        { -0.5f, 0.5f, 0.0f, { 0.0f, 0.0f, 0.0f, 0.0f } }
    };

and then in the constructor of the class check to see if custom vertices have been inputted and if so make the vertices array the inputed array.

Is there a copy array function?
If not how do I clear an array(Would clear the existing default vertices because if the entered vertices are less than the default I will have extra vertices which would be bad for rendering)?

Was it helpful?

Solution

I'm not 100% sure what data you're trying to store in your array, but here is a simplified example of how I store vertex data in the games I've made.

struct Vertex
{
    vec3 pos;
    vec3 nrm;
    vec2 uvs;  // Can replace this with D3DCOLOR for example if you want colors instead of texture samples.
};

To store them in an std::vector, create the vector:

std::vector<Vertex> myVerts;

To add verts to the vector:

Vertex vert;
myVerts.push_back(vert);

To clear the vector:

myVerts.clear();

To copy from an array of Vertex objects to a vector (assign the vector to the array):

// assuming: Vertex otherVerts[] = { ... };
myVerts.assign(otherVerts,otherVerts+otherSize);

If you just want to add an array of new verts to an existing vector:

// assuming: Vertex otherVerts[] = { ... };
myVerts.insert(myVerts.end(),otherVerts,otherVerts+size);

To copy from another vector of verts into this one (assigning this one to the other):

// assuming: std::vector<Vertex> otherVerts(...);
myVerts = otherVerts;

To add another vector of verts to this one:

// assuming: std::vector<Vertex> otherVerts(...);
myVerts.insert(myVerts.end(),otherVerts.begin(),otherVerts.end());

If you absolutely insist on using your own arrays instead of what's available in the STL, then you'll ultimately need to mimic these same functions in your own dynamic array class. If your array does not need to be dynamic (it is a fixed size that is known at compile-time), then you don't necessarily need to encapsulate functionality within a class (although it can be done with std::array), but it's still easier to use a custom Vertex structure with custom constructors than to hand-write every element as a long and harder to read series of floats.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top