initial commit
[shapestoy] / src / cmesh.c
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <limits.h>
4 #include <float.h>
5 #include <assert.h>
6 #include "opengl.h"
7 #include "sdr.h"
8 #include "cmesh.h"
9 #include "assman.h"
10 #include "util.h"
11
12
13 struct cmesh_vattrib {
14         int nelem;      /* num elements per attribute [1, 4] */
15         float *data;
16         unsigned int count;
17         unsigned int vbo;
18         int vbo_valid, data_valid;
19 };
20
21 /* istart,icount are valid only when the mesh is indexed, otherwise icount is 0.
22  * vstart,vcount are define the submesh for non-indexed meshes.
23  * For indexed meshes, vstart,vcount denote the range of vertices used by each
24  * submesh.
25  */
26 struct submesh {
27         char *name;
28         int nfaces;     /* derived from either icount or vcount */
29         int istart, icount;
30         int vstart, vcount;
31         struct cmesh_material mtl;
32         struct submesh *next;
33 };
34
35 struct cmesh {
36         char *name;
37         unsigned int nverts, nfaces;
38
39         struct submesh *sublist, *subtail;
40         int subcount;
41
42         struct cmesh_material mtl;
43
44         /* current value for each attribute for the immediate mode interface */
45         cgm_vec4 cur_val[CMESH_NUM_ATTR];
46
47         unsigned int buffer_objects[CMESH_NUM_ATTR + 1];
48         struct cmesh_vattrib vattr[CMESH_NUM_ATTR];
49
50         unsigned int *idata;
51         unsigned int icount;
52         unsigned int ibo;
53         int ibo_valid, idata_valid;
54
55         /* index buffer for wireframe rendering (constructed on demand) */
56         unsigned int wire_ibo;
57         int wire_ibo_valid;
58
59         /* axis-aligned bounding box */
60         cgm_vec3 aabb_min, aabb_max;
61         int aabb_valid;
62         /* bounding sphere */
63         cgm_vec3 bsph_center;
64         float bsph_radius;
65         int bsph_valid;
66 };
67
68
69 static int clone(struct cmesh *cmdest, struct cmesh *cmsrc, struct submesh *sub);
70 static int pre_draw(struct cmesh *cm);
71 static void post_draw(struct cmesh *cm, int cur_sdr);
72 static void update_buffers(struct cmesh *cm);
73 static void update_wire_ibo(struct cmesh *cm);
74 static void calc_aabb(struct cmesh *cm);
75 static void calc_bsph_noidx(struct cmesh *cm, int start, int count);
76 static void calc_bsph_idx(struct cmesh *cm, int start, int count);
77 static void clear_mtl(struct cmesh_material *mtl);
78 static void clone_mtl(struct cmesh_material *dest, struct cmesh_material *src);
79
80 static int def_nelem[CMESH_NUM_ATTR] = {3, 3, 3, 2, 4, 4, 4, 2};
81
82 static int sdr_loc[CMESH_NUM_ATTR] = {0, 1, 2, 3, 4, 5, 6, 7};
83 static int use_custom_sdr_attr;
84
85 static const struct cmesh_material defmtl = {
86         0, {1, 1, 1}, {0, 0, 0}, {0, 0, 0}, 1, 1, 1
87 };
88
89
90 /* global state */
91 void cmesh_set_attrib_sdrloc(int attr, int loc)
92 {
93         sdr_loc[attr] = loc;
94 }
95
96 int cmesh_get_attrib_sdrloc(int attr)
97 {
98         return sdr_loc[attr];
99 }
100
101 void cmesh_clear_attrib_sdrloc(void)
102 {
103         int i;
104         for(i=0; i<CMESH_NUM_ATTR; i++) {
105                 sdr_loc[i] = -1;
106         }
107 }
108
109 void cmesh_bind_sdrloc(unsigned int sdr)
110 {
111         glBindAttribLocation(sdr, CMESH_ATTR_VERTEX, "attr_vertex");
112         glBindAttribLocation(sdr, CMESH_ATTR_NORMAL, "attr_normal");
113         glBindAttribLocation(sdr, CMESH_ATTR_TANGENT, "attr_tangent");
114         glBindAttribLocation(sdr, CMESH_ATTR_TEXCOORD, "attr_texcoord");
115         glBindAttribLocation(sdr, CMESH_ATTR_COLOR, "attr_color");
116         glBindAttribLocation(sdr, CMESH_ATTR_BONEWEIGHTS, "attr_boneweights");
117         glBindAttribLocation(sdr, CMESH_ATTR_BONEIDX, "attr_boneidx");
118         glBindAttribLocation(sdr, CMESH_ATTR_TEXCOORD2, "attr_texcoord2");
119         link_program(sdr);
120 }
121
122 /* mesh functions */
123 struct cmesh *cmesh_alloc(void)
124 {
125         struct cmesh *cm;
126
127         cm = malloc_nf(sizeof *cm);
128         if(cmesh_init(cm) == -1) {
129                 free(cm);
130                 return 0;
131         }
132         return cm;
133 }
134
135 void cmesh_free(struct cmesh *cm)
136 {
137         cmesh_destroy(cm);
138         free(cm);
139 }
140
141 int cmesh_init(struct cmesh *cm)
142 {
143         int i;
144
145         memset(cm, 0, sizeof *cm);
146         cgm_wcons(cm->cur_val + CMESH_ATTR_COLOR, 1, 1, 1, 1);
147
148         glGenBuffers(CMESH_NUM_ATTR + 1, cm->buffer_objects);
149
150         for(i=0; i<CMESH_NUM_ATTR; i++) {
151                 cm->vattr[i].vbo = cm->buffer_objects[i];
152         }
153
154         cm->ibo = cm->buffer_objects[CMESH_NUM_ATTR];
155
156         cm->mtl = defmtl;
157         return 0;
158 }
159
160 void cmesh_destroy(struct cmesh *cm)
161 {
162         int i;
163
164         free(cm->name);
165
166         for(i=0; i<CMESH_NUM_ATTR; i++) {
167                 free(cm->vattr[i].data);
168         }
169         free(cm->idata);
170
171         cmesh_clear_submeshes(cm);
172
173         glDeleteBuffers(CMESH_NUM_ATTR + 1, cm->buffer_objects);
174         if(cm->wire_ibo) {
175                 glDeleteBuffers(1, &cm->wire_ibo);
176         }
177
178         clear_mtl(&cm->mtl);
179 }
180
181 void cmesh_clear(struct cmesh *cm)
182 {
183         int i;
184
185         for(i=0; i<CMESH_NUM_ATTR; i++) {
186                 cm->vattr[i].nelem = 0;
187                 cm->vattr[i].vbo_valid = 0;
188                 cm->vattr[i].data_valid = 0;
189                 free(cm->vattr[i].data);
190                 cm->vattr[i].data = 0;
191                 cm->vattr[i].count = 0;
192         }
193         cm->ibo_valid = cm->idata_valid = 0;
194         free(cm->idata);
195         cm->idata = 0;
196         cm->icount = 0;
197
198         cm->wire_ibo_valid = 0;
199         cm->nverts = cm->nfaces = 0;
200
201         cm->bsph_valid = cm->aabb_valid = 0;
202
203         cmesh_clear_submeshes(cm);
204         clear_mtl(&cm->mtl);
205 }
206
207 int cmesh_clone(struct cmesh *cmdest, struct cmesh *cmsrc)
208 {
209         return clone(cmdest, cmsrc, 0);
210 }
211
212 static int clone(struct cmesh *cmdest, struct cmesh *cmsrc, struct submesh *sub)
213 {
214         int i, nelem, vstart, vcount, istart, icount;
215         char *srcname, *name = 0;
216         float *varr[CMESH_NUM_ATTR] = {0};
217         float *vptr;
218         unsigned int *iptr, *iarr = 0;
219         struct cmesh_material mtl;
220
221         srcname = sub ? sub->name : cmsrc->name;
222         if(srcname) {
223                 name = malloc_nf(strlen(srcname) + 1);
224                 strcpy(name, srcname);
225         }
226
227         if(sub) {
228                 vstart = sub->vstart;
229                 vcount = sub->vcount;
230                 istart = sub->istart;
231                 icount = sub->icount;
232         } else {
233                 vstart = istart = 0;
234                 vcount = cmsrc->nverts;
235                 icount = cmsrc->icount;
236         }
237
238         if(cmesh_indexed(cmsrc)) {
239                 iarr = malloc_nf(icount * sizeof *iarr);
240         }
241
242         clone_mtl(&mtl, sub ? &sub->mtl : &cmsrc->mtl);
243
244         for(i=0; i<CMESH_NUM_ATTR; i++) {
245                 if(cmesh_has_attrib(cmsrc, i)) {
246                         nelem = cmsrc->vattr[i].nelem;
247                         varr[i] = malloc_nf(vcount * nelem * sizeof(float));
248                 }
249         }
250
251         /* from this point forward nothing can fail */
252         cmesh_clear(cmdest);
253
254         for(i=0; i<CMESH_NUM_ATTR; i++) {
255                 free(cmdest->vattr[i].data);
256
257                 if(cmesh_has_attrib(cmsrc, i)) {
258                         cmesh_attrib(cmsrc, i); /* force validation of the actual data on the source mesh */
259
260                         nelem = cmsrc->vattr[i].nelem;
261                         cmdest->vattr[i].nelem = nelem;
262                         cmdest->vattr[i].data = varr[i];
263                         cmdest->vattr[i].count = vcount;
264                         vptr = cmsrc->vattr[i].data + vstart * nelem;
265                         memcpy(cmdest->vattr[i].data, vptr, vcount * nelem * sizeof(float));
266                         cmdest->vattr[i].data_valid = 1;
267                         cmdest->vattr[i].vbo_valid = 0;
268                 } else {
269                         memset(cmdest->vattr + i, 0, sizeof cmdest->vattr[i]);
270                 }
271         }
272
273         if(cmesh_indexed(cmsrc)) {
274                 cmesh_index(cmsrc);     /* force validation .... */
275
276                 cmdest->idata = iarr;
277                 cmdest->icount = icount;
278                 if(sub) {
279                         /* need to offset all vertex indices by -vstart */
280                         iptr = cmsrc->idata + istart;
281                         for(i=0; i<icount; i++) {
282                                 cmdest->idata[i] = *iptr++ - vstart;
283                         }
284                 } else {
285                         memcpy(cmdest->idata, cmsrc->idata + istart, icount * sizeof *cmdest->idata);
286                 }
287                 cmdest->idata_valid = 1;
288         } else {
289                 cmdest->idata = 0;
290                 cmdest->idata_valid = cmdest->ibo_valid = 0;
291         }
292
293         free(cmdest->name);
294         cmdest->name = name;
295
296         cmdest->nverts = cmsrc->nverts;
297         cmdest->nfaces = sub ? sub->nfaces : cmsrc->nfaces;
298
299         memcpy(cmdest->cur_val, cmsrc->cur_val, sizeof cmdest->cur_val);
300
301         cmdest->aabb_min = cmsrc->aabb_min;
302         cmdest->aabb_max = cmsrc->aabb_max;
303         cmdest->aabb_valid = cmsrc->aabb_valid;
304         cmdest->bsph_center = cmsrc->bsph_center;
305         cmdest->bsph_radius = cmsrc->bsph_radius;
306         cmdest->bsph_valid = cmsrc->bsph_valid;
307
308         /* copy sublist only if we're not cloning a submesh */
309         if(!sub) {
310                 struct submesh *sm, *n, *head = 0, *tail = 0;
311
312                 sm = cmsrc->sublist;
313                 while(sm) {
314                         n = malloc_nf(sizeof *n);
315                         name = strdup_nf(sm->name);
316                         *n = *sm;
317                         n->name = name;
318                         n->next = 0;
319
320                         if(head) {
321                                 tail->next = n;
322                                 tail = n;
323                         } else {
324                                 head = tail = n;
325                         }
326
327                         sm = sm->next;
328                 }
329
330                 cmdest->sublist = head;
331                 cmdest->subtail = tail;
332                 cmdest->subcount = cmsrc->subcount;
333         }
334
335         return 0;
336 }
337
338 int cmesh_set_name(struct cmesh *cm, const char *name)
339 {
340         free(cm->name);
341         cm->name = strdup_nf(name);
342         return 0;
343 }
344
345 const char *cmesh_name(struct cmesh *cm)
346 {
347         return cm->name;
348 }
349
350 struct cmesh_material *cmesh_material(struct cmesh *cm)
351 {
352         return &cm->mtl;
353 }
354
355 struct cmesh_material *cmesh_submesh_material(struct cmesh *cm, int subidx)
356 {
357         struct submesh *sm = cm->sublist;
358
359         while(sm && subidx-- > 0) {
360                 sm = sm->next;
361         }
362         return sm ? &sm->mtl : 0;
363 }
364
365 static int load_textures(struct cmesh_material *mtl)
366 {
367         int i, res = 0;
368         for(i=0; i<CMESH_NUM_TEX; i++) {
369                 if(mtl->tex[i].name && !(mtl->tex[i].id = get_tex2d(mtl->tex[i].name))) {
370                         res = -1;
371                 }
372         }
373         return res;
374 }
375
376 int cmesh_load_textures(struct cmesh *cm)
377 {
378         int res = 0;
379         struct submesh *sm;
380
381         if(load_textures(&cm->mtl) == -1) {
382                 res = -1;
383         }
384
385         sm = cm->sublist;
386         while(sm) {
387                 if(load_textures(&sm->mtl) == -1) {
388                         res = -1;
389                 }
390                 sm = sm->next;
391         }
392         return res;
393 }
394
395 int cmesh_has_attrib(struct cmesh *cm, int attr)
396 {
397         if(attr < 0 || attr >= CMESH_NUM_ATTR) {
398                 return 0;
399         }
400         return cm->vattr[attr].vbo_valid | cm->vattr[attr].data_valid;
401 }
402
403 int cmesh_indexed(struct cmesh *cm)
404 {
405         return cm->ibo_valid | cm->idata_valid;
406 }
407
408 /* vdata can be 0, in which case only memory is allocated
409  * returns pointer to the attribute array
410  */
411 float *cmesh_set_attrib(struct cmesh *cm, int attr, int nelem, unsigned int num,
412                 const float *vdata)
413 {
414         float *newarr;
415
416         if(attr < 0 || attr >= CMESH_NUM_ATTR) {
417                 return 0;
418         }
419         if(cm->nverts && num != cm->nverts) {
420                 return 0;
421         }
422
423         newarr = malloc_nf(num * nelem * sizeof *newarr);
424         if(vdata) {
425                 memcpy(newarr, vdata, num * nelem * sizeof *newarr);
426         }
427
428         cm->nverts = num;
429
430         free(cm->vattr[attr].data);
431         cm->vattr[attr].data = newarr;
432         cm->vattr[attr].count = num * nelem;
433         cm->vattr[attr].nelem = nelem;
434         cm->vattr[attr].data_valid = 1;
435         cm->vattr[attr].vbo_valid = 0;
436         return newarr;
437 }
438
439 float *cmesh_attrib(struct cmesh *cm, int attr)
440 {
441         if(attr < 0 || attr >= CMESH_NUM_ATTR) {
442                 return 0;
443         }
444         cm->vattr[attr].vbo_valid = 0;
445         return (float*)cmesh_attrib_ro(cm, attr);
446 }
447
448 const float *cmesh_attrib_ro(struct cmesh *cm, int attr)
449 {
450         if(attr < 0 || attr >= CMESH_NUM_ATTR) {
451                 return 0;
452         }
453
454         if(!cm->vattr[attr].data_valid) {
455 #if GL_ES_VERSION_2_0
456                 return 0;
457 #else
458                 void *tmp;
459                 int nelem;
460                 if(!cm->vattr[attr].vbo_valid) {
461                         return 0;
462                 }
463
464                 /* local data copy unavailable, grab the data from the vbo */
465                 nelem = cm->vattr[attr].nelem;
466                 cm->vattr[attr].data = malloc_nf(cm->nverts * nelem * sizeof(float));
467                 cm->vattr[attr].count = cm->nverts * nelem;
468
469                 glBindBuffer(GL_ARRAY_BUFFER, cm->vattr[attr].vbo);
470                 tmp = glMapBuffer(GL_ARRAY_BUFFER, GL_READ_ONLY);
471                 memcpy(cm->vattr[attr].data, tmp, cm->nverts * nelem * sizeof(float));
472                 glUnmapBuffer(GL_ARRAY_BUFFER);
473
474                 cm->vattr[attr].data_valid = 1;
475 #endif
476         }
477         return cm->vattr[attr].data;
478 }
479
480 float *cmesh_attrib_at(struct cmesh *cm, int attr, int idx)
481 {
482         float *vptr = cmesh_attrib(cm, attr);
483         return vptr ? vptr + idx * cm->vattr[attr].nelem : 0;
484 }
485
486 const float *cmesh_attrib_at_ro(struct cmesh *cm, int attr, int idx)
487 {
488         const float *vptr = cmesh_attrib_ro(cm, attr);
489         return vptr ? vptr + idx * cm->vattr[attr].nelem : 0;
490 }
491
492 int cmesh_attrib_count(struct cmesh *cm, int attr)
493 {
494         return cmesh_has_attrib(cm, attr) ? cm->nverts : 0;
495 }
496
497 int cmesh_push_attrib(struct cmesh *cm, int attr, float *v)
498 {
499         float *vptr;
500         int i, cursz, newsz;
501
502         if(!cm->vattr[attr].nelem) {
503                 cm->vattr[attr].nelem = def_nelem[attr];
504         }
505
506         cursz = cm->vattr[attr].count;
507         newsz = cursz + cm->vattr[attr].nelem;
508         vptr = realloc_nf(cm->vattr[attr].data, newsz * sizeof(float));
509         cm->vattr[attr].data = vptr;
510         cm->vattr[attr].count = newsz;
511         vptr += cursz;
512
513         for(i=0; i<cm->vattr[attr].nelem; i++) {
514                 *vptr++ = *v++;
515         }
516         cm->vattr[attr].data_valid = 1;
517         cm->vattr[attr].vbo_valid = 0;
518
519         if(attr == CMESH_ATTR_VERTEX) {
520                 cm->nverts = newsz / cm->vattr[attr].nelem;
521         }
522         return 0;
523 }
524
525 int cmesh_push_attrib1f(struct cmesh *cm, int attr, float x)
526 {
527         float v[4];
528         v[0] = x;
529         v[1] = v[2] = 0.0f;
530         v[3] = 1.0f;
531         return cmesh_push_attrib(cm, attr, v);
532 }
533
534 int cmesh_push_attrib2f(struct cmesh *cm, int attr, float x, float y)
535 {
536         float v[4];
537         v[0] = x;
538         v[1] = y;
539         v[2] = 0.0f;
540         v[3] = 1.0f;
541         return cmesh_push_attrib(cm, attr, v);
542 }
543
544 int cmesh_push_attrib3f(struct cmesh *cm, int attr, float x, float y, float z)
545 {
546         float v[4];
547         v[0] = x;
548         v[1] = y;
549         v[2] = z;
550         v[3] = 1.0f;
551         return cmesh_push_attrib(cm, attr, v);
552 }
553
554 int cmesh_push_attrib4f(struct cmesh *cm, int attr, float x, float y, float z, float w)
555 {
556         float v[4];
557         v[0] = x;
558         v[1] = y;
559         v[2] = z;
560         v[3] = w;
561         return cmesh_push_attrib(cm, attr, v);
562 }
563
564 /* indices can be 0, in which case only memory is allocated
565  * returns pointer to the index array
566  */
567 unsigned int *cmesh_set_index(struct cmesh *cm, int num, const unsigned int *indices)
568 {
569         unsigned int *tmp;
570         int nidx = cm->nfaces * 3;
571
572         if(nidx && num != nidx) {
573                 return 0;
574         }
575
576         tmp = malloc_nf(num * sizeof *tmp);
577         if(indices) {
578                 memcpy(tmp, indices, num * sizeof *tmp);
579         }
580
581         free(cm->idata);
582         cm->idata = tmp;
583         cm->icount = num;
584         cm->nfaces = num / 3;
585         cm->idata_valid = 1;
586         cm->ibo_valid = 0;
587         return tmp;
588 }
589
590 unsigned int *cmesh_index(struct cmesh *cm)
591 {
592         cm->ibo_valid = 0;
593         return (unsigned int*)cmesh_index_ro(cm);
594 }
595
596 const unsigned int *cmesh_index_ro(struct cmesh *cm)
597 {
598         if(!cm->idata_valid) {
599 #if GL_ES_VERSION_2_0
600                 return 0;
601 #else
602                 int nidx;
603                 unsigned int *tmp;
604
605                 if(!cm->ibo_valid) {
606                         return 0;
607                 }
608
609                 /* local copy is unavailable, grab the data from the ibo */
610                 nidx = cm->nfaces * 3;
611                 tmp = malloc_nf(nidx * sizeof *cm->idata);
612                 free(cm->idata);
613                 cm->idata = tmp;
614                 cm->icount = nidx;
615
616                 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, cm->ibo);
617                 tmp = glMapBuffer(GL_ELEMENT_ARRAY_BUFFER, GL_READ_ONLY);
618                 memcpy(cm->idata, tmp, nidx * sizeof *cm->idata);
619                 glUnmapBuffer(GL_ELEMENT_ARRAY_BUFFER);
620
621                 cm->idata_valid = 1;
622 #endif
623         }
624         return cm->idata;
625 }
626
627 int cmesh_index_count(struct cmesh *cm)
628 {
629         return cm->nfaces * 3;
630 }
631
632 int cmesh_push_index(struct cmesh *cm, unsigned int idx)
633 {
634         unsigned int *iptr;
635         unsigned int cur_sz = cm->icount;
636         iptr = realloc_nf(cm->idata, (cur_sz + 1) * sizeof *iptr);
637         iptr[cur_sz] = idx;
638         cm->idata = iptr;
639         cm->icount = cur_sz + 1;
640         cm->idata_valid = 1;
641         cm->ibo_valid = 0;
642
643         cm->nfaces = cm->icount / 3;
644         return 0;
645 }
646
647 int cmesh_poly_count(struct cmesh *cm)
648 {
649         if(cm->nfaces) {
650                 return cm->nfaces;
651         }
652         if(cm->nverts) {
653                 return cm->nverts / 3;
654         }
655         return 0;
656 }
657
658 /* attr can be -1 to invalidate all attributes */
659 void cmesh_invalidate_vbo(struct cmesh *cm, int attr)
660 {
661         int i;
662
663         if(attr >= CMESH_NUM_ATTR) {
664                 return;
665         }
666
667         if(attr < 0) {
668                 for(i=0; i<CMESH_NUM_ATTR; i++) {
669                         cm->vattr[i].vbo_valid = 0;
670                 }
671         } else {
672                 cm->vattr[attr].vbo_valid = 0;
673         }
674 }
675
676 void cmesh_invalidate_index(struct cmesh *cm)
677 {
678         cm->ibo_valid = 0;
679 }
680
681 int cmesh_append(struct cmesh *cmdest, struct cmesh *cmsrc)
682 {
683         int i, nelem, newsz, origsz, srcsz;
684         float *vptr;
685         unsigned int *iptr;
686         unsigned int idxoffs;
687
688         if(!cmdest->nverts) {
689                 return cmesh_clone(cmdest, cmsrc);
690         }
691
692         for(i=0; i<CMESH_NUM_ATTR; i++) {
693                 if(cmesh_has_attrib(cmdest, i) && cmesh_has_attrib(cmsrc, i)) {
694                         /* force validation of the data arrays */
695                         cmesh_attrib(cmdest, i);
696                         cmesh_attrib_ro(cmsrc, i);
697
698                         assert(cmdest->vattr[i].nelem == cmsrc->vattr[i].nelem);
699                         nelem = cmdest->vattr[i].nelem;
700                         origsz = cmdest->nverts * nelem;
701                         newsz = cmdest->nverts + cmsrc->nverts * nelem;
702
703                         vptr = realloc_nf(cmdest->vattr[i].data, newsz * sizeof *vptr);
704                         memcpy(vptr + origsz, cmsrc->vattr[i].data, cmsrc->nverts * nelem * sizeof(float));
705                         cmdest->vattr[i].data = vptr;
706                         cmdest->vattr[i].count = newsz;
707                 }
708         }
709
710         if(cmesh_indexed(cmdest)) {
711                 assert(cmesh_indexed(cmsrc));
712                 /* force validation ... */
713                 cmesh_index(cmdest);
714                 cmesh_index_ro(cmsrc);
715
716                 idxoffs = cmdest->nverts;
717                 origsz = cmdest->icount;
718                 srcsz = cmsrc->icount;
719                 newsz = origsz + srcsz;
720
721                 iptr = realloc_nf(cmdest->idata, newsz * sizeof *iptr);
722                 cmdest->idata = iptr;
723                 cmdest->icount = newsz;
724
725                 /* copy and fixup all the new indices */
726                 iptr += origsz;
727                 for(i=0; i<srcsz; i++) {
728                         *iptr++ = cmsrc->idata[i] + idxoffs;
729                 }
730         }
731
732         cmdest->wire_ibo_valid = 0;
733         cmdest->aabb_valid = 0;
734         cmdest->bsph_valid = 0;
735         return 0;
736 }
737
738 void cmesh_clear_submeshes(struct cmesh *cm)
739 {
740         struct submesh *sm;
741
742         while(cm->sublist) {
743                 sm = cm->sublist;
744                 cm->sublist = cm->sublist->next;
745                 free(sm->name);
746                 clear_mtl(&sm->mtl);
747                 free(sm);
748         }
749         cm->subtail = 0;
750         cm->subcount = 0;
751 }
752
753 int cmesh_submesh(struct cmesh *cm, const char *name, int fstart, int fcount)
754 {
755         int i;
756         unsigned int minv = UINT_MAX, maxv = 0;
757         unsigned int *iptr;
758         struct submesh *sm;
759
760         if(fstart < 0 || fcount < 1 || fstart + fcount > cm->nfaces) {
761                 return -1;
762         }
763
764         sm = malloc_nf(sizeof *sm);
765         sm->name = strdup_nf(name);
766         sm->nfaces = fcount;
767         clone_mtl(&sm->mtl, &cm->mtl);
768
769         if(cmesh_indexed(cm)) {
770                 sm->istart = fstart * 3;
771                 sm->icount = fcount * 3;
772
773                 /* find out which vertices are used by this submesh */
774                 iptr = cm->idata + sm->istart;
775                 for(i=0; i<sm->icount; i++) {
776                         unsigned int vidx = *iptr++;
777                         if(vidx < minv) minv = vidx;
778                         if(vidx > maxv) maxv = vidx;
779                 }
780                 sm->vstart = minv;
781                 sm->vcount = maxv - minv + 1;
782         } else {
783                 sm->istart = sm->icount = 0;
784                 sm->vstart = fstart * 3;
785                 sm->vcount = fcount * 3;
786         }
787
788         sm->next = 0;
789         if(cm->sublist) {
790                 cm->subtail->next = sm;
791                 cm->subtail = sm;
792         } else {
793                 cm->sublist = cm->subtail = sm;
794         }
795         cm->subcount++;
796         return 0;
797 }
798
799 int cmesh_remove_submesh(struct cmesh *cm, int idx)
800 {
801         struct submesh dummy;
802         struct submesh *prev, *sm;
803
804         if(idx >= cm->subcount) {
805                 return -1;
806         }
807
808         dummy.next = cm->sublist;
809         prev = &dummy;
810
811         while(prev->next && idx-- > 0) {
812                 prev = prev->next;
813         }
814
815         if(!(sm = prev->next)) return -1;
816
817         prev->next = sm->next;
818         free(sm->name);
819         clear_mtl(&sm->mtl);
820         free(sm);
821
822         cm->subcount--;
823         assert(cm->subcount >= 0);
824
825         cm->sublist = dummy.next;
826         if(!cm->sublist) {
827                 cm->sublist = cm->subtail = 0;
828         } else {
829                 if(cm->subtail == sm) cm->subtail = prev;
830         }
831         return 0;
832 }
833
834 int cmesh_find_submesh(struct cmesh *cm, const char *name)
835 {
836         int idx = 0;
837         struct submesh *sm = cm->sublist;
838         while(sm) {
839                 if(strcmp(sm->name, name) == 0) {
840                         assert(idx <= cm->subcount);
841                         return idx;
842                 }
843                 idx++;
844                 sm = sm->next;
845         }
846         return -1;
847 }
848
849 int cmesh_submesh_count(struct cmesh *cm)
850 {
851         return cm->subcount;
852 }
853
854 static struct submesh *get_submesh(struct cmesh *m, int idx)
855 {
856         struct submesh *sm = m->sublist;
857         while(sm && --idx >= 0) {
858                 sm = sm->next;
859         }
860         return sm;
861 }
862
863 int cmesh_clone_submesh(struct cmesh *cmdest, struct cmesh *cm, int subidx)
864 {
865         struct submesh *sub;
866
867         if(!(sub = get_submesh(cm, subidx))) {
868                 return -1;
869         }
870         return clone(cmdest, cm, sub);
871 }
872
873 const char *cmesh_submesh_name(struct cmesh *cm, int idx)
874 {
875         struct submesh *sub;
876
877         if(!(sub = get_submesh(cm, idx))) {
878                 return 0;
879         }
880         return sub->name;
881 }
882
883
884
885 /* assemble a complete vertex by adding all the useful attributes */
886 int cmesh_vertex(struct cmesh *cm, float x, float y, float z)
887 {
888         int i, j;
889
890         cgm_wcons(cm->cur_val + CMESH_ATTR_VERTEX, x, y, z, 1.0f);
891         cm->vattr[CMESH_ATTR_VERTEX].data_valid = 1;
892         cm->vattr[CMESH_ATTR_VERTEX].nelem = 3;
893
894         for(i=0; i<CMESH_NUM_ATTR; i++) {
895                 if(cm->vattr[i].data_valid) {
896                         int newsz = cm->vattr[i].count + cm->vattr[i].nelem;
897                         float *tmp = realloc_nf(cm->vattr[i].data, newsz * sizeof *tmp);
898                         tmp += cm->vattr[i].count;
899
900                         cm->vattr[i].data = tmp;
901                         cm->vattr[i].count = newsz;
902
903                         for(j=0; j<cm->vattr[i].nelem; j++) {
904                                 *tmp++ = *(&cm->cur_val[i].x + j);
905                         }
906                 }
907                 cm->vattr[i].vbo_valid = 0;
908                 cm->vattr[i].data_valid = 1;
909         }
910
911         if(cm->idata_valid) {
912                 free(cm->idata);
913                 cm->idata = 0;
914                 cm->icount = 0;
915         }
916         cm->ibo_valid = cm->idata_valid = 0;
917         return 0;
918 }
919
920 void cmesh_normal(struct cmesh *cm, float nx, float ny, float nz)
921 {
922         cgm_wcons(cm->cur_val + CMESH_ATTR_NORMAL, nx, ny, nz, 1.0f);
923         cm->vattr[CMESH_ATTR_NORMAL].nelem = 3;
924 }
925
926 void cmesh_tangent(struct cmesh *cm, float tx, float ty, float tz)
927 {
928         cgm_wcons(cm->cur_val + CMESH_ATTR_TANGENT, tx, ty, tz, 1.0f);
929         cm->vattr[CMESH_ATTR_TANGENT].nelem = 3;
930 }
931
932 void cmesh_texcoord(struct cmesh *cm, float u, float v, float w)
933 {
934         cgm_wcons(cm->cur_val + CMESH_ATTR_TEXCOORD, u, v, w, 1.0f);
935         cm->vattr[CMESH_ATTR_TEXCOORD].nelem = 3;
936 }
937
938 void cmesh_boneweights(struct cmesh *cm, float w1, float w2, float w3, float w4)
939 {
940         cgm_wcons(cm->cur_val + CMESH_ATTR_BONEWEIGHTS, w1, w2, w3, w4);
941         cm->vattr[CMESH_ATTR_BONEWEIGHTS].nelem = 4;
942 }
943
944 void cmesh_boneidx(struct cmesh *cm, int idx1, int idx2, int idx3, int idx4)
945 {
946         cgm_wcons(cm->cur_val + CMESH_ATTR_BONEIDX, idx1, idx2, idx3, idx4);
947         cm->vattr[CMESH_ATTR_BONEIDX].nelem = 4;
948 }
949
950 static float *get_vec4(struct cmesh *cm, int attr, int idx, cgm_vec4 *res)
951 {
952         int i;
953         float *sptr, *dptr;
954         cgm_wcons(res, 0, 0, 0, 1);
955         if(!(sptr = cmesh_attrib_at(cm, attr, idx))) {
956                 return 0;
957         }
958         dptr = &res->x;
959
960         for(i=0; i<cm->vattr[attr].nelem; i++) {
961                 *dptr++ = sptr[i];
962         }
963         return sptr;
964 }
965
966 static float *get_vec3(struct cmesh *cm, int attr, int idx, cgm_vec3 *res)
967 {
968         int i;
969         float *sptr, *dptr;
970         cgm_vcons(res, 0, 0, 0);
971         if(!(sptr = cmesh_attrib_at(cm, attr, idx))) {
972                 return 0;
973         }
974         dptr = &res->x;
975
976         for(i=0; i<cm->vattr[attr].nelem; i++) {
977                 *dptr++ = sptr[i];
978         }
979         return sptr;
980 }
981
982 void cmesh_apply_xform(struct cmesh *cm, float *xform, float *dir_xform)
983 {
984         unsigned int i;
985         int j;
986         cgm_vec4 v;
987         cgm_vec3 n, t;
988         float *vptr;
989
990         if(!dir_xform) dir_xform = xform;
991
992         for(i=0; i<cm->nverts; i++) {
993                 if(!(vptr = get_vec4(cm, CMESH_ATTR_VERTEX, i, &v))) {
994                         return;
995                 }
996                 cgm_wmul_m4v4(&v, xform);
997                 for(j=0; j<cm->vattr[CMESH_ATTR_VERTEX].nelem; j++) {
998                         *vptr++ = (&v.x)[j];
999                 }
1000
1001                 if(cmesh_has_attrib(cm, CMESH_ATTR_NORMAL)) {
1002                         if((vptr = get_vec3(cm, CMESH_ATTR_NORMAL, i, &n))) {
1003                                 cgm_vmul_m3v3(&n, dir_xform);
1004                                 for(j=0; j<cm->vattr[CMESH_ATTR_NORMAL].nelem; j++) {
1005                                         *vptr++ = (&n.x)[j];
1006                                 }
1007                         }
1008                 }
1009                 if(cmesh_has_attrib(cm, CMESH_ATTR_TANGENT)) {
1010                         if((vptr = get_vec3(cm, CMESH_ATTR_TANGENT, i, &t))) {
1011                                 cgm_vmul_m3v3(&t, dir_xform);
1012                                 for(j=0; j<cm->vattr[CMESH_ATTR_TANGENT].nelem; j++) {
1013                                         *vptr++ = (&t.x)[j];
1014                                 }
1015                         }
1016                 }
1017         }
1018 }
1019
1020 void cmesh_flip(struct cmesh *cm)
1021 {
1022         cmesh_flip_faces(cm);
1023         cmesh_flip_normals(cm);
1024 }
1025
1026 void cmesh_flip_faces(struct cmesh *cm)
1027 {
1028         int i, j, idxnum, vnum, nelem;
1029         unsigned int *indices;
1030         float *verts, *vptr;
1031
1032         if(cmesh_indexed(cm)) {
1033                 if(!(indices = cmesh_index(cm))) {
1034                         return;
1035                 }
1036                 idxnum = cmesh_index_count(cm);
1037                 for(i=0; i<idxnum; i+=3) {
1038                         unsigned int tmp = indices[i + 2];
1039                         indices[i + 2] = indices[i + 1];
1040                         indices[i + 1] = tmp;
1041                 }
1042         } else {
1043                 if(!(verts = cmesh_attrib(cm, CMESH_ATTR_VERTEX))) {
1044                         return;
1045                 }
1046                 vnum = cmesh_attrib_count(cm, CMESH_ATTR_VERTEX);
1047                 nelem = cm->vattr[CMESH_ATTR_VERTEX].nelem;
1048                 for(i=0; i<vnum; i+=3) {
1049                         for(j=0; j<nelem; j++) {
1050                                 vptr = verts + (i + 1) * nelem + j;
1051                                 float tmp = vptr[nelem];
1052                                 vptr[nelem] = vptr[0];
1053                                 vptr[0] = tmp;
1054                         }
1055                 }
1056         }
1057 }
1058 void cmesh_flip_normals(struct cmesh *cm)
1059 {
1060         int i, num;
1061         float *nptr = cmesh_attrib(cm, CMESH_ATTR_NORMAL);
1062         if(!nptr) return;
1063
1064         num = cm->nverts * cm->vattr[CMESH_ATTR_NORMAL].nelem;
1065         for(i=0; i<num; i++) {
1066                 *nptr = -*nptr;
1067                 nptr++;
1068         }
1069 }
1070
1071 int cmesh_explode(struct cmesh *cm)
1072 {
1073         int i, j, k, idxnum, nnverts;
1074         unsigned int *indices;
1075
1076         if(!cmesh_indexed(cm)) return 0;
1077
1078         indices = cmesh_index(cm);
1079         assert(indices);
1080
1081         idxnum = cmesh_index_count(cm);
1082         nnverts = idxnum;
1083
1084         for(i=0; i<CMESH_NUM_ATTR; i++) {
1085                 const float *srcbuf;
1086                 float *tmpbuf, *dstptr;
1087
1088                 if(!cmesh_has_attrib(cm, i)) continue;
1089
1090                 srcbuf = cmesh_attrib(cm, i);
1091                 tmpbuf = malloc_nf(nnverts * cm->vattr[i].nelem * sizeof(float));
1092                 dstptr = tmpbuf;
1093
1094                 for(j=0; j<idxnum; j++) {
1095                         unsigned int idx = indices[j];
1096                         const float *srcptr = srcbuf + idx * cm->vattr[i].nelem;
1097
1098                         for(k=0; k<cm->vattr[i].nelem; k++) {
1099                                 *dstptr++ = *srcptr++;
1100                         }
1101                 }
1102
1103                 free(cm->vattr[i].data);
1104                 cm->vattr[i].data = tmpbuf;
1105                 cm->vattr[i].count = nnverts * cm->vattr[i].nelem;
1106                 cm->vattr[i].data_valid = 1;
1107         }
1108
1109         cm->ibo_valid = 0;
1110         cm->idata_valid = 0;
1111         free(cm->idata);
1112         cm->idata = 0;
1113         cm->icount = 0;
1114
1115         cm->nverts = nnverts;
1116         cm->nfaces = idxnum / 3;
1117         return 0;
1118 }
1119
1120 void cmesh_calc_face_normals(struct cmesh *cm)
1121 {
1122         /* TODO */
1123 }
1124
1125 static int pre_draw(struct cmesh *cm)
1126 {
1127         int i, loc;
1128
1129         update_buffers(cm);
1130
1131         if(!cm->vattr[CMESH_ATTR_VERTEX].vbo_valid) {
1132                 return -1;
1133         }
1134
1135         if(sdr_loc[CMESH_ATTR_VERTEX] == -1) {
1136                 return -1;
1137         }
1138
1139         for(i=0; i<CMESH_NUM_ATTR; i++) {
1140                 loc = sdr_loc[i];
1141                 if(loc >= 0 && cm->vattr[i].vbo_valid) {
1142                         glBindBuffer(GL_ARRAY_BUFFER, cm->vattr[i].vbo);
1143                         glVertexAttribPointer(loc, cm->vattr[i].nelem, GL_FLOAT, GL_FALSE, 0, 0);
1144                         glEnableVertexAttribArray(loc);
1145                 }
1146         }
1147         glBindBuffer(GL_ARRAY_BUFFER, 0);
1148         return 0;
1149 }
1150
1151 void cmesh_draw(struct cmesh *cm)
1152 {
1153         pre_draw(cm);
1154
1155         if(cm->ibo_valid) {
1156                 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, cm->ibo);
1157                 glDrawElements(GL_TRIANGLES, cm->nfaces * 3, GL_UNSIGNED_INT, 0);
1158                 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
1159         } else {
1160                 glDrawArrays(GL_TRIANGLES, 0, cm->nverts);
1161         }
1162
1163         post_draw(cm, 0);
1164 }
1165
1166 void cmesh_draw_range(struct cmesh *cm, int start, int count)
1167 {
1168         int cur_sdr;
1169
1170         if((cur_sdr = pre_draw(cm)) == -1) {
1171                 return;
1172         }
1173
1174         if(cm->ibo_valid) {
1175                 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, cm->ibo);
1176                 glDrawElements(GL_TRIANGLES, count, GL_UNSIGNED_INT, (void*)(uintptr_t)(start * 4));
1177                 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
1178         } else {
1179                 glDrawArrays(GL_TRIANGLES, start, count);
1180         }
1181
1182         post_draw(cm, cur_sdr);
1183 }
1184
1185 void cmesh_draw_submesh(struct cmesh *cm, int subidx)
1186 {
1187         struct submesh *sm = cm->sublist;
1188
1189         while(sm && subidx-- > 0) {
1190                 sm = sm->next;
1191         }
1192         if(!sm) return;
1193
1194         if(sm->icount) {
1195                 cmesh_draw_range(cm, sm->istart, sm->icount);
1196         } else {
1197                 cmesh_draw_range(cm, sm->vstart, sm->vcount);
1198         }
1199 }
1200
1201 static void post_draw(struct cmesh *cm, int cur_sdr)
1202 {
1203         int i;
1204
1205         for(i=0; i<CMESH_NUM_ATTR; i++) {
1206                 int loc = sdr_loc[i];
1207                 if(loc >= 0 && cm->vattr[i].vbo_valid) {
1208                         glDisableVertexAttribArray(loc);
1209                 }
1210         }
1211 }
1212
1213 void cmesh_draw_wire(struct cmesh *cm, float linesz)
1214 {
1215         int cur_sdr, nfaces;
1216
1217         if((cur_sdr = pre_draw(cm)) == -1) {
1218                 return;
1219         }
1220         update_wire_ibo(cm);
1221
1222         nfaces = cmesh_poly_count(cm);
1223         glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, cm->wire_ibo);
1224         glDrawElements(GL_LINES, nfaces * 6, GL_UNSIGNED_INT, 0);
1225         glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
1226
1227         post_draw(cm, cur_sdr);
1228 }
1229
1230 void cmesh_draw_vertices(struct cmesh *cm, float ptsz)
1231 {
1232         int cur_sdr;
1233         if((cur_sdr = pre_draw(cm)) == -1) {
1234                 return;
1235         }
1236
1237         /* TODO use billboards if needed */
1238         glDrawArrays(GL_POINTS, 0, cm->nverts);
1239
1240         post_draw(cm, cur_sdr);
1241 }
1242
1243 void cmesh_draw_normals(struct cmesh *cm, float len)
1244 {
1245 #ifndef GL_ES_VERSION_2_0
1246         int i, cur_sdr, vert_nelem, norm_nelem;
1247         int loc = -1;
1248         const float *varr, *norm;
1249
1250         varr = cmesh_attrib_ro(cm, CMESH_ATTR_VERTEX);
1251         norm = cmesh_attrib_ro(cm, CMESH_ATTR_NORMAL);
1252         if(!varr || !norm) return;
1253
1254         vert_nelem = cm->vattr[CMESH_ATTR_VERTEX].nelem;
1255         norm_nelem = cm->vattr[CMESH_ATTR_NORMAL].nelem;
1256
1257         glGetIntegerv(GL_CURRENT_PROGRAM, &cur_sdr);
1258         if(cur_sdr && use_custom_sdr_attr) {
1259                 if((loc = sdr_loc[CMESH_ATTR_VERTEX]) < 0) {
1260                         return;
1261                 }
1262         }
1263
1264         glBegin(GL_LINES);
1265         for(i=0; i<cm->nverts; i++) {
1266                 float x, y, z, endx, endy, endz;
1267
1268                 x = varr[i * vert_nelem];
1269                 y = varr[i * vert_nelem + 1];
1270                 z = varr[i * vert_nelem + 2];
1271                 endx = x + norm[i * norm_nelem] * len;
1272                 endy = y + norm[i * norm_nelem + 1] * len;
1273                 endz = z + norm[i * norm_nelem + 2] * len;
1274
1275                 if(loc == -1) {
1276                         glVertex3f(x, y, z);
1277                         glVertex3f(endx, endy, endz);
1278                 } else {
1279                         glVertexAttrib3f(loc, x, y, z);
1280                         glVertexAttrib3f(loc, endx, endy, endz);
1281                 }
1282         }
1283         glEnd();
1284 #endif  /* GL_ES_VERSION_2_0 */
1285 }
1286
1287 void cmesh_draw_tangents(struct cmesh *cm, float len)
1288 {
1289 #ifndef GL_ES_VERSION_2_0
1290         int i, cur_sdr, vert_nelem, tang_nelem;
1291         int loc = -1;
1292         const float *varr, *tang;
1293
1294         varr = cmesh_attrib_ro(cm, CMESH_ATTR_VERTEX);
1295         tang = cmesh_attrib_ro(cm, CMESH_ATTR_TANGENT);
1296         if(!varr || !tang) return;
1297
1298         vert_nelem = cm->vattr[CMESH_ATTR_VERTEX].nelem;
1299         tang_nelem = cm->vattr[CMESH_ATTR_TANGENT].nelem;
1300
1301         glGetIntegerv(GL_CURRENT_PROGRAM, &cur_sdr);
1302         if(cur_sdr && use_custom_sdr_attr) {
1303                 if((loc = sdr_loc[CMESH_ATTR_VERTEX]) < 0) {
1304                         return;
1305                 }
1306         }
1307
1308         glBegin(GL_LINES);
1309         for(i=0; i<cm->nverts; i++) {
1310                 float x, y, z, endx, endy, endz;
1311
1312                 x = varr[i * vert_nelem];
1313                 y = varr[i * vert_nelem + 1];
1314                 z = varr[i * vert_nelem + 2];
1315                 endx = x + tang[i * tang_nelem] * len;
1316                 endy = y + tang[i * tang_nelem + 1] * len;
1317                 endz = z + tang[i * tang_nelem + 2] * len;
1318
1319                 if(loc == -1) {
1320                         glVertex3f(x, y, z);
1321                         glVertex3f(endx, endy, endz);
1322                 } else {
1323                         glVertexAttrib3f(loc, x, y, z);
1324                         glVertexAttrib3f(loc, endx, endy, endz);
1325                 }
1326         }
1327         glEnd();
1328 #endif  /* GL_ES_VERSION_2_0 */
1329 }
1330
1331 static void update_buffers(struct cmesh *cm)
1332 {
1333         int i;
1334
1335         for(i=0; i<CMESH_NUM_ATTR; i++) {
1336                 if(cmesh_has_attrib(cm, i) && !cm->vattr[i].vbo_valid) {
1337                         glBindBuffer(GL_ARRAY_BUFFER, cm->vattr[i].vbo);
1338                         glBufferData(GL_ARRAY_BUFFER, cm->nverts * cm->vattr[i].nelem * sizeof(float),
1339                                         cm->vattr[i].data, GL_STATIC_DRAW);
1340                         cm->vattr[i].vbo_valid = 1;
1341                 }
1342         }
1343         glBindBuffer(GL_ARRAY_BUFFER, 0);
1344
1345         if(cm->idata_valid && !cm->ibo_valid) {
1346                 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, cm->ibo);
1347                 glBufferData(GL_ELEMENT_ARRAY_BUFFER, cm->nfaces * 3 * sizeof(unsigned int),
1348                                 cm->idata, GL_STATIC_DRAW);
1349                 cm->ibo_valid = 1;
1350                 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
1351         }
1352 }
1353
1354 static void update_wire_ibo(struct cmesh *cm)
1355 {
1356         int i, num_faces;
1357         unsigned int *wire_idxarr, *dest;
1358
1359         update_buffers(cm);
1360
1361         if(cm->wire_ibo_valid) return;
1362
1363         if(!cm->wire_ibo) {
1364                 glGenBuffers(1, &cm->wire_ibo);
1365         }
1366         num_faces = cmesh_poly_count(cm);
1367
1368         wire_idxarr = malloc_nf(num_faces * 6 * sizeof *wire_idxarr);
1369         dest = wire_idxarr;
1370
1371         if(cm->ibo_valid) {
1372                 /* we're dealing with an indexed mesh */
1373                 const unsigned int *idxarr = cmesh_index_ro(cm);
1374
1375                 for(i=0; i<num_faces; i++) {
1376                         *dest++ = idxarr[0];
1377                         *dest++ = idxarr[1];
1378                         *dest++ = idxarr[1];
1379                         *dest++ = idxarr[2];
1380                         *dest++ = idxarr[2];
1381                         *dest++ = idxarr[0];
1382                         idxarr += 3;
1383                 }
1384         } else {
1385                 /* not an indexed mesh */
1386                 for(i=0; i<num_faces; i++) {
1387                         int vidx = i * 3;
1388                         *dest++ = vidx;
1389                         *dest++ = vidx + 1;
1390                         *dest++ = vidx + 1;
1391                         *dest++ = vidx + 2;
1392                         *dest++ = vidx + 2;
1393                         *dest++ = vidx;
1394                 }
1395         }
1396
1397         glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, cm->wire_ibo);
1398         glBufferData(GL_ELEMENT_ARRAY_BUFFER, num_faces * 6 * sizeof(unsigned int),
1399                         wire_idxarr, GL_STATIC_DRAW);
1400         free(wire_idxarr);
1401         cm->wire_ibo_valid = 1;
1402         glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
1403 }
1404
1405 static void calc_aabb(struct cmesh *cm)
1406 {
1407         int i, j;
1408
1409         if(!cmesh_attrib_ro(cm, CMESH_ATTR_VERTEX)) {
1410                 return;
1411         }
1412
1413         cgm_vcons(&cm->aabb_min, FLT_MAX, FLT_MAX, FLT_MAX);
1414         cgm_vcons(&cm->aabb_max, -FLT_MAX, -FLT_MAX, -FLT_MAX);
1415
1416         for(i=0; i<cm->nverts; i++) {
1417                 const float *v = cmesh_attrib_at_ro(cm, CMESH_ATTR_VERTEX, i);
1418                 for(j=0; j<3; j++) {
1419                         if(v[j] < (&cm->aabb_min.x)[j]) {
1420                                 (&cm->aabb_min.x)[j] = v[j];
1421                         }
1422                         if(v[j] > (&cm->aabb_max.x)[j]) {
1423                                 (&cm->aabb_max.x)[j] = v[j];
1424                         }
1425                 }
1426         }
1427         cm->aabb_valid = 1;
1428 }
1429
1430 void cmesh_aabbox(struct cmesh *cm, cgm_vec3 *vmin, cgm_vec3 *vmax)
1431 {
1432         if(!cm->aabb_valid) {
1433                 calc_aabb(cm);
1434         }
1435         *vmin = cm->aabb_min;
1436         *vmax = cm->aabb_max;
1437 }
1438
1439 static void calc_bsph_noidx(struct cmesh *cm, int start, int count)
1440 {
1441         int i;
1442         float s, dist_sq;
1443
1444         if(!cmesh_attrib_ro(cm, CMESH_ATTR_VERTEX)) {
1445                 return;
1446         }
1447         if(count <= 0) count = cm->nverts;
1448
1449         cgm_vcons(&cm->bsph_center, 0, 0, 0);
1450
1451         /* first find the center */
1452         for(i=0; i<count; i++) {
1453                 const float *v = cmesh_attrib_at_ro(cm, CMESH_ATTR_VERTEX, i + start);
1454                 cm->bsph_center.x += v[0];
1455                 cm->bsph_center.y += v[1];
1456                 cm->bsph_center.z += v[2];
1457         }
1458         s = 1.0f / (float)count;
1459         cm->bsph_center.x *= s;
1460         cm->bsph_center.y *= s;
1461         cm->bsph_center.z *= s;
1462
1463         cm->bsph_radius = 0.0f;
1464         for(i=0; i<count; i++) {
1465                 const cgm_vec3 *v = (const cgm_vec3*)cmesh_attrib_at_ro(cm, CMESH_ATTR_VERTEX, i + start);
1466                 if((dist_sq = cgm_vdist_sq(v, &cm->bsph_center)) > cm->bsph_radius) {
1467                         cm->bsph_radius = dist_sq;
1468                 }
1469         }
1470         cm->bsph_radius = sqrt(cm->bsph_radius);
1471         cm->bsph_valid = 1;
1472 }
1473
1474 static void calc_bsph_idx(struct cmesh *cm, int start, int count)
1475 {
1476         int i;
1477         float s, dist_sq;
1478
1479         if(!cmesh_attrib_ro(cm, CMESH_ATTR_VERTEX) || !cmesh_index_ro(cm)) {
1480                 return;
1481         }
1482         if(count <= 0) count = cm->icount;
1483
1484         cgm_vcons(&cm->bsph_center, 0, 0, 0);
1485
1486         /* first find the center */
1487         for(i=0; i<count; i++) {
1488                 int idx = cm->idata[i + start];
1489                 const float *v = cmesh_attrib_at_ro(cm, CMESH_ATTR_VERTEX, idx);
1490                 cm->bsph_center.x += v[0];
1491                 cm->bsph_center.y += v[1];
1492                 cm->bsph_center.z += v[2];
1493         }
1494         s = 1.0f / (float)count;
1495         cm->bsph_center.x *= s;
1496         cm->bsph_center.y *= s;
1497         cm->bsph_center.z *= s;
1498
1499         cm->bsph_radius = 0.0f;
1500         for(i=0; i<count; i++) {
1501                 int idx = cm->idata[i + start];
1502                 const cgm_vec3 *v = (const cgm_vec3*)cmesh_attrib_at_ro(cm, CMESH_ATTR_VERTEX, idx);
1503                 if((dist_sq = cgm_vdist_sq(v, &cm->bsph_center)) > cm->bsph_radius) {
1504                         cm->bsph_radius = dist_sq;
1505                 }
1506         }
1507         cm->bsph_radius = sqrt(cm->bsph_radius);
1508         cm->bsph_valid = 1;
1509 }
1510
1511
1512 float cmesh_bsphere(struct cmesh *cm, cgm_vec3 *center, float *rad)
1513 {
1514         if(!cm->bsph_valid) {
1515                 calc_bsph_noidx(cm, 0, 0);
1516         }
1517         if(center) *center = cm->bsph_center;
1518         if(rad) *rad = cm->bsph_radius;
1519         return cm->bsph_radius;
1520 }
1521
1522 float cmesh_submesh_bsphere(struct cmesh *cm, int subidx, cgm_vec3 *center, float *rad)
1523 {
1524         struct submesh *sm = get_submesh(cm, subidx);
1525         if(!sm) {
1526                 cgm_vcons(center, 0, 0, 0);
1527                 *rad = 0;
1528                 return 0;
1529         }
1530
1531         if(sm->icount) {
1532                 calc_bsph_idx(cm, sm->istart, sm->icount);
1533         } else {
1534                 calc_bsph_noidx(cm, sm->vstart, sm->vcount);
1535         }
1536         cm->bsph_valid = 0;
1537
1538         if(center) *center = cm->bsph_center;
1539         if(rad) *rad = cm->bsph_radius;
1540         return cm->bsph_radius;
1541 }
1542
1543 /* TODO */
1544 void cmesh_texcoord_apply_xform(struct cmesh *cm, float *xform);
1545 void cmesh_texcoord_gen_plane(struct cmesh *cm, cgm_vec3 *norm, cgm_vec3 *tang);
1546 void cmesh_texcoord_gen_box(struct cmesh *cm);
1547 void cmesh_texcoord_gen_cylinder(struct cmesh *cm);
1548
1549 int cmesh_dump(struct cmesh *cm, const char *fname)
1550 {
1551         FILE *fp = fopen(fname, "wb");
1552         if(fp) {
1553                 int res = cmesh_dump_file(cm, fp);
1554                 fclose(fp);
1555                 return res;
1556         }
1557         return -1;
1558 }
1559
1560 int cmesh_dump_file(struct cmesh *cm, FILE *fp)
1561 {
1562         static const char *label[] = { "pos", "nor", "tan", "tex", "col", "bw", "bid", "tex2" };
1563         static const char *elemfmt[] = { 0, " %s(%g)", " %s(%g, %g)", " %s(%g, %g, %g)", " %s(%g, %g, %g, %g)", 0 };
1564         int i, j;
1565
1566         if(!cmesh_has_attrib(cm, CMESH_ATTR_VERTEX)) {
1567                 return -1;
1568         }
1569
1570         fprintf(fp, "VERTEX ATTRIBUTES\n");
1571
1572         for(i=0; i<cm->nverts; i++) {
1573                 fprintf(fp, "%5u:", i);
1574                 for(j=0; j<CMESH_NUM_ATTR; j++) {
1575                         if(cmesh_has_attrib(cm, j)) {
1576                                 const float *v = cmesh_attrib_at_ro(cm, j, i);
1577                                 int nelem = cm->vattr[j].nelem;
1578                                 fprintf(fp, elemfmt[nelem], label[j], v[0], nelem > 1 ? v[1] : 0.0f,
1579                                                 nelem > 2 ? v[2] : 0.0f, nelem > 3 ? v[3] : 0.0f);
1580                         }
1581                 }
1582                 fputc('\n', fp);
1583         }
1584
1585         if(cmesh_indexed(cm)) {
1586                 const unsigned int *idx = cmesh_index_ro(cm);
1587                 int numidx = cmesh_index_count(cm);
1588                 int numtri = numidx / 3;
1589                 assert(numidx % 3 == 0);
1590
1591                 fprintf(fp, "FACES\n");
1592
1593                 for(i=0; i<numtri; i++) {
1594                         fprintf(fp, "%5d: %d %d %d\n", i, idx[0], idx[1], idx[2]);
1595                         idx += 3;
1596                 }
1597         }
1598         return 0;
1599 }
1600
1601 int cmesh_dump_obj(struct cmesh *cm, const char *fname)
1602 {
1603         FILE *fp = fopen(fname, "wb");
1604         if(fp) {
1605                 int res = cmesh_dump_obj_file(cm, fp, 0);
1606                 fclose(fp);
1607                 return res;
1608         }
1609         return -1;
1610 }
1611
1612 #define HAS_VN  1
1613 #define HAS_VT  2
1614
1615 int cmesh_dump_obj_file(struct cmesh *cm, FILE *fp, int voffs)
1616 {
1617         static const char *fmtstr[] = {" %u", " %u//%u", " %u/%u", " %u/%u/%u"};
1618         int i, j, num, nelem;
1619         unsigned int aflags = 0;
1620
1621         if(!cmesh_has_attrib(cm, CMESH_ATTR_VERTEX)) {
1622                 return -1;
1623         }
1624
1625
1626         nelem = cm->vattr[CMESH_ATTR_VERTEX].nelem;
1627         if((num = cm->vattr[CMESH_ATTR_VERTEX].count) != cm->nverts * nelem) {
1628                 fprintf(stderr, "vertex array size (%d) != nverts (%d)\n", num, cm->nverts);
1629         }
1630         for(i=0; i<cm->nverts; i++) {
1631                 const float *v = cmesh_attrib_at_ro(cm, CMESH_ATTR_VERTEX, i);
1632                 fprintf(fp, "v %f %f %f\n", v[0], nelem > 1 ? v[1] : 0.0f, nelem > 2 ? v[2] : 0.0f);
1633         }
1634
1635         if(cmesh_has_attrib(cm, CMESH_ATTR_NORMAL)) {
1636                 aflags |= HAS_VN;
1637                 nelem = cm->vattr[CMESH_ATTR_NORMAL].nelem;
1638                 if((num = cm->vattr[CMESH_ATTR_NORMAL].count) != cm->nverts * nelem) {
1639                         fprintf(stderr, "normal array size (%d) != nverts (%d)\n", num, cm->nverts);
1640                 }
1641                 for(i=0; i<cm->nverts; i++) {
1642                         const float *v = cmesh_attrib_at_ro(cm, CMESH_ATTR_NORMAL, i);
1643                         fprintf(fp, "vn %f %f %f\n", v[0], nelem > 1 ? v[1] : 0.0f, nelem > 2 ? v[2] : 0.0f);
1644                 }
1645         }
1646
1647         if(cmesh_has_attrib(cm, CMESH_ATTR_TEXCOORD)) {
1648                 aflags |= HAS_VT;
1649                 nelem = cm->vattr[CMESH_ATTR_TEXCOORD].nelem;
1650                 if((num = cm->vattr[CMESH_ATTR_TEXCOORD].count) != cm->nverts * nelem) {
1651                         fprintf(stderr, "texcoord array size (%d) != nverts (%d)\n", num, cm->nverts);
1652                 }
1653                 for(i=0; i<cm->nverts; i++) {
1654                         const float *v = cmesh_attrib_at_ro(cm, CMESH_ATTR_TEXCOORD, i);
1655                         fprintf(fp, "vt %f %f\n", v[0], nelem > 1 ? v[1] : 0.0f);
1656                 }
1657         }
1658
1659         if(cmesh_indexed(cm)) {
1660                 const unsigned int *idxptr = cmesh_index_ro(cm);
1661                 int numidx = cmesh_index_count(cm);
1662                 int numtri = numidx / 3;
1663                 assert(numidx % 3 == 0);
1664
1665                 for(i=0; i<numtri; i++) {
1666                         fputc('f', fp);
1667                         for(j=0; j<3; j++) {
1668                                 unsigned int idx = *idxptr++ + 1 + voffs;
1669                                 fprintf(fp, fmtstr[aflags], idx, idx, idx);
1670                         }
1671                         fputc('\n', fp);
1672                 }
1673         } else {
1674                 int numtri = cm->nverts / 3;
1675                 unsigned int idx = 1 + voffs;
1676                 for(i=0; i<numtri; i++) {
1677                         fputc('f', fp);
1678                         for(j=0; j<3; j++) {
1679                                 fprintf(fp, fmtstr[aflags], idx, idx, idx);
1680                                 ++idx;
1681                         }
1682                         fputc('\n', fp);
1683                 }
1684         }
1685         return 0;
1686 }
1687
1688 static void clear_mtl(struct cmesh_material *mtl)
1689 {
1690         int i;
1691         if(!mtl) return;
1692         free(mtl->name);
1693         for(i=0; i<CMESH_NUM_TEX; i++) {
1694                 free(mtl->tex[i].name);
1695         }
1696         *mtl = defmtl;
1697 }
1698
1699 static void clone_mtl(struct cmesh_material *dest, struct cmesh_material *src)
1700 {
1701         int i;
1702         *dest = *src;
1703         if(src->name) dest->name = strdup_nf(src->name);
1704         for(i=0; i<CMESH_NUM_TEX; i++) {
1705                 if(src->tex[i].name) {
1706                         dest->tex[i].name = strdup_nf(src->tex[i].name);
1707                 }
1708         }
1709 }