mesh loading
[vrtris] / src / meshload.c
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <ctype.h>
4 #include <assert.h>
5 #include "cmesh.h"
6 #include "dynarr.h"
7 #include "rbtree.h"
8
9 struct vertex_pos_color {
10         float x, y, z;
11         float r, g, b, a;
12 };
13
14 struct facevertex {
15         int vidx, tidx, nidx;
16 };
17
18 static char *clean_line(char *s);
19 static char *parse_face_vert(char *ptr, struct facevertex *fv, int numv, int numt, int numn);
20 static int cmp_facevert(const void *ap, const void *bp);
21 static void free_rbnode_key(struct rbnode *n, void *cls);
22
23 /* merge of different indices per attribute happens during face processing.
24  *
25  * A triplet of (vertex index/texcoord index/normal index) is used as the key
26  * to search in a balanced binary search tree for vertex buffer index assigned
27  * to the same triplet if it has been encountered before. That index is
28  * appended to the index buffer.
29  *
30  * If a particular triplet has not been encountered before, a new vertex is
31  * appended to the vertex buffer. The index of this new vertex is appended to
32  * the index buffer, and also inserted into the tree for future searches.
33  */
34 int cmesh_load(struct cmesh *mesh, const char *fname)
35 {
36         int i, line_num = 0, result = -1;
37         int found_quad = 0;
38         FILE *fp = 0;
39         char buf[256];
40         struct vertex_pos_color *varr = 0;
41         cgm_vec3 *narr = 0;
42         cgm_vec2 *tarr = 0;
43         struct rbtree *rbtree = 0;
44
45         if(!(fp = fopen(fname, "rb"))) {
46                 fprintf(stderr, "load_mesh: failed to open file: %s\n", fname);
47                 goto err;
48         }
49
50         if(!(rbtree = rb_create(cmp_facevert))) {
51                 fprintf(stderr, "load_mesh: failed to create facevertex binary search tree\n");
52                 goto err;
53         }
54         rb_set_delete_func(rbtree, free_rbnode_key, 0);
55
56         if(!(varr = dynarr_alloc(0, sizeof *varr)) ||
57                         !(narr = dynarr_alloc(0, sizeof *narr)) ||
58                         !(tarr = dynarr_alloc(0, sizeof *tarr))) {
59                 fprintf(stderr, "load_mesh: failed to allocate resizable vertex array\n");
60                 goto err;
61         }
62
63         while(fgets(buf, sizeof buf, fp)) {
64                 char *line = clean_line(buf);
65                 ++line_num;
66
67                 if(!*line) continue;
68
69                 switch(line[0]) {
70                 case 'v':
71                         if(isspace(line[1])) {
72                                 /* vertex */
73                                 struct vertex_pos_color v;
74                                 int num;
75
76                                 num = sscanf(line + 2, "%f %f %f %f %f %f %f", &v.x, &v.y, &v.z, &v.r, &v.g, &v.b, &v.a);
77                                 if(num < 3) {
78                                         fprintf(stderr, "%s:%d: invalid vertex definition: \"%s\"\n", fname, line_num, line);
79                                         goto err;
80                                 }
81                                 switch(num) {
82                                 case 3:
83                                         v.r = 1.0f;
84                                 case 4:
85                                         v.g = 1.0f;
86                                 case 5:
87                                         v.b = 1.0f;
88                                 case 6:
89                                         v.a = 1.0f;
90                                 }
91                                 if(!(varr = dynarr_push(varr, &v))) {
92                                         fprintf(stderr, "load_mesh: failed to resize vertex buffer\n");
93                                         goto err;
94                                 }
95
96                         } else if(line[1] == 't' && isspace(line[2])) {
97                                 /* texcoord */
98                                 cgm_vec2 tc;
99                                 if(sscanf(line + 3, "%f %f", &tc.x, &tc.y) != 2) {
100                                         fprintf(stderr, "%s:%d: invalid texcoord definition: \"%s\"\n", fname, line_num, line);
101                                         goto err;
102                                 }
103                                 if(!(tarr = dynarr_push(tarr, &tc))) {
104                                         fprintf(stderr, "load_mesh: failed to resize texcoord buffer\n");
105                                         goto err;
106                                 }
107
108                         } else if(line[1] == 'n' && isspace(line[2])) {
109                                 /* normal */
110                                 cgm_vec3 norm;
111                                 if(sscanf(line + 3, "%f %f %f", &norm.x, &norm.y, &norm.z) != 3) {
112                                         fprintf(stderr, "%s:%d: invalid normal definition: \"%s\"\n", fname, line_num, line);
113                                         goto err;
114                                 }
115                                 if(!(narr = dynarr_push(narr, &norm))) {
116                                         fprintf(stderr, "load_mesh: failed to resize normal buffer\n");
117                                         goto err;
118                                 }
119                         }
120                         break;
121
122                 case 'f':
123                         if(isspace(line[1])) {
124                                 /* face */
125                                 char *ptr = line + 2;
126                                 struct facevertex fv;
127                                 struct rbnode *node;
128                                 int vsz = dynarr_size(varr);
129                                 int tsz = dynarr_size(tarr);
130                                 int nsz = dynarr_size(narr);
131
132                                 for(i=0; i<4; i++) {
133                                         if(!(ptr = parse_face_vert(ptr, &fv, vsz, tsz, nsz))) {
134                                                 if(i < 3 || found_quad) {
135                                                         fprintf(stderr, "%s:%d: invalid face definition: \"%s\"\n", fname, line_num, line);
136                                                         goto err;
137                                                 } else {
138                                                         break;
139                                                 }
140                                         }
141
142                                         if((node = rb_find(rbtree, &fv))) {
143                                                 unsigned int idx = (unsigned int)node->data;
144                                                 if(cmesh_push_index(mesh, idx) == -1) {
145                                                         fprintf(stderr, "load_mesh: failed to resize index array\n");
146                                                         goto err;
147                                                 }
148                                         } else {
149                                                 unsigned int newidx = cmesh_attrib_count(mesh, CMESH_ATTR_VERTEX);
150                                                 struct facevertex *newfv;
151                                                 struct vertex_pos_color *vptr = varr + fv.vidx;
152                                                 float tu, tv;
153
154                                                 if(cmesh_push_attrib3f(mesh, CMESH_ATTR_VERTEX, vptr->x, vptr->y, vptr->z) == -1) {
155                                                         fprintf(stderr, "load_mesh: failed to resize vertex array\n");
156                                                         goto err;
157                                                 }
158                                                 if(cmesh_push_attrib(mesh, CMESH_ATTR_COLOR, &vptr->r) == -1) {
159                                                         fprintf(stderr, "load_mesh: failed to resize color array\n");
160                                                         goto err;
161                                                 }
162                                                 if(fv.tidx >= 0) {
163                                                         tu = tarr[fv.tidx].x;
164                                                         tv = tarr[fv.tidx].y;
165                                                 } else {
166                                                         tu = vptr->x;
167                                                         tv = vptr->y;
168                                                 }
169                                                 if(cmesh_push_attrib2f(mesh, CMESH_ATTR_TEXCOORD, tu, tv) == -1) {
170                                                         fprintf(stderr, "load_mesh: failed to resize texcoord array\n");
171                                                         goto err;
172                                                 }
173
174                                                 if((newfv = malloc(sizeof *newfv))) {
175                                                         *newfv = fv;
176                                                 }
177                                                 if(!newfv || rb_insert(rbtree, newfv, (void*)newidx) == -1) {
178                                                         fprintf(stderr, "load_mesh: failed to insert facevertex to the binary search tree\n");
179                                                         goto err;
180                                                 }
181                                         }
182                                 }
183                                 if(i > 3) found_quad = 1;
184                         }
185                         break;
186
187                 default:
188                         break;
189                 }
190         }
191
192         result = 0;     /* success */
193
194         printf("loaded %s mesh: %s: %d vertices, %d faces\n", found_quad ? "quad" : "triangle",
195                         fname, cmesh_attrib_count(mesh, CMESH_ATTR_VERTEX), cmesh_poly_count(mesh));
196
197 err:
198         if(fp) fclose(fp);
199         dynarr_free(varr);
200         dynarr_free(narr);
201         dynarr_free(tarr);
202         rb_free(rbtree);
203         return result;
204 }
205
206 static char *clean_line(char *s)
207 {
208         char *end;
209
210         while(*s && isspace(*s)) ++s;
211         if(!*s) return 0;
212
213         end = s;
214         while(*end && *end != '#') ++end;
215         *end = 0;
216
217         while(end > s && isspace(*end)) --end;
218         *end = 0;
219
220         return s;
221 }
222
223 static char *parse_idx(char *ptr, int *idx, int arrsz)
224 {
225         char *endp;
226         int val = strtol(ptr, &endp, 10);
227         if(endp == ptr) return 0;
228
229         if(val < 0) {   /* convert negative indices */
230                 *idx = arrsz + val;
231         } else {
232                 *idx = val - 1; /* indices in obj are 1-based */
233         }
234         return endp;
235 }
236
237 /* possible face-vertex definitions:
238  * 1. vertex
239  * 2. vertex/texcoord
240  * 3. vertex//normal
241  * 4. vertex/texcoord/normal
242  */
243 static char *parse_face_vert(char *ptr, struct facevertex *fv, int numv, int numt, int numn)
244 {
245         if(!(ptr = parse_idx(ptr, &fv->vidx, numv)))
246                 return 0;
247         if(*ptr != '/') return (!*ptr || isspace(*ptr)) ? ptr : 0;
248
249         if(*++ptr == '/') {     /* no texcoord */
250                 fv->tidx = -1;
251                 ++ptr;
252         } else {
253                 if(!(ptr = parse_idx(ptr, &fv->tidx, numt)))
254                         return 0;
255                 if(*ptr != '/') return (!*ptr || isspace(*ptr)) ? ptr : 0;
256                 ++ptr;
257         }
258
259         if(!(ptr = parse_idx(ptr, &fv->nidx, numn)))
260                 return 0;
261         return (!*ptr || isspace(*ptr)) ? ptr : 0;
262 }
263
264 static int cmp_facevert(const void *ap, const void *bp)
265 {
266         const struct facevertex *a = ap;
267         const struct facevertex *b = bp;
268
269         if(a->vidx == b->vidx) {
270                 if(a->tidx == b->tidx) {
271                         return a->nidx - b->nidx;
272                 }
273                 return a->tidx - b->tidx;
274         }
275         return a->vidx - b->vidx;
276 }
277
278 static void free_rbnode_key(struct rbnode *n, void *cls)
279 {
280         free(n->key);
281 }