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