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