Search code examples
c++file-iostructmodels

Confused about reading from a file and into a struct within a struct


So I'm trying to write a small piece of code in c++ which will read in a file (of verts, vect normals, vert texture coords and faces (v/vt/vn v/vt/vn v/vt/vn) etc ) and I've lost myself a little bit.

I started small to begin with, reading in only a cube with only verts, colours and faces, but now I've got hold of a much higher poly model (126 faces) where the faces are described differently (before there was no vect normasl or vert textures) and so I figured a struct within a struct would be a good way to go about storing this info.

inFile >> NUM_POLY;
indices = new polygon[NUM_POLY];
for (int i=0; i < NUM_POLY; i++)
{   
inFile >> indices[i].a;
inFile >> indices[i].b;
inFile >> indices[i].c;
}

That is my code currently, with the old system, but I changed the structure to this...

struct vertA {
int v;
int vt;
int vn;
};

struct vertB {
int v;
int vt;
int vn;
};

struct vertC {
int v;
int vt;
int vn;
};

struct polygon {
struct vertA;
struct vertB;
struct vertC;
};

So what has confused me is how I am to store the first 3 integers into the vertA struct, next 3 in vertB, then vertC and loop back around again until end of file...

If anyone can help that would be great thanks!


Solution

  • I'm not sure I'm understanding the problem correctly (so please correct me if necessary), but it looks like you want something like this:

    struct vertex
    {
        int v;
        int vt;
        int vn;
    }
    
    struct polygon
    {
        struct vertex a;
        struct vertex b;
        struct vertex c;
    }
    

    Then, to initialize it, paraphrasing your original example:

    inFile >> NUM_POLY;
    indices = new polygon[NUM_POLY];
    for (int i = 0; i < NUM_POLY; i++)
    {   
        inFile >> indices[i].a.v;
        inFile >> indices[i].a.vt;
        inFile >> indices[i].a.vn;
        inFile >> indices[i].b.v;
        inFile >> indices[i].b.vt;
        inFile >> indices[i].b.vn;
        inFile >> indices[i].c.v;
        inFile >> indices[i].c.vt;
        inFile >> indices[i].c.vn;
    }
    

    You could also shorten that code up a bit by using an array rather than three individual vertex structures:

    struct polygon
    {
        struct vertex v[3];
    }
    

    And then initialize using a loop:

    inFile >> NUM_POLY;
    indices = new polygon[NUM_POLY];
    for (int i = 0; i < NUM_POLY; i++)
    {   
        for (int i = 0; j < 3; j++)
        {
            inFile >> indices[i].v[j].v;
            inFile >> indices[i].v[j].vt;
            inFile >> indices[i].v[j].vn;
        }
    }