Home > Software design >  Extracting vectors from Structure in header file
Extracting vectors from Structure in header file

Time:02-17

This is the header file in question:

namespace osc {
using namespace gdt;

  struct TriangleMesh {
    std::vector<vec3f> vertex;
    std::vector<vec3f> normal;
    std::vector<vec2f> texcoord;
    std::vector<vec3i> index;

    // material data:
    vec3f              diffuse;
  };

  struct Model {
    ~Model()
    { for (auto mesh : meshes) delete mesh; }

    std::vector<TriangleMesh *> meshes;
    //! bounding box of all vertices in the model
    box3f bounds;
  };

  Model *loadOBJ(const std::string &objFile);
}

I have successfully been able to use this header file to import an .obj of the 3D model in my main C code using the loadOBJ() function described in the header. I now want to operate on the vertices of that model. From the looks of it, the vertex points are in the structures defined in the header file. How do I extract these vertex vectors from the structure (and display them)?

CodePudding user response:

loadOBJ() gives you a pointer to a Model object.

Model has a std::vector (a dynamic array) member named meshes that holds pointers to TriangleMesh objects.

TriangleMesh has a std::vector member named vertex holding vec3f objects.

You can iterate the various vectors like this:

osc::Model *model = osc::loadOBJ(...);
if (!model) ... // error handling

for (auto&& mesh : model->meshes)
{
    cout << "vertex:\n";
    for (auto&& vtx : mesh->vertex)
    {
        cout << "x=" << vtx.x << ", y=" << vtx.y << "z=" << vtx.z << "\n";
    }
    cout << "\n";

    // repeat for mesh->normal, mesh->texcoord, mesh->index, etc...
}

delete model;

CodePudding user response:

std::vector is a dynamic array in c

if you want to enumerate

 std::vector<vec3f> vertex;

you do

 for(auto vert: vertex)
 {
    // here vert is of type vec3F
  }

you can also access it like an array

 vec3f v2 = vertex[2];

of course you must make sure vertex has at least 2 elements. You can find the length with vertex.size()

  •  Tags:  
  • c
  • Related