// Vertex and Face data structure used in the mesh reader // Feel free to change them typedef struct _point { float x,y,z; } point; typedef struct _color { float r,g,b; } color; typedef struct _faceStruct { int c; int NumVerts; int *v; } faceStruct; int verts, faces, colors; // Number of vertices, faces, and colors color *colorList; // Color List point *vertList; // Vertex List faceStruct *faceList; // Face List // The mesh reader itself // It can read *very* simple obj files void meshReader (char *filename,int sign) { float x,y,z,len; int i,j; char letter; int ic,iv; FILE *fp; char line[100]; fp = fopen(filename, "r"); if (fp == NULL) { printf("Cannot open %s\n!", filename); exit(0); } // Count the number of vertices and faces while(!feof(fp)) { letter = 'n'; fscanf(fp,"%c",&letter); if (letter == 'c') { colors++; } else if (letter == 'v') { verts++; } else if (letter == 'f') { faces++; } if (fgets(line,100,fp) == NULL) { continue; } } fclose(fp); printf("colors : %d\n", colors); printf("verts : %d\n", verts); printf("faces : %d\n", faces); if (colors > 0) { // Dynamic allocation of vertex and face lists faceList = (faceStruct *)malloc(sizeof(faceStruct)*faces); vertList = (point *)malloc(sizeof(point)*verts); colorList = (color *)malloc(sizeof(color)*colors); fp = fopen(filename, "r"); // Read the colors for(i = 0;i < colors;i++) { fscanf(fp,"%c %f %f %f\n",&letter,&x,&y,&z); colorList[i].r = x; colorList[i].g = y; colorList[i].b = z; } // Read the vertices for(i = 0;i < verts;i++) { fscanf(fp,"%c %f %f %f\n",&letter,&x,&y,&z); vertList[i].x = x; vertList[i].y = y; vertList[i].z = z; } // Read the faces for(i = 0;i < faces;i++) { fscanf(fp,"%c %d %d",&letter,&ic,&(faceList[i].NumVerts)); faceList[i].c = ic - 1; faceList[i].v = (int *)malloc(sizeof(int)*faceList[i].NumVerts); for (j=0; j< faceList[i].NumVerts; j++) { fscanf(fp," %d",&iv); faceList[i].v[j] = iv - 1; } fscanf(fp,"\n",&iv); } } else { colors = faces; // Dynamic allocation of vertex and face lists faceList = (faceStruct *)malloc(sizeof(faceStruct)*faces); vertList = (point *)malloc(sizeof(point)*verts); colorList = (color *)malloc(sizeof(color)*colors); // Create a random array of colors for(i = 0;i < colors;i++) { colorList[i].r = ((float)rand())/((float)RAND_MAX); colorList[i].g = ((float)rand())/((float)RAND_MAX); colorList[i].b = ((float)rand())/((float)RAND_MAX); } fp = fopen(filename, "r"); // Read the veritces for(i = 0;i < verts;i++) { fscanf(fp,"%c %f %f %f\n",&letter,&x,&y,&z); vertList[i].x = x; vertList[i].y = y; vertList[i].z = z; } // Read the faces for(i = 0;i < faces;i++) { fscanf(fp,"%c",&letter); faceList[i].c = i; faceList[i].NumVerts = 3; faceList[i].v = (int *)malloc(sizeof(int)*faceList[i].NumVerts); for (j=0; j< faceList[i].NumVerts; j++) { fscanf(fp," %d",&iv); faceList[i].v[j] = iv - 1; } fscanf(fp,"\n"); } } fclose(fp); }