CMake fixes for r38303 (splitting up the outliner code).
[blender.git] / source / blender / blenkernel / intern / cdderivedmesh.c
1 /*
2 * $Id$
3 *
4 * ***** BEGIN GPL LICENSE BLOCK *****
5 *
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License
8 * as published by the Free Software Foundation; either version 2
9 * of the License, or (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software  Foundation,
18 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19 *
20 * The Original Code is Copyright (C) 2006 Blender Foundation.
21 * All rights reserved.
22 *
23 * The Original Code is: all of this file.
24 *
25 * Contributor(s): Ben Batt <benbatt@gmail.com>
26 *
27 * ***** END GPL LICENSE BLOCK *****
28 *
29 * Implementation of CDDerivedMesh.
30 *
31 * BKE_cdderivedmesh.h contains the function prototypes for this file.
32 *
33 */
34
35 /** \file blender/blenkernel/intern/cdderivedmesh.c
36  *  \ingroup bke
37  */
38  
39
40 /* TODO maybe BIF_gl.h should include string.h? */
41 #include <string.h>
42 #include "BIF_gl.h"
43
44 #include "BLI_blenlib.h"
45 #include "BLI_edgehash.h"
46 #include "BLI_editVert.h"
47 #include "BLI_math.h"
48 #include "BLI_pbvh.h"
49 #include "BLI_utildefines.h"
50
51 #include "BKE_cdderivedmesh.h"
52 #include "BKE_global.h"
53 #include "BKE_mesh.h"
54 #include "BKE_paint.h"
55
56
57 #include "DNA_meshdata_types.h"
58 #include "DNA_object_types.h"
59 #include "DNA_curve_types.h" /* for Curve */
60
61 #include "MEM_guardedalloc.h"
62
63 #include "GPU_buffers.h"
64 #include "GPU_draw.h"
65 #include "GPU_extensions.h"
66 #include "GPU_material.h"
67
68 #include <string.h>
69 #include <limits.h>
70 #include <math.h>
71
72 typedef struct {
73         DerivedMesh dm;
74
75         /* these point to data in the DerivedMesh custom data layers,
76            they are only here for efficiency and convenience **/
77         MVert *mvert;
78         MEdge *medge;
79         MFace *mface;
80
81         /* Cached */
82         struct PBVH *pbvh;
83         int pbvh_draw;
84
85         /* Mesh connectivity */
86         struct ListBase *fmap;
87         struct IndexNode *fmap_mem;
88 } CDDerivedMesh;
89
90 /**************** DerivedMesh interface functions ****************/
91 static int cdDM_getNumVerts(DerivedMesh *dm)
92 {
93         return dm->numVertData;
94 }
95
96 static int cdDM_getNumEdges(DerivedMesh *dm)
97 {
98         return dm->numEdgeData;
99 }
100
101 static int cdDM_getNumFaces(DerivedMesh *dm)
102 {
103         return dm->numFaceData;
104 }
105
106 static void cdDM_getVert(DerivedMesh *dm, int index, MVert *vert_r)
107 {
108         CDDerivedMesh *cddm = (CDDerivedMesh *)dm;
109         *vert_r = cddm->mvert[index];
110 }
111
112 static void cdDM_getEdge(DerivedMesh *dm, int index, MEdge *edge_r)
113 {
114         CDDerivedMesh *cddm = (CDDerivedMesh *)dm;
115         *edge_r = cddm->medge[index];
116 }
117
118 static void cdDM_getFace(DerivedMesh *dm, int index, MFace *face_r)
119 {
120         CDDerivedMesh *cddm = (CDDerivedMesh *)dm;
121         *face_r = cddm->mface[index];
122 }
123
124 static void cdDM_copyVertArray(DerivedMesh *dm, MVert *vert_r)
125 {
126         CDDerivedMesh *cddm = (CDDerivedMesh *)dm;
127         memcpy(vert_r, cddm->mvert, sizeof(*vert_r) * dm->numVertData);
128 }
129
130 static void cdDM_copyEdgeArray(DerivedMesh *dm, MEdge *edge_r)
131 {
132         CDDerivedMesh *cddm = (CDDerivedMesh *)dm;
133         memcpy(edge_r, cddm->medge, sizeof(*edge_r) * dm->numEdgeData);
134 }
135
136 static void cdDM_copyFaceArray(DerivedMesh *dm, MFace *face_r)
137 {
138         CDDerivedMesh *cddm = (CDDerivedMesh *)dm;
139         memcpy(face_r, cddm->mface, sizeof(*face_r) * dm->numFaceData);
140 }
141
142 static void cdDM_getMinMax(DerivedMesh *dm, float min_r[3], float max_r[3])
143 {
144         CDDerivedMesh *cddm = (CDDerivedMesh*) dm;
145         int i;
146
147         if (dm->numVertData) {
148                 for (i=0; i<dm->numVertData; i++) {
149                         DO_MINMAX(cddm->mvert[i].co, min_r, max_r);
150                 }
151         } else {
152                 min_r[0] = min_r[1] = min_r[2] = max_r[0] = max_r[1] = max_r[2] = 0.0;
153         }
154 }
155
156 static void cdDM_getVertCo(DerivedMesh *dm, int index, float co_r[3])
157 {
158         CDDerivedMesh *cddm = (CDDerivedMesh*) dm;
159
160         VECCOPY(co_r, cddm->mvert[index].co);
161 }
162
163 static void cdDM_getVertCos(DerivedMesh *dm, float (*cos_r)[3])
164 {
165         MVert *mv = CDDM_get_verts(dm);
166         int i;
167
168         for(i = 0; i < dm->numVertData; i++, mv++)
169                 VECCOPY(cos_r[i], mv->co);
170 }
171
172 static void cdDM_getVertNo(DerivedMesh *dm, int index, float no_r[3])
173 {
174         CDDerivedMesh *cddm = (CDDerivedMesh*) dm;
175         normal_short_to_float_v3(no_r, cddm->mvert[index].no);
176 }
177
178 static ListBase *cdDM_getFaceMap(Object *ob, DerivedMesh *dm)
179 {
180         CDDerivedMesh *cddm = (CDDerivedMesh*) dm;
181
182         if(!cddm->fmap && ob->type == OB_MESH) {
183                 Mesh *me= ob->data;
184
185                 create_vert_face_map(&cddm->fmap, &cddm->fmap_mem, me->mface,
186                                          me->totvert, me->totface);
187         }
188
189         return cddm->fmap;
190 }
191
192 static int can_pbvh_draw(Object *ob, DerivedMesh *dm)
193 {
194         CDDerivedMesh *cddm = (CDDerivedMesh*) dm;
195         Mesh *me= ob->data;
196         int deformed= 0;
197
198         /* active modifiers means extra deformation, which can't be handled correct
199            on bith of PBVH and sculpt "layer" levels, so use PBVH only for internal brush
200            stuff and show final DerivedMesh so user would see actual object shape */
201         deformed|= ob->sculpt->modifiers_active;
202
203         /* as in case with modifiers, we can't synchronize deformation made against
204            PBVH and non-locked keyblock, so also use PBVH only for brushes and
205            final DM to give final result to user */
206         deformed|= ob->sculpt->kb && (ob->shapeflag&OB_SHAPE_LOCK) == 0;
207
208         if(deformed)
209                 return 0;
210
211         return (cddm->mvert == me->mvert) || ob->sculpt->kb;
212 }
213
214 static struct PBVH *cdDM_getPBVH(Object *ob, DerivedMesh *dm)
215 {
216         CDDerivedMesh *cddm = (CDDerivedMesh*) dm;
217
218         if(!ob) {
219                 cddm->pbvh= NULL;
220                 return NULL;
221         }
222
223         if(!ob->sculpt)
224                 return NULL;
225         if(ob->sculpt->pbvh) {
226                 cddm->pbvh= ob->sculpt->pbvh;
227                 cddm->pbvh_draw = can_pbvh_draw(ob, dm);
228         }
229
230         /* always build pbvh from original mesh, and only use it for drawing if
231            this derivedmesh is just original mesh. it's the multires subsurf dm
232            that this is actually for, to support a pbvh on a modified mesh */
233         if(!cddm->pbvh && ob->type == OB_MESH) {
234                 SculptSession *ss= ob->sculpt;
235                 Mesh *me= ob->data;
236                 cddm->pbvh = BLI_pbvh_new();
237                 cddm->pbvh_draw = can_pbvh_draw(ob, dm);
238                 BLI_pbvh_build_mesh(cddm->pbvh, me->mface, me->mvert,
239                                    me->totface, me->totvert);
240
241                 if(ss->modifiers_active && ob->derivedDeform) {
242                         DerivedMesh *deformdm= ob->derivedDeform;
243                         float (*vertCos)[3];
244                         int totvert;
245
246                         totvert= deformdm->getNumVerts(deformdm);
247                         vertCos= MEM_callocN(3*totvert*sizeof(float), "cdDM_getPBVH vertCos");
248                         deformdm->getVertCos(deformdm, vertCos);
249                         BLI_pbvh_apply_vertCos(cddm->pbvh, vertCos);
250                         MEM_freeN(vertCos);
251                 }
252         }
253
254         return cddm->pbvh;
255 }
256
257 /* update vertex normals so that drawing smooth faces works during sculpt
258    TODO: proper fix is to support the pbvh in all drawing modes */
259 static void cdDM_update_normals_from_pbvh(DerivedMesh *dm)
260 {
261         CDDerivedMesh *cddm = (CDDerivedMesh*) dm;
262         float (*face_nors)[3];
263
264         if(!cddm->pbvh || !cddm->pbvh_draw || !dm->numFaceData)
265                 return;
266
267         face_nors = CustomData_get_layer(&dm->faceData, CD_NORMAL);
268
269         BLI_pbvh_update(cddm->pbvh, PBVH_UpdateNormals, face_nors);
270 }
271
272 static void cdDM_drawVerts(DerivedMesh *dm)
273 {
274         CDDerivedMesh *cddm = (CDDerivedMesh*) dm;
275         MVert *mv = cddm->mvert;
276         int i;
277
278         if( GPU_buffer_legacy(dm) ) {
279                 glBegin(GL_POINTS);
280                 for(i = 0; i < dm->numVertData; i++, mv++)
281                         glVertex3fv(mv->co);
282                 glEnd();
283         }
284         else {  /* use OpenGL VBOs or Vertex Arrays instead for better, faster rendering */
285                 GPU_vertex_setup(dm);
286                 if( !GPU_buffer_legacy(dm) ) {
287                         if(dm->drawObject->nelements)   glDrawArrays(GL_POINTS,0, dm->drawObject->nelements);
288                         else                                                    glDrawArrays(GL_POINTS,0, dm->drawObject->nlooseverts);
289                 }
290                 GPU_buffer_unbind();
291         }
292 }
293
294 static void cdDM_drawUVEdges(DerivedMesh *dm)
295 {
296         CDDerivedMesh *cddm = (CDDerivedMesh*) dm;
297         MFace *mf = cddm->mface;
298         MTFace *tf = DM_get_face_data_layer(dm, CD_MTFACE);
299         int i;
300
301         if(mf) {
302                 if( GPU_buffer_legacy(dm) ) {
303                         glBegin(GL_LINES);
304                         for(i = 0; i < dm->numFaceData; i++, mf++, tf++) {
305                                 if(!(mf->flag&ME_HIDE)) {
306                                         glVertex2fv(tf->uv[0]);
307                                         glVertex2fv(tf->uv[1]);
308
309                                         glVertex2fv(tf->uv[1]);
310                                         glVertex2fv(tf->uv[2]);
311
312                                         if(!mf->v4) {
313                                                 glVertex2fv(tf->uv[2]);
314                                                 glVertex2fv(tf->uv[0]);
315                                         } else {
316                                                 glVertex2fv(tf->uv[2]);
317                                                 glVertex2fv(tf->uv[3]);
318
319                                                 glVertex2fv(tf->uv[3]);
320                                                 glVertex2fv(tf->uv[0]);
321                                         }
322                                 }
323                         }
324                         glEnd();
325                 }
326                 else {
327                         int prevstart = 0;
328                         int prevdraw = 1;
329                         int draw = 1;
330                         int curpos = 0;
331
332                         GPU_uvedge_setup(dm);
333                         if( !GPU_buffer_legacy(dm) ) {
334                                 for(i = 0; i < dm->numFaceData; i++, mf++) {
335                                         if(!(mf->flag&ME_HIDE)) {
336                                                 draw = 1;
337                                         } 
338                                         else {
339                                                 draw = 0;
340                                         }
341                                         if( prevdraw != draw ) {
342                                                 if( prevdraw > 0 && (curpos-prevstart) > 0) {
343                                                         glDrawArrays(GL_LINES,prevstart,curpos-prevstart);
344                                                 }
345                                                 prevstart = curpos;
346                                         }
347                                         if( mf->v4 ) {
348                                                 curpos += 8;
349                                         }
350                                         else {
351                                                 curpos += 6;
352                                         }
353                                         prevdraw = draw;
354                                 }
355                                 if( prevdraw > 0 && (curpos-prevstart) > 0 ) {
356                                         glDrawArrays(GL_LINES,prevstart,curpos-prevstart);
357                                 }
358                         }
359                         GPU_buffer_unbind();
360                 }
361         }
362 }
363
364 static void cdDM_drawEdges(DerivedMesh *dm, int drawLooseEdges, int drawAllEdges)
365 {
366         CDDerivedMesh *cddm = (CDDerivedMesh*) dm;
367         MVert *mvert = cddm->mvert;
368         MEdge *medge = cddm->medge;
369         int i;
370         
371         if( GPU_buffer_legacy(dm) ) {
372                 DEBUG_VBO( "Using legacy code. cdDM_drawEdges\n" );
373                 glBegin(GL_LINES);
374                 for(i = 0; i < dm->numEdgeData; i++, medge++) {
375                         if((drawAllEdges || (medge->flag&ME_EDGEDRAW))
376                            && (drawLooseEdges || !(medge->flag&ME_LOOSEEDGE))) {
377                                 glVertex3fv(mvert[medge->v1].co);
378                                 glVertex3fv(mvert[medge->v2].co);
379                         }
380                 }
381                 glEnd();
382         }
383         else {  /* use OpenGL VBOs or Vertex Arrays instead for better, faster rendering */
384                 int prevstart = 0;
385                 int prevdraw = 1;
386                 int draw = 1;
387
388                 GPU_edge_setup(dm);
389                 if( !GPU_buffer_legacy(dm) ) {
390                         for(i = 0; i < dm->numEdgeData; i++, medge++) {
391                                 if((drawAllEdges || (medge->flag&ME_EDGEDRAW))
392                                    && (drawLooseEdges || !(medge->flag&ME_LOOSEEDGE))) {
393                                         draw = 1;
394                                 } 
395                                 else {
396                                         draw = 0;
397                                 }
398                                 if( prevdraw != draw ) {
399                                         if( prevdraw > 0 && (i-prevstart) > 0 ) {
400                                                 GPU_buffer_draw_elements( dm->drawObject->edges, GL_LINES, prevstart*2, (i-prevstart)*2  );
401                                         }
402                                         prevstart = i;
403                                 }
404                                 prevdraw = draw;
405                         }
406                         if( prevdraw > 0 && (i-prevstart) > 0 ) {
407                                 GPU_buffer_draw_elements( dm->drawObject->edges, GL_LINES, prevstart*2, (i-prevstart)*2  );
408                         }
409                 }
410                 GPU_buffer_unbind();
411         }
412 }
413
414 static void cdDM_drawLooseEdges(DerivedMesh *dm)
415 {
416         CDDerivedMesh *cddm = (CDDerivedMesh*) dm;
417         MVert *mvert = cddm->mvert;
418         MEdge *medge = cddm->medge;
419         int i;
420
421         if( GPU_buffer_legacy(dm) ) {
422                 DEBUG_VBO( "Using legacy code. cdDM_drawLooseEdges\n" );
423                 glBegin(GL_LINES);
424                 for(i = 0; i < dm->numEdgeData; i++, medge++) {
425                         if(medge->flag&ME_LOOSEEDGE) {
426                                 glVertex3fv(mvert[medge->v1].co);
427                                 glVertex3fv(mvert[medge->v2].co);
428                         }
429                 }
430                 glEnd();
431         }
432         else {  /* use OpenGL VBOs or Vertex Arrays instead for better, faster rendering */
433                 int prevstart = 0;
434                 int prevdraw = 1;
435                 int draw = 1;
436
437                 GPU_edge_setup(dm);
438                 if( !GPU_buffer_legacy(dm) ) {
439                         for(i = 0; i < dm->numEdgeData; i++, medge++) {
440                                 if(medge->flag&ME_LOOSEEDGE) {
441                                         draw = 1;
442                                 } 
443                                 else {
444                                         draw = 0;
445                                 }
446                                 if( prevdraw != draw ) {
447                                         if( prevdraw > 0 && (i-prevstart) > 0) {
448                                                 GPU_buffer_draw_elements( dm->drawObject->edges, GL_LINES, prevstart*2, (i-prevstart)*2  );
449                                         }
450                                         prevstart = i;
451                                 }
452                                 prevdraw = draw;
453                         }
454                         if( prevdraw > 0 && (i-prevstart) > 0 ) {
455                                 GPU_buffer_draw_elements( dm->drawObject->edges, GL_LINES, prevstart*2, (i-prevstart)*2  );
456                         }
457                 }
458                 GPU_buffer_unbind();
459         }
460 }
461
462 static void cdDM_drawFacesSolid(DerivedMesh *dm,
463                                 float (*partial_redraw_planes)[4],
464                                 int UNUSED(fast), int (*setMaterial)(int, void *attribs))
465 {
466         CDDerivedMesh *cddm = (CDDerivedMesh*) dm;
467         MVert *mvert = cddm->mvert;
468         MFace *mface = cddm->mface;
469         float *nors= dm->getFaceDataArray(dm, CD_NORMAL);
470         int a, glmode = -1, shademodel = -1, matnr = -1, drawCurrentMat = 1;
471
472 #define PASSVERT(index) {                                               \
473         if(shademodel == GL_SMOOTH) {                           \
474                 short *no = mvert[index].no;                    \
475                 glNormal3sv(no);                                                \
476         }                                                                                       \
477         glVertex3fv(mvert[index].co);   \
478 }
479
480         if(cddm->pbvh && cddm->pbvh_draw) {
481                 if(dm->numFaceData) {
482                         float (*face_nors)[3] = CustomData_get_layer(&dm->faceData, CD_NORMAL);
483
484                         /* should be per face */
485                         if(!setMaterial(mface->mat_nr+1, NULL))
486                                 return;
487
488                         glShadeModel((mface->flag & ME_SMOOTH)? GL_SMOOTH: GL_FLAT);
489                         BLI_pbvh_draw(cddm->pbvh, partial_redraw_planes, face_nors, (mface->flag & ME_SMOOTH));
490                         glShadeModel(GL_FLAT);
491                 }
492
493                 return;
494         }
495
496         if( GPU_buffer_legacy(dm) ) {
497                 DEBUG_VBO( "Using legacy code. cdDM_drawFacesSolid\n" );
498                 glBegin(glmode = GL_QUADS);
499                 for(a = 0; a < dm->numFaceData; a++, mface++) {
500                         int new_glmode, new_matnr, new_shademodel;
501
502                         new_glmode = mface->v4?GL_QUADS:GL_TRIANGLES;
503                         new_matnr = mface->mat_nr + 1;
504                         new_shademodel = (mface->flag & ME_SMOOTH)?GL_SMOOTH:GL_FLAT;
505                         
506                         if(new_glmode != glmode || new_matnr != matnr
507                            || new_shademodel != shademodel) {
508                                 glEnd();
509
510                                 drawCurrentMat = setMaterial(matnr = new_matnr, NULL);
511
512                                 glShadeModel(shademodel = new_shademodel);
513                                 glBegin(glmode = new_glmode);
514                         } 
515                         
516                         if(drawCurrentMat) {
517                                 if(shademodel == GL_FLAT) {
518                                         if (nors) {
519                                                 glNormal3fv(nors);
520                                         }
521                                         else {
522                                                 /* TODO make this better (cache facenormals as layer?) */
523                                                 float nor[3];
524                                                 if(mface->v4) {
525                                                         normal_quad_v3( nor,mvert[mface->v1].co, mvert[mface->v2].co, mvert[mface->v3].co, mvert[mface->v4].co);
526                                                 } else {
527                                                         normal_tri_v3( nor,mvert[mface->v1].co, mvert[mface->v2].co, mvert[mface->v3].co);
528                                                 }
529                                                 glNormal3fv(nor);
530                                         }
531                                 }
532
533                                 PASSVERT(mface->v1);
534                                 PASSVERT(mface->v2);
535                                 PASSVERT(mface->v3);
536                                 if(mface->v4) {
537                                         PASSVERT(mface->v4);
538                                 }
539                         }
540
541                         if(nors) nors += 3;
542                 }
543                 glEnd();
544         }
545         else {  /* use OpenGL VBOs or Vertex Arrays instead for better, faster rendering */
546                 GPU_vertex_setup( dm );
547                 GPU_normal_setup( dm );
548                 if( !GPU_buffer_legacy(dm) ) {
549                         glShadeModel(GL_SMOOTH);
550                         for( a = 0; a < dm->drawObject->nmaterials; a++ ) {
551                                 if( setMaterial(dm->drawObject->materials[a].mat_nr+1, NULL) )
552                                         glDrawArrays(GL_TRIANGLES, dm->drawObject->materials[a].start, dm->drawObject->materials[a].end-dm->drawObject->materials[a].start);
553                         }
554                 }
555                 GPU_buffer_unbind( );
556         }
557
558 #undef PASSVERT
559         glShadeModel(GL_FLAT);
560 }
561
562 static void cdDM_drawFacesColored(DerivedMesh *dm, int useTwoSided, unsigned char *col1, unsigned char *col2)
563 {
564         CDDerivedMesh *cddm = (CDDerivedMesh*) dm;
565         int a, glmode;
566         unsigned char *cp1, *cp2;
567         MVert *mvert = cddm->mvert;
568         MFace *mface = cddm->mface;
569
570         cp1 = col1;
571         if(col2) {
572                 cp2 = col2;
573         } else {
574                 cp2 = NULL;
575                 useTwoSided = 0;
576         }
577
578         /* there's a conflict here... twosided colors versus culling...? */
579         /* defined by history, only texture faces have culling option */
580         /* we need that as mesh option builtin, next to double sided lighting */
581         if(col2) {
582                 glEnable(GL_CULL_FACE);
583         }
584
585         cdDM_update_normals_from_pbvh(dm);
586
587         if( GPU_buffer_legacy(dm) ) {
588                 DEBUG_VBO( "Using legacy code. cdDM_drawFacesColored\n" );
589                 glShadeModel(GL_SMOOTH);
590                 glBegin(glmode = GL_QUADS);
591                 for(a = 0; a < dm->numFaceData; a++, mface++, cp1 += 16) {
592                         int new_glmode = mface->v4?GL_QUADS:GL_TRIANGLES;
593
594                         if(new_glmode != glmode) {
595                                 glEnd();
596                                 glBegin(glmode = new_glmode);
597                         }
598                                 
599                         glColor3ubv(cp1+0);
600                         glVertex3fv(mvert[mface->v1].co);
601                         glColor3ubv(cp1+4);
602                         glVertex3fv(mvert[mface->v2].co);
603                         glColor3ubv(cp1+8);
604                         glVertex3fv(mvert[mface->v3].co);
605                         if(mface->v4) {
606                                 glColor3ubv(cp1+12);
607                                 glVertex3fv(mvert[mface->v4].co);
608                         }
609                                 
610                         if(useTwoSided) {
611                                 glColor3ubv(cp2+8);
612                                 glVertex3fv(mvert[mface->v3].co );
613                                 glColor3ubv(cp2+4);
614                                 glVertex3fv(mvert[mface->v2].co );
615                                 glColor3ubv(cp2+0);
616                                 glVertex3fv(mvert[mface->v1].co );
617                                 if(mface->v4) {
618                                         glColor3ubv(cp2+12);
619                                         glVertex3fv(mvert[mface->v4].co );
620                                 }
621                         }
622                         if(col2) cp2 += 16;
623                 }
624                 glEnd();
625         }
626         else { /* use OpenGL VBOs or Vertex Arrays instead for better, faster rendering */
627                 GPU_color4_upload(dm,cp1);
628                 GPU_vertex_setup(dm);
629                 GPU_color_setup(dm);
630                 if( !GPU_buffer_legacy(dm) ) {
631                         glShadeModel(GL_SMOOTH);
632                         glDrawArrays(GL_TRIANGLES, 0, dm->drawObject->nelements);
633
634                         if( useTwoSided ) {
635                                 GPU_color4_upload(dm,cp2);
636                                 GPU_color_setup(dm);
637                                 glCullFace(GL_FRONT);
638                                 glDrawArrays(GL_TRIANGLES, 0, dm->drawObject->nelements);
639                                 glCullFace(GL_BACK);
640                         }
641                 }
642                 GPU_buffer_unbind();
643         }
644
645         glShadeModel(GL_FLAT);
646         glDisable(GL_CULL_FACE);
647 }
648
649 static void cdDM_drawFacesTex_common(DerivedMesh *dm,
650                            int (*drawParams)(MTFace *tface, MCol *mcol, int matnr),
651                            int (*drawParamsMapped)(void *userData, int index),
652                            void *userData) 
653 {
654         CDDerivedMesh *cddm = (CDDerivedMesh*) dm;
655         MVert *mv = cddm->mvert;
656         MFace *mf = DM_get_face_data_layer(dm, CD_MFACE);
657         MCol *realcol = dm->getFaceDataArray(dm, CD_TEXTURE_MCOL);
658         float *nors= dm->getFaceDataArray(dm, CD_NORMAL);
659         MTFace *tf = DM_get_face_data_layer(dm, CD_MTFACE);
660         int i, j, orig, *index = DM_get_face_data_layer(dm, CD_ORIGINDEX);
661         int startFace = 0, lastFlag = 0xdeadbeef;
662         MCol *mcol = dm->getFaceDataArray(dm, CD_WEIGHT_MCOL);
663         if(!mcol)
664                 mcol = dm->getFaceDataArray(dm, CD_MCOL);
665
666         cdDM_update_normals_from_pbvh(dm);
667
668         if( GPU_buffer_legacy(dm) ) {
669                 DEBUG_VBO( "Using legacy code. cdDM_drawFacesTex_common\n" );
670                 for(i = 0; i < dm->numFaceData; i++, mf++) {
671                         MVert *mvert;
672                         int flag;
673                         unsigned char *cp = NULL;
674
675                         if(drawParams) {
676                                 flag = drawParams(tf? &tf[i]: NULL, mcol? &mcol[i*4]: NULL, mf->mat_nr);
677                         }
678                         else {
679                                 if(index) {
680                                         orig = *index++;
681                                         if(orig == ORIGINDEX_NONE)              { if(nors) nors += 3; continue; }
682                                         if(drawParamsMapped) flag = drawParamsMapped(userData, orig);
683                                         else    { if(nors) nors += 3; continue; }
684                                 }
685                                 else
686                                         if(drawParamsMapped) flag = drawParamsMapped(userData, i);
687                                         else    { if(nors) nors += 3; continue; }
688                         }
689                         
690                         if(flag != 0) {
691                                 if (flag==1 && mcol)
692                                         cp= (unsigned char*) &mcol[i*4];
693
694                                 if(!(mf->flag&ME_SMOOTH)) {
695                                         if (nors) {
696                                                 glNormal3fv(nors);
697                                         }
698                                         else {
699                                                 float nor[3];
700                                                 if(mf->v4) {
701                                                         normal_quad_v3( nor,mv[mf->v1].co, mv[mf->v2].co, mv[mf->v3].co, mv[mf->v4].co);
702                                                 } else {
703                                                         normal_tri_v3( nor,mv[mf->v1].co, mv[mf->v2].co, mv[mf->v3].co);
704                                                 }
705                                                 glNormal3fv(nor);
706                                         }
707                                 }
708
709                                 glBegin(mf->v4?GL_QUADS:GL_TRIANGLES);
710                                 if(tf) glTexCoord2fv(tf[i].uv[0]);
711                                 if(cp) glColor3ub(cp[3], cp[2], cp[1]);
712                                 mvert = &mv[mf->v1];
713                                 if(mf->flag&ME_SMOOTH) glNormal3sv(mvert->no);
714                                 glVertex3fv(mvert->co);
715                                         
716                                 if(tf) glTexCoord2fv(tf[i].uv[1]);
717                                 if(cp) glColor3ub(cp[7], cp[6], cp[5]);
718                                 mvert = &mv[mf->v2];
719                                 if(mf->flag&ME_SMOOTH) glNormal3sv(mvert->no);
720                                 glVertex3fv(mvert->co);
721
722                                 if(tf) glTexCoord2fv(tf[i].uv[2]);
723                                 if(cp) glColor3ub(cp[11], cp[10], cp[9]);
724                                 mvert = &mv[mf->v3];
725                                 if(mf->flag&ME_SMOOTH) glNormal3sv(mvert->no);
726                                 glVertex3fv(mvert->co);
727
728                                 if(mf->v4) {
729                                         if(tf) glTexCoord2fv(tf[i].uv[3]);
730                                         if(cp) glColor3ub(cp[15], cp[14], cp[13]);
731                                         mvert = &mv[mf->v4];
732                                         if(mf->flag&ME_SMOOTH) glNormal3sv(mvert->no);
733                                         glVertex3fv(mvert->co);
734                                 }
735                                 glEnd();
736                         }
737                         
738                         if(nors) nors += 3;
739                 }
740         } else { /* use OpenGL VBOs or Vertex Arrays instead for better, faster rendering */
741                 MCol *col = realcol;
742                 if(!col)
743                         col = mcol;
744
745                 GPU_vertex_setup( dm );
746                 GPU_normal_setup( dm );
747                 GPU_uv_setup( dm );
748                 if( col != NULL ) {
749                         /*if( realcol && dm->drawObject->colType == CD_TEXTURE_MCOL )  {
750                                 col = 0;
751                         } else if( mcol && dm->drawObject->colType == CD_MCOL ) {
752                                 col = 0;
753                         }
754                         
755                         if( col != 0 ) {*/
756                                 unsigned char *colors = MEM_mallocN(dm->getNumFaces(dm)*4*3*sizeof(unsigned char), "cdDM_drawFacesTex_common");
757                                 for( i=0; i < dm->getNumFaces(dm); i++ ) {
758                                         for( j=0; j < 4; j++ ) {
759                                                 colors[i*12+j*3] = col[i*4+j].r;
760                                                 colors[i*12+j*3+1] = col[i*4+j].g;
761                                                 colors[i*12+j*3+2] = col[i*4+j].b;
762                                         }
763                                 }
764                                 GPU_color3_upload(dm,colors);
765                                 MEM_freeN(colors);
766                                 if(realcol)
767                                         dm->drawObject->colType = CD_TEXTURE_MCOL;
768                                 else if(mcol)
769                                         dm->drawObject->colType = CD_MCOL;
770                         //}
771                         GPU_color_setup( dm );
772                 }
773
774                 if( !GPU_buffer_legacy(dm) ) {
775                         /* warning!, this logic is incorrect, see bug [#27175]
776                          * firstly, there are no checks for changes in context, such as texface image.
777                          * secondly, drawParams() sets the GL context, so checking if there is a change
778                          * from lastFlag is too late once glDrawArrays() runs, since drawing the arrays
779                          * will use the modified, OpenGL settings.
780                          * 
781                          * However its tricky to fix this without duplicating the internal logic
782                          * of drawParams(), perhaps we need an argument like...
783                          * drawParams(..., keep_gl_state_but_return_when_changed) ?.
784                          *
785                          * We could also just disable VBO's here, since texface may be deprecated - campbell.
786                          */
787                         
788                         glShadeModel( GL_SMOOTH );
789                         lastFlag = 0;
790                         for(i = 0; i < dm->drawObject->nelements/3; i++) {
791                                 int actualFace = dm->drawObject->faceRemap[i];
792                                 int flag = 1;
793
794                                 if(drawParams) {
795                                         flag = drawParams(tf? &tf[actualFace]: NULL, mcol? &mcol[actualFace*4]: NULL, mf[actualFace].mat_nr);
796                                 }
797                                 else {
798                                         if(index) {
799                                                 orig = index[actualFace];
800                                                 if(orig == ORIGINDEX_NONE) continue;
801                                                 if(drawParamsMapped)
802                                                         flag = drawParamsMapped(userData, orig);
803                                         }
804                                         else
805                                                 if(drawParamsMapped)
806                                                         flag = drawParamsMapped(userData, actualFace);
807                                 }
808                                 if( flag != lastFlag ) {
809                                         if( startFace < i ) {
810                                                 if( lastFlag != 0 ) { /* if the flag is 0 it means the face is hidden or invisible */
811                                                         if (lastFlag==1 && col)
812                                                                 GPU_color_switch(1);
813                                                         else
814                                                                 GPU_color_switch(0);
815                                                         glDrawArrays(GL_TRIANGLES,startFace*3,(i-startFace)*3);
816                                                 }
817                                         }
818                                         lastFlag = flag;
819                                         startFace = i;
820                                 }
821                         }
822                         if( startFace < dm->drawObject->nelements/3 ) {
823                                 if( lastFlag != 0 ) { /* if the flag is 0 it means the face is hidden or invisible */
824                                         if (lastFlag==1 && col)
825                                                 GPU_color_switch(1);
826                                         else
827                                                 GPU_color_switch(0);
828                                         glDrawArrays(GL_TRIANGLES,startFace*3,dm->drawObject->nelements-startFace*3);
829                                 }
830                         }
831                 }
832
833                 GPU_buffer_unbind();
834                 glShadeModel( GL_FLAT );
835         }
836 }
837
838 static void cdDM_drawFacesTex(DerivedMesh *dm, int (*setDrawOptions)(MTFace *tface, MCol *mcol, int matnr))
839 {
840         cdDM_drawFacesTex_common(dm, setDrawOptions, NULL, NULL);
841 }
842
843 static void cdDM_drawMappedFaces(DerivedMesh *dm, int (*setDrawOptions)(void *userData, int index, int *drawSmooth_r), void *userData, int useColors, int (*setMaterial)(int, void *attribs))
844 {
845         CDDerivedMesh *cddm = (CDDerivedMesh*) dm;
846         MVert *mv = cddm->mvert;
847         MFace *mf = cddm->mface;
848         MCol *mc;
849         float *nors= dm->getFaceDataArray(dm, CD_NORMAL);
850         int i, orig, *index = DM_get_face_data_layer(dm, CD_ORIGINDEX);
851
852         mc = DM_get_face_data_layer(dm, CD_ID_MCOL);
853         if(!mc)
854                 mc = DM_get_face_data_layer(dm, CD_WEIGHT_MCOL);
855         if(!mc)
856                 mc = DM_get_face_data_layer(dm, CD_MCOL);
857
858         cdDM_update_normals_from_pbvh(dm);
859
860         /* back-buffer always uses legacy since VBO's would need the
861          * color array temporarily overwritten for drawing, then reset. */
862         if( GPU_buffer_legacy(dm) || G.f & G_BACKBUFSEL) {
863                 DEBUG_VBO( "Using legacy code. cdDM_drawMappedFaces\n" );
864                 for(i = 0; i < dm->numFaceData; i++, mf++) {
865                         int drawSmooth = (mf->flag & ME_SMOOTH);
866                         int draw= 1;
867
868                         orig= (index==NULL) ? i : *index++;
869                         
870                         if(orig == ORIGINDEX_NONE)
871                                 draw= setMaterial(mf->mat_nr + 1, NULL);
872                         else if (setDrawOptions != NULL)
873                                 draw= setDrawOptions(userData, orig, &drawSmooth);
874
875                         if(draw) {
876                                 unsigned char *cp = NULL;
877
878                                 if(useColors && mc)
879                                         cp = (unsigned char *)&mc[i * 4];
880
881                                 glShadeModel(drawSmooth?GL_SMOOTH:GL_FLAT);
882                                 glBegin(mf->v4?GL_QUADS:GL_TRIANGLES);
883
884                                 if (!drawSmooth) {
885                                         if (nors) {
886                                                 glNormal3fv(nors);
887                                         }
888                                         else {
889                                                 float nor[3];
890                                                 if(mf->v4) {
891                                                         normal_quad_v3( nor,mv[mf->v1].co, mv[mf->v2].co, mv[mf->v3].co, mv[mf->v4].co);
892                                                 } else {
893                                                         normal_tri_v3( nor,mv[mf->v1].co, mv[mf->v2].co, mv[mf->v3].co);
894                                                 }
895                                                 glNormal3fv(nor);
896                                         }
897
898                                         if(cp) glColor3ub(cp[3], cp[2], cp[1]);
899                                         glVertex3fv(mv[mf->v1].co);
900                                         if(cp) glColor3ub(cp[7], cp[6], cp[5]);
901                                         glVertex3fv(mv[mf->v2].co);
902                                         if(cp) glColor3ub(cp[11], cp[10], cp[9]);
903                                         glVertex3fv(mv[mf->v3].co);
904                                         if(mf->v4) {
905                                                 if(cp) glColor3ub(cp[15], cp[14], cp[13]);
906                                                 glVertex3fv(mv[mf->v4].co);
907                                         }
908                                 } else {
909                                         if(cp) glColor3ub(cp[3], cp[2], cp[1]);
910                                         glNormal3sv(mv[mf->v1].no);
911                                         glVertex3fv(mv[mf->v1].co);
912                                         if(cp) glColor3ub(cp[7], cp[6], cp[5]);
913                                         glNormal3sv(mv[mf->v2].no);
914                                         glVertex3fv(mv[mf->v2].co);
915                                         if(cp) glColor3ub(cp[11], cp[10], cp[9]);
916                                         glNormal3sv(mv[mf->v3].no);
917                                         glVertex3fv(mv[mf->v3].co);
918                                         if(mf->v4) {
919                                                 if(cp) glColor3ub(cp[15], cp[14], cp[13]);
920                                                 glNormal3sv(mv[mf->v4].no);
921                                                 glVertex3fv(mv[mf->v4].co);
922                                         }
923                                 }
924
925                                 glEnd();
926                         }
927                         
928                         if (nors) nors += 3;
929                 }
930         }
931         else { /* use OpenGL VBOs or Vertex Arrays instead for better, faster rendering */
932                 int prevstart = 0;
933                 GPU_vertex_setup(dm);
934                 GPU_normal_setup(dm);
935                 if( useColors && mc )
936                         GPU_color_setup(dm);
937                 if( !GPU_buffer_legacy(dm) ) {
938                         int tottri = dm->drawObject->nelements/3;
939                         glShadeModel(GL_SMOOTH);
940                         
941                         if(tottri == 0) {
942                                 /* avoid buffer problems in following code */
943                         }
944                         if(setDrawOptions == NULL) {
945                                 /* just draw the entire face array */
946                                 glDrawArrays(GL_TRIANGLES, 0, (tottri-1) * 3);
947                         }
948                         else {
949                                 /* we need to check if the next material changes */
950                                 int next_actualFace= dm->drawObject->faceRemap[0];
951                                 
952                                 for( i = 0; i < tottri; i++ ) {
953                                         //int actualFace = dm->drawObject->faceRemap[i];
954                                         int actualFace = next_actualFace;
955                                         MFace *mface= mf + actualFace;
956                                         int drawSmooth= (mface->flag & ME_SMOOTH);
957                                         int draw = 1;
958
959                                         if(i != tottri-1)
960                                                 next_actualFace= dm->drawObject->faceRemap[i+1];
961
962                                         orig= (index==NULL) ? actualFace : index[actualFace];
963
964                                         if(orig == ORIGINDEX_NONE)
965                                                 draw= setMaterial(mface->mat_nr + 1, NULL);
966                                         else if (setDrawOptions != NULL)
967                                                 draw= setDrawOptions(userData, orig, &drawSmooth);
968         
969                                         /* Goal is to draw as long of a contiguous triangle
970                                            array as possible, so draw when we hit either an
971                                            invisible triangle or at the end of the array */
972                                         if(!draw || i == tottri - 1 || mf[actualFace].mat_nr != mf[next_actualFace].mat_nr) {
973                                                 if(prevstart != i)
974                                                         /* Add one to the length (via `draw')
975                                                            if we're drawing at the end of the array */
976                                                         glDrawArrays(GL_TRIANGLES,prevstart*3, (i-prevstart+draw)*3);
977                                                 prevstart = i + 1;
978                                         }
979                                 }
980                         }
981
982                         glShadeModel(GL_FLAT);
983                 }
984                 GPU_buffer_unbind();
985         }
986 }
987
988 static void cdDM_drawMappedFacesTex(DerivedMesh *dm, int (*setDrawOptions)(void *userData, int index), void *userData)
989 {
990         cdDM_drawFacesTex_common(dm, NULL, setDrawOptions, userData);
991 }
992
993 static void cdDM_drawMappedFacesGLSL(DerivedMesh *dm, int (*setMaterial)(int, void *attribs), int (*setDrawOptions)(void *userData, int index), void *userData)
994 {
995         CDDerivedMesh *cddm = (CDDerivedMesh*) dm;
996         GPUVertexAttribs gattribs;
997         DMVertexAttribs attribs;
998         MVert *mvert = cddm->mvert;
999         MFace *mface = cddm->mface;
1000         MTFace *tf = dm->getFaceDataArray(dm, CD_MTFACE);
1001         float (*nors)[3] = dm->getFaceDataArray(dm, CD_NORMAL);
1002         int a, b, dodraw, matnr, new_matnr;
1003         int transp, new_transp, orig_transp;
1004         int orig, *index = dm->getFaceDataArray(dm, CD_ORIGINDEX);
1005
1006         cdDM_update_normals_from_pbvh(dm);
1007
1008         matnr = -1;
1009         dodraw = 0;
1010         transp = GPU_get_material_blend_mode();
1011         orig_transp = transp;
1012
1013         glShadeModel(GL_SMOOTH);
1014
1015         if( GPU_buffer_legacy(dm) || setDrawOptions != NULL ) {
1016                 DEBUG_VBO( "Using legacy code. cdDM_drawMappedFacesGLSL\n" );
1017                 memset(&attribs, 0, sizeof(attribs));
1018
1019                 glBegin(GL_QUADS);
1020
1021                 for(a = 0; a < dm->numFaceData; a++, mface++) {
1022                         const int smoothnormal = (mface->flag & ME_SMOOTH);
1023                         new_matnr = mface->mat_nr + 1;
1024
1025                         if(new_matnr != matnr) {
1026                                 glEnd();
1027
1028                                 dodraw = setMaterial(matnr = new_matnr, &gattribs);
1029                                 if(dodraw)
1030                                         DM_vertex_attributes_from_gpu(dm, &gattribs, &attribs);
1031
1032                                 glBegin(GL_QUADS);
1033                         }
1034
1035                         if(!dodraw) {
1036                                 continue;
1037                         }
1038                         else if(setDrawOptions) {
1039                                 orig = (index)? index[a]: a;
1040
1041                                 if(orig == ORIGINDEX_NONE) {
1042                                         /* since the material is set by setMaterial(), faces with no
1043                                          * origin can be assumed to be generated by a modifier */ 
1044                                         
1045                                         /* continue */
1046                                 }
1047                                 else if(!setDrawOptions(userData, orig))
1048                                         continue;
1049                         }
1050
1051                         if(tf) {
1052                                 new_transp = tf[a].transp;
1053
1054                                 if(new_transp != transp) {
1055                                         glEnd();
1056
1057                                         if(new_transp == GPU_BLEND_SOLID && orig_transp != GPU_BLEND_SOLID)
1058                                                 GPU_set_material_blend_mode(orig_transp);
1059                                         else
1060                                                 GPU_set_material_blend_mode(new_transp);
1061                                         transp = new_transp;
1062
1063                                         glBegin(GL_QUADS);
1064                                 }
1065                         }
1066
1067                         if(!smoothnormal) {
1068                                 if(nors) {
1069                                         glNormal3fv(nors[a]);
1070                                 }
1071                                 else {
1072                                         /* TODO ideally a normal layer should always be available */
1073                                         float nor[3];
1074                                         if(mface->v4) {
1075                                                 normal_quad_v3( nor,mvert[mface->v1].co, mvert[mface->v2].co, mvert[mface->v3].co, mvert[mface->v4].co);
1076                                         } else {
1077                                                 normal_tri_v3( nor,mvert[mface->v1].co, mvert[mface->v2].co, mvert[mface->v3].co);
1078                                         }
1079                                         glNormal3fv(nor);
1080                                 }
1081                         }
1082
1083 #define PASSVERT(index, vert) {                                                                                                 \
1084                 if(attribs.totorco)                                                                                                                     \
1085                         glVertexAttrib3fvARB(attribs.orco.glIndex, attribs.orco.array[index]);  \
1086                 for(b = 0; b < attribs.tottface; b++) {                                                                         \
1087                         MTFace *tf = &attribs.tface[b].array[a];                                                                \
1088                         glVertexAttrib2fvARB(attribs.tface[b].glIndex, tf->uv[vert]);                   \
1089                 }                                                                                                                                                       \
1090                 for(b = 0; b < attribs.totmcol; b++) {                                                                          \
1091                         MCol *cp = &attribs.mcol[b].array[a*4 + vert];                                                  \
1092                         GLubyte col[4];                                                                                                                 \
1093                         col[0]= cp->b; col[1]= cp->g; col[2]= cp->r; col[3]= cp->a;                             \
1094                         glVertexAttrib4ubvARB(attribs.mcol[b].glIndex, col);                                    \
1095                 }                                                                                                                                                       \
1096                 if(attribs.tottang) {                                                                                                           \
1097                         float *tang = attribs.tang.array[a*4 + vert];                                                   \
1098                         glVertexAttrib4fvARB(attribs.tang.glIndex, tang);                                               \
1099                 }                                                                                                                                                       \
1100                 if(smoothnormal)                                                                                                                        \
1101                         glNormal3sv(mvert[index].no);                                                                                   \
1102                 glVertex3fv(mvert[index].co);                                                                                           \
1103         }
1104
1105                         PASSVERT(mface->v1, 0);
1106                         PASSVERT(mface->v2, 1);
1107                         PASSVERT(mface->v3, 2);
1108                         if(mface->v4)
1109                                 PASSVERT(mface->v4, 3)
1110                         else
1111                                 PASSVERT(mface->v3, 2)
1112
1113 #undef PASSVERT
1114                 }
1115                 glEnd();
1116         }
1117         else {
1118                 GPUBuffer *buffer = NULL;
1119                 char *varray = NULL;
1120                 int numdata = 0, elementsize = 0, offset;
1121                 int start = 0, numfaces = 0, prevdraw = 0, curface = 0;
1122                 int i;
1123
1124                 MFace *mf = mface;
1125                 GPUAttrib datatypes[GPU_MAX_ATTRIB]; /* TODO, messing up when switching materials many times - [#21056]*/
1126                 memset(&attribs, 0, sizeof(attribs));
1127
1128                 GPU_vertex_setup(dm);
1129                 GPU_normal_setup(dm);
1130
1131                 if( !GPU_buffer_legacy(dm) ) {
1132                         for( i = 0; i < dm->drawObject->nelements/3; i++ ) {
1133
1134                                 a = dm->drawObject->faceRemap[i];
1135
1136                                 mface = mf + a;
1137                                 new_matnr = mface->mat_nr + 1;
1138
1139                                 if(new_matnr != matnr ) {
1140                                         numfaces = curface - start;
1141                                         if( numfaces > 0 ) {
1142
1143                                                 if( dodraw ) {
1144
1145                                                         if( numdata != 0 ) {
1146
1147                                                                 GPU_buffer_unlock(buffer);
1148
1149                                                                 GPU_interleaved_attrib_setup(buffer,datatypes,numdata);
1150                                                         }
1151
1152                                                         glDrawArrays(GL_TRIANGLES,start*3,numfaces*3);
1153
1154                                                         if( numdata != 0 ) {
1155
1156                                                                 GPU_buffer_free(buffer, NULL);
1157
1158                                                                 buffer = NULL;
1159                                                         }
1160
1161                                                 }
1162                                         }
1163                                         numdata = 0;
1164                                         start = curface;
1165                                         prevdraw = dodraw;
1166                                         dodraw = setMaterial(matnr = new_matnr, &gattribs);
1167                                         if(dodraw) {
1168                                                 DM_vertex_attributes_from_gpu(dm, &gattribs, &attribs);
1169
1170                                                 if(attribs.totorco) {
1171                                                         datatypes[numdata].index = attribs.orco.glIndex;
1172                                                         datatypes[numdata].size = 3;
1173                                                         datatypes[numdata].type = GL_FLOAT;
1174                                                         numdata++;
1175                                                 }
1176                                                 for(b = 0; b < attribs.tottface; b++) {
1177                                                         datatypes[numdata].index = attribs.tface[b].glIndex;
1178                                                         datatypes[numdata].size = 2;
1179                                                         datatypes[numdata].type = GL_FLOAT;
1180                                                         numdata++;
1181                                                 }       
1182                                                 for(b = 0; b < attribs.totmcol; b++) {
1183                                                         datatypes[numdata].index = attribs.mcol[b].glIndex;
1184                                                         datatypes[numdata].size = 4;
1185                                                         datatypes[numdata].type = GL_UNSIGNED_BYTE;
1186                                                         numdata++;
1187                                                 }       
1188                                                 if(attribs.tottang) {
1189                                                         datatypes[numdata].index = attribs.tang.glIndex;
1190                                                         datatypes[numdata].size = 4;
1191                                                         datatypes[numdata].type = GL_FLOAT;
1192                                                         numdata++;
1193                                                 }
1194                                                 if( numdata != 0 ) {
1195                                                         elementsize = GPU_attrib_element_size( datatypes, numdata );
1196                                                         buffer = GPU_buffer_alloc( elementsize*dm->drawObject->nelements, NULL );
1197                                                         if( buffer == NULL ) {
1198                                                                 GPU_buffer_unbind();
1199                                                                 dm->drawObject->legacy = 1;
1200                                                                 return;
1201                                                         }
1202                                                         varray = GPU_buffer_lock_stream(buffer);
1203                                                         if( varray == NULL ) {
1204                                                                 GPU_buffer_unbind();
1205                                                                 GPU_buffer_free(buffer, NULL);
1206                                                                 dm->drawObject->legacy = 1;
1207                                                                 return;
1208                                                         }
1209                                                 }
1210                                                 else {
1211                                                         /* if the buffer was set, dont use it again.
1212                                                          * prevdraw was assumed true but didnt run so set to false - [#21036] */
1213                                                         prevdraw= 0;
1214                                                         buffer= NULL;
1215                                                 }
1216                                         }
1217                                 }
1218                                 if(!dodraw) {
1219                                         continue;
1220                                 }
1221
1222                                 if(tf) {
1223                                         new_transp = tf[a].transp;
1224
1225                                         if(new_transp != transp) {
1226                                                 numfaces = curface - start;
1227                                                 if( numfaces > 0 ) {
1228                                                         if( dodraw ) {
1229                                                                 if( numdata != 0 ) {
1230                                                                         GPU_buffer_unlock(buffer);
1231                                                                         GPU_interleaved_attrib_setup(buffer,datatypes,numdata);
1232                                                                 }
1233                                                                 glDrawArrays(GL_TRIANGLES,start*3,(curface-start)*3);
1234                                                                 if( numdata != 0 ) {
1235                                                                         varray = GPU_buffer_lock_stream(buffer);
1236                                                                 }
1237                                                         }
1238                                                 }
1239                                                 start = curface;
1240
1241                                                 if(new_transp == GPU_BLEND_SOLID && orig_transp != GPU_BLEND_SOLID)
1242                                                         GPU_set_material_blend_mode(orig_transp);
1243                                                 else
1244                                                         GPU_set_material_blend_mode(new_transp);
1245                                                 transp = new_transp;
1246                                         }
1247                                 }
1248                                 
1249                                 if( numdata != 0 ) {
1250                                         offset = 0;
1251                                         if(attribs.totorco) {
1252                                                 VECCOPY((float *)&varray[elementsize*curface*3],(float *)attribs.orco.array[mface->v1]);
1253                                                 VECCOPY((float *)&varray[elementsize*curface*3+elementsize],(float *)attribs.orco.array[mface->v2]);
1254                                                 VECCOPY((float *)&varray[elementsize*curface*3+elementsize*2],(float *)attribs.orco.array[mface->v3]);
1255                                                 offset += sizeof(float)*3;
1256                                         }
1257                                         for(b = 0; b < attribs.tottface; b++) {
1258                                                 MTFace *tf = &attribs.tface[b].array[a];
1259                                                 VECCOPY2D((float *)&varray[elementsize*curface*3+offset],tf->uv[0]);
1260                                                 VECCOPY2D((float *)&varray[elementsize*curface*3+offset+elementsize],tf->uv[1]);
1261
1262                                                 VECCOPY2D((float *)&varray[elementsize*curface*3+offset+elementsize*2],tf->uv[2]);
1263                                                 offset += sizeof(float)*2;
1264                                         }
1265                                         for(b = 0; b < attribs.totmcol; b++) {
1266                                                 MCol *cp = &attribs.mcol[b].array[a*4 + 0];
1267                                                 GLubyte col[4];
1268                                                 col[0]= cp->b; col[1]= cp->g; col[2]= cp->r; col[3]= cp->a;
1269                                                 QUATCOPY((unsigned char *)&varray[elementsize*curface*3+offset], col);
1270                                                 cp = &attribs.mcol[b].array[a*4 + 1];
1271                                                 col[0]= cp->b; col[1]= cp->g; col[2]= cp->r; col[3]= cp->a;
1272                                                 QUATCOPY((unsigned char *)&varray[elementsize*curface*3+offset+elementsize], col);
1273                                                 cp = &attribs.mcol[b].array[a*4 + 2];
1274                                                 col[0]= cp->b; col[1]= cp->g; col[2]= cp->r; col[3]= cp->a;
1275                                                 QUATCOPY((unsigned char *)&varray[elementsize*curface*3+offset+elementsize*2], col);
1276                                                 offset += sizeof(unsigned char)*4;
1277                                         }       
1278                                         if(attribs.tottang) {
1279                                                 float *tang = attribs.tang.array[a*4 + 0];
1280                                                 QUATCOPY((float *)&varray[elementsize*curface*3+offset], tang);
1281                                                 tang = attribs.tang.array[a*4 + 1];
1282                                                 QUATCOPY((float *)&varray[elementsize*curface*3+offset+elementsize], tang);
1283                                                 tang = attribs.tang.array[a*4 + 2];
1284                                                 QUATCOPY((float *)&varray[elementsize*curface*3+offset+elementsize*2], tang);
1285                                                 offset += sizeof(float)*4;
1286                                         }
1287                                 }
1288                                 curface++;
1289                                 if(mface->v4) {
1290                                         if( numdata != 0 ) {
1291                                                 offset = 0;
1292                                                 if(attribs.totorco) {
1293                                                         VECCOPY((float *)&varray[elementsize*curface*3],(float *)attribs.orco.array[mface->v3]);
1294                                                         VECCOPY((float *)&varray[elementsize*curface*3+elementsize],(float *)attribs.orco.array[mface->v4]);
1295                                                         VECCOPY((float *)&varray[elementsize*curface*3+elementsize*2],(float *)attribs.orco.array[mface->v1]);
1296                                                         offset += sizeof(float)*3;
1297                                                 }
1298                                                 for(b = 0; b < attribs.tottface; b++) {
1299                                                         MTFace *tf = &attribs.tface[b].array[a];
1300                                                         VECCOPY2D((float *)&varray[elementsize*curface*3+offset],tf->uv[2]);
1301                                                         VECCOPY2D((float *)&varray[elementsize*curface*3+offset+elementsize],tf->uv[3]);
1302                                                         VECCOPY2D((float *)&varray[elementsize*curface*3+offset+elementsize*2],tf->uv[0]);
1303                                                         offset += sizeof(float)*2;
1304                                                 }
1305                                                 for(b = 0; b < attribs.totmcol; b++) {
1306                                                         MCol *cp = &attribs.mcol[b].array[a*4 + 2];
1307                                                         GLubyte col[4];
1308                                                         col[0]= cp->b; col[1]= cp->g; col[2]= cp->r; col[3]= cp->a;
1309                                                         QUATCOPY((unsigned char *)&varray[elementsize*curface*3+offset], col);
1310                                                         cp = &attribs.mcol[b].array[a*4 + 3];
1311                                                         col[0]= cp->b; col[1]= cp->g; col[2]= cp->r; col[3]= cp->a;
1312                                                         QUATCOPY((unsigned char *)&varray[elementsize*curface*3+offset+elementsize], col);
1313                                                         cp = &attribs.mcol[b].array[a*4 + 0];
1314                                                         col[0]= cp->b; col[1]= cp->g; col[2]= cp->r; col[3]= cp->a;
1315                                                         QUATCOPY((unsigned char *)&varray[elementsize*curface*3+offset+elementsize*2], col);
1316                                                         offset += sizeof(unsigned char)*4;
1317                                                 }       
1318                                                 if(attribs.tottang) {
1319                                                         float *tang = attribs.tang.array[a*4 + 2];
1320                                                         QUATCOPY((float *)&varray[elementsize*curface*3+offset], tang);
1321                                                         tang = attribs.tang.array[a*4 + 3];
1322                                                         QUATCOPY((float *)&varray[elementsize*curface*3+offset+elementsize], tang);
1323                                                         tang = attribs.tang.array[a*4 + 0];
1324                                                         QUATCOPY((float *)&varray[elementsize*curface*3+offset+elementsize*2], tang);
1325                                                         offset += sizeof(float)*4;
1326                                                 }
1327                                         }
1328                                         curface++;
1329                                         i++;
1330                                 }
1331                         }
1332                         numfaces = curface - start;
1333                         if( numfaces > 0 ) {
1334                                 if( dodraw ) {
1335                                         if( numdata != 0 ) {
1336                                                 GPU_buffer_unlock(buffer);
1337                                                 GPU_interleaved_attrib_setup(buffer,datatypes,numdata);
1338                                         }
1339                                         glDrawArrays(GL_TRIANGLES,start*3,(curface-start)*3);
1340                                 }
1341                         }
1342                         GPU_buffer_unbind();
1343                 }
1344                 GPU_buffer_free( buffer, NULL );
1345         }
1346
1347         glShadeModel(GL_FLAT);
1348 }
1349
1350 static void cdDM_drawFacesGLSL(DerivedMesh *dm, int (*setMaterial)(int, void *attribs))
1351 {
1352         dm->drawMappedFacesGLSL(dm, setMaterial, NULL, NULL);
1353 }
1354
1355 static void cdDM_drawMappedEdges(DerivedMesh *dm, int (*setDrawOptions)(void *userData, int index), void *userData)
1356 {
1357         CDDerivedMesh *cddm = (CDDerivedMesh*) dm;
1358         MVert *vert = cddm->mvert;
1359         MEdge *edge = cddm->medge;
1360         int i, orig, *index = DM_get_edge_data_layer(dm, CD_ORIGINDEX);
1361
1362         glBegin(GL_LINES);
1363         for(i = 0; i < dm->numEdgeData; i++, edge++) {
1364                 if(index) {
1365                         orig = *index++;
1366                         if(setDrawOptions && orig == ORIGINDEX_NONE) continue;
1367                 }
1368                 else
1369                         orig = i;
1370
1371                 if(!setDrawOptions || setDrawOptions(userData, orig)) {
1372                         glVertex3fv(vert[edge->v1].co);
1373                         glVertex3fv(vert[edge->v2].co);
1374                 }
1375         }
1376         glEnd();
1377 }
1378
1379 static void cdDM_foreachMappedVert(
1380                                                    DerivedMesh *dm,
1381                                                    void (*func)(void *userData, int index, float *co,
1382                                                                                 float *no_f, short *no_s),
1383                                                    void *userData)
1384 {
1385         MVert *mv = CDDM_get_verts(dm);
1386         int i, orig, *index = DM_get_vert_data_layer(dm, CD_ORIGINDEX);
1387
1388         for(i = 0; i < dm->numVertData; i++, mv++) {
1389                 if(index) {
1390                         orig = *index++;
1391                         if(orig == ORIGINDEX_NONE) continue;
1392                         func(userData, orig, mv->co, NULL, mv->no);
1393                 }
1394                 else
1395                         func(userData, i, mv->co, NULL, mv->no);
1396         }
1397 }
1398
1399 static void cdDM_foreachMappedEdge(
1400                                                    DerivedMesh *dm,
1401                                                    void (*func)(void *userData, int index,
1402                                                                                 float *v0co, float *v1co),
1403                                                    void *userData)
1404 {
1405         CDDerivedMesh *cddm = (CDDerivedMesh*) dm;
1406         MVert *mv = cddm->mvert;
1407         MEdge *med = cddm->medge;
1408         int i, orig, *index = DM_get_edge_data_layer(dm, CD_ORIGINDEX);
1409
1410         for(i = 0; i < dm->numEdgeData; i++, med++) {
1411                 if (index) {
1412                         orig = *index++;
1413                         if(orig == ORIGINDEX_NONE) continue;
1414                         func(userData, orig, mv[med->v1].co, mv[med->v2].co);
1415                 }
1416                 else
1417                         func(userData, i, mv[med->v1].co, mv[med->v2].co);
1418         }
1419 }
1420
1421 static void cdDM_foreachMappedFaceCenter(
1422                                                    DerivedMesh *dm,
1423                                                    void (*func)(void *userData, int index,
1424                                                                                 float *cent, float *no),
1425                                                    void *userData)
1426 {
1427         CDDerivedMesh *cddm = (CDDerivedMesh*)dm;
1428         MVert *mv = cddm->mvert;
1429         MFace *mf = cddm->mface;
1430         int i, orig, *index = DM_get_face_data_layer(dm, CD_ORIGINDEX);
1431
1432         for(i = 0; i < dm->numFaceData; i++, mf++) {
1433                 float cent[3];
1434                 float no[3];
1435
1436                 if (index) {
1437                         orig = *index++;
1438                         if(orig == ORIGINDEX_NONE) continue;
1439                 }
1440                 else
1441                         orig = i;
1442
1443                 VECCOPY(cent, mv[mf->v1].co);
1444                 add_v3_v3(cent, mv[mf->v2].co);
1445                 add_v3_v3(cent, mv[mf->v3].co);
1446
1447                 if (mf->v4) {
1448                         normal_quad_v3( no,mv[mf->v1].co, mv[mf->v2].co, mv[mf->v3].co, mv[mf->v4].co);
1449                         add_v3_v3(cent, mv[mf->v4].co);
1450                         mul_v3_fl(cent, 0.25f);
1451                 } else {
1452                         normal_tri_v3( no,mv[mf->v1].co, mv[mf->v2].co, mv[mf->v3].co);
1453                         mul_v3_fl(cent, 0.33333333333f);
1454                 }
1455
1456                 func(userData, orig, cent, no);
1457         }
1458 }
1459
1460 static void cdDM_free_internal(CDDerivedMesh *cddm)
1461 {
1462         if(cddm->fmap) MEM_freeN(cddm->fmap);
1463         if(cddm->fmap_mem) MEM_freeN(cddm->fmap_mem);
1464 }
1465
1466 static void cdDM_release(DerivedMesh *dm)
1467 {
1468         CDDerivedMesh *cddm = (CDDerivedMesh*)dm;
1469
1470         if (DM_release(dm)) {
1471                 cdDM_free_internal(cddm);
1472                 MEM_freeN(cddm);
1473         }
1474 }
1475
1476 /**************** CDDM interface functions ****************/
1477 static CDDerivedMesh *cdDM_create(const char *desc)
1478 {
1479         CDDerivedMesh *cddm;
1480         DerivedMesh *dm;
1481
1482         cddm = MEM_callocN(sizeof(*cddm), desc);
1483         dm = &cddm->dm;
1484
1485         dm->getMinMax = cdDM_getMinMax;
1486
1487         dm->getNumVerts = cdDM_getNumVerts;
1488         dm->getNumFaces = cdDM_getNumFaces;
1489         dm->getNumEdges = cdDM_getNumEdges;
1490
1491         dm->getVert = cdDM_getVert;
1492         dm->getEdge = cdDM_getEdge;
1493         dm->getFace = cdDM_getFace;
1494         dm->copyVertArray = cdDM_copyVertArray;
1495         dm->copyEdgeArray = cdDM_copyEdgeArray;
1496         dm->copyFaceArray = cdDM_copyFaceArray;
1497         dm->getVertData = DM_get_vert_data;
1498         dm->getEdgeData = DM_get_edge_data;
1499         dm->getFaceData = DM_get_face_data;
1500         dm->getVertDataArray = DM_get_vert_data_layer;
1501         dm->getEdgeDataArray = DM_get_edge_data_layer;
1502         dm->getFaceDataArray = DM_get_face_data_layer;
1503
1504         dm->getVertCos = cdDM_getVertCos;
1505         dm->getVertCo = cdDM_getVertCo;
1506         dm->getVertNo = cdDM_getVertNo;
1507
1508         dm->getPBVH = cdDM_getPBVH;
1509         dm->getFaceMap = cdDM_getFaceMap;
1510
1511         dm->drawVerts = cdDM_drawVerts;
1512
1513         dm->drawUVEdges = cdDM_drawUVEdges;
1514         dm->drawEdges = cdDM_drawEdges;
1515         dm->drawLooseEdges = cdDM_drawLooseEdges;
1516         dm->drawMappedEdges = cdDM_drawMappedEdges;
1517
1518         dm->drawFacesSolid = cdDM_drawFacesSolid;
1519         dm->drawFacesColored = cdDM_drawFacesColored;
1520         dm->drawFacesTex = cdDM_drawFacesTex;
1521         dm->drawFacesGLSL = cdDM_drawFacesGLSL;
1522         dm->drawMappedFaces = cdDM_drawMappedFaces;
1523         dm->drawMappedFacesTex = cdDM_drawMappedFacesTex;
1524         dm->drawMappedFacesGLSL = cdDM_drawMappedFacesGLSL;
1525
1526         dm->foreachMappedVert = cdDM_foreachMappedVert;
1527         dm->foreachMappedEdge = cdDM_foreachMappedEdge;
1528         dm->foreachMappedFaceCenter = cdDM_foreachMappedFaceCenter;
1529
1530         dm->release = cdDM_release;
1531
1532         return cddm;
1533 }
1534
1535 DerivedMesh *CDDM_new(int numVerts, int numEdges, int numFaces)
1536 {
1537         CDDerivedMesh *cddm = cdDM_create("CDDM_new dm");
1538         DerivedMesh *dm = &cddm->dm;
1539
1540         DM_init(dm, DM_TYPE_CDDM, numVerts, numEdges, numFaces);
1541
1542         CustomData_add_layer(&dm->vertData, CD_ORIGINDEX, CD_CALLOC, NULL, numVerts);
1543         CustomData_add_layer(&dm->edgeData, CD_ORIGINDEX, CD_CALLOC, NULL, numEdges);
1544         CustomData_add_layer(&dm->faceData, CD_ORIGINDEX, CD_CALLOC, NULL, numFaces);
1545
1546         CustomData_add_layer(&dm->vertData, CD_MVERT, CD_CALLOC, NULL, numVerts);
1547         CustomData_add_layer(&dm->edgeData, CD_MEDGE, CD_CALLOC, NULL, numEdges);
1548         CustomData_add_layer(&dm->faceData, CD_MFACE, CD_CALLOC, NULL, numFaces);
1549
1550         cddm->mvert = CustomData_get_layer(&dm->vertData, CD_MVERT);
1551         cddm->medge = CustomData_get_layer(&dm->edgeData, CD_MEDGE);
1552         cddm->mface = CustomData_get_layer(&dm->faceData, CD_MFACE);
1553
1554         return dm;
1555 }
1556
1557 DerivedMesh *CDDM_from_mesh(Mesh *mesh, Object *UNUSED(ob))
1558 {
1559         CDDerivedMesh *cddm = cdDM_create("CDDM_from_mesh dm");
1560         DerivedMesh *dm = &cddm->dm;
1561         CustomDataMask mask = CD_MASK_MESH & (~CD_MASK_MDISPS);
1562         int alloctype;
1563
1564         /* this does a referenced copy, with an exception for fluidsim */
1565
1566         DM_init(dm, DM_TYPE_CDDM, mesh->totvert, mesh->totedge, mesh->totface);
1567
1568         dm->deformedOnly = 1;
1569
1570         alloctype= CD_REFERENCE;
1571
1572         CustomData_merge(&mesh->vdata, &dm->vertData, mask, alloctype,
1573                                          mesh->totvert);
1574         CustomData_merge(&mesh->edata, &dm->edgeData, mask, alloctype,
1575                                          mesh->totedge);
1576         CustomData_merge(&mesh->fdata, &dm->faceData, mask, alloctype,
1577                                          mesh->totface);
1578
1579         cddm->mvert = CustomData_get_layer(&dm->vertData, CD_MVERT);
1580         cddm->medge = CustomData_get_layer(&dm->edgeData, CD_MEDGE);
1581         cddm->mface = CustomData_get_layer(&dm->faceData, CD_MFACE);
1582
1583         return dm;
1584 }
1585
1586 DerivedMesh *CDDM_from_editmesh(EditMesh *em, Mesh *UNUSED(me))
1587 {
1588         DerivedMesh *dm = CDDM_new(BLI_countlist(&em->verts),
1589                                                            BLI_countlist(&em->edges),
1590                                                            BLI_countlist(&em->faces));
1591         CDDerivedMesh *cddm = (CDDerivedMesh*)dm;
1592         EditVert *eve;
1593         EditEdge *eed;
1594         EditFace *efa;
1595         MVert *mvert = cddm->mvert;
1596         MEdge *medge = cddm->medge;
1597         MFace *mface = cddm->mface;
1598         int i, *index;
1599
1600         dm->deformedOnly = 1;
1601
1602         CustomData_merge(&em->vdata, &dm->vertData, CD_MASK_DERIVEDMESH,
1603                                          CD_CALLOC, dm->numVertData);
1604         /* CustomData_merge(&em->edata, &dm->edgeData, CD_MASK_DERIVEDMESH,
1605                                          CD_CALLOC, dm->numEdgeData); */
1606         CustomData_merge(&em->fdata, &dm->faceData, CD_MASK_DERIVEDMESH,
1607                                          CD_CALLOC, dm->numFaceData);
1608
1609         /* set eve->hash to vert index */
1610         for(i = 0, eve = em->verts.first; eve; eve = eve->next, ++i)
1611                 eve->tmp.l = i;
1612
1613         /* Need to be able to mark loose edges */
1614         for(eed = em->edges.first; eed; eed = eed->next) {
1615                 eed->f2 = 0;
1616         }
1617         for(efa = em->faces.first; efa; efa = efa->next) {
1618                 efa->e1->f2 = 1;
1619                 efa->e2->f2 = 1;
1620                 efa->e3->f2 = 1;
1621                 if(efa->e4) efa->e4->f2 = 1;
1622         }
1623
1624         index = dm->getVertDataArray(dm, CD_ORIGINDEX);
1625         for(i = 0, eve = em->verts.first; i < dm->numVertData;
1626                 i++, eve = eve->next, index++) {
1627                 MVert *mv = &mvert[i];
1628
1629                 VECCOPY(mv->co, eve->co);
1630
1631                 normal_float_to_short_v3(mv->no, eve->no);
1632                 mv->bweight = (unsigned char) (eve->bweight * 255.0f);
1633
1634                 mv->flag = 0;
1635
1636                 *index = i;
1637
1638                 CustomData_from_em_block(&em->vdata, &dm->vertData, eve->data, i);
1639         }
1640
1641         index = dm->getEdgeDataArray(dm, CD_ORIGINDEX);
1642         for(i = 0, eed = em->edges.first; i < dm->numEdgeData;
1643                 i++, eed = eed->next, index++) {
1644                 MEdge *med = &medge[i];
1645
1646                 med->v1 = eed->v1->tmp.l;
1647                 med->v2 = eed->v2->tmp.l;
1648                 med->crease = (unsigned char) (eed->crease * 255.0f);
1649                 med->bweight = (unsigned char) (eed->bweight * 255.0f);
1650                 med->flag = ME_EDGEDRAW|ME_EDGERENDER;
1651                 
1652                 if(eed->seam) med->flag |= ME_SEAM;
1653                 if(eed->sharp) med->flag |= ME_SHARP;
1654                 if(!eed->f2) med->flag |= ME_LOOSEEDGE;
1655
1656                 *index = i;
1657
1658                 /* CustomData_from_em_block(&em->edata, &dm->edgeData, eed->data, i); */
1659         }
1660
1661         index = dm->getFaceDataArray(dm, CD_ORIGINDEX);
1662         for(i = 0, efa = em->faces.first; i < dm->numFaceData;
1663                 i++, efa = efa->next, index++) {
1664                 MFace *mf = &mface[i];
1665
1666                 mf->v1 = efa->v1->tmp.l;
1667                 mf->v2 = efa->v2->tmp.l;
1668                 mf->v3 = efa->v3->tmp.l;
1669                 mf->v4 = efa->v4 ? efa->v4->tmp.l : 0;
1670                 mf->mat_nr = efa->mat_nr;
1671                 mf->flag = efa->flag;
1672
1673                 *index = i;
1674
1675                 CustomData_from_em_block(&em->fdata, &dm->faceData, efa->data, i);
1676                 test_index_face(mf, &dm->faceData, i, efa->v4?4:3);
1677         }
1678
1679         return dm;
1680 }
1681
1682 DerivedMesh *CDDM_from_curve(Object *ob)
1683 {
1684         return CDDM_from_curve_customDB(ob, &ob->disp);
1685 }
1686
1687 DerivedMesh *CDDM_from_curve_customDB(Object *ob, ListBase *dispbase)
1688 {
1689         DerivedMesh *dm;
1690         CDDerivedMesh *cddm;
1691         MVert *allvert;
1692         MEdge *alledge;
1693         MFace *allface;
1694         int totvert, totedge, totface;
1695
1696         if (nurbs_to_mdata_customdb(ob, dispbase, &allvert, &totvert, &alledge,
1697                 &totedge, &allface, &totface) != 0) {
1698                 /* Error initializing mdata. This often happens when curve is empty */
1699                 return CDDM_new(0, 0, 0);
1700         }
1701
1702         dm = CDDM_new(totvert, totedge, totface);
1703         dm->deformedOnly = 1;
1704
1705         cddm = (CDDerivedMesh*)dm;
1706
1707         memcpy(cddm->mvert, allvert, totvert*sizeof(MVert));
1708         memcpy(cddm->medge, alledge, totedge*sizeof(MEdge));
1709         memcpy(cddm->mface, allface, totface*sizeof(MFace));
1710
1711         MEM_freeN(allvert);
1712         MEM_freeN(alledge);
1713         MEM_freeN(allface);
1714
1715         return dm;
1716 }
1717
1718 DerivedMesh *CDDM_copy(DerivedMesh *source)
1719 {
1720         CDDerivedMesh *cddm = cdDM_create("CDDM_copy cddm");
1721         DerivedMesh *dm = &cddm->dm;
1722         int numVerts = source->numVertData;
1723         int numEdges = source->numEdgeData;
1724         int numFaces = source->numFaceData;
1725
1726         /* ensure these are created if they are made on demand */
1727         source->getVertDataArray(source, CD_ORIGINDEX);
1728         source->getEdgeDataArray(source, CD_ORIGINDEX);
1729         source->getFaceDataArray(source, CD_ORIGINDEX);
1730
1731         /* this initializes dm, and copies all non mvert/medge/mface layers */
1732         DM_from_template(dm, source, DM_TYPE_CDDM, numVerts, numEdges, numFaces);
1733         dm->deformedOnly = source->deformedOnly;
1734
1735         CustomData_copy_data(&source->vertData, &dm->vertData, 0, 0, numVerts);
1736         CustomData_copy_data(&source->edgeData, &dm->edgeData, 0, 0, numEdges);
1737         CustomData_copy_data(&source->faceData, &dm->faceData, 0, 0, numFaces);
1738
1739         /* now add mvert/medge/mface layers */
1740         cddm->mvert = source->dupVertArray(source);
1741         cddm->medge = source->dupEdgeArray(source);
1742         cddm->mface = source->dupFaceArray(source);
1743
1744         CustomData_add_layer(&dm->vertData, CD_MVERT, CD_ASSIGN, cddm->mvert, numVerts);
1745         CustomData_add_layer(&dm->edgeData, CD_MEDGE, CD_ASSIGN, cddm->medge, numEdges);
1746         CustomData_add_layer(&dm->faceData, CD_MFACE, CD_ASSIGN, cddm->mface, numFaces);
1747
1748         return dm;
1749 }
1750
1751 /* note, the CD_ORIGINDEX layers are all 0, so if there is a direct
1752  * relationship betwen mesh data this needs to be set by the caller. */
1753 DerivedMesh *CDDM_from_template(DerivedMesh *source,
1754                                                                 int numVerts, int numEdges, int numFaces)
1755 {
1756         CDDerivedMesh *cddm = cdDM_create("CDDM_from_template dest");
1757         DerivedMesh *dm = &cddm->dm;
1758
1759         /* ensure these are created if they are made on demand */
1760         source->getVertDataArray(source, CD_ORIGINDEX);
1761         source->getEdgeDataArray(source, CD_ORIGINDEX);
1762         source->getFaceDataArray(source, CD_ORIGINDEX);
1763
1764         /* this does a copy of all non mvert/medge/mface layers */
1765         DM_from_template(dm, source, DM_TYPE_CDDM, numVerts, numEdges, numFaces);
1766
1767         /* now add mvert/medge/mface layers */
1768         CustomData_add_layer(&dm->vertData, CD_MVERT, CD_CALLOC, NULL, numVerts);
1769         CustomData_add_layer(&dm->edgeData, CD_MEDGE, CD_CALLOC, NULL, numEdges);
1770         CustomData_add_layer(&dm->faceData, CD_MFACE, CD_CALLOC, NULL, numFaces);
1771
1772         if(!CustomData_get_layer(&dm->vertData, CD_ORIGINDEX))
1773                 CustomData_add_layer(&dm->vertData, CD_ORIGINDEX, CD_CALLOC, NULL, numVerts);
1774         if(!CustomData_get_layer(&dm->edgeData, CD_ORIGINDEX))
1775                 CustomData_add_layer(&dm->edgeData, CD_ORIGINDEX, CD_CALLOC, NULL, numEdges);
1776         if(!CustomData_get_layer(&dm->faceData, CD_ORIGINDEX))
1777                 CustomData_add_layer(&dm->faceData, CD_ORIGINDEX, CD_CALLOC, NULL, numFaces);
1778
1779         cddm->mvert = CustomData_get_layer(&dm->vertData, CD_MVERT);
1780         cddm->medge = CustomData_get_layer(&dm->edgeData, CD_MEDGE);
1781         cddm->mface = CustomData_get_layer(&dm->faceData, CD_MFACE);
1782
1783         return dm;
1784 }
1785
1786 void CDDM_apply_vert_coords(DerivedMesh *dm, float (*vertCoords)[3])
1787 {
1788         CDDerivedMesh *cddm = (CDDerivedMesh*)dm;
1789         MVert *vert;
1790         int i;
1791
1792         /* this will just return the pointer if it wasn't a referenced layer */
1793         vert = CustomData_duplicate_referenced_layer(&dm->vertData, CD_MVERT);
1794         cddm->mvert = vert;
1795
1796         for(i = 0; i < dm->numVertData; ++i, ++vert)
1797                 VECCOPY(vert->co, vertCoords[i]);
1798 }
1799
1800 void CDDM_apply_vert_normals(DerivedMesh *dm, short (*vertNormals)[3])
1801 {
1802         CDDerivedMesh *cddm = (CDDerivedMesh*)dm;
1803         MVert *vert;
1804         int i;
1805
1806         /* this will just return the pointer if it wasn't a referenced layer */
1807         vert = CustomData_duplicate_referenced_layer(&dm->vertData, CD_MVERT);
1808         cddm->mvert = vert;
1809
1810         for(i = 0; i < dm->numVertData; ++i, ++vert)
1811                 VECCOPY(vert->no, vertNormals[i]);
1812 }
1813
1814 void CDDM_calc_normals(DerivedMesh *dm)
1815 {
1816         CDDerivedMesh *cddm = (CDDerivedMesh*)dm;
1817         float (*face_nors)[3];
1818
1819         if(dm->numVertData == 0) return;
1820
1821         /* we don't want to overwrite any referenced layers */
1822         cddm->mvert = CustomData_duplicate_referenced_layer(&dm->vertData, CD_MVERT);
1823
1824         /* make a face normal layer if not present */
1825         face_nors = CustomData_get_layer(&dm->faceData, CD_NORMAL);
1826         if(!face_nors)
1827                 face_nors = CustomData_add_layer(&dm->faceData, CD_NORMAL, CD_CALLOC,
1828                                                                                  NULL, dm->numFaceData);
1829
1830         /* calculate face normals */
1831         mesh_calc_normals(cddm->mvert, dm->numVertData, CDDM_get_faces(dm), dm->numFaceData, face_nors);
1832 }
1833
1834 void CDDM_calc_edges(DerivedMesh *dm)
1835 {
1836         CDDerivedMesh *cddm = (CDDerivedMesh*)dm;
1837         CustomData edgeData;
1838         EdgeHashIterator *ehi;
1839         MFace *mf = cddm->mface;
1840         MEdge *med;
1841         EdgeHash *eh = BLI_edgehash_new();
1842         int i, *index, numEdges, maxFaces = dm->numFaceData;
1843
1844         for (i = 0; i < maxFaces; i++, mf++) {
1845                 if (!BLI_edgehash_haskey(eh, mf->v1, mf->v2))
1846                         BLI_edgehash_insert(eh, mf->v1, mf->v2, NULL);
1847                 if (!BLI_edgehash_haskey(eh, mf->v2, mf->v3))
1848                         BLI_edgehash_insert(eh, mf->v2, mf->v3, NULL);
1849                 
1850                 if (mf->v4) {
1851                         if (!BLI_edgehash_haskey(eh, mf->v3, mf->v4))
1852                                 BLI_edgehash_insert(eh, mf->v3, mf->v4, NULL);
1853                         if (!BLI_edgehash_haskey(eh, mf->v4, mf->v1))
1854                                 BLI_edgehash_insert(eh, mf->v4, mf->v1, NULL);
1855                 } else {
1856                         if (!BLI_edgehash_haskey(eh, mf->v3, mf->v1))
1857                                 BLI_edgehash_insert(eh, mf->v3, mf->v1, NULL);
1858                 }
1859         }
1860
1861         numEdges = BLI_edgehash_size(eh);
1862
1863         /* write new edges into a temporary CustomData */
1864         memset(&edgeData, 0, sizeof(edgeData));
1865         CustomData_add_layer(&edgeData, CD_MEDGE, CD_CALLOC, NULL, numEdges);
1866         CustomData_add_layer(&edgeData, CD_ORIGINDEX, CD_CALLOC, NULL, numEdges);
1867
1868         ehi = BLI_edgehashIterator_new(eh);
1869         med = CustomData_get_layer(&edgeData, CD_MEDGE);
1870         index = CustomData_get_layer(&edgeData, CD_ORIGINDEX);
1871         for(i = 0; !BLI_edgehashIterator_isDone(ehi);
1872                 BLI_edgehashIterator_step(ehi), ++i, ++med, ++index) {
1873                 BLI_edgehashIterator_getKey(ehi, (int*)&med->v1, (int*)&med->v2);
1874
1875                 med->flag = ME_EDGEDRAW|ME_EDGERENDER;
1876                 *index = ORIGINDEX_NONE;
1877         }
1878         BLI_edgehashIterator_free(ehi);
1879
1880         /* free old CustomData and assign new one */
1881         CustomData_free(&dm->edgeData, dm->numEdgeData);
1882         dm->edgeData = edgeData;
1883         dm->numEdgeData = numEdges;
1884
1885         cddm->medge = CustomData_get_layer(&dm->edgeData, CD_MEDGE);
1886
1887         BLI_edgehash_free(eh, NULL);
1888 }
1889
1890 void CDDM_lower_num_verts(DerivedMesh *dm, int numVerts)
1891 {
1892         if (numVerts < dm->numVertData)
1893                 CustomData_free_elem(&dm->vertData, numVerts, dm->numVertData-numVerts);
1894
1895         dm->numVertData = numVerts;
1896 }
1897
1898 void CDDM_lower_num_edges(DerivedMesh *dm, int numEdges)
1899 {
1900         if (numEdges < dm->numEdgeData)
1901                 CustomData_free_elem(&dm->edgeData, numEdges, dm->numEdgeData-numEdges);
1902
1903         dm->numEdgeData = numEdges;
1904 }
1905
1906 void CDDM_lower_num_faces(DerivedMesh *dm, int numFaces)
1907 {
1908         if (numFaces < dm->numFaceData)
1909                 CustomData_free_elem(&dm->faceData, numFaces, dm->numFaceData-numFaces);
1910
1911         dm->numFaceData = numFaces;
1912 }
1913
1914 MVert *CDDM_get_vert(DerivedMesh *dm, int index)
1915 {
1916         return &((CDDerivedMesh*)dm)->mvert[index];
1917 }
1918
1919 MEdge *CDDM_get_edge(DerivedMesh *dm, int index)
1920 {
1921         return &((CDDerivedMesh*)dm)->medge[index];
1922 }
1923
1924 MFace *CDDM_get_face(DerivedMesh *dm, int index)
1925 {
1926         return &((CDDerivedMesh*)dm)->mface[index];
1927 }
1928
1929 MVert *CDDM_get_verts(DerivedMesh *dm)
1930 {
1931         return ((CDDerivedMesh*)dm)->mvert;
1932 }
1933
1934 MEdge *CDDM_get_edges(DerivedMesh *dm)
1935 {
1936         return ((CDDerivedMesh*)dm)->medge;
1937 }
1938
1939 MFace *CDDM_get_faces(DerivedMesh *dm)
1940 {
1941         return ((CDDerivedMesh*)dm)->mface;
1942 }
1943