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