Read 3D Model file (.obj) by C


平常我們使用的IO就很普通,依照我們自己訂的格式處理文字檔案內容

但是如果現在是讀取別人定義的檔案的內容呢? 有註解甚麼的...

例如3D model 的obj檔就是這種類型,它的內容會像下面這樣:

# OBJ Exporter 

#
# object default
#

v  -10.2650 -20.0004 -0.1661
v  -33.1047 -15.3601 6.8245
v  -37.5988 -4.1297 6.0812
v  -50.8819 -34.2326 4.6293
v  -50.0595 -34.4188 4.7378
v  -47.7293 -34.3242 4.7756
v  -49.0474 -34.5628 4.8344
v  -48.4015 -35.0652 5.0741
# 53 vertices

g default
f 1 2 3 
f 3 2 1 
f 1 3 4 
f 4 3 1 
f 5 4 3 
f 3 4 5 
f 53 51 52 
f 52 51 53 
# 102 faces


那我們該怎麼讀取到C的程式中呢?

#include <stdio.h>

typedef struct
{
  float x,y,z;
} fPoint;    
 
typedef struct
{
  float x,y,z;
} vPoint;

int main()
{
    int i;
    float f;
    int data;
    FILE *in, *out;
   
    int reval;
    float fx, fy, fz;
    
    char* p_chr;
    char line_str[1024] = {0};    
    char c;
    
    fPoint fPos[1000];
    vPoint vPos[1000];
    int fidx=0, vidx=0;
     
    // read - two pass strategy
    in = fopen("myfile.txt","r");
    
    //1-pass for length of data
    if (in == NULL)
    {
       fprintf(stderr, "input file error!\n");
    }
    else
    {      
      do 
      {        
        if (fscanf(in, "%[^\n]", line_str) > 0)
        {
          // process line data   
          
          // # is the comment, ignore any char after the '#' sign
          p_chr = line_str;
          while(*p_chr!='\0' && *p_chr!='#')
            p_chr++;
          *p_chr = '\0';

          reval = sscanf(line_str, "%[vf] %f %f %f", &c, &fx, &fy, &fz);
          if (reval < 4)
          {
            if (reval>=0)
              printf("we cannot process the data=\"%s\"\n", line_str);
          }
          else
          {                  
            if (c=='v')
            {
              vPoint p;
              p.x = fx;
              p.y = fy;
              p.z = fz;
              vPos[vidx++] = p;
              printf("v data (x,y,z)=(%.3f,%.3f,%.3f)\n", fx, fy, fz);
            }
            else if (c=='f')
            {
              fPoint p;
              p.x = fx;
              p.y = fy;
              p.z = fz;
              fPos[fidx++] = p;
              printf("f data (x,y,z)=(%.3f,%.3f,%.3f)\n", fx, fy, fz);
            }
            
          }
        }
      }
      while(fscanf(in, "%*c")!=EOF);
      
      fclose(in);
    }

    return 0;
}

留言