Camera tracking: support of tripod motion solving
[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_math.h"
40 #include "BLI_blenlib.h"
41 #include "BLI_edgehash.h"
42 #include "BLI_math.h"
43 #include "BLI_pbvh.h"
44 #include "BLI_array.h"
45 #include "BLI_smallhash.h"
46 #include "BLI_utildefines.h"
47 #include "BLI_scanfill.h"
48
49 #include "BKE_cdderivedmesh.h"
50 #include "BKE_global.h"
51 #include "BKE_mesh.h"
52 #include "BKE_paint.h"
53 #include "BKE_utildefines.h"
54 #include "BKE_tessmesh.h"
55
56 #include "DNA_mesh_types.h"
57 #include "DNA_meshdata_types.h"
58 #include "DNA_object_types.h"
59 #include "DNA_curve_types.h" /* for Curve */
60
61 #include "MEM_guardedalloc.h"
62
63 #include "GPU_buffers.h"
64 #include "GPU_draw.h"
65 #include "GPU_extensions.h"
66 #include "GPU_material.h"
67
68 #include <string.h>
69 #include <limits.h>
70 #include <math.h>
71
72 typedef struct {
73         DerivedMesh dm;
74
75         /* these point to data in the DerivedMesh custom data layers,
76          * they are only here for efficiency and convenience **/
77         MVert *mvert;
78         MEdge *medge;
79         MFace *mface;
80         MLoop *mloop;
81         MPoly *mpoly;
82
83         /* Cached */
84         struct PBVH *pbvh;
85         int pbvh_draw;
86
87         /* Mesh connectivity */
88         MeshElemMap *pmap;
89         int *pmap_mem;
90 } CDDerivedMesh;
91
92 /**************** DerivedMesh interface functions ****************/
93 static int cdDM_getNumVerts(DerivedMesh *dm)
94 {
95         return dm->numVertData;
96 }
97
98 static int cdDM_getNumEdges(DerivedMesh *dm)
99 {
100         return dm->numEdgeData;
101 }
102
103 static int cdDM_getNumTessFaces(DerivedMesh *dm)
104 {
105         /* uncomment and add a breakpoint on the printf()
106          * to help debug tessfaces issues since BMESH merge. */
107 #if 0
108         if (dm->numTessFaceData == 0 && dm->numPolyData != 0) {
109                 printf("%s: has no faces!, call DM_ensure_tessface() if you need them\n");
110         }
111 #endif
112         return dm->numTessFaceData;
113 }
114
115 static int cdDM_getNumLoops(DerivedMesh *dm)
116 {
117         return dm->numLoopData;
118 }
119
120 static int cdDM_getNumPolys(DerivedMesh *dm)
121 {
122         return dm->numPolyData;
123 }
124
125 static void cdDM_getVert(DerivedMesh *dm, int index, MVert *vert_r)
126 {
127         CDDerivedMesh *cddm = (CDDerivedMesh *)dm;
128         *vert_r = cddm->mvert[index];
129 }
130
131 static void cdDM_getEdge(DerivedMesh *dm, int index, MEdge *edge_r)
132 {
133         CDDerivedMesh *cddm = (CDDerivedMesh *)dm;
134         *edge_r = cddm->medge[index];
135 }
136
137 static void cdDM_getTessFace(DerivedMesh *dm, int index, MFace *face_r)
138 {
139         CDDerivedMesh *cddm = (CDDerivedMesh *)dm;
140         *face_r = cddm->mface[index];
141 }
142
143 static void cdDM_copyVertArray(DerivedMesh *dm, MVert *vert_r)
144 {
145         CDDerivedMesh *cddm = (CDDerivedMesh *)dm;
146         memcpy(vert_r, cddm->mvert, sizeof(*vert_r) * dm->numVertData);
147 }
148
149 static void cdDM_copyEdgeArray(DerivedMesh *dm, MEdge *edge_r)
150 {
151         CDDerivedMesh *cddm = (CDDerivedMesh *)dm;
152         memcpy(edge_r, cddm->medge, sizeof(*edge_r) * dm->numEdgeData);
153 }
154
155 static void cdDM_copyTessFaceArray(DerivedMesh *dm, MFace *face_r)
156 {
157         CDDerivedMesh *cddm = (CDDerivedMesh *)dm;
158         memcpy(face_r, cddm->mface, sizeof(*face_r) * dm->numTessFaceData);
159 }
160
161 static void cdDM_copyLoopArray(DerivedMesh *dm, MLoop *loop_r)
162 {
163         CDDerivedMesh *cddm = (CDDerivedMesh *)dm;
164         memcpy(loop_r, cddm->mloop, sizeof(*loop_r) * dm->numLoopData);
165 }
166
167 static void cdDM_copyPolyArray(DerivedMesh *dm, MPoly *poly_r)
168 {
169         CDDerivedMesh *cddm = (CDDerivedMesh *)dm;
170         memcpy(poly_r, cddm->mpoly, sizeof(*poly_r) * dm->numPolyData);
171 }
172
173 static void cdDM_getMinMax(DerivedMesh *dm, float min_r[3], float max_r[3])
174 {
175         CDDerivedMesh *cddm = (CDDerivedMesh*) dm;
176         int i;
177
178         if (dm->numVertData) {
179                 for (i=0; i<dm->numVertData; i++) {
180                         DO_MINMAX(cddm->mvert[i].co, min_r, max_r);
181                 }
182         }
183         else {
184                 zero_v3(min_r);
185                 zero_v3(max_r);
186         }
187 }
188
189 static void cdDM_getVertCo(DerivedMesh *dm, int index, float co_r[3])
190 {
191         CDDerivedMesh *cddm = (CDDerivedMesh*) dm;
192
193         copy_v3_v3(co_r, cddm->mvert[index].co);
194 }
195
196 static void cdDM_getVertCos(DerivedMesh *dm, float (*cos_r)[3])
197 {
198         MVert *mv = CDDM_get_verts(dm);
199         int i;
200
201         for (i = 0; i < dm->numVertData; i++, mv++)
202                 copy_v3_v3(cos_r[i], mv->co);
203 }
204
205 static void cdDM_getVertNo(DerivedMesh *dm, int index, float no_r[3])
206 {
207         CDDerivedMesh *cddm = (CDDerivedMesh*) dm;
208         normal_short_to_float_v3(no_r, cddm->mvert[index].no);
209 }
210
211 static const MeshElemMap *cdDM_getPolyMap(Object *ob, DerivedMesh *dm)
212 {
213         CDDerivedMesh *cddm = (CDDerivedMesh*) dm;
214
215         if (!cddm->pmap && ob->type == OB_MESH) {
216                 Mesh *me= ob->data;
217
218                 create_vert_poly_map(&cddm->pmap, &cddm->pmap_mem,
219                                      me->mpoly, me->mloop,
220                                      me->totvert, me->totpoly, me->totloop);
221         }
222
223         return cddm->pmap;
224 }
225
226 static int can_pbvh_draw(Object *ob, DerivedMesh *dm)
227 {
228         CDDerivedMesh *cddm = (CDDerivedMesh*) dm;
229         Mesh *me= ob->data;
230         int deformed= 0;
231
232         /* active modifiers means extra deformation, which can't be handled correct
233          * on birth of PBVH and sculpt "layer" levels, so use PBVH only for internal brush
234          * stuff and show final DerivedMesh so user would see actual object shape */
235         deformed|= ob->sculpt->modifiers_active;
236
237         /* as in case with modifiers, we can't synchronize deformation made against
238          * PBVH and non-locked keyblock, so also use PBVH only for brushes and
239          * final DM to give final result to user */
240         deformed|= ob->sculpt->kb && (ob->shapeflag&OB_SHAPE_LOCK) == 0;
241
242         if (deformed)
243                 return 0;
244
245         return cddm->mvert == me->mvert || ob->sculpt->kb;
246 }
247
248 static struct PBVH *cdDM_getPBVH(Object *ob, DerivedMesh *dm)
249 {
250         CDDerivedMesh *cddm = (CDDerivedMesh*) dm;
251
252         if (!ob) {
253                 cddm->pbvh= NULL;
254                 return NULL;
255         }
256
257         if (!ob->sculpt)
258                 return NULL;
259         if (ob->sculpt->pbvh) {
260                 cddm->pbvh= ob->sculpt->pbvh;
261                 cddm->pbvh_draw = can_pbvh_draw(ob, dm);
262         }
263
264         /* always build pbvh from original mesh, and only use it for drawing if
265          * this derivedmesh is just original mesh. it's the multires subsurf dm
266          * that this is actually for, to support a pbvh on a modified mesh */
267         if (!cddm->pbvh && ob->type == OB_MESH) {
268                 SculptSession *ss= ob->sculpt;
269                 Mesh *me= ob->data;
270                 cddm->pbvh = BLI_pbvh_new();
271                 cddm->pbvh_draw = can_pbvh_draw(ob, dm);
272
273                 BKE_mesh_tessface_ensure(me);
274                 
275                 BLI_pbvh_build_mesh(cddm->pbvh, me->mface, me->mvert,
276                                     me->totface, me->totvert);
277
278                 if (ss->modifiers_active && ob->derivedDeform) {
279                         DerivedMesh *deformdm= ob->derivedDeform;
280                         float (*vertCos)[3];
281                         int totvert;
282
283                         totvert= deformdm->getNumVerts(deformdm);
284                         vertCos= MEM_callocN(3*totvert*sizeof(float), "cdDM_getPBVH vertCos");
285                         deformdm->getVertCos(deformdm, vertCos);
286                         BLI_pbvh_apply_vertCos(cddm->pbvh, vertCos);
287                         MEM_freeN(vertCos);
288                 }
289         }
290
291         return cddm->pbvh;
292 }
293
294 /* update vertex normals so that drawing smooth faces works during sculpt
295  * TODO: proper fix is to support the pbvh in all drawing modes */
296 static void cdDM_update_normals_from_pbvh(DerivedMesh *dm)
297 {
298         CDDerivedMesh *cddm = (CDDerivedMesh*) dm;
299         float (*face_nors)[3];
300
301         if (!cddm->pbvh || !cddm->pbvh_draw || !dm->numTessFaceData)
302                 return;
303
304         face_nors = CustomData_get_layer(&dm->faceData, CD_NORMAL);
305
306         BLI_pbvh_update(cddm->pbvh, PBVH_UpdateNormals, face_nors);
307 }
308
309 static void cdDM_drawVerts(DerivedMesh *dm)
310 {
311         CDDerivedMesh *cddm = (CDDerivedMesh*) dm;
312         MVert *mv = cddm->mvert;
313         int i;
314
315         if ( GPU_buffer_legacy(dm) ) {
316                 glBegin(GL_POINTS);
317                 for (i = 0; i < dm->numVertData; i++, mv++)
318                         glVertex3fv(mv->co);
319                 glEnd();
320         }
321         else {  /* use OpenGL VBOs or Vertex Arrays instead for better, faster rendering */
322                 GPU_vertex_setup(dm);
323                 if ( !GPU_buffer_legacy(dm) ) {
324                         if (dm->drawObject->tot_triangle_point)
325                                 glDrawArrays(GL_POINTS,0, dm->drawObject->tot_triangle_point);
326                         else
327                                 glDrawArrays(GL_POINTS,0, dm->drawObject->tot_loose_point);
328                 }
329                 GPU_buffer_unbind();
330         }
331 }
332
333 static void cdDM_drawUVEdges(DerivedMesh *dm)
334 {
335         CDDerivedMesh *cddm = (CDDerivedMesh*) dm;
336         MFace *mf = cddm->mface;
337         MTFace *tf = DM_get_tessface_data_layer(dm, CD_MTFACE);
338         int i;
339
340         if (mf) {
341                 if ( GPU_buffer_legacy(dm) ) {
342                         glBegin(GL_LINES);
343                         for (i = 0; i < dm->numTessFaceData; i++, mf++, tf++) {
344                                 if (!(mf->flag&ME_HIDE)) {
345                                         glVertex2fv(tf->uv[0]);
346                                         glVertex2fv(tf->uv[1]);
347
348                                         glVertex2fv(tf->uv[1]);
349                                         glVertex2fv(tf->uv[2]);
350
351                                         if (!mf->v4) {
352                                                 glVertex2fv(tf->uv[2]);
353                                                 glVertex2fv(tf->uv[0]);
354                                         }
355                                         else {
356                                                 glVertex2fv(tf->uv[2]);
357                                                 glVertex2fv(tf->uv[3]);
358
359                                                 glVertex2fv(tf->uv[3]);
360                                                 glVertex2fv(tf->uv[0]);
361                                         }
362                                 }
363                         }
364                         glEnd();
365                 }
366                 else {
367                         int prevstart = 0;
368                         int prevdraw = 1;
369                         int draw = 1;
370                         int curpos = 0;
371
372                         GPU_uvedge_setup(dm);
373                         if ( !GPU_buffer_legacy(dm) ) {
374                                 for (i = 0; i < dm->numTessFaceData; i++, mf++) {
375                                         if (!(mf->flag&ME_HIDE)) {
376                                                 draw = 1;
377                                         } 
378                                         else {
379                                                 draw = 0;
380                                         }
381                                         if ( prevdraw != draw ) {
382                                                 if ( prevdraw > 0 && (curpos-prevstart) > 0) {
383                                                         glDrawArrays(GL_LINES,prevstart,curpos-prevstart);
384                                                 }
385                                                 prevstart = curpos;
386                                         }
387                                         if ( mf->v4 ) {
388                                                 curpos += 8;
389                                         }
390                                         else {
391                                                 curpos += 6;
392                                         }
393                                         prevdraw = draw;
394                                 }
395                                 if ( prevdraw > 0 && (curpos-prevstart) > 0 ) {
396                                         glDrawArrays(GL_LINES,prevstart,curpos-prevstart);
397                                 }
398                         }
399                         GPU_buffer_unbind();
400                 }
401         }
402 }
403
404 static void cdDM_drawEdges(DerivedMesh *dm, int drawLooseEdges, int drawAllEdges)
405 {
406         CDDerivedMesh *cddm = (CDDerivedMesh*) dm;
407         MVert *mvert = cddm->mvert;
408         MEdge *medge = cddm->medge;
409         int i;
410         
411         if ( GPU_buffer_legacy(dm) ) {
412                 DEBUG_VBO( "Using legacy code. cdDM_drawEdges\n" );
413                 glBegin(GL_LINES);
414                 for (i = 0; i < dm->numEdgeData; i++, medge++) {
415                         if ((drawAllEdges || (medge->flag & ME_EDGEDRAW)) &&
416                             (drawLooseEdges || !(medge->flag & ME_LOOSEEDGE)))
417                         {
418                                 glVertex3fv(mvert[medge->v1].co);
419                                 glVertex3fv(mvert[medge->v2].co);
420                         }
421                 }
422                 glEnd();
423         }
424         else {  /* use OpenGL VBOs or Vertex Arrays instead for better, faster rendering */
425                 int prevstart = 0;
426                 int prevdraw = 1;
427                 int draw = TRUE;
428
429                 GPU_edge_setup(dm);
430                 if (!GPU_buffer_legacy(dm)) {
431                         for (i = 0; i < dm->numEdgeData; i++, medge++) {
432                                 if ((drawAllEdges || (medge->flag & ME_EDGEDRAW)) &&
433                                     (drawLooseEdges || !(medge->flag & ME_LOOSEEDGE)))
434                                 {
435                                         draw = TRUE;
436                                 } 
437                                 else {
438                                         draw = FALSE;
439                                 }
440                                 if ( prevdraw != draw ) {
441                                         if ( prevdraw > 0 && (i-prevstart) > 0 ) {
442                                                 GPU_buffer_draw_elements(dm->drawObject->edges, GL_LINES, prevstart * 2, (i - prevstart) * 2);
443                                         }
444                                         prevstart = i;
445                                 }
446                                 prevdraw = draw;
447                         }
448                         if ( prevdraw > 0 && (i-prevstart) > 0 ) {
449                                 GPU_buffer_draw_elements(dm->drawObject->edges, GL_LINES, prevstart * 2, (i-prevstart) * 2);
450                         }
451                 }
452                 GPU_buffer_unbind();
453         }
454 }
455
456 static void cdDM_drawLooseEdges(DerivedMesh *dm)
457 {
458         CDDerivedMesh *cddm = (CDDerivedMesh*) dm;
459         MVert *mvert = cddm->mvert;
460         MEdge *medge = cddm->medge;
461         int i;
462
463         if ( GPU_buffer_legacy(dm) ) {
464                 DEBUG_VBO( "Using legacy code. cdDM_drawLooseEdges\n" );
465                 glBegin(GL_LINES);
466                 for (i = 0; i < dm->numEdgeData; i++, medge++) {
467                         if (medge->flag&ME_LOOSEEDGE) {
468                                 glVertex3fv(mvert[medge->v1].co);
469                                 glVertex3fv(mvert[medge->v2].co);
470                         }
471                 }
472                 glEnd();
473         }
474         else {  /* use OpenGL VBOs or Vertex Arrays instead for better, faster rendering */
475                 int prevstart = 0;
476                 int prevdraw = 1;
477                 int draw = 1;
478
479                 GPU_edge_setup(dm);
480                 if ( !GPU_buffer_legacy(dm) ) {
481                         for (i = 0; i < dm->numEdgeData; i++, medge++) {
482                                 if (medge->flag&ME_LOOSEEDGE) {
483                                         draw = 1;
484                                 } 
485                                 else {
486                                         draw = 0;
487                                 }
488                                 if ( prevdraw != draw ) {
489                                         if ( prevdraw > 0 && (i-prevstart) > 0) {
490                                                 GPU_buffer_draw_elements(dm->drawObject->edges, GL_LINES, prevstart * 2, (i - prevstart) * 2);
491                                         }
492                                         prevstart = i;
493                                 }
494                                 prevdraw = draw;
495                         }
496                         if ( prevdraw > 0 && (i-prevstart) > 0 ) {
497                                 GPU_buffer_draw_elements(dm->drawObject->edges, GL_LINES, prevstart * 2, (i - prevstart) * 2);
498                         }
499                 }
500                 GPU_buffer_unbind();
501         }
502 }
503
504 static void cdDM_drawFacesSolid(DerivedMesh *dm,
505                                 float (*partial_redraw_planes)[4],
506                                 int UNUSED(fast), DMSetMaterial setMaterial)
507 {
508         CDDerivedMesh *cddm = (CDDerivedMesh*) dm;
509         MVert *mvert = cddm->mvert;
510         MFace *mface = cddm->mface;
511         float *nors= dm->getTessFaceDataArray(dm, CD_NORMAL);
512         int a, glmode = -1, shademodel = -1, matnr = -1, drawCurrentMat = 1;
513
514 #define PASSVERT(index) {                                               \
515         if (shademodel == GL_SMOOTH) {                          \
516                 short *no = mvert[index].no;                    \
517                 glNormal3sv(no);                                                \
518         }                                                                                       \
519         glVertex3fv(mvert[index].co);   \
520 }
521
522         if (cddm->pbvh && cddm->pbvh_draw) {
523                 if (dm->numTessFaceData) {
524                         float (*face_nors)[3] = CustomData_get_layer(&dm->faceData, CD_NORMAL);
525
526                         BLI_pbvh_draw(cddm->pbvh, partial_redraw_planes, face_nors, setMaterial);
527                         glShadeModel(GL_FLAT);
528                 }
529
530                 return;
531         }
532
533         if ( GPU_buffer_legacy(dm) ) {
534                 DEBUG_VBO( "Using legacy code. cdDM_drawFacesSolid\n" );
535                 glBegin(glmode = GL_QUADS);
536                 for (a = 0; a < dm->numTessFaceData; a++, mface++) {
537                         int new_glmode, new_matnr, new_shademodel;
538
539                         new_glmode = mface->v4?GL_QUADS:GL_TRIANGLES;
540                         new_matnr = mface->mat_nr + 1;
541                         new_shademodel = (mface->flag & ME_SMOOTH)?GL_SMOOTH:GL_FLAT;
542                         
543                         if (new_glmode != glmode || new_matnr != matnr || new_shademodel != shademodel) {
544                                 glEnd();
545
546                                 drawCurrentMat = setMaterial(matnr = new_matnr, NULL);
547
548                                 glShadeModel(shademodel = new_shademodel);
549                                 glBegin(glmode = new_glmode);
550                         } 
551                         
552                         if (drawCurrentMat) {
553                                 if (shademodel == GL_FLAT) {
554                                         if (nors) {
555                                                 glNormal3fv(nors);
556                                         }
557                                         else {
558                                                 /* TODO make this better (cache facenormals as layer?) */
559                                                 float nor[3];
560                                                 if (mface->v4) {
561                                                         normal_quad_v3( nor,mvert[mface->v1].co, mvert[mface->v2].co, mvert[mface->v3].co, mvert[mface->v4].co);
562                                                 }
563                                                 else {
564                                                         normal_tri_v3( nor,mvert[mface->v1].co, mvert[mface->v2].co, mvert[mface->v3].co);
565                                                 }
566                                                 glNormal3fv(nor);
567                                         }
568                                 }
569
570                                 PASSVERT(mface->v1);
571                                 PASSVERT(mface->v2);
572                                 PASSVERT(mface->v3);
573                                 if (mface->v4) {
574                                         PASSVERT(mface->v4);
575                                 }
576                         }
577
578                         if (nors) nors += 3;
579                 }
580                 glEnd();
581         }
582         else {  /* use OpenGL VBOs or Vertex Arrays instead for better, faster rendering */
583                 GPU_vertex_setup( dm );
584                 GPU_normal_setup( dm );
585                 if ( !GPU_buffer_legacy(dm) ) {
586                         glShadeModel(GL_SMOOTH);
587                         for (a = 0; a < dm->drawObject->totmaterial; a++) {
588                                 if (setMaterial(dm->drawObject->materials[a].mat_nr + 1, NULL)) {
589                                         glDrawArrays(GL_TRIANGLES, dm->drawObject->materials[a].start,
590                                                      dm->drawObject->materials[a].totpoint);
591                                 }
592                         }
593                 }
594                 GPU_buffer_unbind( );
595         }
596
597 #undef PASSVERT
598         glShadeModel(GL_FLAT);
599 }
600
601 static void cdDM_drawFacesTex_common(DerivedMesh *dm,
602                            DMSetDrawOptionsTex drawParams,
603                            DMSetDrawOptions drawParamsMapped,
604                            DMCompareDrawOptions compareDrawOptions,
605                            void *userData) 
606 {
607         CDDerivedMesh *cddm = (CDDerivedMesh*) dm;
608         MVert *mv = cddm->mvert;
609         MFace *mf = DM_get_tessface_data_layer(dm, CD_MFACE);
610         MCol *realcol = dm->getTessFaceDataArray(dm, CD_TEXTURE_MCOL);
611         float *nors= dm->getTessFaceDataArray(dm, CD_NORMAL);
612         MTFace *tf = DM_get_tessface_data_layer(dm, CD_MTFACE);
613         int i, j, orig, *index = DM_get_tessface_data_layer(dm, CD_ORIGINDEX);
614         int startFace = 0 /*, lastFlag = 0xdeadbeef */ /* UNUSED */;
615         MCol *mcol = dm->getTessFaceDataArray(dm, CD_PREVIEW_MCOL);
616         if (!mcol)
617                 mcol = dm->getTessFaceDataArray(dm, CD_MCOL);
618
619         cdDM_update_normals_from_pbvh(dm);
620
621         if ( GPU_buffer_legacy(dm) ) {
622                 DEBUG_VBO( "Using legacy code. cdDM_drawFacesTex_common\n" );
623                 for (i = 0; i < dm->numTessFaceData; i++, mf++) {
624                         MVert *mvert;
625                         DMDrawOption draw_option;
626                         unsigned char *cp = NULL;
627
628                         if (drawParams) {
629                                 draw_option = drawParams(tf? &tf[i]: NULL, (mcol != NULL), mf->mat_nr);
630                         }
631                         else {
632                                 if (index) {
633                                         orig = *index++;
634                                         if (orig == ORIGINDEX_NONE)             { if (nors) nors += 3; continue; }
635                                         if (drawParamsMapped) draw_option = drawParamsMapped(userData, orig);
636                                         else    { if (nors) nors += 3; continue; }
637                                 }
638                                 else
639                                         if (drawParamsMapped) draw_option = drawParamsMapped(userData, i);
640                                         else    { if (nors) nors += 3; continue; }
641                         }
642                         
643                         if (draw_option != DM_DRAW_OPTION_SKIP) {
644                                 if (draw_option != DM_DRAW_OPTION_NO_MCOL && mcol)
645                                         cp= (unsigned char*) &mcol[i*4];
646
647                                 if (!(mf->flag&ME_SMOOTH)) {
648                                         if (nors) {
649                                                 glNormal3fv(nors);
650                                         }
651                                         else {
652                                                 float nor[3];
653                                                 if (mf->v4) {
654                                                         normal_quad_v3( nor,mv[mf->v1].co, mv[mf->v2].co, mv[mf->v3].co, mv[mf->v4].co);
655                                                 }
656                                                 else {
657                                                         normal_tri_v3( nor,mv[mf->v1].co, mv[mf->v2].co, mv[mf->v3].co);
658                                                 }
659                                                 glNormal3fv(nor);
660                                         }
661                                 }
662
663                                 glBegin(mf->v4?GL_QUADS:GL_TRIANGLES);
664                                 if (tf) glTexCoord2fv(tf[i].uv[0]);
665                                 if (cp) glColor3ub(cp[3], cp[2], cp[1]);
666                                 mvert = &mv[mf->v1];
667                                 if (mf->flag&ME_SMOOTH) glNormal3sv(mvert->no);
668                                 glVertex3fv(mvert->co);
669                                         
670                                 if (tf) glTexCoord2fv(tf[i].uv[1]);
671                                 if (cp) glColor3ub(cp[7], cp[6], cp[5]);
672                                 mvert = &mv[mf->v2];
673                                 if (mf->flag&ME_SMOOTH) glNormal3sv(mvert->no);
674                                 glVertex3fv(mvert->co);
675
676                                 if (tf) glTexCoord2fv(tf[i].uv[2]);
677                                 if (cp) glColor3ub(cp[11], cp[10], cp[9]);
678                                 mvert = &mv[mf->v3];
679                                 if (mf->flag&ME_SMOOTH) glNormal3sv(mvert->no);
680                                 glVertex3fv(mvert->co);
681
682                                 if (mf->v4) {
683                                         if (tf) glTexCoord2fv(tf[i].uv[3]);
684                                         if (cp) glColor3ub(cp[15], cp[14], cp[13]);
685                                         mvert = &mv[mf->v4];
686                                         if (mf->flag&ME_SMOOTH) glNormal3sv(mvert->no);
687                                         glVertex3fv(mvert->co);
688                                 }
689                                 glEnd();
690                         }
691                         
692                         if (nors) nors += 3;
693                 }
694         }
695         else { /* use OpenGL VBOs or Vertex Arrays instead for better, faster rendering */
696                 MCol *col = realcol;
697                 if (!col)
698                         col = mcol;
699
700                 GPU_vertex_setup( dm );
701                 GPU_normal_setup( dm );
702                 GPU_uv_setup( dm );
703                 if ( col != NULL ) {
704 #if 0
705                         if ( realcol && dm->drawObject->colType == CD_TEXTURE_MCOL ) {
706                                 col = 0;
707                         }
708                         else if ( mcol && dm->drawObject->colType == CD_MCOL ) {
709                                 col = 0;
710                         }
711                         
712                         if ( col != 0 )
713 #endif
714                         {
715                                 unsigned char *colors = MEM_mallocN(dm->getNumTessFaces(dm)*4*3*sizeof(unsigned char), "cdDM_drawFacesTex_common");
716                                 for ( i=0; i < dm->getNumTessFaces(dm); i++ ) {
717                                         for ( j=0; j < 4; j++ ) {
718                                                 /* bgr -> rgb is intentional (and stupid), but how its stored internally */
719                                                 colors[i*12+j*3] = col[i*4+j].b;
720                                                 colors[i*12+j*3+1] = col[i*4+j].g;
721                                                 colors[i*12+j*3+2] = col[i*4+j].r;
722                                         }
723                                 }
724                                 GPU_color3_upload(dm,colors);
725                                 MEM_freeN(colors);
726                                 if (realcol)
727                                         dm->drawObject->colType = CD_TEXTURE_MCOL;
728                                 else if (mcol)
729                                         dm->drawObject->colType = CD_MCOL;
730                         }
731                         GPU_color_setup( dm );
732                 }
733
734                 if ( !GPU_buffer_legacy(dm) ) {
735                         int tottri = dm->drawObject->tot_triangle_point/3;
736                         int next_actualFace= dm->drawObject->triangle_to_mface[0];
737
738                         glShadeModel( GL_SMOOTH );
739                         /* lastFlag = 0; */ /* UNUSED */
740                         for (i = 0; i < tottri; i++) {
741                                 int actualFace = next_actualFace;
742                                 DMDrawOption draw_option = DM_DRAW_OPTION_NORMAL;
743                                 int flush = 0;
744
745                                 if (i != tottri-1)
746                                         next_actualFace= dm->drawObject->triangle_to_mface[i+1];
747
748                                 if (drawParams) {
749                                         draw_option = drawParams(tf? &tf[actualFace]: NULL, (mcol != NULL), mf[actualFace].mat_nr);
750                                 }
751                                 else {
752                                         if (index) {
753                                                 orig = index[actualFace];
754                                                 if (orig == ORIGINDEX_NONE) continue;
755                                                 if (drawParamsMapped)
756                                                         draw_option = drawParamsMapped(userData, orig);
757                                         }
758                                         else
759                                                 if (drawParamsMapped)
760                                                         draw_option = drawParamsMapped(userData, actualFace);
761                                 }
762
763                                 /* flush buffer if current triangle isn't drawable or it's last triangle */
764                                 flush= (draw_option == DM_DRAW_OPTION_SKIP) || (i == tottri - 1);
765
766                                 if (!flush && compareDrawOptions) {
767                                         /* also compare draw options and flush buffer if they're different
768                                          * need for face selection highlight in edit mode */
769                                         flush|= compareDrawOptions(userData, actualFace, next_actualFace) == 0;
770                                 }
771
772                                 if (flush) {
773                                         int first= startFace*3;
774                                         /* Add one to the length if we're drawing at the end of the array */
775                                         int count= (i-startFace+(draw_option != DM_DRAW_OPTION_SKIP ? 1 : 0))*3;
776
777                                         if (count) {
778                                                 if (col)
779                                                         GPU_color_switch(1);
780                                                 else
781                                                         GPU_color_switch(0);
782
783                                                 glDrawArrays(GL_TRIANGLES, first, count);
784                                         }
785
786                                         startFace = i + 1;
787                                 }
788                         }
789                 }
790
791                 GPU_buffer_unbind();
792                 glShadeModel( GL_FLAT );
793         }
794 }
795
796 static void cdDM_drawFacesTex(DerivedMesh *dm,
797                            DMSetDrawOptionsTex setDrawOptions,
798                            DMCompareDrawOptions compareDrawOptions,
799                            void *userData)
800 {
801         cdDM_drawFacesTex_common(dm, setDrawOptions, NULL, compareDrawOptions, userData);
802 }
803
804 static void cdDM_drawMappedFaces(DerivedMesh *dm,
805                         DMSetDrawOptions setDrawOptions,
806                         DMSetMaterial setMaterial,
807                         DMCompareDrawOptions compareDrawOptions,
808                         void *userData, DMDrawFlag flag)
809 {
810         CDDerivedMesh *cddm = (CDDerivedMesh*) dm;
811         MVert *mv = cddm->mvert;
812         MFace *mf = cddm->mface;
813         MCol *mc;
814         float *nors= DM_get_tessface_data_layer(dm, CD_NORMAL);
815         int useColors = flag & DM_DRAW_USE_COLORS;
816         int i, orig, *index = DM_get_tessface_data_layer(dm, CD_ORIGINDEX);
817
818         mc = DM_get_tessface_data_layer(dm, CD_ID_MCOL);
819         if (!mc)
820                 mc = DM_get_tessface_data_layer(dm, CD_PREVIEW_MCOL);
821         if (!mc)
822                 mc = DM_get_tessface_data_layer(dm, CD_MCOL);
823
824         cdDM_update_normals_from_pbvh(dm);
825
826         /* back-buffer always uses legacy since VBO's would need the
827          * color array temporarily overwritten for drawing, then reset. */
828         if ( GPU_buffer_legacy(dm) || G.f & G_BACKBUFSEL) {
829                 DEBUG_VBO( "Using legacy code. cdDM_drawMappedFaces\n" );
830                 for (i = 0; i < dm->numTessFaceData; i++, mf++) {
831                         int drawSmooth = (flag & DM_DRAW_ALWAYS_SMOOTH) ? 1 : (mf->flag & ME_SMOOTH);
832                         DMDrawOption draw_option= DM_DRAW_OPTION_NORMAL;
833
834                         orig= (index==NULL) ? i : *index++;
835                         
836                         if (orig == ORIGINDEX_NONE)
837                                 draw_option= setMaterial(mf->mat_nr + 1, NULL);
838                         else if (setDrawOptions != NULL)
839                                 draw_option= setDrawOptions(userData, orig);
840
841                         if (draw_option != DM_DRAW_OPTION_SKIP) {
842                                 unsigned char *cp = NULL;
843
844                                 if (useColors && mc)
845                                         cp = (unsigned char *)&mc[i * 4];
846
847                                 /* no need to set shading mode to flat because
848                                  *  normals are already used to change shading */
849                                 glShadeModel(GL_SMOOTH);
850                                 glBegin(mf->v4?GL_QUADS:GL_TRIANGLES);
851
852                                 if (!drawSmooth) {
853                                         if (nors) {
854                                                 glNormal3fv(nors);
855                                         }
856                                         else {
857                                                 float nor[3];
858                                                 if (mf->v4) {
859                                                         normal_quad_v3( nor,mv[mf->v1].co, mv[mf->v2].co, mv[mf->v3].co, mv[mf->v4].co);
860                                                 }
861                                                 else {
862                                                         normal_tri_v3( nor,mv[mf->v1].co, mv[mf->v2].co, mv[mf->v3].co);
863                                                 }
864                                                 glNormal3fv(nor);
865                                         }
866
867                                         if (cp) glColor3ub(cp[3], cp[2], cp[1]);
868                                         glVertex3fv(mv[mf->v1].co);
869                                         if (cp) glColor3ub(cp[7], cp[6], cp[5]);
870                                         glVertex3fv(mv[mf->v2].co);
871                                         if (cp) glColor3ub(cp[11], cp[10], cp[9]);
872                                         glVertex3fv(mv[mf->v3].co);
873                                         if (mf->v4) {
874                                                 if (cp) glColor3ub(cp[15], cp[14], cp[13]);
875                                                 glVertex3fv(mv[mf->v4].co);
876                                         }
877                                 }
878                                 else {
879                                         if (cp) glColor3ub(cp[3], cp[2], cp[1]);
880                                         glNormal3sv(mv[mf->v1].no);
881                                         glVertex3fv(mv[mf->v1].co);
882                                         if (cp) glColor3ub(cp[7], cp[6], cp[5]);
883                                         glNormal3sv(mv[mf->v2].no);
884                                         glVertex3fv(mv[mf->v2].co);
885                                         if (cp) glColor3ub(cp[11], cp[10], cp[9]);
886                                         glNormal3sv(mv[mf->v3].no);
887                                         glVertex3fv(mv[mf->v3].co);
888                                         if (mf->v4) {
889                                                 if (cp) glColor3ub(cp[15], cp[14], cp[13]);
890                                                 glNormal3sv(mv[mf->v4].no);
891                                                 glVertex3fv(mv[mf->v4].co);
892                                         }
893                                 }
894
895                                 glEnd();
896                         }
897                         
898                         if (nors) nors += 3;
899                 }
900         }
901         else { /* use OpenGL VBOs or Vertex Arrays instead for better, faster rendering */
902                 int prevstart = 0;
903                 GPU_vertex_setup(dm);
904                 GPU_normal_setup(dm);
905                 if ( useColors && mc )
906                         GPU_color_setup(dm);
907                 if ( !GPU_buffer_legacy(dm) ) {
908                         int tottri = dm->drawObject->tot_triangle_point/3;
909                         glShadeModel(GL_SMOOTH);
910                         
911                         if (tottri == 0) {
912                                 /* avoid buffer problems in following code */
913                         }
914                         if (setDrawOptions == NULL) {
915                                 /* just draw the entire face array */
916                                 glDrawArrays(GL_TRIANGLES, 0, (tottri) * 3);
917                         }
918                         else {
919                                 /* we need to check if the next material changes */
920                                 int next_actualFace= dm->drawObject->triangle_to_mface[0];
921                                 
922                                 for ( i = 0; i < tottri; i++ ) {
923                                         //int actualFace = dm->drawObject->triangle_to_mface[i];
924                                         int actualFace = next_actualFace;
925                                         MFace *mface= mf + actualFace;
926                                         /*int drawSmooth= (flag & DM_DRAW_ALWAYS_SMOOTH) ? 1 : (mface->flag & ME_SMOOTH);*/ /* UNUSED */
927                                         DMDrawOption draw_option = DM_DRAW_OPTION_NORMAL;
928                                         int flush = 0;
929
930                                         if (i != tottri-1)
931                                                 next_actualFace= dm->drawObject->triangle_to_mface[i+1];
932
933                                         orig= (index==NULL) ? actualFace : index[actualFace];
934
935                                         if (orig == ORIGINDEX_NONE)
936                                                 draw_option= setMaterial(mface->mat_nr + 1, NULL);
937                                         else if (setDrawOptions != NULL)
938                                                 draw_option= setDrawOptions(userData, orig);
939         
940                                         /* Goal is to draw as long of a contiguous triangle
941                                          * array as possible, so draw when we hit either an
942                                          * invisible triangle or at the end of the array */
943
944                                         /* flush buffer if current triangle isn't drawable or it's last triangle... */
945                                         flush= (draw_option == DM_DRAW_OPTION_SKIP) || (i == tottri - 1);
946
947                                         /* ... or when material setting is dissferent  */
948                                         flush|= mf[actualFace].mat_nr != mf[next_actualFace].mat_nr;
949
950                                         if (!flush && compareDrawOptions) {
951                                                 flush|= compareDrawOptions(userData, actualFace, next_actualFace) == 0;
952                                         }
953
954                                         if (flush) {
955                                                 int first= prevstart*3;
956                                                 /* Add one to the length if we're drawing at the end of the array */
957                                                 int count= (i-prevstart+(draw_option != DM_DRAW_OPTION_SKIP ? 1 : 0))*3;
958
959                                                 if (count)
960                                                         glDrawArrays(GL_TRIANGLES, first, count);
961
962                                                 prevstart = i + 1;
963                                         }
964                                 }
965                         }
966
967                         glShadeModel(GL_FLAT);
968                 }
969                 GPU_buffer_unbind();
970         }
971 }
972
973 static void cdDM_drawMappedFacesTex(DerivedMesh *dm,
974                            DMSetDrawOptions setDrawOptions,
975                            DMCompareDrawOptions compareDrawOptions,
976                            void *userData)
977 {
978         cdDM_drawFacesTex_common(dm, NULL, setDrawOptions, compareDrawOptions, userData);
979 }
980
981 static void cddm_draw_attrib_vertex(DMVertexAttribs *attribs, MVert *mvert, int a, int index, int vert, int smoothnormal)
982 {
983         int b;
984
985         /* orco texture coordinates */
986         if (attribs->totorco) {
987                 if (attribs->orco.glTexco)
988                         glTexCoord3fv(attribs->orco.array[index]);
989                 else
990                         glVertexAttrib3fvARB(attribs->orco.glIndex, attribs->orco.array[index]);
991         }
992
993         /* uv texture coordinates */
994         for (b = 0; b < attribs->tottface; b++) {
995                 MTFace *tf = &attribs->tface[b].array[a];
996
997                 if (attribs->tface[b].glTexco)
998                         glTexCoord2fv(tf->uv[vert]);
999                 else
1000                         glVertexAttrib2fvARB(attribs->tface[b].glIndex, tf->uv[vert]);
1001         }
1002
1003         /* vertex colors */
1004         for (b = 0; b < attribs->totmcol; b++) {
1005                 MCol *cp = &attribs->mcol[b].array[a*4 + vert];
1006                 GLubyte col[4];
1007                 col[0]= cp->b; col[1]= cp->g; col[2]= cp->r; col[3]= cp->a;
1008                 glVertexAttrib4ubvARB(attribs->mcol[b].glIndex, col);
1009         }
1010
1011         /* tangent for normal mapping */
1012         if (attribs->tottang) {
1013                 float *tang = attribs->tang.array[a*4 + vert];
1014                 glVertexAttrib4fvARB(attribs->tang.glIndex, tang);
1015         }
1016
1017         /* vertex normal */
1018         if (smoothnormal)
1019                 glNormal3sv(mvert[index].no);
1020         
1021         /* vertex coordinate */
1022         glVertex3fv(mvert[index].co);
1023 }
1024
1025 static void cdDM_drawMappedFacesGLSL(DerivedMesh *dm,
1026                            DMSetMaterial setMaterial,
1027                            DMSetDrawOptions setDrawOptions,
1028                            void *userData)
1029 {
1030         CDDerivedMesh *cddm = (CDDerivedMesh*) dm;
1031         GPUVertexAttribs gattribs;
1032         DMVertexAttribs attribs;
1033         MVert *mvert = cddm->mvert;
1034         MFace *mface = cddm->mface;
1035         /* MTFace *tf = dm->getTessFaceDataArray(dm, CD_MTFACE); */ /* UNUSED */
1036         float (*nors)[3] = dm->getTessFaceDataArray(dm, CD_NORMAL);
1037         int a, b, dodraw, matnr, new_matnr;
1038         int orig, *index = dm->getTessFaceDataArray(dm, CD_ORIGINDEX);
1039
1040         cdDM_update_normals_from_pbvh(dm);
1041
1042         matnr = -1;
1043         dodraw = 0;
1044
1045         glShadeModel(GL_SMOOTH);
1046
1047         if ( GPU_buffer_legacy(dm) || setDrawOptions != NULL ) {
1048                 DEBUG_VBO( "Using legacy code. cdDM_drawMappedFacesGLSL\n" );
1049                 memset(&attribs, 0, sizeof(attribs));
1050
1051                 glBegin(GL_QUADS);
1052
1053                 for (a = 0; a < dm->numTessFaceData; a++, mface++) {
1054                         const int smoothnormal = (mface->flag & ME_SMOOTH);
1055                         new_matnr = mface->mat_nr + 1;
1056
1057                         if (new_matnr != matnr) {
1058                                 glEnd();
1059
1060                                 dodraw = setMaterial(matnr = new_matnr, &gattribs);
1061                                 if (dodraw)
1062                                         DM_vertex_attributes_from_gpu(dm, &gattribs, &attribs);
1063
1064                                 glBegin(GL_QUADS);
1065                         }
1066
1067                         if (!dodraw) {
1068                                 continue;
1069                         }
1070                         else if (setDrawOptions) {
1071                                 orig = (index)? index[a]: a;
1072
1073                                 if (orig == ORIGINDEX_NONE) {
1074                                         /* since the material is set by setMaterial(), faces with no
1075                                          * origin can be assumed to be generated by a modifier */ 
1076                                         
1077                                         /* continue */
1078                                 }
1079                                 else if (setDrawOptions(userData, orig) == DM_DRAW_OPTION_SKIP)
1080                                         continue;
1081                         }
1082
1083                         if (!smoothnormal) {
1084                                 if (nors) {
1085                                         glNormal3fv(nors[a]);
1086                                 }
1087                                 else {
1088                                         /* TODO ideally a normal layer should always be available */
1089                                         float nor[3];
1090                                         if (mface->v4) {
1091                                                 normal_quad_v3( nor,mvert[mface->v1].co, mvert[mface->v2].co, mvert[mface->v3].co, mvert[mface->v4].co);
1092                                         }
1093                                         else {
1094                                                 normal_tri_v3( nor,mvert[mface->v1].co, mvert[mface->v2].co, mvert[mface->v3].co);
1095                                         }
1096                                         glNormal3fv(nor);
1097                                 }
1098                         }
1099
1100                         cddm_draw_attrib_vertex(&attribs, mvert, a, mface->v1, 0, smoothnormal);
1101                         cddm_draw_attrib_vertex(&attribs, mvert, a, mface->v2, 1, smoothnormal);
1102                         cddm_draw_attrib_vertex(&attribs, mvert, a, mface->v3, 2, smoothnormal);
1103
1104                         if (mface->v4)
1105                                 cddm_draw_attrib_vertex(&attribs, mvert, a, mface->v4, 3, smoothnormal);
1106                         else
1107                                 cddm_draw_attrib_vertex(&attribs, mvert, a, mface->v3, 2, smoothnormal);
1108                 }
1109                 glEnd();
1110         }
1111         else {
1112                 GPUBuffer *buffer = NULL;
1113                 char *varray = NULL;
1114                 int numdata = 0, elementsize = 0, offset;
1115                 int start = 0, numfaces = 0 /* , prevdraw = 0 */ /* UNUSED */, curface = 0;
1116                 int i;
1117
1118                 MFace *mf = mface;
1119                 GPUAttrib datatypes[GPU_MAX_ATTRIB]; /* TODO, messing up when switching materials many times - [#21056]*/
1120                 memset(&attribs, 0, sizeof(attribs));
1121
1122                 GPU_vertex_setup(dm);
1123                 GPU_normal_setup(dm);
1124
1125                 if ( !GPU_buffer_legacy(dm) ) {
1126                         for ( i = 0; i < dm->drawObject->tot_triangle_point/3; i++ ) {
1127
1128                                 a = dm->drawObject->triangle_to_mface[i];
1129
1130                                 mface = mf + a;
1131                                 new_matnr = mface->mat_nr + 1;
1132
1133                                 if (new_matnr != matnr ) {
1134                                         numfaces = curface - start;
1135                                         if ( numfaces > 0 ) {
1136
1137                                                 if ( dodraw ) {
1138
1139                                                         if ( numdata != 0 ) {
1140
1141                                                                 GPU_buffer_unlock(buffer);
1142
1143                                                                 GPU_interleaved_attrib_setup(buffer,datatypes,numdata);
1144                                                         }
1145
1146                                                         glDrawArrays(GL_TRIANGLES,start*3,numfaces*3);
1147
1148                                                         if ( numdata != 0 ) {
1149
1150                                                                 GPU_buffer_free(buffer);
1151
1152                                                                 buffer = NULL;
1153                                                         }
1154
1155                                                 }
1156                                         }
1157                                         numdata = 0;
1158                                         start = curface;
1159                                         /* prevdraw = dodraw; */ /* UNUSED */
1160                                         dodraw = setMaterial(matnr = new_matnr, &gattribs);
1161                                         if (dodraw) {
1162                                                 DM_vertex_attributes_from_gpu(dm, &gattribs, &attribs);
1163
1164                                                 if (attribs.totorco) {
1165                                                         datatypes[numdata].index = attribs.orco.glIndex;
1166                                                         datatypes[numdata].size = 3;
1167                                                         datatypes[numdata].type = GL_FLOAT;
1168                                                         numdata++;
1169                                                 }
1170                                                 for (b = 0; b < attribs.tottface; b++) {
1171                                                         datatypes[numdata].index = attribs.tface[b].glIndex;
1172                                                         datatypes[numdata].size = 2;
1173                                                         datatypes[numdata].type = GL_FLOAT;
1174                                                         numdata++;
1175                                                 }       
1176                                                 for (b = 0; b < attribs.totmcol; b++) {
1177                                                         datatypes[numdata].index = attribs.mcol[b].glIndex;
1178                                                         datatypes[numdata].size = 4;
1179                                                         datatypes[numdata].type = GL_UNSIGNED_BYTE;
1180                                                         numdata++;
1181                                                 }       
1182                                                 if (attribs.tottang) {
1183                                                         datatypes[numdata].index = attribs.tang.glIndex;
1184                                                         datatypes[numdata].size = 4;
1185                                                         datatypes[numdata].type = GL_FLOAT;
1186                                                         numdata++;
1187                                                 }
1188                                                 if ( numdata != 0 ) {
1189                                                         elementsize = GPU_attrib_element_size( datatypes, numdata );
1190                                                         buffer = GPU_buffer_alloc( elementsize*dm->drawObject->tot_triangle_point);
1191                                                         if ( buffer == NULL ) {
1192                                                                 GPU_buffer_unbind();
1193                                                                 dm->drawObject->legacy = 1;
1194                                                                 return;
1195                                                         }
1196                                                         varray = GPU_buffer_lock_stream(buffer);
1197                                                         if ( varray == NULL ) {
1198                                                                 GPU_buffer_unbind();
1199                                                                 GPU_buffer_free(buffer);
1200                                                                 dm->drawObject->legacy = 1;
1201                                                                 return;
1202                                                         }
1203                                                 }
1204                                                 else {
1205                                                         /* if the buffer was set, don't use it again.
1206                                                          * prevdraw was assumed true but didnt run so set to false - [#21036] */
1207                                                         /* prevdraw= 0; */ /* UNUSED */
1208                                                         buffer= NULL;
1209                                                 }
1210                                         }
1211                                 }
1212
1213                                 if (dodraw && numdata != 0 ) {
1214                                         offset = 0;
1215                                         if (attribs.totorco) {
1216                                                 copy_v3_v3((float *)&varray[elementsize*curface*3],(float *)attribs.orco.array[mface->v1]);
1217                                                 copy_v3_v3((float *)&varray[elementsize*curface*3+elementsize],(float *)attribs.orco.array[mface->v2]);
1218                                                 copy_v3_v3((float *)&varray[elementsize*curface*3+elementsize*2],(float *)attribs.orco.array[mface->v3]);
1219                                                 offset += sizeof(float)*3;
1220                                         }
1221                                         for (b = 0; b < attribs.tottface; b++) {
1222                                                 MTFace *tf = &attribs.tface[b].array[a];
1223                                                 copy_v2_v2((float *)&varray[elementsize*curface*3+offset],tf->uv[0]);
1224                                                 copy_v2_v2((float *)&varray[elementsize*curface*3+offset+elementsize],tf->uv[1]);
1225
1226                                                 copy_v2_v2((float *)&varray[elementsize*curface*3+offset+elementsize*2],tf->uv[2]);
1227                                                 offset += sizeof(float)*2;
1228                                         }
1229                                         for (b = 0; b < attribs.totmcol; b++) {
1230                                                 MCol *cp = &attribs.mcol[b].array[a*4 + 0];
1231                                                 GLubyte col[4];
1232                                                 col[0]= cp->b; col[1]= cp->g; col[2]= cp->r; col[3]= cp->a;
1233                                                 copy_v4_v4_char((char *)&varray[elementsize*curface*3+offset], (char *)col);
1234                                                 cp = &attribs.mcol[b].array[a*4 + 1];
1235                                                 col[0]= cp->b; col[1]= cp->g; col[2]= cp->r; col[3]= cp->a;
1236                                                 copy_v4_v4_char((char *)&varray[elementsize*curface*3+offset+elementsize], (char *)col);
1237                                                 cp = &attribs.mcol[b].array[a*4 + 2];
1238                                                 col[0]= cp->b; col[1]= cp->g; col[2]= cp->r; col[3]= cp->a;
1239                                                 copy_v4_v4_char((char *)&varray[elementsize*curface*3+offset+elementsize*2], (char *)col);
1240                                                 offset += sizeof(unsigned char)*4;
1241                                         }       
1242                                         if (attribs.tottang) {
1243                                                 float *tang = attribs.tang.array[a*4 + 0];
1244                                                 copy_v4_v4((float *)&varray[elementsize*curface*3+offset], tang);
1245                                                 tang = attribs.tang.array[a*4 + 1];
1246                                                 copy_v4_v4((float *)&varray[elementsize*curface*3+offset+elementsize], tang);
1247                                                 tang = attribs.tang.array[a*4 + 2];
1248                                                 copy_v4_v4((float *)&varray[elementsize*curface*3+offset+elementsize*2], tang);
1249                                                 offset += sizeof(float)*4;
1250                                         }
1251                                         (void)offset;
1252                                 }
1253                                 curface++;
1254                                 if (mface->v4) {
1255                                         if (dodraw && numdata != 0 ) {
1256                                                 offset = 0;
1257                                                 if (attribs.totorco) {
1258                                                         copy_v3_v3((float *)&varray[elementsize*curface*3],(float *)attribs.orco.array[mface->v3]);
1259                                                         copy_v3_v3((float *)&varray[elementsize*curface*3+elementsize],(float *)attribs.orco.array[mface->v4]);
1260                                                         copy_v3_v3((float *)&varray[elementsize*curface*3+elementsize*2],(float *)attribs.orco.array[mface->v1]);
1261                                                         offset += sizeof(float)*3;
1262                                                 }
1263                                                 for (b = 0; b < attribs.tottface; b++) {
1264                                                         MTFace *tf = &attribs.tface[b].array[a];
1265                                                         copy_v2_v2((float *)&varray[elementsize*curface*3+offset],tf->uv[2]);
1266                                                         copy_v2_v2((float *)&varray[elementsize*curface*3+offset+elementsize],tf->uv[3]);
1267                                                         copy_v2_v2((float *)&varray[elementsize*curface*3+offset+elementsize*2],tf->uv[0]);
1268                                                         offset += sizeof(float)*2;
1269                                                 }
1270                                                 for (b = 0; b < attribs.totmcol; b++) {
1271                                                         MCol *cp = &attribs.mcol[b].array[a*4 + 2];
1272                                                         GLubyte col[4];
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], (char *)col);
1275                                                         cp = &attribs.mcol[b].array[a*4 + 3];
1276                                                         col[0]= cp->b; col[1]= cp->g; col[2]= cp->r; col[3]= cp->a;
1277                                                         copy_v4_v4_char((char *)&varray[elementsize*curface*3+offset+elementsize], (char *)col);
1278                                                         cp = &attribs.mcol[b].array[a*4 + 0];
1279                                                         col[0]= cp->b; col[1]= cp->g; col[2]= cp->r; col[3]= cp->a;
1280                                                         copy_v4_v4_char((char *)&varray[elementsize*curface*3+offset+elementsize*2], (char *)col);
1281                                                         offset += sizeof(unsigned char)*4;
1282                                                 }       
1283                                                 if (attribs.tottang) {
1284                                                         float *tang = attribs.tang.array[a*4 + 2];
1285                                                         copy_v4_v4((float *)&varray[elementsize*curface*3+offset], tang);
1286                                                         tang = attribs.tang.array[a*4 + 3];
1287                                                         copy_v4_v4((float *)&varray[elementsize*curface*3+offset+elementsize], tang);
1288                                                         tang = attribs.tang.array[a*4 + 0];
1289                                                         copy_v4_v4((float *)&varray[elementsize*curface*3+offset+elementsize*2], tang);
1290                                                         offset += sizeof(float)*4;
1291                                                 }
1292                                                 (void)offset;
1293                                         }
1294                                         curface++;
1295                                         i++;
1296                                 }
1297                         }
1298                         numfaces = curface - start;
1299                         if ( numfaces > 0 ) {
1300                                 if ( dodraw ) {
1301                                         if ( numdata != 0 ) {
1302                                                 GPU_buffer_unlock(buffer);
1303                                                 GPU_interleaved_attrib_setup(buffer,datatypes,numdata);
1304                                         }
1305                                         glDrawArrays(GL_TRIANGLES,start*3,(curface-start)*3);
1306                                 }
1307                         }
1308                         GPU_buffer_unbind();
1309                 }
1310                 GPU_buffer_free(buffer);
1311         }
1312
1313         glShadeModel(GL_FLAT);
1314 }
1315
1316 static void cdDM_drawFacesGLSL(DerivedMesh *dm, DMSetMaterial setMaterial)
1317 {
1318         dm->drawMappedFacesGLSL(dm, setMaterial, NULL, NULL);
1319 }
1320
1321 static void cdDM_drawMappedFacesMat(DerivedMesh *dm,
1322         void (*setMaterial)(void *userData, int, void *attribs),
1323         int (*setFace)(void *userData, int index), void *userData)
1324 {
1325         CDDerivedMesh *cddm = (CDDerivedMesh*) dm;
1326         GPUVertexAttribs gattribs;
1327         DMVertexAttribs attribs;
1328         MVert *mvert = cddm->mvert;
1329         MFace *mf = cddm->mface;
1330         float (*nors)[3] = dm->getTessFaceDataArray(dm, CD_NORMAL);
1331         int a, matnr, new_matnr;
1332         int orig, *index = dm->getTessFaceDataArray(dm, CD_ORIGINDEX);
1333
1334         cdDM_update_normals_from_pbvh(dm);
1335
1336         matnr = -1;
1337
1338         glShadeModel(GL_SMOOTH);
1339
1340         memset(&attribs, 0, sizeof(attribs));
1341
1342         glBegin(GL_QUADS);
1343
1344         for (a = 0; a < dm->numTessFaceData; a++, mf++) {
1345                 const int smoothnormal = (mf->flag & ME_SMOOTH);
1346
1347                 /* material */
1348                 new_matnr = mf->mat_nr + 1;
1349
1350                 if (new_matnr != matnr) {
1351                         glEnd();
1352
1353                         setMaterial(userData, matnr = new_matnr, &gattribs);
1354                         DM_vertex_attributes_from_gpu(dm, &gattribs, &attribs);
1355
1356                         glBegin(GL_QUADS);
1357                 }
1358
1359                 /* skipping faces */
1360                 if (setFace) {
1361                         orig = (index)? index[a]: a;
1362
1363                         if (orig != ORIGINDEX_NONE && !setFace(userData, orig))
1364                                 continue;
1365                 }
1366
1367                 /* smooth normal */
1368                 if (!smoothnormal) {
1369                         if (nors) {
1370                                 glNormal3fv(nors[a]);
1371                         }
1372                         else {
1373                                 /* TODO ideally a normal layer should always be available */
1374                                 float nor[3];
1375
1376                                 if (mf->v4)
1377                                         normal_quad_v3( nor,mvert[mf->v1].co, mvert[mf->v2].co, mvert[mf->v3].co, mvert[mf->v4].co);
1378                                 else
1379                                         normal_tri_v3( nor,mvert[mf->v1].co, mvert[mf->v2].co, mvert[mf->v3].co);
1380
1381                                 glNormal3fv(nor);
1382                         }
1383                 }
1384
1385                 /* vertices */
1386                 cddm_draw_attrib_vertex(&attribs, mvert, a, mf->v1, 0, smoothnormal);
1387                 cddm_draw_attrib_vertex(&attribs, mvert, a, mf->v2, 1, smoothnormal);
1388                 cddm_draw_attrib_vertex(&attribs, mvert, a, mf->v3, 2, smoothnormal);
1389
1390                 if (mf->v4)
1391                         cddm_draw_attrib_vertex(&attribs, mvert, a, mf->v4, 3, smoothnormal);
1392                 else
1393                         cddm_draw_attrib_vertex(&attribs, mvert, a, mf->v3, 2, smoothnormal);
1394         }
1395         glEnd();
1396
1397         glShadeModel(GL_FLAT);
1398 }
1399
1400 static void cdDM_drawMappedEdges(DerivedMesh *dm, DMSetDrawOptions setDrawOptions, void *userData)
1401 {
1402         CDDerivedMesh *cddm = (CDDerivedMesh*) dm;
1403         MVert *vert = cddm->mvert;
1404         MEdge *edge = cddm->medge;
1405         int i, orig, *index = DM_get_edge_data_layer(dm, CD_ORIGINDEX);
1406
1407         glBegin(GL_LINES);
1408         for (i = 0; i < dm->numEdgeData; i++, edge++) {
1409                 if (index) {
1410                         orig = *index++;
1411                         if (setDrawOptions && orig == ORIGINDEX_NONE) continue;
1412                 }
1413                 else
1414                         orig = i;
1415
1416                 if (!setDrawOptions || (setDrawOptions(userData, orig) != DM_DRAW_OPTION_SKIP)) {
1417                         glVertex3fv(vert[edge->v1].co);
1418                         glVertex3fv(vert[edge->v2].co);
1419                 }
1420         }
1421         glEnd();
1422 }
1423
1424 static void cdDM_foreachMappedVert(
1425         DerivedMesh *dm,
1426         void (*func)(void *userData, int index, const float co[3], const float no_f[3], const short no_s[3]),
1427         void *userData)
1428 {
1429         MVert *mv = CDDM_get_verts(dm);
1430         int i, orig, *index = DM_get_vert_data_layer(dm, CD_ORIGINDEX);
1431
1432         for (i = 0; i < dm->numVertData; i++, mv++) {
1433                 if (index) {
1434                         orig = *index++;
1435                         if (orig == ORIGINDEX_NONE) continue;
1436                         func(userData, orig, mv->co, NULL, mv->no);
1437                 }
1438                 else
1439                         func(userData, i, mv->co, NULL, mv->no);
1440         }
1441 }
1442
1443 static void cdDM_foreachMappedEdge(
1444         DerivedMesh *dm,
1445         void (*func)(void *userData, int index, const float v0co[3], const float v1co[3]),
1446         void *userData)
1447 {
1448         CDDerivedMesh *cddm = (CDDerivedMesh*) dm;
1449         MVert *mv = cddm->mvert;
1450         MEdge *med = cddm->medge;
1451         int i, orig, *index = DM_get_edge_data_layer(dm, CD_ORIGINDEX);
1452
1453         for (i = 0; i < dm->numEdgeData; i++, med++) {
1454                 if (index) {
1455                         orig = *index++;
1456                         if (orig == ORIGINDEX_NONE) continue;
1457                         func(userData, orig, mv[med->v1].co, mv[med->v2].co);
1458                 }
1459                 else
1460                         func(userData, i, mv[med->v1].co, mv[med->v2].co);
1461         }
1462 }
1463
1464 static void cdDM_foreachMappedFaceCenter(
1465         DerivedMesh *dm,
1466         void (*func)(void *userData, int index, const float cent[3], const float no[3]),
1467         void *userData)
1468 {
1469         CDDerivedMesh *cddm = (CDDerivedMesh*)dm;
1470         MVert *mv = cddm->mvert;
1471         MPoly *mp = cddm->mpoly;
1472         MLoop *ml = cddm->mloop;
1473         int i, j, orig, *index;
1474
1475         index = CustomData_get_layer(&dm->polyData, CD_ORIGINDEX);
1476         mp = cddm->mpoly;
1477         for (i = 0; i < dm->numPolyData; i++, mp++) {
1478                 float cent[3];
1479                 float no[3];
1480
1481                 if (index) {
1482                         orig = *index++;
1483                         if (orig == ORIGINDEX_NONE) continue;
1484                 }
1485                 else
1486                         orig = i;
1487                 
1488                 ml = &cddm->mloop[mp->loopstart];
1489                 cent[0] = cent[1] = cent[2] = 0.0f;
1490                 for (j=0; j<mp->totloop; j++, ml++) {
1491                         add_v3_v3v3(cent, cent, mv[ml->v].co);
1492                 }
1493                 mul_v3_fl(cent, 1.0f / (float)j);
1494
1495                 ml = &cddm->mloop[mp->loopstart];
1496                 if (j > 3) {
1497                         normal_quad_v3(no,
1498                                        mv[(ml + 0)->v].co,
1499                                        mv[(ml + 1)->v].co,
1500                                        mv[(ml + 2)->v].co,
1501                                        mv[(ml + 3)->v].co);
1502                 }
1503                 else {
1504                         normal_tri_v3(no,
1505                                       mv[(ml + 0)->v].co,
1506                                       mv[(ml + 1)->v].co,
1507                                       mv[(ml + 2)->v].co);
1508                 }
1509
1510                 func(userData, orig, cent, no);
1511         }
1512
1513 }
1514
1515 void CDDM_recalc_tessellation_ex(DerivedMesh *dm, const int do_face_nor_cpy)
1516 {
1517         CDDerivedMesh *cddm = (CDDerivedMesh*)dm;
1518
1519         dm->numTessFaceData = mesh_recalcTessellation(&dm->faceData, &dm->loopData, &dm->polyData,
1520                                                      cddm->mvert,
1521                                                      dm->numTessFaceData, dm->numLoopData, dm->numPolyData,
1522                                                      do_face_nor_cpy);
1523
1524         if (!CustomData_get_layer(&dm->faceData, CD_ORIGINDEX)) {
1525                 int *polyIndex = CustomData_get_layer(&dm->faceData, CD_POLYINDEX);
1526                 CustomData_add_layer(&dm->faceData, CD_ORIGINDEX, CD_REFERENCE, polyIndex, dm->numTessFaceData);
1527         }
1528
1529         cddm->mface = CustomData_get_layer(&dm->faceData, CD_MFACE);
1530
1531         /* Tessellation recreated faceData, and the active layer indices need to get re-propagated
1532          * from loops and polys to faces */
1533         CustomData_bmesh_update_active_layers(&dm->faceData, &dm->polyData, &dm->loopData);
1534 }
1535
1536 void CDDM_recalc_tessellation(DerivedMesh *dm)
1537 {
1538         CDDM_recalc_tessellation_ex(dm, TRUE);
1539 }
1540
1541 static void cdDM_free_internal(CDDerivedMesh *cddm)
1542 {
1543         if (cddm->pmap) MEM_freeN(cddm->pmap);
1544         if (cddm->pmap_mem) MEM_freeN(cddm->pmap_mem);
1545 }
1546
1547 static void cdDM_release(DerivedMesh *dm)
1548 {
1549         CDDerivedMesh *cddm = (CDDerivedMesh*)dm;
1550
1551         if (DM_release(dm)) {
1552                 cdDM_free_internal(cddm);
1553                 MEM_freeN(cddm);
1554         }
1555 }
1556
1557 int CDDM_Check(DerivedMesh *dm)
1558 {
1559         return dm && dm->getMinMax == cdDM_getMinMax;
1560 }
1561
1562 /**************** CDDM interface functions ****************/
1563 static CDDerivedMesh *cdDM_create(const char *desc)
1564 {
1565         CDDerivedMesh *cddm;
1566         DerivedMesh *dm;
1567
1568         cddm = MEM_callocN(sizeof(*cddm), desc);
1569         dm = &cddm->dm;
1570
1571         dm->getMinMax = cdDM_getMinMax;
1572
1573         dm->getNumVerts = cdDM_getNumVerts;
1574         dm->getNumEdges = cdDM_getNumEdges;
1575         dm->getNumTessFaces = cdDM_getNumTessFaces;
1576         dm->getNumLoops = cdDM_getNumLoops;
1577         dm->getNumPolys = cdDM_getNumPolys;
1578
1579         dm->getVert = cdDM_getVert;
1580         dm->getEdge = cdDM_getEdge;
1581         dm->getTessFace = cdDM_getTessFace;
1582
1583         dm->copyVertArray = cdDM_copyVertArray;
1584         dm->copyEdgeArray = cdDM_copyEdgeArray;
1585         dm->copyTessFaceArray = cdDM_copyTessFaceArray;
1586         dm->copyLoopArray = cdDM_copyLoopArray;
1587         dm->copyPolyArray = cdDM_copyPolyArray;
1588
1589         dm->getVertData = DM_get_vert_data;
1590         dm->getEdgeData = DM_get_edge_data;
1591         dm->getTessFaceData = DM_get_tessface_data;
1592         dm->getVertDataArray = DM_get_vert_data_layer;
1593         dm->getEdgeDataArray = DM_get_edge_data_layer;
1594         dm->getTessFaceDataArray = DM_get_tessface_data_layer;
1595
1596         dm->calcNormals = CDDM_calc_normals_mapping;
1597         dm->recalcTessellation = CDDM_recalc_tessellation;
1598
1599         dm->getVertCos = cdDM_getVertCos;
1600         dm->getVertCo = cdDM_getVertCo;
1601         dm->getVertNo = cdDM_getVertNo;
1602
1603         dm->getPBVH = cdDM_getPBVH;
1604         dm->getPolyMap = cdDM_getPolyMap;
1605
1606         dm->drawVerts = cdDM_drawVerts;
1607
1608         dm->drawUVEdges = cdDM_drawUVEdges;
1609         dm->drawEdges = cdDM_drawEdges;
1610         dm->drawLooseEdges = cdDM_drawLooseEdges;
1611         dm->drawMappedEdges = cdDM_drawMappedEdges;
1612
1613         dm->drawFacesSolid = cdDM_drawFacesSolid;
1614         dm->drawFacesTex = cdDM_drawFacesTex;
1615         dm->drawFacesGLSL = cdDM_drawFacesGLSL;
1616         dm->drawMappedFaces = cdDM_drawMappedFaces;
1617         dm->drawMappedFacesTex = cdDM_drawMappedFacesTex;
1618         dm->drawMappedFacesGLSL = cdDM_drawMappedFacesGLSL;
1619         dm->drawMappedFacesMat = cdDM_drawMappedFacesMat;
1620
1621         dm->foreachMappedVert = cdDM_foreachMappedVert;
1622         dm->foreachMappedEdge = cdDM_foreachMappedEdge;
1623         dm->foreachMappedFaceCenter = cdDM_foreachMappedFaceCenter;
1624
1625         dm->release = cdDM_release;
1626
1627         return cddm;
1628 }
1629
1630 DerivedMesh *CDDM_new(int numVerts, int numEdges, int numTessFaces, int numLoops, int numPolys)
1631 {
1632         CDDerivedMesh *cddm = cdDM_create("CDDM_new dm");
1633         DerivedMesh *dm = &cddm->dm;
1634
1635         DM_init(dm, DM_TYPE_CDDM, numVerts, numEdges, numTessFaces, numLoops, numPolys);
1636
1637         CustomData_add_layer(&dm->vertData, CD_ORIGINDEX, CD_CALLOC, NULL, numVerts);
1638         CustomData_add_layer(&dm->edgeData, CD_ORIGINDEX, CD_CALLOC, NULL, numEdges);
1639         CustomData_add_layer(&dm->faceData, CD_ORIGINDEX, CD_CALLOC, NULL, numTessFaces);
1640         CustomData_add_layer(&dm->faceData, CD_POLYINDEX, CD_CALLOC, NULL, numTessFaces);
1641         CustomData_add_layer(&dm->polyData, CD_ORIGINDEX, CD_CALLOC, NULL, numPolys);
1642
1643         CustomData_add_layer(&dm->vertData, CD_MVERT, CD_CALLOC, NULL, numVerts);
1644         CustomData_add_layer(&dm->edgeData, CD_MEDGE, CD_CALLOC, NULL, numEdges);
1645         CustomData_add_layer(&dm->faceData, CD_MFACE, CD_CALLOC, NULL, numTessFaces);
1646         CustomData_add_layer(&dm->loopData, CD_MLOOP, CD_CALLOC, NULL, numLoops);
1647         CustomData_add_layer(&dm->polyData, CD_MPOLY, CD_CALLOC, NULL, numPolys);
1648
1649         cddm->mvert = CustomData_get_layer(&dm->vertData, CD_MVERT);
1650         cddm->medge = CustomData_get_layer(&dm->edgeData, CD_MEDGE);
1651         cddm->mface = CustomData_get_layer(&dm->faceData, CD_MFACE);
1652         cddm->mloop = CustomData_get_layer(&dm->loopData, CD_MLOOP);
1653         cddm->mpoly = CustomData_get_layer(&dm->polyData, CD_MPOLY);
1654
1655         return dm;
1656 }
1657
1658 DerivedMesh *CDDM_from_mesh(Mesh *mesh, Object *UNUSED(ob))
1659 {
1660         CDDerivedMesh *cddm = cdDM_create("CDDM_from_mesh dm");
1661         DerivedMesh *dm = &cddm->dm;
1662         CustomDataMask mask = CD_MASK_MESH & (~CD_MASK_MDISPS);
1663         int alloctype;
1664         int *polyindex = NULL;
1665
1666         /* this does a referenced copy, with an exception for fluidsim */
1667
1668         DM_init(dm, DM_TYPE_CDDM, mesh->totvert, mesh->totedge, mesh->totface,
1669                     mesh->totloop, mesh->totpoly);
1670
1671         dm->deformedOnly = 1;
1672
1673         alloctype= CD_REFERENCE;
1674
1675         CustomData_merge(&mesh->vdata, &dm->vertData, mask, alloctype,
1676                                          mesh->totvert);
1677         CustomData_merge(&mesh->edata, &dm->edgeData, mask, alloctype,
1678                                          mesh->totedge);
1679         CustomData_merge(&mesh->fdata, &dm->faceData, mask|CD_MASK_POLYINDEX, alloctype,
1680                                          mesh->totface);
1681         CustomData_merge(&mesh->ldata, &dm->loopData, mask, alloctype,
1682                          mesh->totloop);
1683         CustomData_merge(&mesh->pdata, &dm->polyData, mask, alloctype,
1684                          mesh->totpoly);
1685
1686         cddm->mvert = CustomData_get_layer(&dm->vertData, CD_MVERT);
1687         cddm->medge = CustomData_get_layer(&dm->edgeData, CD_MEDGE);
1688         cddm->mloop = CustomData_get_layer(&dm->loopData, CD_MLOOP);
1689         cddm->mpoly = CustomData_get_layer(&dm->polyData, CD_MPOLY);
1690         cddm->mface = CustomData_get_layer(&dm->faceData, CD_MFACE);
1691
1692         /* commented since even when CD_POLYINDEX was first added this line fails
1693          * on the default cube, (after editmode toggle too) - campbell */
1694 #if 0
1695         BLI_assert(CustomData_has_layer(&cddm->dm.faceData, CD_POLYINDEX));
1696 #endif
1697
1698         polyindex = CustomData_get_layer(&dm->faceData, CD_POLYINDEX);
1699         if (!CustomData_has_layer(&cddm->dm.faceData, CD_ORIGINDEX)) {
1700                 CustomData_add_layer(&dm->faceData, CD_ORIGINDEX, CD_REFERENCE, polyindex, mesh->totface);
1701         }
1702
1703         return dm;
1704 }
1705
1706 DerivedMesh *CDDM_from_curve(Object *ob)
1707 {
1708         return CDDM_from_curve_customDB(ob, &ob->disp);
1709 }
1710
1711 DerivedMesh *CDDM_from_curve_customDB(Object *ob, ListBase *dispbase)
1712 {
1713         DerivedMesh *dm;
1714         CDDerivedMesh *cddm;
1715         MVert *allvert;
1716         MEdge *alledge;
1717         MLoop *allloop;
1718         MPoly *allpoly;
1719         int totvert, totedge, totloop, totpoly;
1720
1721         if (nurbs_to_mdata_customdb(ob, dispbase, &allvert, &totvert, &alledge,
1722                 &totedge, &allloop, &allpoly, &totloop, &totpoly) != 0) {
1723                 /* Error initializing mdata. This often happens when curve is empty */
1724                 return CDDM_new(0, 0, 0, 0, 0);
1725         }
1726
1727         dm = CDDM_new(totvert, totedge, 0, totloop, totpoly);
1728         dm->deformedOnly = 1;
1729
1730         cddm = (CDDerivedMesh*)dm;
1731
1732         memcpy(cddm->mvert, allvert, totvert*sizeof(MVert));
1733         memcpy(cddm->medge, alledge, totedge*sizeof(MEdge));
1734         memcpy(cddm->mloop, allloop, totloop*sizeof(MLoop));
1735         memcpy(cddm->mpoly, allpoly, totpoly*sizeof(MPoly));
1736
1737         MEM_freeN(allvert);
1738         MEM_freeN(alledge);
1739         MEM_freeN(allloop);
1740         MEM_freeN(allpoly);
1741
1742         CDDM_calc_edges(dm);
1743
1744         return dm;
1745 }
1746
1747 static void loops_to_customdata_corners(BMesh *bm, CustomData *facedata,
1748                                           int cdindex, BMLoop *l3[3],
1749                                           int numCol, int numTex)
1750 {
1751         BMLoop *l;
1752         BMFace *f = l3[0]->f;
1753         MTFace *texface;
1754         MTexPoly *texpoly;
1755         MCol *mcol;
1756         MLoopCol *mloopcol;
1757         MLoopUV *mloopuv;
1758         int i, j, hasPCol = CustomData_has_layer(&bm->ldata, CD_PREVIEW_MLOOPCOL);
1759
1760         for (i=0; i < numTex; i++) {
1761                 texface = CustomData_get_n(facedata, CD_MTFACE, cdindex, i);
1762                 texpoly = CustomData_bmesh_get_n(&bm->pdata, f->head.data, CD_MTEXPOLY, i);
1763                 
1764                 ME_MTEXFACE_CPY(texface, texpoly);
1765         
1766                 for (j=0; j<3; j++) {
1767                         l = l3[j];
1768                         mloopuv = CustomData_bmesh_get_n(&bm->ldata, l->head.data, CD_MLOOPUV, i);
1769                         copy_v2_v2(texface->uv[j], mloopuv->uv);
1770                 }
1771         }
1772
1773         for (i=0; i < numCol; i++) {
1774                 mcol = CustomData_get_n(facedata, CD_MCOL, cdindex, i);
1775                 
1776                 for (j=0; j<3; j++) {
1777                         l = l3[j];
1778                         mloopcol = CustomData_bmesh_get_n(&bm->ldata, l->head.data, CD_MLOOPCOL, i);
1779                         MESH_MLOOPCOL_TO_MCOL(mloopcol, &mcol[j]);
1780                 }
1781         }
1782
1783         if (hasPCol) {
1784                 mcol = CustomData_get(facedata, cdindex, CD_PREVIEW_MCOL);
1785
1786                 for (j=0; j<3; j++) {
1787                         l = l3[j];
1788                         mloopcol = CustomData_bmesh_get(&bm->ldata, l->head.data, CD_PREVIEW_MLOOPCOL);
1789                         MESH_MLOOPCOL_TO_MCOL(mloopcol, &mcol[j]);
1790                 }
1791         }
1792 }
1793
1794 DerivedMesh *CDDM_from_BMEditMesh(BMEditMesh *em, Mesh *UNUSED(me), int use_mdisps, int use_tessface)
1795 {
1796         BMesh *bm = em->bm;
1797
1798         DerivedMesh *dm = CDDM_new(bm->totvert,
1799                                    bm->totedge,
1800                                    use_tessface ? em->tottri : 0,
1801                                    bm->totloop,
1802                                    bm->totface);
1803
1804         CDDerivedMesh *cddm = (CDDerivedMesh*)dm;
1805         BMIter iter, liter;
1806         BMVert *eve;
1807         BMEdge *eed;
1808         BMFace *efa;
1809         MVert *mvert = cddm->mvert;
1810         MEdge *medge = cddm->medge;
1811         MFace *mface = cddm->mface;
1812         MLoop *mloop = cddm->mloop;
1813         MPoly *mpoly = cddm->mpoly;
1814         int numCol = CustomData_number_of_layers(&bm->ldata, CD_MLOOPCOL);
1815         int numTex = CustomData_number_of_layers(&bm->pdata, CD_MTEXPOLY);
1816         int *index, add_orig;
1817         int has_crease, has_edge_bweight, has_vert_bweight;
1818         CustomDataMask mask;
1819         unsigned int i, j;
1820         
1821         has_edge_bweight = CustomData_has_layer(&bm->edata, CD_BWEIGHT);
1822         has_vert_bweight = CustomData_has_layer(&bm->vdata, CD_BWEIGHT);
1823         has_crease = CustomData_has_layer(&bm->edata, CD_CREASE);
1824         
1825         dm->deformedOnly = 1;
1826         
1827         /*don't add origindex layer if one already exists*/
1828         add_orig = !CustomData_has_layer(&bm->pdata, CD_ORIGINDEX);
1829
1830         mask = use_mdisps ? CD_MASK_DERIVEDMESH|CD_MASK_MDISPS : CD_MASK_DERIVEDMESH;
1831         
1832         /* don't process shapekeys, we only feed them through the modifier stack as needed,
1833          * e.g. for applying modifiers or the like*/
1834         mask &= ~CD_MASK_SHAPEKEY;
1835         CustomData_merge(&bm->vdata, &dm->vertData, mask,
1836                          CD_CALLOC, dm->numVertData);
1837         CustomData_merge(&bm->edata, &dm->edgeData, mask,
1838                          CD_CALLOC, dm->numEdgeData);
1839         CustomData_merge(&bm->ldata, &dm->loopData, mask,
1840                          CD_CALLOC, dm->numLoopData);
1841         CustomData_merge(&bm->pdata, &dm->polyData, mask,
1842                          CD_CALLOC, dm->numPolyData);
1843         
1844         /*add tessellation mface layers*/
1845         if (use_tessface) {
1846                 CustomData_from_bmeshpoly(&dm->faceData, &dm->polyData, &dm->loopData, em->tottri);
1847         }
1848
1849         index = dm->getVertDataArray(dm, CD_ORIGINDEX);
1850
1851         eve = BM_iter_new(&iter, bm, BM_VERTS_OF_MESH, NULL);
1852         for (i=0; eve; eve=BM_iter_step(&iter), i++, index++) {
1853                 MVert *mv = &mvert[i];
1854
1855                 copy_v3_v3(mv->co, eve->co);
1856
1857                 BM_elem_index_set(eve, i); /* set_inline */
1858
1859                 normal_float_to_short_v3(mv->no, eve->no);
1860
1861                 mv->flag = BM_vert_flag_to_mflag(eve);
1862
1863                 if (has_vert_bweight)
1864                         mv->bweight = (unsigned char)(BM_elem_float_data_get(&bm->vdata, eve, CD_BWEIGHT)*255.0f);
1865
1866                 if (add_orig) *index = i;
1867
1868                 CustomData_from_bmesh_block(&bm->vdata, &dm->vertData, eve->head.data, i);
1869         }
1870         bm->elem_index_dirty &= ~BM_VERT;
1871
1872         index = dm->getEdgeDataArray(dm, CD_ORIGINDEX);
1873         eed = BM_iter_new(&iter, bm, BM_EDGES_OF_MESH, NULL);
1874         for (i=0; eed; eed=BM_iter_step(&iter), i++, index++) {
1875                 MEdge *med = &medge[i];
1876
1877                 BM_elem_index_set(eed, i); /* set_inline */
1878
1879                 med->v1 = BM_elem_index_get(eed->v1);
1880                 med->v2 = BM_elem_index_get(eed->v2);
1881
1882                 if (has_crease)
1883                         med->crease = (unsigned char)(BM_elem_float_data_get(&bm->edata, eed, CD_CREASE)*255.0f);
1884                 if (has_edge_bweight)
1885                         med->bweight = (unsigned char)(BM_elem_float_data_get(&bm->edata, eed, CD_BWEIGHT)*255.0f);
1886                 
1887                 med->flag = BM_edge_flag_to_mflag(eed);
1888
1889                 CustomData_from_bmesh_block(&bm->edata, &dm->edgeData, eed->head.data, i);
1890                 if (add_orig) *index = i;
1891         }
1892         bm->elem_index_dirty &= ~BM_EDGE;
1893
1894         /* avoid this where possiblem, takes extra memory */
1895         if (use_tessface) {
1896                 int *polyindex;
1897
1898                 BM_mesh_elem_index_ensure(bm, BM_FACE);
1899
1900                 polyindex = dm->getTessFaceDataArray(dm, CD_POLYINDEX);
1901                 index = dm->getTessFaceDataArray(dm, CD_ORIGINDEX);
1902                 for (i = 0; i < dm->numTessFaceData; i++, index++, polyindex++) {
1903                         MFace *mf = &mface[i];
1904                         BMLoop **l = em->looptris[i];
1905                         efa = l[0]->f;
1906
1907                         mf->v1 = BM_elem_index_get(l[0]->v);
1908                         mf->v2 = BM_elem_index_get(l[1]->v);
1909                         mf->v3 = BM_elem_index_get(l[2]->v);
1910                         mf->v4 = 0;
1911                         mf->mat_nr = efa->mat_nr;
1912                         mf->flag = BM_face_flag_to_mflag(efa);
1913
1914                         *index = add_orig ? BM_elem_index_get(efa) : *(int*)CustomData_bmesh_get(&bm->pdata, efa->head.data, CD_ORIGINDEX);
1915                         *polyindex = BM_elem_index_get(efa);
1916
1917                         loops_to_customdata_corners(bm, &dm->faceData, i, l, numCol, numTex);
1918                         test_index_face(mf, &dm->faceData, i, 3);
1919                 }
1920         }
1921         
1922         index = CustomData_get_layer(&dm->polyData, CD_ORIGINDEX);
1923         j = 0;
1924         efa = BM_iter_new(&iter, bm, BM_FACES_OF_MESH, NULL);
1925         for (i=0; efa; i++, efa=BM_iter_step(&iter), index++) {
1926                 BMLoop *l;
1927                 MPoly *mp = &mpoly[i];
1928
1929                 BM_elem_index_set(efa, i); /* set_inline */
1930
1931                 mp->totloop = efa->len;
1932                 mp->flag = BM_face_flag_to_mflag(efa);
1933                 mp->loopstart = j;
1934                 mp->mat_nr = efa->mat_nr;
1935                 
1936                 BM_ITER_ELEM (l, &liter, efa, BM_LOOPS_OF_FACE) {
1937                         mloop->v = BM_elem_index_get(l->v);
1938                         mloop->e = BM_elem_index_get(l->e);
1939                         CustomData_from_bmesh_block(&bm->ldata, &dm->loopData, l->head.data, j);
1940
1941                         j++;
1942                         mloop++;
1943                 }
1944
1945                 CustomData_from_bmesh_block(&bm->pdata, &dm->polyData, efa->head.data, i);
1946
1947                 if (add_orig) *index = i;
1948         }
1949         bm->elem_index_dirty &= ~BM_FACE;
1950
1951         return dm;
1952 }
1953
1954 static DerivedMesh *cddm_copy_ex(DerivedMesh *source, int faces_from_tessfaces)
1955 {
1956         CDDerivedMesh *cddm = cdDM_create("CDDM_copy cddm");
1957         DerivedMesh *dm = &cddm->dm;
1958         int numVerts = source->numVertData;
1959         int numEdges = source->numEdgeData;
1960         int numTessFaces = source->numTessFaceData;
1961         int numLoops = source->numLoopData;
1962         int numPolys = source->numPolyData;
1963
1964         /* ensure these are created if they are made on demand */
1965         source->getVertDataArray(source, CD_ORIGINDEX);
1966         source->getEdgeDataArray(source, CD_ORIGINDEX);
1967         source->getTessFaceDataArray(source, CD_ORIGINDEX);
1968
1969         /* this initializes dm, and copies all non mvert/medge/mface layers */
1970         DM_from_template(dm, source, DM_TYPE_CDDM, numVerts, numEdges, numTessFaces,
1971                 numLoops, numPolys);
1972         dm->deformedOnly = source->deformedOnly;
1973         dm->dirty = source->dirty;
1974
1975         CustomData_copy_data(&source->vertData, &dm->vertData, 0, 0, numVerts);
1976         CustomData_copy_data(&source->edgeData, &dm->edgeData, 0, 0, numEdges);
1977         CustomData_copy_data(&source->faceData, &dm->faceData, 0, 0, numTessFaces);
1978
1979         /* now add mvert/medge/mface layers */
1980         cddm->mvert = source->dupVertArray(source);
1981         cddm->medge = source->dupEdgeArray(source);
1982         cddm->mface = source->dupTessFaceArray(source);
1983
1984         CustomData_add_layer(&dm->vertData, CD_MVERT, CD_ASSIGN, cddm->mvert, numVerts);
1985         CustomData_add_layer(&dm->edgeData, CD_MEDGE, CD_ASSIGN, cddm->medge, numEdges);
1986         CustomData_add_layer(&dm->faceData, CD_MFACE, CD_ASSIGN, cddm->mface, numTessFaces);
1987         
1988         if (!faces_from_tessfaces)
1989                 DM_DupPolys(source, dm);
1990         else
1991                 CDDM_tessfaces_to_faces(dm);
1992
1993         cddm->mloop = CustomData_get_layer(&dm->loopData, CD_MLOOP);
1994         cddm->mpoly = CustomData_get_layer(&dm->polyData, CD_MPOLY);
1995
1996         return dm;
1997 }
1998
1999 DerivedMesh *CDDM_copy(DerivedMesh *source)
2000 {
2001         return cddm_copy_ex(source, 0);
2002 }
2003
2004 DerivedMesh *CDDM_copy_from_tessface(DerivedMesh *source)
2005 {
2006         return cddm_copy_ex(source, 1);
2007 }
2008
2009 /* note, the CD_ORIGINDEX layers are all 0, so if there is a direct
2010  * relationship between mesh data this needs to be set by the caller. */
2011 DerivedMesh *CDDM_from_template(DerivedMesh *source,
2012                                 int numVerts, int numEdges, int numTessFaces,
2013                                 int numLoops, int numPolys)
2014 {
2015         CDDerivedMesh *cddm = cdDM_create("CDDM_from_template dest");
2016         DerivedMesh *dm = &cddm->dm;
2017
2018         /* ensure these are created if they are made on demand */
2019         source->getVertDataArray(source, CD_ORIGINDEX);
2020         source->getEdgeDataArray(source, CD_ORIGINDEX);
2021         source->getTessFaceDataArray(source, CD_ORIGINDEX);
2022
2023         /* this does a copy of all non mvert/medge/mface layers */
2024         DM_from_template(dm, source, DM_TYPE_CDDM, numVerts, numEdges, numTessFaces, numLoops, numPolys);
2025
2026         /* now add mvert/medge/mface layers */
2027         CustomData_add_layer(&dm->vertData, CD_MVERT, CD_CALLOC, NULL, numVerts);
2028         CustomData_add_layer(&dm->edgeData, CD_MEDGE, CD_CALLOC, NULL, numEdges);
2029         CustomData_add_layer(&dm->faceData, CD_MFACE, CD_CALLOC, NULL, numTessFaces);
2030         CustomData_add_layer(&dm->loopData, CD_MLOOP, CD_CALLOC, NULL, numLoops);
2031         CustomData_add_layer(&dm->polyData, CD_MPOLY, CD_CALLOC, NULL, numPolys);
2032
2033         if (!CustomData_get_layer(&dm->vertData, CD_ORIGINDEX))
2034                 CustomData_add_layer(&dm->vertData, CD_ORIGINDEX, CD_CALLOC, NULL, numVerts);
2035         if (!CustomData_get_layer(&dm->edgeData, CD_ORIGINDEX))
2036                 CustomData_add_layer(&dm->edgeData, CD_ORIGINDEX, CD_CALLOC, NULL, numEdges);
2037         if (!CustomData_get_layer(&dm->faceData, CD_ORIGINDEX))
2038                 CustomData_add_layer(&dm->faceData, CD_ORIGINDEX, CD_CALLOC, NULL, numTessFaces);
2039         if (!CustomData_get_layer(&dm->faceData, CD_POLYINDEX))
2040                 CustomData_add_layer(&dm->faceData, CD_POLYINDEX, CD_CALLOC, NULL, numTessFaces);
2041
2042         cddm->mvert = CustomData_get_layer(&dm->vertData, CD_MVERT);
2043         cddm->medge = CustomData_get_layer(&dm->edgeData, CD_MEDGE);
2044         cddm->mface = CustomData_get_layer(&dm->faceData, CD_MFACE);
2045         cddm->mloop = CustomData_get_layer(&dm->loopData, CD_MLOOP);
2046         cddm->mpoly = CustomData_get_layer(&dm->polyData, CD_MPOLY);
2047
2048         return dm;
2049 }
2050
2051 void CDDM_apply_vert_coords(DerivedMesh *dm, float (*vertCoords)[3])
2052 {
2053         CDDerivedMesh *cddm = (CDDerivedMesh*)dm;
2054         MVert *vert;
2055         int i;
2056
2057         /* this will just return the pointer if it wasn't a referenced layer */
2058         vert = CustomData_duplicate_referenced_layer(&dm->vertData, CD_MVERT, dm->numVertData);
2059         cddm->mvert = vert;
2060
2061         for (i = 0; i < dm->numVertData; ++i, ++vert)
2062                 copy_v3_v3(vert->co, vertCoords[i]);
2063 }
2064
2065 void CDDM_apply_vert_normals(DerivedMesh *dm, short (*vertNormals)[3])
2066 {
2067         CDDerivedMesh *cddm = (CDDerivedMesh*)dm;
2068         MVert *vert;
2069         int i;
2070
2071         /* this will just return the pointer if it wasn't a referenced layer */
2072         vert = CustomData_duplicate_referenced_layer(&dm->vertData, CD_MVERT, dm->numVertData);
2073         cddm->mvert = vert;
2074
2075         for (i = 0; i < dm->numVertData; ++i, ++vert)
2076                 copy_v3_v3_short(vert->no, vertNormals[i]);
2077 }
2078
2079 void CDDM_calc_normals_mapping_ex(DerivedMesh *dm, const short only_face_normals)
2080 {
2081         CDDerivedMesh *cddm = (CDDerivedMesh*)dm;
2082         float (*face_nors)[3] = NULL;
2083
2084         if (dm->numVertData == 0) return;
2085
2086         /* now we skip calculating vertex normals for referenced layer,
2087          * no need to duplicate verts.
2088          * WATCH THIS, bmesh only change!,
2089          * need to take care of the side effects here - campbell */
2090         #if 0
2091         /* we don't want to overwrite any referenced layers */
2092         cddm->mvert = CustomData_duplicate_referenced_layer(&dm->vertData, CD_MVERT, dm->numVertData);
2093         #endif
2094
2095
2096         if (dm->numTessFaceData == 0) {
2097                 /* No tessellation on this mesh yet, need to calculate one.
2098                  *
2099                  * Important not to update face normals from polys since it
2100                  * interfears with assigning the new normal layer in the following code.
2101                  */
2102                 CDDM_recalc_tessellation_ex(dm, FALSE);
2103         }
2104         else {
2105                 /* A tessellation already exists, it should always have a CD_POLYINDEX */
2106                 BLI_assert(CustomData_has_layer(&dm->faceData, CD_POLYINDEX));
2107                 CustomData_free_layers(&dm->faceData, CD_NORMAL, dm->numTessFaceData);
2108         }
2109
2110
2111         face_nors = MEM_mallocN(sizeof(float)*3*dm->numTessFaceData, "face_nors");
2112
2113         /* calculate face normals */
2114         mesh_calc_normals_mapping_ex(cddm->mvert, dm->numVertData, CDDM_get_loops(dm), CDDM_get_polys(dm),
2115                                                                  dm->numLoopData, dm->numPolyData, NULL, cddm->mface, dm->numTessFaceData,
2116                                                                  CustomData_get_layer(&dm->faceData, CD_POLYINDEX), face_nors,
2117                                                                  only_face_normals);
2118
2119         CustomData_add_layer(&dm->faceData, CD_NORMAL, CD_ASSIGN,
2120                                                  face_nors, dm->numTessFaceData);
2121 }
2122
2123
2124 void CDDM_calc_normals_mapping(DerivedMesh *dm)
2125 {
2126         /* use this to skip calculating normals on original vert's, this may need to be changed */
2127         const short only_face_normals = CustomData_is_referenced_layer(&dm->vertData, CD_MVERT);
2128
2129         CDDM_calc_normals_mapping_ex(dm, only_face_normals);
2130 }
2131
2132 /* bmesh note: this matches what we have in trunk */
2133 void CDDM_calc_normals(DerivedMesh *dm)
2134 {
2135         CDDerivedMesh *cddm = (CDDerivedMesh*)dm;
2136         float (*poly_nors)[3];
2137
2138         if (dm->numVertData == 0) return;
2139
2140         /* we don't want to overwrite any referenced layers */
2141         cddm->mvert = CustomData_duplicate_referenced_layer(&dm->vertData, CD_MVERT, dm->numVertData);
2142
2143         /* fill in if it exists */
2144         poly_nors = CustomData_get_layer(&dm->polyData, CD_NORMAL);
2145         if (!poly_nors) {
2146                 poly_nors = CustomData_add_layer(&dm->polyData, CD_NORMAL, CD_CALLOC, NULL, dm->numPolyData);
2147         }
2148
2149         mesh_calc_normals(cddm->mvert, dm->numVertData, CDDM_get_loops(dm), CDDM_get_polys(dm),
2150                           dm->numLoopData, dm->numPolyData, poly_nors);
2151 }
2152
2153 void CDDM_calc_normals_tessface(DerivedMesh *dm)
2154 {
2155         CDDerivedMesh *cddm = (CDDerivedMesh*)dm;
2156         float (*face_nors)[3];
2157
2158         if (dm->numVertData == 0) return;
2159
2160         /* we don't want to overwrite any referenced layers */
2161         cddm->mvert = CustomData_duplicate_referenced_layer(&dm->vertData, CD_MVERT, dm->numVertData);
2162
2163         /* fill in if it exists */
2164         face_nors = CustomData_get_layer(&dm->faceData, CD_NORMAL);
2165         if (!face_nors) {
2166                 face_nors = CustomData_add_layer(&dm->faceData, CD_NORMAL, CD_CALLOC, NULL, dm->numTessFaceData);
2167         }
2168
2169         mesh_calc_normals_tessface(cddm->mvert, dm->numVertData,
2170                                                            cddm->mface, dm->numTessFaceData, face_nors);
2171 }
2172
2173 #if 1
2174 /* merge verts
2175  *
2176  * vtargetmap is a table that maps vertices to target vertices.  a value of -1
2177  * indicates a vertex is a target, and is to be kept.
2178  *
2179  * this frees dm, and returns a new one.
2180  *
2181  * this is a really horribly written function.  ger. - joeedh
2182  *
2183  * note, CDDM_recalc_tessellation has to run on the returned DM if you want to access tessfaces.
2184  */
2185 DerivedMesh *CDDM_merge_verts(DerivedMesh *dm, const int *vtargetmap)
2186 {
2187         CDDerivedMesh *cddm = (CDDerivedMesh*)dm;
2188         CDDerivedMesh *cddm2 = NULL;
2189         MVert *mv, *mvert = NULL;
2190         BLI_array_declare(mvert);
2191         MEdge *med, *medge = NULL;
2192         BLI_array_declare(medge);
2193         MPoly *mp, *mpoly = NULL;
2194         BLI_array_declare(mpoly);
2195         MLoop *ml, *mloop = NULL;
2196         BLI_array_declare(mloop);
2197         EdgeHash *ehash = BLI_edgehash_new();
2198         int *newv = NULL, *newe = NULL, *newl = NULL;
2199         int *oldv = NULL, *olde = NULL, *oldl = NULL, *oldp = NULL;
2200         BLI_array_declare(oldv); BLI_array_declare(olde); BLI_array_declare(oldl); BLI_array_declare(oldp);
2201         int i, j, c, totloop, totpoly;
2202         
2203         totloop = dm->numLoopData;
2204         totpoly = dm->numPolyData;
2205         
2206         newv = MEM_callocN(sizeof(int)*dm->numVertData, "newv vtable CDDM_merge_verts");
2207         newe = MEM_callocN(sizeof(int)*dm->numEdgeData, "newv etable CDDM_merge_verts");
2208         newl = MEM_callocN(sizeof(int)*totloop, "newv ltable CDDM_merge_verts");
2209         
2210         /*fill newl with destination vertex indices*/
2211         mv = cddm->mvert;
2212         c = 0;
2213         for (i=0; i<dm->numVertData; i++, mv++) {
2214                 if (vtargetmap[i] == -1) {
2215                         BLI_array_append(oldv, i);
2216                         newv[i] = c++;
2217                         BLI_array_append(mvert, *mv);
2218                 }
2219         }
2220         
2221         /*now link target vertices to destination indices*/
2222         for (i=0; i<dm->numVertData; i++) {
2223                 if (vtargetmap[i] != -1) {
2224                         newv[i] = newv[vtargetmap[i]];
2225                 }
2226         }
2227         
2228         /*find-replace merged vertices with target vertices*/   
2229         ml = cddm->mloop;
2230         for (i=0; i<totloop; i++, ml++) {
2231                 if (vtargetmap[ml->v] != -1) {
2232                         ml->v = vtargetmap[ml->v];
2233                 }
2234         }
2235
2236         /*now go through and fix edges and faces*/
2237         med = cddm->medge;
2238         c = 0;
2239         for (i=0; i<dm->numEdgeData; i++, med++) {
2240                 
2241                 if (LIKELY(med->v1 != med->v2)) {
2242                         const unsigned int v1 = (vtargetmap[med->v1] != -1) ? vtargetmap[med->v1] : med->v1;
2243                         const unsigned int v2 = (vtargetmap[med->v2] != -1) ? vtargetmap[med->v2] : med->v2;
2244                         void **eh_p= BLI_edgehash_lookup_p(ehash, v1, v2);
2245
2246                         if (eh_p) {
2247                                 newe[i] = GET_INT_FROM_POINTER(*eh_p);
2248                         }
2249                         else {
2250                                 BLI_array_append(olde, i);
2251                                 newe[i] = c;
2252                                 BLI_array_append(medge, *med);
2253                                 BLI_edgehash_insert(ehash, v1, v2, SET_INT_IN_POINTER(c));
2254                                 c++;
2255                         }
2256                 }
2257                 else {
2258                         newe[i] = -1;
2259                 }
2260         }
2261         
2262         mp = cddm->mpoly;
2263         for (i=0; i<totpoly; i++, mp++) {
2264                 MPoly *mp2;
2265                 
2266                 ml = cddm->mloop + mp->loopstart;
2267
2268                 c = 0;
2269                 for (j=0; j<mp->totloop; j++, ml++) {
2270                         med = cddm->medge + ml->e;
2271                         if (LIKELY(med->v1 != med->v2)) {
2272                                 newl[j+mp->loopstart] = BLI_array_count(mloop);
2273                                 BLI_array_append(oldl, j+mp->loopstart);
2274                                 BLI_array_append(mloop, *ml);
2275                                 c++;
2276                         }
2277                 }
2278
2279                 if (UNLIKELY(c == 0)) {
2280                         continue;
2281                 }
2282                 
2283                 mp2 = BLI_array_append_r(mpoly, *mp);
2284                 mp2->totloop = c;
2285                 mp2->loopstart = BLI_array_count(mloop) - c;
2286                 
2287                 BLI_array_append(oldp, i);
2288         }
2289         
2290         /*create new cddm*/     
2291         cddm2 = (CDDerivedMesh*) CDDM_from_template((DerivedMesh*)cddm, BLI_array_count(mvert), BLI_array_count(medge), 0, BLI_array_count(mloop), BLI_array_count(mpoly));
2292         
2293         /*update edge indices and copy customdata*/
2294         med = medge;
2295         for (i=0; i<cddm2->dm.numEdgeData; i++, med++) {
2296                 if (newv[med->v1] != -1)
2297                         med->v1 = newv[med->v1];
2298                 if (newv[med->v2] != -1)
2299                         med->v2 = newv[med->v2];
2300                 
2301                 CustomData_copy_data(&dm->edgeData, &cddm2->dm.edgeData, olde[i], i, 1);
2302         }
2303         
2304         /*update loop indices and copy customdata*/
2305         ml = mloop;
2306         for (i=0; i<cddm2->dm.numLoopData; i++, ml++) {
2307                 if (newe[ml->e] != -1)
2308                         ml->e = newe[ml->e];
2309                 if (newv[ml->v] != -1)
2310                         ml->v = newv[ml->v];
2311                         
2312                 CustomData_copy_data(&dm->loopData, &cddm2->dm.loopData, oldl[i], i, 1);
2313         }
2314         
2315         /*copy vertex customdata*/      
2316         mv = mvert;
2317         for (i=0; i<cddm2->dm.numVertData; i++, mv++) {
2318                 CustomData_copy_data(&dm->vertData, &cddm2->dm.vertData, oldv[i], i, 1);
2319         }
2320         
2321         /*copy poly customdata*/
2322         mp = mpoly;
2323         for (i=0; i<cddm2->dm.numPolyData; i++, mp++) {
2324                 CustomData_copy_data(&dm->polyData, &cddm2->dm.polyData, oldp[i], i, 1);
2325         }
2326         
2327         /*copy over data.  CustomData_add_layer can do this, need to look it up.*/
2328         memcpy(cddm2->mvert, mvert, sizeof(MVert)*BLI_array_count(mvert));
2329         memcpy(cddm2->medge, medge, sizeof(MEdge)*BLI_array_count(medge));
2330         memcpy(cddm2->mloop, mloop, sizeof(MLoop)*BLI_array_count(mloop));
2331         memcpy(cddm2->mpoly, mpoly, sizeof(MPoly)*BLI_array_count(mpoly));
2332         BLI_array_free(mvert); BLI_array_free(medge); BLI_array_free(mloop); BLI_array_free(mpoly);
2333         
2334         if (newv) 
2335                 MEM_freeN(newv); 
2336         if (newe)
2337                 MEM_freeN(newe); 
2338         if (newl)
2339                 MEM_freeN(newl);
2340         if (oldv) 
2341                 MEM_freeN(oldv); 
2342         if (olde) 
2343                 MEM_freeN(olde); 
2344         if (oldl) 
2345                 MEM_freeN(oldl); 
2346         if (oldp) 
2347                 MEM_freeN(oldp);
2348         if (ehash)
2349                 BLI_edgehash_free(ehash, NULL);
2350
2351         /*free old derivedmesh*/
2352         dm->needsFree = 1;
2353         dm->release(dm);
2354         
2355         return (DerivedMesh*)cddm2;
2356 }
2357 #endif
2358
2359 void CDDM_calc_edges_tessface(DerivedMesh *dm)
2360 {
2361         CDDerivedMesh *cddm = (CDDerivedMesh*)dm;
2362         CustomData edgeData;
2363         EdgeHashIterator *ehi;
2364         MFace *mf = cddm->mface;
2365         MEdge *med;
2366         EdgeHash *eh = BLI_edgehash_new();
2367         int i, *index, numEdges, maxFaces = dm->numTessFaceData;
2368
2369         for (i = 0; i < maxFaces; i++, mf++) {
2370                 if (!BLI_edgehash_haskey(eh, mf->v1, mf->v2))
2371                         BLI_edgehash_insert(eh, mf->v1, mf->v2, NULL);
2372                 if (!BLI_edgehash_haskey(eh, mf->v2, mf->v3))
2373                         BLI_edgehash_insert(eh, mf->v2, mf->v3, NULL);
2374                 
2375                 if (mf->v4) {
2376                         if (!BLI_edgehash_haskey(eh, mf->v3, mf->v4))
2377                                 BLI_edgehash_insert(eh, mf->v3, mf->v4, NULL);
2378                         if (!BLI_edgehash_haskey(eh, mf->v4, mf->v1))
2379                                 BLI_edgehash_insert(eh, mf->v4, mf->v1, NULL);
2380                 }
2381                 else {
2382                         if (!BLI_edgehash_haskey(eh, mf->v3, mf->v1))
2383                                 BLI_edgehash_insert(eh, mf->v3, mf->v1, NULL);
2384                 }
2385         }
2386
2387         numEdges = BLI_edgehash_size(eh);
2388
2389         /* write new edges into a temporary CustomData */
2390         memset(&edgeData, 0, sizeof(edgeData));
2391         CustomData_add_layer(&edgeData, CD_MEDGE, CD_CALLOC, NULL, numEdges);
2392         CustomData_add_layer(&edgeData, CD_ORIGINDEX, CD_CALLOC, NULL, numEdges);
2393
2394         ehi = BLI_edgehashIterator_new(eh);
2395         med = CustomData_get_layer(&edgeData, CD_MEDGE);
2396         index = CustomData_get_layer(&edgeData, CD_ORIGINDEX);
2397         for (i = 0; !BLI_edgehashIterator_isDone(ehi);
2398                 BLI_edgehashIterator_step(ehi), ++i, ++med, ++index) {
2399                 BLI_edgehashIterator_getKey(ehi, &med->v1, &med->v2);
2400
2401                 med->flag = ME_EDGEDRAW|ME_EDGERENDER;
2402                 *index = ORIGINDEX_NONE;
2403         }
2404         BLI_edgehashIterator_free(ehi);
2405
2406         /* free old CustomData and assign new one */
2407         CustomData_free(&dm->edgeData, dm->numEdgeData);
2408         dm->edgeData = edgeData;
2409         dm->numEdgeData = numEdges;
2410
2411         cddm->medge = CustomData_get_layer(&dm->edgeData, CD_MEDGE);
2412
2413         BLI_edgehash_free(eh, NULL);
2414 }
2415
2416 /* warning, this uses existing edges but CDDM_calc_edges_tessface() doesn't */
2417 void CDDM_calc_edges(DerivedMesh *dm)
2418 {
2419         CDDerivedMesh *cddm = (CDDerivedMesh*)dm;
2420         CustomData edgeData;
2421         EdgeHashIterator *ehi;
2422         MPoly *mp = cddm->mpoly;
2423         MLoop *ml;
2424         MEdge *med;
2425         EdgeHash *eh = BLI_edgehash_new();
2426         int v1, v2;
2427         int *eindex;
2428         int i, j, *index, numEdges = cddm->dm.numEdgeData, maxFaces = dm->numPolyData;
2429
2430         eindex = DM_get_edge_data_layer(dm, CD_ORIGINDEX);
2431
2432         med = cddm->medge;
2433         if (med) {
2434                 for (i=0; i < numEdges; i++, med++) {
2435                         BLI_edgehash_insert(eh, med->v1, med->v2, SET_INT_IN_POINTER(i+1));
2436                 }
2437         }
2438
2439         for (i=0; i < maxFaces; i++, mp++) {
2440                 ml = cddm->mloop + mp->loopstart;
2441                 for (j=0; j<mp->totloop; j++, ml++) {
2442                         v1 = ml->v;
2443                         v2 = ME_POLY_LOOP_NEXT(cddm->mloop, mp, j)->v;
2444                         if (!BLI_edgehash_haskey(eh, v1, v2)) {
2445                                 BLI_edgehash_insert(eh, v1, v2, NULL);
2446                         }
2447                 }
2448         }
2449
2450         numEdges = BLI_edgehash_size(eh);
2451
2452         /* write new edges into a temporary CustomData */
2453         memset(&edgeData, 0, sizeof(edgeData));
2454         CustomData_add_layer(&edgeData, CD_MEDGE, CD_CALLOC, NULL, numEdges);
2455         CustomData_add_layer(&edgeData, CD_ORIGINDEX, CD_CALLOC, NULL, numEdges);
2456
2457         ehi = BLI_edgehashIterator_new(eh);
2458         med = CustomData_get_layer(&edgeData, CD_MEDGE);
2459         index = CustomData_get_layer(&edgeData, CD_ORIGINDEX);
2460         for (i = 0; !BLI_edgehashIterator_isDone(ehi);
2461             BLI_edgehashIterator_step(ehi), ++i, ++med, ++index) {
2462                 BLI_edgehashIterator_getKey(ehi, &med->v1, &med->v2);
2463                 j = GET_INT_FROM_POINTER(BLI_edgehashIterator_getValue(ehi));
2464
2465                 med->flag = ME_EDGEDRAW|ME_EDGERENDER;
2466                 *index = j==0 ? ORIGINDEX_NONE : eindex[j-1];
2467
2468                 BLI_edgehashIterator_setValue(ehi, SET_INT_IN_POINTER(i));
2469         }
2470         BLI_edgehashIterator_free(ehi);
2471
2472         /* free old CustomData and assign new one */
2473         CustomData_free(&dm->edgeData, dm->numEdgeData);
2474         dm->edgeData = edgeData;
2475         dm->numEdgeData = numEdges;
2476
2477         cddm->medge = CustomData_get_layer(&dm->edgeData, CD_MEDGE);
2478
2479         mp = cddm->mpoly;
2480         for (i=0; i < maxFaces; i++, mp++) {
2481                 ml = cddm->mloop + mp->loopstart;
2482                 for (j=0; j<mp->totloop; j++, ml++) {
2483                         v1 = ml->v;
2484                         v2 = ME_POLY_LOOP_NEXT(cddm->mloop, mp, j)->v;
2485                         ml->e = GET_INT_FROM_POINTER(BLI_edgehash_lookup(eh, v1, v2));
2486                 }
2487         }
2488
2489         BLI_edgehash_free(eh, NULL);
2490 }
2491
2492 void CDDM_lower_num_verts(DerivedMesh *dm, int numVerts)
2493 {
2494         if (numVerts < dm->numVertData)
2495                 CustomData_free_elem(&dm->vertData, numVerts, dm->numVertData-numVerts);
2496
2497         dm->numVertData = numVerts;
2498 }
2499
2500 void CDDM_lower_num_edges(DerivedMesh *dm, int numEdges)
2501 {
2502         if (numEdges < dm->numEdgeData)
2503                 CustomData_free_elem(&dm->edgeData, numEdges, dm->numEdgeData-numEdges);
2504
2505         dm->numEdgeData = numEdges;
2506 }
2507
2508 void CDDM_lower_num_tessfaces(DerivedMesh *dm, int numTessFaces)
2509 {
2510         if (numTessFaces < dm->numTessFaceData)
2511                 CustomData_free_elem(&dm->faceData, numTessFaces, dm->numTessFaceData-numTessFaces);
2512
2513         dm->numTessFaceData = numTessFaces;
2514 }
2515
2516 void CDDM_lower_num_polys(DerivedMesh *dm, int numPolys)
2517 {
2518         if (numPolys < dm->numPolyData)
2519                 CustomData_free_elem(&dm->polyData, numPolys, dm->numPolyData-numPolys);
2520
2521         dm->numPolyData = numPolys;
2522 }
2523
2524 /* mesh element access functions */
2525
2526 MVert *CDDM_get_vert(DerivedMesh *dm, int index)
2527 {
2528         return &((CDDerivedMesh*)dm)->mvert[index];
2529 }
2530
2531 MEdge *CDDM_get_edge(DerivedMesh *dm, int index)
2532 {
2533         return &((CDDerivedMesh*)dm)->medge[index];
2534 }
2535
2536 MFace *CDDM_get_tessface(DerivedMesh *dm, int index)
2537 {
2538         return &((CDDerivedMesh*)dm)->mface[index];
2539 }
2540
2541 MLoop *CDDM_get_loop(DerivedMesh *dm, int index)
2542 {
2543         return &((CDDerivedMesh*)dm)->mloop[index];
2544 }
2545
2546 MPoly *CDDM_get_poly(DerivedMesh *dm, int index)
2547 {
2548         return &((CDDerivedMesh*)dm)->mpoly[index];
2549 }
2550
2551 /* array access functions */
2552
2553 MVert *CDDM_get_verts(DerivedMesh *dm)
2554 {
2555         return ((CDDerivedMesh*)dm)->mvert;
2556 }
2557
2558 MEdge *CDDM_get_edges(DerivedMesh *dm)
2559 {
2560         return ((CDDerivedMesh*)dm)->medge;
2561 }
2562
2563 MFace *CDDM_get_tessfaces(DerivedMesh *dm)
2564 {
2565         return ((CDDerivedMesh*)dm)->mface;
2566 }
2567
2568 MLoop *CDDM_get_loops(DerivedMesh *dm)
2569 {
2570         return ((CDDerivedMesh*)dm)->mloop;
2571 }
2572
2573 MPoly *CDDM_get_polys(DerivedMesh *dm)
2574 {
2575         return ((CDDerivedMesh*)dm)->mpoly;
2576 }
2577
2578 void CDDM_tessfaces_to_faces(DerivedMesh *dm)
2579 {
2580         /*converts mfaces to mpolys/mloops*/
2581         CDDerivedMesh *cddm = (CDDerivedMesh*)dm;
2582         MFace *mf;
2583         MEdge *me;
2584         EdgeHash *eh = BLI_edgehash_new();
2585         int i, totloop;
2586
2587         /* ... on second thaughts, better comment this and assume caller knows edge state. */
2588 #if 0
2589         /* ensure we have all the edges we need */
2590         CDDM_calc_edges_tessface(dm);
2591 #else
2592 #  ifndef NDEBUG
2593         {
2594                 /* ensure we have correct edges on non release builds */
2595                 i = cddm->dm.numEdgeData;
2596                 CDDM_calc_edges_tessface(dm);
2597                 BLI_assert(cddm->dm.numEdgeData == i);
2598         }
2599 #  endif
2600 #endif
2601
2602         /*build edge hash*/
2603         me = cddm->medge;
2604         for (i=0; i<cddm->dm.numEdgeData; i++, me++) {
2605                 BLI_edgehash_insert(eh, me->v1, me->v2, SET_INT_IN_POINTER(i));
2606         }
2607
2608         mf = cddm->mface;
2609         totloop = 0;
2610         for (i=0; i<cddm->dm.numTessFaceData; i++, mf++) {
2611                 totloop += mf->v4 ? 4 : 3;
2612         }
2613
2614         CustomData_free(&cddm->dm.polyData, cddm->dm.numPolyData);
2615         CustomData_free(&cddm->dm.loopData, cddm->dm.numLoopData);
2616         
2617         cddm->dm.numLoopData = totloop;
2618         cddm->dm.numPolyData = cddm->dm.numTessFaceData;
2619
2620         if (totloop) {
2621                 MLoop *ml;
2622                 MPoly *mp;
2623                 int l, *polyindex;
2624
2625                 cddm->mloop = MEM_callocN(sizeof(MLoop)*totloop, "cddm->mloop in CDDM_tessfaces_to_faces");
2626                 cddm->mpoly = MEM_callocN(sizeof(MPoly)*cddm->dm.numTessFaceData, "cddm->mpoly in CDDM_tessfaces_to_faces");
2627
2628                 CustomData_add_layer(&cddm->dm.loopData, CD_MLOOP, CD_ASSIGN, cddm->mloop, totloop);
2629                 CustomData_add_layer(&cddm->dm.polyData, CD_MPOLY, CD_ASSIGN, cddm->mpoly, cddm->dm.numPolyData);
2630                 CustomData_merge(&cddm->dm.faceData, &cddm->dm.polyData,
2631                         CD_MASK_ORIGINDEX, CD_DUPLICATE, cddm->dm.numTessFaceData);
2632
2633                 polyindex = CustomData_get_layer(&cddm->dm.faceData, CD_POLYINDEX);
2634
2635                 mf = cddm->mface;
2636                 mp = cddm->mpoly;
2637                 ml = cddm->mloop;
2638                 l = 0;
2639                 for (i=0; i<cddm->dm.numTessFaceData; i++, mf++, mp++, polyindex++) {
2640                         mp->flag = mf->flag;
2641                         mp->loopstart = l;
2642                         mp->mat_nr = mf->mat_nr;
2643                         mp->totloop = mf->v4 ? 4 : 3;
2644
2645                         ml->v = mf->v1;
2646                         ml->e = GET_INT_FROM_POINTER(BLI_edgehash_lookup(eh, mf->v1, mf->v2));
2647                         ml++, l++;
2648
2649                         ml->v = mf->v2;
2650                         ml->e = GET_INT_FROM_POINTER(BLI_edgehash_lookup(eh, mf->v2, mf->v3));
2651                         ml++, l++;
2652
2653                         ml->v = mf->v3;
2654                         ml->e = GET_INT_FROM_POINTER(BLI_edgehash_lookup(eh, mf->v3, mf->v4?mf->v4:mf->v1));
2655                         ml++, l++;
2656
2657                         if (mf->v4) {
2658                                 ml->v = mf->v4;
2659                                 ml->e = GET_INT_FROM_POINTER(BLI_edgehash_lookup(eh, mf->v4, mf->v1));
2660                                 ml++, l++;
2661                         }
2662
2663                         *polyindex = i;
2664                 }
2665         }
2666
2667         BLI_edgehash_free(eh, NULL);
2668 }
2669
2670 void CDDM_set_mvert(DerivedMesh *dm, MVert *mvert)
2671 {
2672         CDDerivedMesh *cddm = (CDDerivedMesh*)dm;
2673         
2674         if (!CustomData_has_layer(&dm->vertData, CD_MVERT))
2675                 CustomData_add_layer(&dm->vertData, CD_MVERT, CD_ASSIGN, mvert, dm->numVertData);
2676                                 
2677         cddm->mvert = mvert;
2678 }
2679
2680 void CDDM_set_medge(DerivedMesh *dm, MEdge *medge)
2681 {
2682         CDDerivedMesh *cddm = (CDDerivedMesh*)dm;
2683
2684         if (!CustomData_has_layer(&dm->edgeData, CD_MEDGE))
2685                 CustomData_add_layer(&dm->edgeData, CD_MEDGE, CD_ASSIGN, medge, dm->numEdgeData);
2686
2687         cddm->medge = medge;
2688 }
2689
2690 void CDDM_set_mface(DerivedMesh *dm, MFace *mface)
2691 {
2692         CDDerivedMesh *cddm = (CDDerivedMesh*)dm;
2693
2694         if (!CustomData_has_layer(&dm->faceData, CD_MFACE))
2695                 CustomData_add_layer(&dm->faceData, CD_MFACE, CD_ASSIGN, mface, dm->numTessFaceData);
2696
2697         cddm->mface = mface;
2698 }
2699
2700 void CDDM_set_mloop(DerivedMesh *dm, MLoop *mloop)
2701 {
2702         CDDerivedMesh *cddm = (CDDerivedMesh*)dm;
2703
2704         if (!CustomData_has_layer(&dm->loopData, CD_MLOOP))
2705                 CustomData_add_layer(&dm->loopData, CD_MLOOP, CD_ASSIGN, mloop, dm->numLoopData);
2706
2707         cddm->mloop = mloop;
2708 }
2709
2710 void CDDM_set_mpoly(DerivedMesh *dm, MPoly *mpoly)
2711 {
2712         CDDerivedMesh *cddm = (CDDerivedMesh*)dm;
2713
2714         if (!CustomData_has_layer(&dm->polyData, CD_MPOLY))
2715                 CustomData_add_layer(&dm->polyData, CD_MPOLY, CD_ASSIGN, mpoly, dm->numPolyData);
2716
2717         cddm->mpoly = mpoly;
2718 }