1 | #include <stdio.h> |
---|
2 | |
---|
3 | #define MaxVertices 400000 |
---|
4 | #define MaxFaces 400000 |
---|
5 | #define MaxGroups 100 |
---|
6 | |
---|
7 | float vertex[MaxVertices*3]; |
---|
8 | unsigned int face[MaxFaces*3]; |
---|
9 | char group_name[MaxGroups][80]; |
---|
10 | int start_face[MaxGroups]; |
---|
11 | |
---|
12 | int vertices = 0; |
---|
13 | int faces = 0; |
---|
14 | int groups = 0; |
---|
15 | |
---|
16 | void read_wavefront(const char *filename) |
---|
17 | { |
---|
18 | char line[80]; |
---|
19 | FILE *f = fopen(filename, "r"); |
---|
20 | while(fgets(line, sizeof(line), f)) |
---|
21 | switch(line[0]) |
---|
22 | { |
---|
23 | case 'v': |
---|
24 | sscanf(&line[1], "%f %f %f", &vertex[vertices*3], |
---|
25 | &vertex[vertices*3+1], &vertex[vertices*3+2]); |
---|
26 | ++vertices; |
---|
27 | break; |
---|
28 | case 'g': |
---|
29 | sscanf(&line[1], "%s", group_name[groups]); |
---|
30 | start_face[groups++] = faces; |
---|
31 | break; |
---|
32 | case 'f': |
---|
33 | sscanf(&line[1], "%d %d %d", &face[faces*3], |
---|
34 | &face[faces*3+1], &face[faces*3+2]); |
---|
35 | --face[faces*3]; --face[faces*3+1]; |
---|
36 | --face[faces*3+2]; ++faces; |
---|
37 | break; |
---|
38 | } |
---|
39 | fclose(f); |
---|
40 | start_face[groups] = faces; |
---|
41 | printf("Read %d vertices and %d faces within %d groups from %s\n", |
---|
42 | vertices, faces, groups, filename); |
---|
43 | } |
---|
44 | |
---|
45 | void write_wavefront(int group_number) |
---|
46 | { |
---|
47 | int i = 0; char n[80], *p = group_name[group_number]; |
---|
48 | while (*p != '%' && *p != '\0') n[i++] = *p++; // remove % from name |
---|
49 | n[i++] = '.'; n[i++] = 'o'; n[i++] = 'b'; n[i++] = 'j'; n[i] = '\0'; |
---|
50 | FILE *f = fopen(n, "w"); fprintf(f, "# Wavefront OBJ file\n"); |
---|
51 | for (i = 0; i < vertices; i++) |
---|
52 | fprintf(f, "v %g %g %g\n", vertex[i*3], vertex[i*3+1], vertex[i*3+2]); |
---|
53 | fprintf(f, "g %s\n", group_name[group_number]); |
---|
54 | for (i = start_face[group_number]; i < start_face[group_number+1]; ++i) |
---|
55 | fprintf(f, "f %d %d %d\n", face[i*3]+1, face[i*3+1]+1, face[i*3+2]+1); |
---|
56 | fclose(f); |
---|
57 | } |
---|
58 | |
---|
59 | int main(int argc, char **argv) |
---|
60 | { |
---|
61 | int i; |
---|
62 | read_wavefront("motorBike.obj"); |
---|
63 | for(i = 0; i < groups; i++) write_wavefront(i); |
---|
64 | return 0; |
---|
65 | } |
---|