initial commit
[meshfrac] / src / meshload.c
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <stdint.h>
4 #include <ctype.h>
5 #include <assert.h>
6 #include "cmesh.h"
7
8 #ifdef USE_ASSIMP
9 #include <assimp/cimport.h>
10 #include <assimp/postprocess.h>
11 #include <assimp/mesh.h>
12 #include <assimp/scene.h>
13 #include <assimp/types.h>
14 #else
15 #include "dynarr.h"
16 #include "rbtree.h"
17 #endif
18
19
20 #ifdef USE_ASSIMP
21
22 static int add_mesh(struct cmesh *mesh, struct aiMesh *aimesh);
23
24 #define AIPPFLAGS \
25         (aiProcess_JoinIdenticalVertices | aiProcess_PreTransformVertices | \
26          aiProcess_Triangulate | aiProcess_SortByPType | aiProcess_FlipUVs)
27
28 int cmesh_load(struct cmesh *mesh, const char *fname)
29 {
30         int i;
31         const struct aiScene *aiscn;
32
33         if(!(aiscn = aiImportFile(fname, AIPPFLAGS))) {
34                 fprintf(stderr, "failed to open mesh file: %s\n", fname);
35                 return -1;
36         }
37
38         for(i=0; i<(int)aiscn->mNumMeshes; i++) {
39                 add_mesh(mesh, aiscn->mMeshes[i]);
40         }
41
42         aiReleaseImport(aiscn);
43         return 0;
44 }
45
46 static int add_mesh(struct cmesh *mesh, struct aiMesh *aim)
47 {
48         int i, j, voffs, foffs;
49
50         voffs = cmesh_attrib_count(mesh, CMESH_ATTR_VERTEX);
51         foffs = cmesh_poly_count(mesh);
52
53         for(i=0; i<aim->mNumVertices; i++) {
54                 struct aiVector3D *v = aim->mVertices + i;
55                 cmesh_push_attrib3f(mesh, CMESH_ATTR_VERTEX, v->x, v->y, v->z);
56
57                 if(aim->mNormals) {
58                         v = aim->mNormals + i;
59                         cmesh_push_attrib3f(mesh, CMESH_ATTR_NORMAL, v->x, v->y, v->z);
60                 }
61                 if(aim->mTangents) {
62                         v = aim->mTangents + i;
63                         cmesh_push_attrib3f(mesh, CMESH_ATTR_TANGENT, v->x, v->y, v->z);
64                 }
65                 if(aim->mColors[0]) {
66                         struct aiColor4D *col = aim->mColors[0] + i;
67                         cmesh_push_attrib4f(mesh, CMESH_ATTR_COLOR, col->r, col->g, col->b, col->a);
68                 }
69                 if(aim->mTextureCoords[0]) {
70                         v = aim->mTextureCoords[0] + i;
71                         cmesh_push_attrib2f(mesh, CMESH_ATTR_TEXCOORD, v->x, v->y);
72                 }
73                 if(aim->mTextureCoords[1]) {
74                         v = aim->mTextureCoords[1] + i;
75                         cmesh_push_attrib2f(mesh, CMESH_ATTR_TEXCOORD2, v->x, v->y);
76                 }
77         }
78
79         if(aim->mFaces) {
80                 for(i=0; i<aim->mNumFaces; i++) {
81                         assert(aim->mFaces[i].mNumIndices == 3);
82                         for(j=0; j<3; j++) {
83                                 cmesh_push_index(mesh, aim->mFaces[i].mIndices[j] + voffs);
84                         }
85                 }
86                 cmesh_submesh(mesh, aim->mName.data, foffs, aim->mNumFaces);
87         }
88         return 0;
89 }
90
91 #else
92
93 struct vertex_pos {
94         float x, y, z;
95 };
96
97 struct facevertex {
98         int vidx, tidx, nidx;
99 };
100
101 static char *clean_line(char *s);
102 static char *parse_face_vert(char *ptr, struct facevertex *fv, int numv, int numt, int numn);
103 static int cmp_facevert(const void *ap, const void *bp);
104 static void free_rbnode_key(struct rbnode *n, void *cls);
105
106 /* merge of different indices per attribute happens during face processing.
107  *
108  * A triplet of (vertex index/texcoord index/normal index) is used as the key
109  * to search in a balanced binary search tree for vertex buffer index assigned
110  * to the same triplet if it has been encountered before. That index is
111  * appended to the index buffer.
112  *
113  * If a particular triplet has not been encountered before, a new vertex is
114  * appended to the vertex buffer. The index of this new vertex is appended to
115  * the index buffer, and also inserted into the tree for future searches.
116  */
117 int cmesh_load(struct cmesh *mesh, const char *fname)
118 {
119         int i, line_num = 0, result = -1;
120         int found_quad = 0;
121         FILE *fp = 0;
122         char buf[256];
123         struct vertex_pos *varr = 0;
124         cgm_vec3 *narr = 0;
125         cgm_vec2 *tarr = 0;
126         struct rbtree *rbtree = 0;
127         char *subname = 0;
128         int substart = 0, subcount = 0;
129
130         if(!(fp = fopen(fname, "rb"))) {
131                 fprintf(stderr, "load_mesh: failed to open file: %s\n", fname);
132                 goto err;
133         }
134
135         if(!(rbtree = rb_create(cmp_facevert))) {
136                 fprintf(stderr, "load_mesh: failed to create facevertex binary search tree\n");
137                 goto err;
138         }
139         rb_set_delete_func(rbtree, free_rbnode_key, 0);
140
141         if(!(varr = dynarr_alloc(0, sizeof *varr)) ||
142                         !(narr = dynarr_alloc(0, sizeof *narr)) ||
143                         !(tarr = dynarr_alloc(0, sizeof *tarr))) {
144                 fprintf(stderr, "load_mesh: failed to allocate resizable vertex array\n");
145                 goto err;
146         }
147
148         while(fgets(buf, sizeof buf, fp)) {
149                 char *line = clean_line(buf);
150                 ++line_num;
151
152                 if(!*line) continue;
153
154                 switch(line[0]) {
155                 case 'v':
156                         if(isspace(line[1])) {
157                                 /* vertex */
158                                 struct vertex_pos v;
159                                 int num;
160
161                                 num = sscanf(line + 2, "%f %f %f", &v.x, &v.y, &v.z);
162                                 if(num < 3) {
163                                         fprintf(stderr, "%s:%d: invalid vertex definition: \"%s\"\n", fname, line_num, line);
164                                         goto err;
165                                 }
166                                 if(!(varr = dynarr_push(varr, &v))) {
167                                         fprintf(stderr, "load_mesh: failed to resize vertex buffer\n");
168                                         goto err;
169                                 }
170
171                         } else if(line[1] == 't' && isspace(line[2])) {
172                                 /* texcoord */
173                                 cgm_vec2 tc;
174                                 if(sscanf(line + 3, "%f %f", &tc.x, &tc.y) != 2) {
175                                         fprintf(stderr, "%s:%d: invalid texcoord definition: \"%s\"\n", fname, line_num, line);
176                                         goto err;
177                                 }
178                                 tc.y = 1.0f - tc.y;
179                                 if(!(tarr = dynarr_push(tarr, &tc))) {
180                                         fprintf(stderr, "load_mesh: failed to resize texcoord buffer\n");
181                                         goto err;
182                                 }
183
184                         } else if(line[1] == 'n' && isspace(line[2])) {
185                                 /* normal */
186                                 cgm_vec3 norm;
187                                 if(sscanf(line + 3, "%f %f %f", &norm.x, &norm.y, &norm.z) != 3) {
188                                         fprintf(stderr, "%s:%d: invalid normal definition: \"%s\"\n", fname, line_num, line);
189                                         goto err;
190                                 }
191                                 if(!(narr = dynarr_push(narr, &norm))) {
192                                         fprintf(stderr, "load_mesh: failed to resize normal buffer\n");
193                                         goto err;
194                                 }
195                         }
196                         break;
197
198                 case 'f':
199                         if(isspace(line[1])) {
200                                 /* face */
201                                 char *ptr = line + 2;
202                                 struct facevertex fv;
203                                 struct rbnode *node;
204                                 int vsz = dynarr_size(varr);
205                                 int tsz = dynarr_size(tarr);
206                                 int nsz = dynarr_size(narr);
207
208                                 for(i=0; i<4; i++) {
209                                         if(!(ptr = parse_face_vert(ptr, &fv, vsz, tsz, nsz))) {
210                                                 if(i < 3 || found_quad) {
211                                                         fprintf(stderr, "%s:%d: invalid face definition: \"%s\"\n", fname, line_num, line);
212                                                         goto err;
213                                                 } else {
214                                                         break;
215                                                 }
216                                         }
217
218                                         if((node = rb_find(rbtree, &fv))) {
219                                                 unsigned int idx = (intptr_t)node->data;
220                                                 assert(idx < cmesh_attrib_count(mesh, CMESH_ATTR_VERTEX));
221                                                 if(cmesh_push_index(mesh, idx) == -1) {
222                                                         fprintf(stderr, "load_mesh: failed to resize index array\n");
223                                                         goto err;
224                                                 }
225                                                 subcount++;     /* inc number of submesh indices, in case we have submeshes */
226                                         } else {
227                                                 unsigned int newidx = cmesh_attrib_count(mesh, CMESH_ATTR_VERTEX);
228                                                 struct facevertex *newfv;
229                                                 struct vertex_pos *vptr = varr + fv.vidx;
230
231                                                 if(cmesh_push_attrib3f(mesh, CMESH_ATTR_VERTEX, vptr->x, vptr->y, vptr->z) == -1) {
232                                                         fprintf(stderr, "load_mesh: failed to resize vertex array\n");
233                                                         goto err;
234                                                 }
235                                                 if(fv.nidx >= 0) {
236                                                         float nx = narr[fv.nidx].x;
237                                                         float ny = narr[fv.nidx].y;
238                                                         float nz = narr[fv.nidx].z;
239                                                         if(cmesh_push_attrib3f(mesh, CMESH_ATTR_NORMAL, nx, ny, nz) == -1) {
240                                                                 fprintf(stderr, "load_mesh: failed to resize normal array\n");
241                                                                 goto err;
242                                                         }
243                                                 }
244                                                 if(fv.tidx >= 0) {
245                                                         float tu = tarr[fv.tidx].x;
246                                                         float tv = tarr[fv.tidx].y;
247                                                         if(cmesh_push_attrib2f(mesh, CMESH_ATTR_TEXCOORD, tu, tv) == -1) {
248                                                                 fprintf(stderr, "load_mesh: failed to resize texcoord array\n");
249                                                                 goto err;
250                                                         }
251                                                 }
252
253                                                 if(cmesh_push_index(mesh, newidx) == -1) {
254                                                         fprintf(stderr, "load_mesh: failed to resize index array\n");
255                                                         goto err;
256                                                 }
257                                                 subcount++;     /* inc number of submesh indices, in case we have submeshes */
258
259                                                 if((newfv = malloc(sizeof *newfv))) {
260                                                         *newfv = fv;
261                                                 }
262                                                 if(!newfv || rb_insert(rbtree, newfv, (void*)(intptr_t)newidx) == -1) {
263                                                         fprintf(stderr, "load_mesh: failed to insert facevertex to the binary search tree\n");
264                                                         goto err;
265                                                 }
266                                         }
267                                 }
268                                 if(i > 3) found_quad = 1;
269                         }
270                         break;
271
272                 case 'o':
273                         if(subcount > 0) {
274                                 printf("adding submesh: %s\n", subname);
275                                 cmesh_submesh(mesh, subname, substart / 3, subcount / 3);
276                         }
277                         free(subname);
278                         if((subname = malloc(strlen(line)))) {
279                                 strcpy(subname, clean_line(line + 2));
280                         }
281                         substart += subcount;
282                         subcount = 0;
283                         break;
284
285                 default:
286                         break;
287                 }
288         }
289
290         if(subcount > 0) {
291                 /* don't add the final submesh if we never found another. an obj file with a
292                  * single 'o' for the whole list of faces, is a single mesh without submeshes
293                  */
294                 if(cmesh_submesh_count(mesh) > 0) {
295                         printf("adding submesh: %s\n", subname);
296                         cmesh_submesh(mesh, subname, substart / 3, subcount / 3);
297                 } else {
298                         /* ... but use the 'o' name as the name of the mesh instead of the filename */
299                         if(subname && *subname) {
300                                 cmesh_set_name(mesh, subname);
301                         }
302                 }
303         }
304
305         result = 0;     /* success */
306
307         printf("loaded %s mesh: %s (%d submeshes): %d vertices, %d faces\n",
308                         found_quad ? "quad" : "triangle", fname, cmesh_submesh_count(mesh),
309                         cmesh_attrib_count(mesh, CMESH_ATTR_VERTEX), cmesh_poly_count(mesh));
310
311 err:
312         if(fp) fclose(fp);
313         dynarr_free(varr);
314         dynarr_free(narr);
315         dynarr_free(tarr);
316         rb_free(rbtree);
317         free(subname);
318         return result;
319 }
320
321
322 static char *clean_line(char *s)
323 {
324         char *end;
325
326         while(*s && isspace(*s)) ++s;
327         if(!*s) return 0;
328
329         end = s;
330         while(*end && *end != '#') ++end;
331         *end-- = 0;
332
333         while(end > s && isspace(*end)) {
334                 *end-- = 0;
335         }
336
337         return s;
338 }
339
340 static char *parse_idx(char *ptr, int *idx, int arrsz)
341 {
342         char *endp;
343         int val = strtol(ptr, &endp, 10);
344         if(endp == ptr) return 0;
345
346         if(val < 0) {   /* convert negative indices */
347                 *idx = arrsz + val;
348         } else {
349                 *idx = val - 1; /* indices in obj are 1-based */
350         }
351         return endp;
352 }
353
354 /* possible face-vertex definitions:
355  * 1. vertex
356  * 2. vertex/texcoord
357  * 3. vertex//normal
358  * 4. vertex/texcoord/normal
359  */
360 static char *parse_face_vert(char *ptr, struct facevertex *fv, int numv, int numt, int numn)
361 {
362         if(!(ptr = parse_idx(ptr, &fv->vidx, numv)))
363                 return 0;
364         if(*ptr != '/') return (!*ptr || isspace(*ptr)) ? ptr : 0;
365
366         if(*++ptr == '/') {     /* no texcoord */
367                 fv->tidx = -1;
368                 ++ptr;
369         } else {
370                 if(!(ptr = parse_idx(ptr, &fv->tidx, numt)))
371                         return 0;
372                 if(*ptr != '/') return (!*ptr || isspace(*ptr)) ? ptr : 0;
373                 ++ptr;
374         }
375
376         if(!(ptr = parse_idx(ptr, &fv->nidx, numn)))
377                 return 0;
378         return (!*ptr || isspace(*ptr)) ? ptr : 0;
379 }
380
381 static int cmp_facevert(const void *ap, const void *bp)
382 {
383         const struct facevertex *a = ap;
384         const struct facevertex *b = bp;
385
386         if(a->vidx == b->vidx) {
387                 if(a->tidx == b->tidx) {
388                         return a->nidx - b->nidx;
389                 }
390                 return a->tidx - b->tidx;
391         }
392         return a->vidx - b->vidx;
393 }
394
395 static void free_rbnode_key(struct rbnode *n, void *cls)
396 {
397         free(n->key);
398 }
399 #endif