Vertex/Weight Paint: Use PBVH for painting
[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 "atomic_ops.h"
38
39 #include "BLI_math.h"
40 #include "BLI_edgehash.h"
41 #include "BLI_utildefines.h"
42 #include "BLI_utildefines_stack.h"
43
44 #include "BKE_pbvh.h"
45 #include "BKE_cdderivedmesh.h"
46 #include "BKE_global.h"
47 #include "BKE_mesh.h"
48 #include "BKE_mesh_mapping.h"
49 #include "BKE_paint.h"
50 #include "BKE_editmesh.h"
51 #include "BKE_curve.h"
52
53 #include "DNA_mesh_types.h"
54 #include "DNA_meshdata_types.h"
55 #include "DNA_object_types.h"
56 #include "DNA_curve_types.h" /* for Curve */
57
58 #include "MEM_guardedalloc.h"
59
60 #include "GPU_buffers.h"
61 #include "GPU_draw.h"
62 #include "GPU_glew.h"
63 #include "GPU_shader.h"
64 #include "GPU_basic_shader.h"
65
66 #include <string.h>
67 #include <limits.h>
68 #include <math.h>
69
70 typedef struct {
71         DerivedMesh dm;
72
73         /* these point to data in the DerivedMesh custom data layers,
74          * they are only here for efficiency and convenience **/
75         MVert *mvert;
76         MEdge *medge;
77         MFace *mface;
78         MLoop *mloop;
79         MPoly *mpoly;
80
81         /* Cached */
82         struct PBVH *pbvh;
83         bool pbvh_draw;
84
85         /* Mesh connectivity */
86         MeshElemMap *pmap;
87         int *pmap_mem;
88 } CDDerivedMesh;
89
90 /**************** DerivedMesh interface functions ****************/
91 static int cdDM_getNumVerts(DerivedMesh *dm)
92 {
93         return dm->numVertData;
94 }
95
96 static int cdDM_getNumEdges(DerivedMesh *dm)
97 {
98         return dm->numEdgeData;
99 }
100
101 static int cdDM_getNumTessFaces(DerivedMesh *dm)
102 {
103         /* uncomment and add a breakpoint on the printf()
104          * to help debug tessfaces issues since BMESH merge. */
105 #if 0
106         if (dm->numTessFaceData == 0 && dm->numPolyData != 0) {
107                 printf("%s: has no faces!, call DM_ensure_tessface() if you need them\n");
108         }
109 #endif
110         return dm->numTessFaceData;
111 }
112
113 static int cdDM_getNumLoops(DerivedMesh *dm)
114 {
115         return dm->numLoopData;
116 }
117
118 static int cdDM_getNumPolys(DerivedMesh *dm)
119 {
120         return dm->numPolyData;
121 }
122
123 static void cdDM_getVert(DerivedMesh *dm, int index, MVert *r_vert)
124 {
125         CDDerivedMesh *cddm = (CDDerivedMesh *)dm;
126         *r_vert = cddm->mvert[index];
127 }
128
129 static void cdDM_getEdge(DerivedMesh *dm, int index, MEdge *r_edge)
130 {
131         CDDerivedMesh *cddm = (CDDerivedMesh *)dm;
132         *r_edge = cddm->medge[index];
133 }
134
135 static void cdDM_getTessFace(DerivedMesh *dm, int index, MFace *r_face)
136 {
137         CDDerivedMesh *cddm = (CDDerivedMesh *)dm;
138         *r_face = cddm->mface[index];
139 }
140
141 static void cdDM_copyVertArray(DerivedMesh *dm, MVert *r_vert)
142 {
143         CDDerivedMesh *cddm = (CDDerivedMesh *)dm;
144         memcpy(r_vert, cddm->mvert, sizeof(*r_vert) * dm->numVertData);
145 }
146
147 static void cdDM_copyEdgeArray(DerivedMesh *dm, MEdge *r_edge)
148 {
149         CDDerivedMesh *cddm = (CDDerivedMesh *)dm;
150         memcpy(r_edge, cddm->medge, sizeof(*r_edge) * dm->numEdgeData);
151 }
152
153 static void cdDM_copyTessFaceArray(DerivedMesh *dm, MFace *r_face)
154 {
155         CDDerivedMesh *cddm = (CDDerivedMesh *)dm;
156         memcpy(r_face, cddm->mface, sizeof(*r_face) * dm->numTessFaceData);
157 }
158
159 static void cdDM_copyLoopArray(DerivedMesh *dm, MLoop *r_loop)
160 {
161         CDDerivedMesh *cddm = (CDDerivedMesh *)dm;
162         memcpy(r_loop, cddm->mloop, sizeof(*r_loop) * dm->numLoopData);
163 }
164
165 static void cdDM_copyPolyArray(DerivedMesh *dm, MPoly *r_poly)
166 {
167         CDDerivedMesh *cddm = (CDDerivedMesh *)dm;
168         memcpy(r_poly, cddm->mpoly, sizeof(*r_poly) * dm->numPolyData);
169 }
170
171 static void cdDM_getMinMax(DerivedMesh *dm, float r_min[3], float r_max[3])
172 {
173         CDDerivedMesh *cddm = (CDDerivedMesh *) dm;
174         int i;
175
176         if (dm->numVertData) {
177                 for (i = 0; i < dm->numVertData; i++) {
178                         minmax_v3v3_v3(r_min, r_max, cddm->mvert[i].co);
179                 }
180         }
181         else {
182                 zero_v3(r_min);
183                 zero_v3(r_max);
184         }
185 }
186
187 static void cdDM_getVertCo(DerivedMesh *dm, int index, float r_co[3])
188 {
189         CDDerivedMesh *cddm = (CDDerivedMesh *) dm;
190
191         copy_v3_v3(r_co, cddm->mvert[index].co);
192 }
193
194 static void cdDM_getVertCos(DerivedMesh *dm, float (*r_cos)[3])
195 {
196         MVert *mv = CDDM_get_verts(dm);
197         int i;
198
199         for (i = 0; i < dm->numVertData; i++, mv++)
200                 copy_v3_v3(r_cos[i], mv->co);
201 }
202
203 static void cdDM_getVertNo(DerivedMesh *dm, int index, float r_no[3])
204 {
205         CDDerivedMesh *cddm = (CDDerivedMesh *) dm;
206         normal_short_to_float_v3(r_no, cddm->mvert[index].no);
207 }
208
209 static const MeshElemMap *cdDM_getPolyMap(Object *ob, DerivedMesh *dm)
210 {
211         CDDerivedMesh *cddm = (CDDerivedMesh *) dm;
212
213         if (!cddm->pmap && ob->type == OB_MESH) {
214                 Mesh *me = ob->data;
215
216                 BKE_mesh_vert_poly_map_create(
217                         &cddm->pmap, &cddm->pmap_mem,
218                         me->mpoly, me->mloop,
219                         me->totvert, me->totpoly, me->totloop);
220         }
221
222         return cddm->pmap;
223 }
224
225 static bool check_sculpt_object_deformed(Object *object, bool for_construction)
226 {
227         bool deformed = false;
228
229         /* Active modifiers means extra deformation, which can't be handled correct
230          * on birth of PBVH and sculpt "layer" levels, so use PBVH only for internal brush
231          * stuff and show final DerivedMesh so user would see actual object shape.
232          */
233         deformed |= object->sculpt->modifiers_active;
234
235         if (for_construction) {
236                 deformed |= object->sculpt->kb != NULL;
237         }
238         else {
239                 /* As in case with modifiers, we can't synchronize deformation made against
240                  * PBVH and non-locked keyblock, so also use PBVH only for brushes and
241                  * final DM to give final result to user.
242                  */
243                 deformed |= object->sculpt->kb && (object->shapeflag & OB_SHAPE_LOCK) == 0;
244         }
245
246         return deformed;
247 }
248
249 static bool can_pbvh_draw(Object *ob, DerivedMesh *dm)
250 {
251         CDDerivedMesh *cddm = (CDDerivedMesh *) dm;
252         Mesh *me = ob->data;
253         bool deformed = check_sculpt_object_deformed(ob, false);
254
255         if (deformed) {
256                 return false;
257         }
258
259         return cddm->mvert == me->mvert || ob->sculpt->kb;
260 }
261
262 static PBVH *cdDM_getPBVH(Object *ob, DerivedMesh *dm)
263 {
264         CDDerivedMesh *cddm = (CDDerivedMesh *) dm;
265
266         if (!ob) {
267                 cddm->pbvh = NULL;
268                 return NULL;
269         }
270
271         if (!ob->sculpt)
272                 return NULL;
273
274         if (ob->sculpt->pbvh) {
275                 cddm->pbvh = ob->sculpt->pbvh;
276                 cddm->pbvh_draw = can_pbvh_draw(ob, dm);
277         }
278
279         /* Sculpting on a BMesh (dynamic-topology) gets a special PBVH */
280         if (!cddm->pbvh && ob->sculpt->bm) {
281                 cddm->pbvh = BKE_pbvh_new();
282                 cddm->pbvh_draw = true;
283
284                 BKE_pbvh_build_bmesh(cddm->pbvh, ob->sculpt->bm,
285                                      ob->sculpt->bm_smooth_shading,
286                                      ob->sculpt->bm_log, ob->sculpt->cd_vert_node_offset,
287                                      ob->sculpt->cd_face_node_offset);
288
289                 pbvh_show_diffuse_color_set(cddm->pbvh, ob->sculpt->show_diffuse_color);
290         }
291                 
292
293         /* always build pbvh from original mesh, and only use it for drawing if
294          * this derivedmesh is just original mesh. it's the multires subsurf dm
295          * that this is actually for, to support a pbvh on a modified mesh */
296         if (!cddm->pbvh && ob->type == OB_MESH) {
297                 Mesh *me = ob->data;
298                 const int looptris_num = poly_to_tri_count(me->totpoly, me->totloop);
299                 MLoopTri *looptri;
300                 bool deformed;
301
302                 cddm->pbvh = BKE_pbvh_new();
303                 cddm->pbvh_draw = can_pbvh_draw(ob, dm);
304
305                 looptri = MEM_mallocN(sizeof(*looptri) * looptris_num, __func__);
306
307                 BKE_mesh_recalc_looptri(
308                         me->mloop, me->mpoly,
309                         me->mvert,
310                         me->totloop, me->totpoly,
311                         looptri);
312                 
313                 BKE_pbvh_build_mesh(
314                         cddm->pbvh,
315                         me->mpoly, me->mloop,
316                         me->mvert, me->totvert, &me->vdata,
317                         looptri, looptris_num);
318
319                 pbvh_show_diffuse_color_set(cddm->pbvh, ob->sculpt->show_diffuse_color);
320
321                 deformed = check_sculpt_object_deformed(ob, true);
322
323                 if (deformed && ob->derivedDeform) {
324                         DerivedMesh *deformdm = ob->derivedDeform;
325                         float (*vertCos)[3];
326                         int totvert;
327
328                         totvert = deformdm->getNumVerts(deformdm);
329                         vertCos = MEM_mallocN(totvert * sizeof(float[3]), "cdDM_getPBVH vertCos");
330                         deformdm->getVertCos(deformdm, vertCos);
331                         BKE_pbvh_apply_vertCos(cddm->pbvh, vertCos);
332                         MEM_freeN(vertCos);
333                 }
334         }
335
336         return cddm->pbvh;
337 }
338
339 /* update vertex normals so that drawing smooth faces works during sculpt
340  * TODO: proper fix is to support the pbvh in all drawing modes */
341 static void cdDM_update_normals_from_pbvh(DerivedMesh *dm)
342 {
343         CDDerivedMesh *cddm = (CDDerivedMesh *) dm;
344         float (*face_nors)[3];
345
346         /* Some callbacks do not use optimal PBVH draw, so needs all the
347          * possible data (like normals) to be copied from PBVH back to DM.
348          *
349          * This is safe to do if PBVH and DM are representing the same mesh,
350          * which could be wrong when modifiers are enabled for sculpt.
351          * So here we only doing update when there's no modifiers applied
352          * during sculpt.
353          *
354          * It's safe to do nothing if there are modifiers, because in this
355          * case modifier stack is re-constructed from scratch on every
356          * update.
357          */
358         if (!cddm->pbvh_draw) {
359                 return;
360         }
361
362         face_nors = CustomData_get_layer(&dm->polyData, CD_NORMAL);
363
364         BKE_pbvh_update(cddm->pbvh, PBVH_UpdateNormals, face_nors);
365 }
366
367 static void cdDM_drawVerts(DerivedMesh *dm)
368 {
369         GPU_vertex_setup(dm);
370         if (dm->drawObject->tot_loop_verts)
371                 glDrawArrays(GL_POINTS, 0, dm->drawObject->tot_loop_verts);
372         else
373                 glDrawArrays(GL_POINTS, 0, dm->drawObject->tot_loose_point);
374         GPU_buffers_unbind();
375 }
376
377 static void cdDM_drawUVEdges(DerivedMesh *dm)
378 {
379         CDDerivedMesh *cddm = (CDDerivedMesh *) dm;
380         const MPoly *mpoly = cddm->mpoly;
381         int totpoly = dm->getNumPolys(dm);
382         int prevstart = 0;
383         bool prevdraw = true;
384         int curpos = 0;
385         int i;
386
387         GPU_uvedge_setup(dm);
388         for (i = 0; i < totpoly; i++, mpoly++) {
389                 const bool draw = (mpoly->flag & ME_HIDE) == 0;
390
391                 if (prevdraw != draw) {
392                         if (prevdraw && (curpos != prevstart)) {
393                                 glDrawArrays(GL_LINES, prevstart, curpos - prevstart);
394                         }
395                         prevstart = curpos;
396                 }
397
398                 curpos += 2 * mpoly->totloop;
399                 prevdraw = draw;
400         }
401         if (prevdraw && (curpos != prevstart)) {
402                 glDrawArrays(GL_LINES, prevstart, curpos - prevstart);
403         }
404         GPU_buffers_unbind();
405 }
406
407 static void cdDM_drawEdges(DerivedMesh *dm, bool drawLooseEdges, bool drawAllEdges)
408 {
409         CDDerivedMesh *cddm = (CDDerivedMesh *) dm;
410         GPUDrawObject *gdo;
411         if (cddm->pbvh && cddm->pbvh_draw &&
412             BKE_pbvh_type(cddm->pbvh) == PBVH_BMESH)
413         {
414                 BKE_pbvh_draw(cddm->pbvh, NULL, NULL, NULL, true, false);
415
416                 return;
417         }
418         
419         GPU_edge_setup(dm);
420         gdo = dm->drawObject;
421         if (gdo->edges && gdo->points) {
422                 if (drawAllEdges && drawLooseEdges) {
423                         GPU_buffer_draw_elements(gdo->edges, GL_LINES, 0, gdo->totedge * 2);
424                 }
425                 else if (drawAllEdges) {
426                         GPU_buffer_draw_elements(gdo->edges, GL_LINES, 0, gdo->loose_edge_offset * 2);
427                 }
428                 else {
429                         GPU_buffer_draw_elements(gdo->edges, GL_LINES, 0, gdo->tot_edge_drawn * 2);
430                         GPU_buffer_draw_elements(gdo->edges, GL_LINES, gdo->loose_edge_offset * 2, dm->drawObject->tot_loose_edge_drawn * 2);
431                 }
432         }
433         GPU_buffers_unbind();
434 }
435
436 static void cdDM_drawLooseEdges(DerivedMesh *dm)
437 {
438         int start;
439         int count;
440
441         GPU_edge_setup(dm);
442
443         start = (dm->drawObject->loose_edge_offset * 2);
444         count = (dm->drawObject->totedge - dm->drawObject->loose_edge_offset) * 2;
445
446         if (count) {
447                 GPU_buffer_draw_elements(dm->drawObject->edges, GL_LINES, start, count);
448         }
449
450         GPU_buffers_unbind();
451 }
452
453 static void cdDM_drawFacesSolid(
454         DerivedMesh *dm,
455         float (*partial_redraw_planes)[4],
456         bool UNUSED(fast), DMSetMaterial setMaterial)
457 {
458         CDDerivedMesh *cddm = (CDDerivedMesh *) dm;
459         int a;
460
461         if (cddm->pbvh) {
462                 if (cddm->pbvh_draw && BKE_pbvh_has_faces(cddm->pbvh)) {
463                         float (*face_nors)[3] = CustomData_get_layer(&dm->polyData, CD_NORMAL);
464
465                         BKE_pbvh_draw(cddm->pbvh, partial_redraw_planes, face_nors,
466                                       setMaterial, false, false);
467                         return;
468                 }
469         }
470         
471         GPU_vertex_setup(dm);
472         GPU_normal_setup(dm);
473         GPU_triangle_setup(dm);
474         for (a = 0; a < dm->drawObject->totmaterial; a++) {
475                 if (!setMaterial || setMaterial(dm->drawObject->materials[a].mat_nr + 1, NULL)) {
476                         GPU_buffer_draw_elements(
477                                     dm->drawObject->triangles, GL_TRIANGLES,
478                                     dm->drawObject->materials[a].start, dm->drawObject->materials[a].totelements);
479                 }
480         }
481         GPU_buffers_unbind();
482 }
483
484 static void cdDM_drawFacesTex_common(
485         DerivedMesh *dm,
486         DMSetDrawOptionsTex drawParams,
487         DMSetDrawOptionsMappedTex drawParamsMapped,
488         DMCompareDrawOptions compareDrawOptions,
489         void *userData, DMDrawFlag flag)
490 {
491         CDDerivedMesh *cddm = (CDDerivedMesh *) dm;
492         const MPoly *mpoly = cddm->mpoly;
493         MTexPoly *mtexpoly = DM_get_poly_data_layer(dm, CD_MTEXPOLY);
494         const  MLoopCol *mloopcol = NULL;
495         int i;
496         int colType, start_element, tot_drawn;
497         const bool use_hide = (flag & DM_DRAW_SKIP_HIDDEN) != 0;
498         const bool use_tface = (flag & DM_DRAW_USE_ACTIVE_UV) != 0;
499         const bool use_colors = (flag & DM_DRAW_USE_COLORS) != 0;
500         int totpoly;
501         int next_actualFace;
502         int mat_index;
503         int tot_element;
504
505         /* double lookup */
506         const int *index_mp_to_orig  = dm->getPolyDataArray(dm, CD_ORIGINDEX);
507
508         /* TODO: not entirely correct, but currently dynamic topology will
509          *       destroy UVs anyway, so textured display wouldn't work anyway
510          *
511          *       this will do more like solid view with lights set up for
512          *       textured view, but object itself will be displayed gray
513          *       (the same as it'll display without UV maps in textured view)
514          */
515         if (cddm->pbvh) {
516                 if (cddm->pbvh_draw &&
517                     BKE_pbvh_type(cddm->pbvh) == PBVH_BMESH &&
518                     BKE_pbvh_has_faces(cddm->pbvh))
519                 {
520                         GPU_set_tpage(NULL, false, false);
521                         BKE_pbvh_draw(cddm->pbvh, NULL, NULL, NULL, false, false);
522                         return;
523                 }
524                 else {
525                         cdDM_update_normals_from_pbvh(dm);
526                 }
527         }
528
529         if (use_colors) {
530                 colType = CD_TEXTURE_MLOOPCOL;
531                 mloopcol = dm->getLoopDataArray(dm, colType);
532                 if (!mloopcol) {
533                         colType = CD_PREVIEW_MLOOPCOL;
534                         mloopcol = dm->getLoopDataArray(dm, colType);
535                 }
536                 if (!mloopcol) {
537                         colType = CD_MLOOPCOL;
538                         mloopcol = dm->getLoopDataArray(dm, colType);
539                 }
540         }
541
542         GPU_vertex_setup(dm);
543         GPU_normal_setup(dm);
544         GPU_triangle_setup(dm);
545         if (flag & DM_DRAW_USE_TEXPAINT_UV)
546                 GPU_texpaint_uv_setup(dm);
547         else
548                 GPU_uv_setup(dm);
549         if (mloopcol) {
550                 GPU_color_setup(dm, colType);
551         }
552
553         /* lastFlag = 0; */ /* UNUSED */
554         for (mat_index = 0; mat_index < dm->drawObject->totmaterial; mat_index++) {
555                 GPUBufferMaterial *bufmat = dm->drawObject->materials + mat_index;
556                 next_actualFace = bufmat->polys[0];
557                 totpoly = bufmat->totpolys;
558
559                 tot_element = 0;
560                 tot_drawn = 0;
561                 start_element = 0;
562
563                 for (i = 0; i < totpoly; i++) {
564                         int actualFace = bufmat->polys[i];
565                         DMDrawOption draw_option = DM_DRAW_OPTION_NORMAL;
566                         int flush = 0;
567                         int tot_tri_verts;
568
569                         if (i != totpoly - 1)
570                                 next_actualFace = bufmat->polys[i + 1];
571
572                         if (use_hide && (mpoly[actualFace].flag & ME_HIDE)) {
573                                 draw_option = DM_DRAW_OPTION_SKIP;
574                         }
575                         else if (drawParams) {
576                                 MTexPoly *tp = use_tface && mtexpoly ? &mtexpoly[actualFace] : NULL;
577                                 draw_option = drawParams(tp, (mloopcol != NULL), mpoly[actualFace].mat_nr);
578                         }
579                         else {
580                                 if (index_mp_to_orig) {
581                                         const int orig = index_mp_to_orig[actualFace];
582                                         if (orig == ORIGINDEX_NONE) {
583                                                 /* XXX, this is not really correct
584                                                  * it will draw the previous faces context for this one when we don't know its settings.
585                                                  * but better then skipping it altogether. - campbell */
586                                                 draw_option = DM_DRAW_OPTION_NORMAL;
587                                         }
588                                         else if (drawParamsMapped) {
589                                                 draw_option = drawParamsMapped(userData, orig, mpoly[actualFace].mat_nr);
590                                         }
591                                 }
592                                 else if (drawParamsMapped) {
593                                         draw_option = drawParamsMapped(userData, actualFace, mpoly[actualFace].mat_nr);
594                                 }
595                         }
596
597                         /* flush buffer if current triangle isn't drawable or it's last triangle */
598                         flush = (draw_option == DM_DRAW_OPTION_SKIP) || (i == totpoly - 1);
599
600                         if (!flush && compareDrawOptions) {
601                                 /* also compare draw options and flush buffer if they're different
602                                  * need for face selection highlight in edit mode */
603                                 flush |= compareDrawOptions(userData, actualFace, next_actualFace) == 0;
604                         }
605
606                         tot_tri_verts = ME_POLY_TRI_TOT(&mpoly[actualFace]) * 3;
607                         tot_element += tot_tri_verts;
608
609                         if (flush) {
610                                 if (draw_option != DM_DRAW_OPTION_SKIP)
611                                         tot_drawn += tot_tri_verts;
612
613                                 if (tot_drawn) {
614                                         if (mloopcol && draw_option != DM_DRAW_OPTION_NO_MCOL)
615                                                 GPU_color_switch(1);
616                                         else
617                                                 GPU_color_switch(0);
618
619                                         GPU_buffer_draw_elements(dm->drawObject->triangles, GL_TRIANGLES, bufmat->start + start_element, tot_drawn);
620                                         tot_drawn = 0;
621                                 }
622                                 start_element = tot_element;
623                         }
624                         else {
625                                 tot_drawn += tot_tri_verts;
626                         }
627                 }
628         }
629
630         GPU_buffers_unbind();
631         
632 }
633
634 static void cdDM_drawFacesTex(
635         DerivedMesh *dm,
636         DMSetDrawOptionsTex setDrawOptions,
637         DMCompareDrawOptions compareDrawOptions,
638         void *userData, DMDrawFlag flag)
639 {
640         cdDM_drawFacesTex_common(dm, setDrawOptions, NULL, compareDrawOptions, userData, flag);
641 }
642
643 static void cdDM_drawMappedFaces(
644         DerivedMesh *dm,
645         DMSetDrawOptions setDrawOptions,
646         DMSetMaterial setMaterial,
647         DMCompareDrawOptions compareDrawOptions,
648         void *userData, DMDrawFlag flag)
649 {
650         CDDerivedMesh *cddm = (CDDerivedMesh *) dm;
651         const MPoly *mpoly = cddm->mpoly;
652         const MLoopCol *mloopcol = NULL;
653         const bool use_colors = (flag & DM_DRAW_USE_COLORS) != 0;
654         const bool use_hide = (flag & DM_DRAW_SKIP_HIDDEN) != 0;
655         int colType;
656         int i, j;
657         int start_element = 0, tot_element, tot_drawn;
658         int totpoly;
659         int tot_tri_elem;
660         int mat_index;
661         GPUBuffer *findex_buffer = NULL;
662
663         const int *index_mp_to_orig  = dm->getPolyDataArray(dm, CD_ORIGINDEX);
664
665         if (cddm->pbvh) {
666                 if (G.debug_value == 14)
667                         BKE_pbvh_draw_BB(cddm->pbvh);
668         }
669
670         /* fist, setup common buffers */
671         GPU_vertex_setup(dm);
672         GPU_triangle_setup(dm);
673
674         totpoly = dm->getNumPolys(dm);
675
676         /* if we do selection, fill the selection buffer color */
677         if (G.f & G_BACKBUFSEL) {
678                 if (!(flag & DM_DRAW_SKIP_SELECT)) {
679                         Mesh *me = NULL;
680                         BMesh *bm = NULL;
681                         unsigned int *fi_map;
682
683                         if (flag & DM_DRAW_SELECT_USE_EDITMODE)
684                                 bm = userData;
685                         else
686                                 me = userData;
687
688                         findex_buffer = GPU_buffer_alloc(dm->drawObject->tot_loop_verts * sizeof(int));
689                         fi_map = GPU_buffer_lock(findex_buffer, GPU_BINDING_ARRAY);
690
691                         if (fi_map) {
692                                 for (i = 0; i < totpoly; i++, mpoly++) {
693                                         int selcol = 0xFFFFFFFF;
694                                         const int orig = (index_mp_to_orig) ? index_mp_to_orig[i] : i;
695                                         bool is_hidden;
696
697                                         if (orig != ORIGINDEX_NONE) {
698                                                 if (use_hide) {
699                                                         if (flag & DM_DRAW_SELECT_USE_EDITMODE) {
700                                                                 BMFace *efa = BM_face_at_index(bm, orig);
701                                                                 is_hidden = BM_elem_flag_test(efa, BM_ELEM_HIDDEN) != 0;
702                                                         }
703                                                         else {
704                                                                 is_hidden = (me->mpoly[orig].flag & ME_HIDE) != 0;
705                                                         }
706
707                                                         if (!is_hidden) {
708                                                                 GPU_select_index_get(orig + 1, &selcol);
709                                                         }
710                                                 }
711                                                 else {
712                                                         GPU_select_index_get(orig + 1, &selcol);
713                                                 }
714                                         }
715
716                                         for (j = 0; j < mpoly->totloop; j++)
717                                                 fi_map[start_element++] = selcol;
718                                 }
719
720                                 start_element = 0;
721                                 mpoly = cddm->mpoly;
722
723                                 GPU_buffer_unlock(findex_buffer, GPU_BINDING_ARRAY);
724                                 GPU_buffer_bind_as_color(findex_buffer);
725                         }
726                 }
727         }
728         else {
729                 GPU_normal_setup(dm);
730
731                 if (use_colors) {
732                         colType = CD_TEXTURE_MLOOPCOL;
733                         mloopcol = DM_get_loop_data_layer(dm, colType);
734                         if (!mloopcol) {
735                                 colType = CD_PREVIEW_MLOOPCOL;
736                                 mloopcol = DM_get_loop_data_layer(dm, colType);
737                         }
738                         if (!mloopcol) {
739                                 colType = CD_MLOOPCOL;
740                                 mloopcol = DM_get_loop_data_layer(dm, colType);
741                         }
742
743                         if (use_colors && mloopcol) {
744                                 GPU_color_setup(dm, colType);
745                         }
746                 }
747         }
748
749         tot_tri_elem = dm->drawObject->tot_triangle_point;
750
751         if (tot_tri_elem == 0) {
752                 /* avoid buffer problems in following code */
753         }
754         else if (setDrawOptions == NULL) {
755                 /* just draw the entire face array */
756                 GPU_buffer_draw_elements(dm->drawObject->triangles, GL_TRIANGLES, 0, tot_tri_elem);
757         }
758         else {
759                 for (mat_index = 0; mat_index < dm->drawObject->totmaterial; mat_index++) {
760                         GPUBufferMaterial *bufmat = dm->drawObject->materials + mat_index;
761                         DMDrawOption draw_option = DM_DRAW_OPTION_NORMAL;
762                         int next_actualFace = bufmat->polys[0];
763                         totpoly = use_hide ? bufmat->totvisiblepolys : bufmat->totpolys;
764
765                         tot_element = 0;
766                         start_element = 0;
767                         tot_drawn = 0;
768
769                         if (setMaterial)
770                                 draw_option = setMaterial(bufmat->mat_nr + 1, NULL);
771
772                         if (draw_option != DM_DRAW_OPTION_SKIP) {
773                                 DMDrawOption last_draw_option = DM_DRAW_OPTION_NORMAL;
774
775                                 for (i = 0; i < totpoly; i++) {
776                                         int actualFace = next_actualFace;
777                                         int flush = 0;
778                                         int tot_tri_verts;
779
780                                         draw_option = DM_DRAW_OPTION_NORMAL;
781
782                                         if (i != totpoly - 1)
783                                                 next_actualFace = bufmat->polys[i + 1];
784
785                                         if (setDrawOptions) {
786                                                 const int orig = (index_mp_to_orig) ? index_mp_to_orig[actualFace] : actualFace;
787
788                                                 if (orig != ORIGINDEX_NONE) {
789                                                         draw_option = setDrawOptions(userData, orig);
790                                                 }
791                                         }
792
793                                         /* Goal is to draw as long of a contiguous triangle
794                                          * array as possible, so draw when we hit either an
795                                          * invisible triangle or at the end of the array */
796
797                                         /* flush buffer if current triangle isn't drawable or it's last triangle... */
798                                         flush = (draw_option != last_draw_option) || (i == totpoly - 1);
799
800                                         if (!flush && compareDrawOptions) {
801                                                 flush |= compareDrawOptions(userData, actualFace, next_actualFace) == 0;
802                                         }
803
804                                         tot_tri_verts = ME_POLY_TRI_TOT(&mpoly[actualFace]) * 3;
805                                         tot_element += tot_tri_verts;
806
807                                         if (flush) {
808                                                 if (draw_option != DM_DRAW_OPTION_SKIP) {
809                                                         tot_drawn += tot_tri_verts;
810
811                                                         if (last_draw_option != draw_option) {
812                                                                 if (draw_option == DM_DRAW_OPTION_STIPPLE) {
813                                                                         GPU_basic_shader_bind(GPU_SHADER_STIPPLE | GPU_SHADER_USE_COLOR);
814                                                                         GPU_basic_shader_stipple(GPU_SHADER_STIPPLE_QUARTTONE);
815                                                                 }
816                                                                 else {
817                                                                         GPU_basic_shader_bind(GPU_SHADER_USE_COLOR);
818                                                                 }
819                                                         }
820                                                 }
821
822                                                 if (tot_drawn) {
823                                                         GPU_buffer_draw_elements(dm->drawObject->triangles, GL_TRIANGLES, bufmat->start + start_element, tot_drawn);
824                                                         tot_drawn = 0;
825                                                 }
826
827                                                 last_draw_option = draw_option;
828                                                 start_element = tot_element;
829                                         }
830                                         else {
831                                                 if (draw_option != DM_DRAW_OPTION_SKIP) {
832                                                         tot_drawn += tot_tri_verts;
833                                                 }
834                                                 else {
835                                                         start_element = tot_element;
836                                                 }
837                                         }
838                                 }
839                         }
840                 }
841         }
842
843         GPU_basic_shader_bind(GPU_SHADER_USE_COLOR);
844
845         GPU_buffers_unbind();
846
847         if (findex_buffer)
848                 GPU_buffer_free(findex_buffer);
849
850 }
851
852 static void cdDM_drawMappedFacesTex(
853         DerivedMesh *dm,
854         DMSetDrawOptionsMappedTex setDrawOptions,
855         DMCompareDrawOptions compareDrawOptions,
856         void *userData, DMDrawFlag flag)
857 {
858         cdDM_drawFacesTex_common(dm, NULL, setDrawOptions, compareDrawOptions, userData, flag);
859 }
860
861 static void cddm_draw_attrib_vertex(
862         DMVertexAttribs *attribs, const MVert *mvert, int a, int index, int loop, int vert,
863         const float *lnor, const bool smoothnormal)
864 {
865         DM_draw_attrib_vertex(attribs, a, index, vert, loop);
866
867         /* vertex normal */
868         if (lnor) {
869                 glNormal3fv(lnor);
870         }
871         else if (smoothnormal) {
872                 glNormal3sv(mvert[index].no);
873         }
874
875         /* vertex coordinate */
876         glVertex3fv(mvert[index].co);
877 }
878
879 typedef struct {
880         DMVertexAttribs attribs;
881         int numdata;
882
883         GPUAttrib datatypes[GPU_MAX_ATTRIB]; /* TODO, messing up when switching materials many times - [#21056]*/
884 } GPUMaterialConv;
885
886 static void cdDM_drawMappedFacesGLSL(
887         DerivedMesh *dm,
888         DMSetMaterial setMaterial,
889         DMSetDrawOptions setDrawOptions,
890         void *userData)
891 {
892         CDDerivedMesh *cddm = (CDDerivedMesh *) dm;
893         GPUVertexAttribs gattribs;
894         const MVert *mvert = cddm->mvert;
895         const MPoly *mpoly = cddm->mpoly;
896         const MLoop *mloop = cddm->mloop;
897         const MLoopTri *lt = dm->getLoopTriArray(dm);
898         const int tottri = dm->getNumLoopTri(dm);
899         /* MTFace *tf = dm->getTessFaceDataArray(dm, CD_MTFACE); */ /* UNUSED */
900         const float (*nors)[3] = dm->getPolyDataArray(dm, CD_NORMAL);
901         const float (*lnors)[3] = dm->getLoopDataArray(dm, CD_NORMAL);
902         const int totpoly = dm->getNumPolys(dm);
903         const short dm_totmat = dm->totmat;
904         int a, b, matnr, new_matnr;
905         bool do_draw;
906         int orig;
907
908         const int *index_mp_to_orig  = dm->getPolyDataArray(dm, CD_ORIGINDEX);
909
910         /* TODO: same as for solid draw, not entirely correct, but works fine for now,
911          *       will skip using textures (dyntopo currently destroys UV anyway) and
912          *       works fine for matcap
913          */
914         if (cddm->pbvh) {
915                 if (cddm->pbvh_draw &&
916                     BKE_pbvh_type(cddm->pbvh) == PBVH_BMESH &&
917                     BKE_pbvh_has_faces(cddm->pbvh))
918                 {
919                         setMaterial(1, &gattribs);
920                         BKE_pbvh_draw(cddm->pbvh, NULL, NULL, NULL, false, false);
921                         return;
922                 }
923                 else {
924                         cdDM_update_normals_from_pbvh(dm);
925                 }
926         }
927
928         matnr = -1;
929         do_draw = false;
930
931         if (setDrawOptions != NULL) {
932                 DMVertexAttribs attribs;
933                 DEBUG_VBO("Using legacy code. cdDM_drawMappedFacesGLSL\n");
934                 memset(&attribs, 0, sizeof(attribs));
935
936                 glBegin(GL_TRIANGLES);
937
938                 for (a = 0; a < tottri; a++, lt++) {
939                         const MPoly *mp = &mpoly[lt->poly];
940                         const unsigned int  vtri[3] = {mloop[lt->tri[0]].v, mloop[lt->tri[1]].v, mloop[lt->tri[2]].v};
941                         const unsigned int *ltri = lt->tri;
942                         const float *ln1 = NULL, *ln2 = NULL, *ln3 = NULL;
943                         const bool smoothnormal = lnors || (mp->flag & ME_SMOOTH);
944                         new_matnr = mp->mat_nr;
945
946                         if (new_matnr != matnr) {
947                                 glEnd();
948
949                                 matnr = new_matnr;
950                                 do_draw = setMaterial(matnr + 1, &gattribs);
951                                 if (do_draw) {
952                                         DM_vertex_attributes_from_gpu(dm, &gattribs, &attribs);
953                                         DM_draw_attrib_vertex_uniforms(&attribs);
954                                 }
955
956                                 glBegin(GL_TRIANGLES);
957                         }
958
959                         if (!do_draw) {
960                                 continue;
961                         }
962                         else /* if (setDrawOptions) */ {
963                                 orig = (index_mp_to_orig) ? index_mp_to_orig[lt->poly] : lt->poly;
964
965                                 if (orig == ORIGINDEX_NONE) {
966                                         /* since the material is set by setMaterial(), faces with no
967                                          * origin can be assumed to be generated by a modifier */ 
968                                         
969                                         /* continue */
970                                 }
971                                 else if (setDrawOptions(userData, orig) == DM_DRAW_OPTION_SKIP)
972                                         continue;
973                         }
974
975                         if (!smoothnormal) {
976                                 if (nors) {
977                                         glNormal3fv(nors[lt->poly]);
978                                 }
979                                 else {
980                                         /* TODO ideally a normal layer should always be available */
981                                         float nor[3];
982                                         normal_tri_v3(nor, mvert[vtri[0]].co, mvert[vtri[1]].co, mvert[vtri[2]].co);
983                                         glNormal3fv(nor);
984                                 }
985                         }
986                         else if (lnors) {
987                                 ln1 = lnors[ltri[0]];
988                                 ln2 = lnors[ltri[1]];
989                                 ln3 = lnors[ltri[2]];
990                         }
991                         
992                         cddm_draw_attrib_vertex(&attribs, mvert, a, vtri[0], ltri[0], 0, ln1, smoothnormal);
993                         cddm_draw_attrib_vertex(&attribs, mvert, a, vtri[1], ltri[1], 1, ln2, smoothnormal);
994                         cddm_draw_attrib_vertex(&attribs, mvert, a, vtri[2], ltri[2], 2, ln3, smoothnormal);
995                 }
996                 glEnd();
997         }
998         else {
999                 GPUMaterialConv *matconv;
1000                 int offset;
1001                 int *mat_orig_to_new;
1002                 int tot_active_mat;
1003                 GPUBuffer *buffer = NULL;
1004                 unsigned char *varray;
1005                 size_t max_element_size = 0;
1006                 int tot_loops = 0;
1007
1008                 GPU_vertex_setup(dm);
1009                 GPU_normal_setup(dm);
1010                 GPU_triangle_setup(dm);
1011
1012                 tot_active_mat = dm->drawObject->totmaterial;
1013
1014                 matconv = MEM_callocN(sizeof(*matconv) * tot_active_mat,
1015                                       "cdDM_drawMappedFacesGLSL.matconv");
1016                 mat_orig_to_new = MEM_mallocN(sizeof(*mat_orig_to_new) * dm->totmat,
1017                                               "cdDM_drawMappedFacesGLSL.mat_orig_to_new");
1018
1019                 /* part one, check what attributes are needed per material */
1020                 for (a = 0; a < tot_active_mat; a++) {
1021                         new_matnr = dm->drawObject->materials[a].mat_nr;
1022
1023                         /* map from original material index to new
1024                          * GPUBufferMaterial index */
1025                         mat_orig_to_new[new_matnr] = a;
1026                         do_draw = setMaterial(new_matnr + 1, &gattribs);
1027
1028                         if (do_draw) {
1029                                 int numdata = 0;
1030                                 DM_vertex_attributes_from_gpu(dm, &gattribs, &matconv[a].attribs);
1031
1032                                 if (matconv[a].attribs.totorco && matconv[a].attribs.orco.array) {
1033                                         matconv[a].datatypes[numdata].index = matconv[a].attribs.orco.gl_index;
1034                                         matconv[a].datatypes[numdata].info_index = matconv[a].attribs.orco.gl_info_index;
1035                                         matconv[a].datatypes[numdata].size = 3;
1036                                         matconv[a].datatypes[numdata].type = GL_FLOAT;
1037                                         numdata++;
1038                                 }
1039                                 for (b = 0; b < matconv[a].attribs.tottface; b++) {
1040                                         if (matconv[a].attribs.tface[b].array) {
1041                                                 matconv[a].datatypes[numdata].index = matconv[a].attribs.tface[b].gl_index;
1042                                                 matconv[a].datatypes[numdata].info_index = matconv[a].attribs.tface[b].gl_info_index;
1043                                                 matconv[a].datatypes[numdata].size = 2;
1044                                                 matconv[a].datatypes[numdata].type = GL_FLOAT;
1045                                                 numdata++;
1046                                         }
1047                                 }
1048                                 for (b = 0; b < matconv[a].attribs.totmcol; b++) {
1049                                         if (matconv[a].attribs.mcol[b].array) {
1050                                                 matconv[a].datatypes[numdata].index = matconv[a].attribs.mcol[b].gl_index;
1051                                                 matconv[a].datatypes[numdata].info_index = matconv[a].attribs.mcol[b].gl_info_index;
1052                                                 matconv[a].datatypes[numdata].size = 4;
1053                                                 matconv[a].datatypes[numdata].type = GL_UNSIGNED_BYTE;
1054                                                 numdata++;
1055                                         }
1056                                 }
1057                                 for (b = 0; b < matconv[a].attribs.tottang; b++) {
1058                                         if (matconv[a].attribs.tang[b].array) {
1059                                                 matconv[a].datatypes[numdata].index = matconv[a].attribs.tang[b].gl_index;
1060                                                 matconv[a].datatypes[numdata].info_index = matconv[a].attribs.tang[b].gl_info_index;
1061                                                 matconv[a].datatypes[numdata].size = 4;
1062                                                 matconv[a].datatypes[numdata].type = GL_FLOAT;
1063                                                 numdata++;
1064                                         }
1065                                 }
1066                                 if (numdata != 0) {
1067                                         matconv[a].numdata = numdata;
1068                                         max_element_size = max_ii(GPU_attrib_element_size(matconv[a].datatypes, numdata), max_element_size);
1069                                 }
1070                         }
1071                 }
1072
1073                 /* part two, generate and fill the arrays with the data */
1074                 if (max_element_size > 0) {
1075                         buffer = GPU_buffer_alloc(max_element_size * dm->drawObject->tot_loop_verts);
1076
1077                         varray = GPU_buffer_lock_stream(buffer, GPU_BINDING_ARRAY);
1078                         if (varray == NULL) {
1079                                 GPU_buffers_unbind();
1080                                 GPU_buffer_free(buffer);
1081                                 MEM_freeN(mat_orig_to_new);
1082                                 MEM_freeN(matconv);
1083                                 fprintf(stderr, "Out of memory, can't draw object\n");
1084                                 return;
1085                         }
1086
1087                         for (a = 0; a < totpoly; a++, mpoly++) {
1088                                 const short mat_nr = ME_MAT_NR_TEST(mpoly->mat_nr, dm_totmat);
1089                                 int j;
1090                                 int i = mat_orig_to_new[mat_nr];
1091                                 offset = tot_loops * max_element_size;
1092
1093                                 if (matconv[i].numdata != 0) {
1094                                         if (matconv[i].attribs.totorco && matconv[i].attribs.orco.array) {
1095                                                 for (j = 0; j < mpoly->totloop; j++)
1096                                                         copy_v3_v3((float *)&varray[offset + j * max_element_size],
1097                                                                    (float *)matconv[i].attribs.orco.array[mloop[mpoly->loopstart + j].v]);
1098                                                 offset += sizeof(float) * 3;
1099                                         }
1100                                         for (b = 0; b < matconv[i].attribs.tottface; b++) {
1101                                                 if (matconv[i].attribs.tface[b].array) {
1102                                                         const MLoopUV *mloopuv = matconv[i].attribs.tface[b].array;
1103                                                         for (j = 0; j < mpoly->totloop; j++)
1104                                                                 copy_v2_v2((float *)&varray[offset + j * max_element_size], mloopuv[mpoly->loopstart + j].uv);
1105                                                         offset += sizeof(float) * 2;
1106                                                 }
1107                                         }
1108                                         for (b = 0; b < matconv[i].attribs.totmcol; b++) {
1109                                                 if (matconv[i].attribs.mcol[b].array) {
1110                                                         const MLoopCol *mloopcol = matconv[i].attribs.mcol[b].array;
1111                                                         for (j = 0; j < mpoly->totloop; j++)
1112                                                                 copy_v4_v4_uchar(&varray[offset + j * max_element_size], &mloopcol[mpoly->loopstart + j].r);
1113                                                         offset += sizeof(unsigned char) * 4;
1114                                                 }
1115                                         }
1116                                         for (b = 0; b < matconv[i].attribs.tottang; b++) {
1117                                                 if (matconv[i].attribs.tottang && matconv[i].attribs.tang[b].array) {
1118                                                         const float (*looptang)[4] = (const float (*)[4])matconv[i].attribs.tang[b].array;
1119                                                         for (j = 0; j < mpoly->totloop; j++)
1120                                                                 copy_v4_v4((float *)&varray[offset + j * max_element_size], looptang[mpoly->loopstart + j]);
1121                                                         offset += sizeof(float) * 4;
1122                                                 }
1123                                         }
1124                                 }
1125
1126                                 tot_loops += mpoly->totloop;
1127                         }
1128                         GPU_buffer_unlock(buffer, GPU_BINDING_ARRAY);
1129                 }
1130
1131                 for (a = 0; a < tot_active_mat; a++) {
1132                         new_matnr = dm->drawObject->materials[a].mat_nr;
1133
1134                         do_draw = setMaterial(new_matnr + 1, &gattribs);
1135
1136                         if (do_draw) {
1137                                 if (matconv[a].numdata) {
1138                                         GPU_interleaved_attrib_setup(buffer, matconv[a].datatypes, matconv[a].numdata, max_element_size);
1139                                 }
1140                                 GPU_buffer_draw_elements(dm->drawObject->triangles, GL_TRIANGLES,
1141                                                          dm->drawObject->materials[a].start, dm->drawObject->materials[a].totelements);
1142                                 if (matconv[a].numdata) {
1143                                         GPU_interleaved_attrib_unbind();
1144                                 }
1145                         }
1146                 }
1147
1148                 GPU_buffers_unbind();
1149                 if (buffer)
1150                         GPU_buffer_free(buffer);
1151
1152                 MEM_freeN(mat_orig_to_new);
1153                 MEM_freeN(matconv);
1154         }
1155 }
1156
1157 static void cdDM_drawFacesGLSL(DerivedMesh *dm, DMSetMaterial setMaterial)
1158 {
1159         dm->drawMappedFacesGLSL(dm, setMaterial, NULL, NULL);
1160 }
1161
1162 static void cdDM_drawMappedFacesMat(
1163         DerivedMesh *dm,
1164         void (*setMaterial)(void *userData, int matnr, void *attribs),
1165         bool (*setFace)(void *userData, int index), void *userData)
1166 {
1167         CDDerivedMesh *cddm = (CDDerivedMesh *) dm;
1168         GPUVertexAttribs gattribs;
1169         DMVertexAttribs attribs;
1170         MVert *mvert = cddm->mvert;
1171         const MPoly *mpoly = cddm->mpoly;
1172         const MLoop *mloop = cddm->mloop;
1173         const MLoopTri *lt = dm->getLoopTriArray(dm);
1174         const int tottri = dm->getNumLoopTri(dm);
1175         const float (*nors)[3] = dm->getPolyDataArray(dm, CD_NORMAL);
1176         const float (*lnors)[3] = dm->getLoopDataArray(dm, CD_NORMAL);
1177         int a, matnr, new_matnr;
1178         int orig;
1179
1180         const int *index_mp_to_orig  = dm->getPolyDataArray(dm, CD_ORIGINDEX);
1181
1182         /* TODO: same as for solid draw, not entirely correct, but works fine for now,
1183          *       will skip using textures (dyntopo currently destroys UV anyway) and
1184          *       works fine for matcap
1185          */
1186
1187         if (cddm->pbvh) {
1188                 if (cddm->pbvh_draw &&
1189                     BKE_pbvh_type(cddm->pbvh) == PBVH_BMESH &&
1190                     BKE_pbvh_has_faces(cddm->pbvh))
1191                 {
1192                         setMaterial(userData, 1, &gattribs);
1193                         BKE_pbvh_draw(cddm->pbvh, NULL, NULL, NULL, false, false);
1194                         return;
1195                 }
1196                 else {
1197                         cdDM_update_normals_from_pbvh(dm);
1198                 }
1199         }
1200
1201         matnr = -1;
1202
1203         memset(&attribs, 0, sizeof(attribs));
1204
1205         glBegin(GL_TRIANGLES);
1206
1207         for (a = 0; a < tottri; a++, lt++) {
1208                 const MPoly *mp = &mpoly[lt->poly];
1209                 const unsigned int  vtri[3] = {mloop[lt->tri[0]].v, mloop[lt->tri[1]].v, mloop[lt->tri[2]].v};
1210                 const unsigned int *ltri = lt->tri;
1211                 const bool smoothnormal = lnors || (mp->flag & ME_SMOOTH);
1212                 const float *ln1 = NULL, *ln2 = NULL, *ln3 = NULL;
1213
1214                 /* material */
1215                 new_matnr = mp->mat_nr + 1;
1216
1217                 if (new_matnr != matnr) {
1218                         glEnd();
1219
1220                         setMaterial(userData, matnr = new_matnr, &gattribs);
1221                         DM_vertex_attributes_from_gpu(dm, &gattribs, &attribs);
1222                         DM_draw_attrib_vertex_uniforms(&attribs);
1223
1224                         glBegin(GL_TRIANGLES);
1225                 }
1226
1227                 /* skipping faces */
1228                 if (setFace) {
1229                         orig = (index_mp_to_orig) ? index_mp_to_orig[lt->poly] : lt->poly;
1230
1231                         if (orig != ORIGINDEX_NONE && !setFace(userData, orig))
1232                                 continue;
1233                 }
1234
1235                 /* smooth normal */
1236                 if (!smoothnormal) {
1237                         if (nors) {
1238                                 glNormal3fv(nors[lt->poly]);
1239                         }
1240                         else {
1241                                 /* TODO ideally a normal layer should always be available */
1242                                 float nor[3];
1243                                 normal_tri_v3(nor, mvert[vtri[0]].co, mvert[vtri[1]].co, mvert[vtri[2]].co);
1244                                 glNormal3fv(nor);
1245                         }
1246                 }
1247                 else if (lnors) {
1248                         ln1 = lnors[ltri[0]];
1249                         ln2 = lnors[ltri[1]];
1250                         ln3 = lnors[ltri[2]];
1251                 }
1252
1253                 /* vertices */
1254                 cddm_draw_attrib_vertex(&attribs, mvert, a, vtri[0], ltri[0], 0, ln1, smoothnormal);
1255                 cddm_draw_attrib_vertex(&attribs, mvert, a, vtri[1], ltri[1], 1, ln2, smoothnormal);
1256                 cddm_draw_attrib_vertex(&attribs, mvert, a, vtri[2], ltri[2], 2, ln3, smoothnormal);
1257         }
1258         glEnd();
1259 }
1260
1261 static void cdDM_drawMappedEdges(DerivedMesh *dm, DMSetDrawOptions setDrawOptions, void *userData)
1262 {
1263         CDDerivedMesh *cddm = (CDDerivedMesh *) dm;
1264         MVert *vert = cddm->mvert;
1265         MEdge *edge = cddm->medge;
1266         int i, orig, *index = DM_get_edge_data_layer(dm, CD_ORIGINDEX);
1267
1268         glBegin(GL_LINES);
1269         for (i = 0; i < dm->numEdgeData; i++, edge++) {
1270                 if (index) {
1271                         orig = *index++;
1272                         if (setDrawOptions && orig == ORIGINDEX_NONE) continue;
1273                 }
1274                 else
1275                         orig = i;
1276
1277                 if (!setDrawOptions || (setDrawOptions(userData, orig) != DM_DRAW_OPTION_SKIP)) {
1278                         glVertex3fv(vert[edge->v1].co);
1279                         glVertex3fv(vert[edge->v2].co);
1280                 }
1281         }
1282         glEnd();
1283 }
1284
1285 typedef struct FaceCount {
1286         unsigned int i_visible;
1287         unsigned int i_hidden;
1288         unsigned int i_tri_visible;
1289         unsigned int i_tri_hidden;
1290 } FaceCount;
1291
1292 static void cdDM_buffer_copy_triangles(
1293         DerivedMesh *dm, unsigned int *varray,
1294         const int *mat_orig_to_new)
1295 {
1296         GPUBufferMaterial *gpumat, *gpumaterials = dm->drawObject->materials;
1297         int i, j, start;
1298
1299         const int gpu_totmat = dm->drawObject->totmaterial;
1300         const short dm_totmat = dm->totmat;
1301         const MPoly *mpoly = dm->getPolyArray(dm);
1302         const MLoopTri *lt = dm->getLoopTriArray(dm);
1303         const int totpoly = dm->getNumPolys(dm);
1304
1305         FaceCount *fc = MEM_mallocN(sizeof(*fc) * gpu_totmat, "gpumaterial.facecount");
1306
1307         for (i = 0; i < gpu_totmat; i++) {
1308                 fc[i].i_visible = 0;
1309                 fc[i].i_tri_visible = 0;
1310                 fc[i].i_hidden = gpumaterials[i].totpolys - 1;
1311                 fc[i].i_tri_hidden = gpumaterials[i].totelements - 1;
1312         }
1313
1314         for (i = 0; i < totpoly; i++) {
1315                 const short mat_nr = ME_MAT_NR_TEST(mpoly[i].mat_nr, dm_totmat);
1316                 int tottri = ME_POLY_TRI_TOT(&mpoly[i]);
1317                 int mati = mat_orig_to_new[mat_nr];
1318                 gpumat = gpumaterials + mati;
1319
1320                 if (mpoly[i].flag & ME_HIDE) {
1321                         for (j = 0; j < tottri; j++, lt++) {
1322                                 start = gpumat->start + fc[mati].i_tri_hidden;
1323                                 /* v1 v2 v3 */
1324                                 varray[start--] = lt->tri[2];
1325                                 varray[start--] = lt->tri[1];
1326                                 varray[start--] = lt->tri[0];
1327                                 fc[mati].i_tri_hidden -= 3;
1328                         }
1329                         gpumat->polys[fc[mati].i_hidden--] = i;
1330                 }
1331                 else {
1332                         for (j = 0; j < tottri; j++, lt++) {
1333                                 start = gpumat->start + fc[mati].i_tri_visible;
1334                                 /* v1 v2 v3 */
1335                                 varray[start++] = lt->tri[0];
1336                                 varray[start++] = lt->tri[1];
1337                                 varray[start++] = lt->tri[2];
1338                                 fc[mati].i_tri_visible += 3;
1339                         }
1340                         gpumat->polys[fc[mati].i_visible++] = i;
1341                 }
1342         }
1343
1344         /* set the visible polygons */
1345         for (i = 0; i < gpu_totmat; i++) {
1346                 gpumaterials[i].totvisiblepolys = fc[i].i_visible;
1347         }
1348
1349         MEM_freeN(fc);
1350 }
1351
1352 static void cdDM_buffer_copy_vertex(
1353         DerivedMesh *dm, float *varray)
1354 {
1355         const MVert *mvert;
1356         const MPoly *mpoly;
1357         const MLoop *mloop;
1358
1359         int i, j, start, totpoly;
1360
1361         mvert = dm->getVertArray(dm);
1362         mpoly = dm->getPolyArray(dm);
1363         mloop = dm->getLoopArray(dm);
1364         totpoly = dm->getNumPolys(dm);
1365
1366         start = 0;
1367
1368         for (i = 0; i < totpoly; i++, mpoly++) {
1369                 for (j = 0; j < mpoly->totloop; j++) {
1370                         copy_v3_v3(&varray[start], mvert[mloop[mpoly->loopstart + j].v].co);
1371                         start += 3;
1372                 }
1373         }
1374
1375         /* copy loose points */
1376         j = dm->drawObject->tot_loop_verts * 3;
1377         for (i = 0; i < dm->drawObject->totvert; i++) {
1378                 if (dm->drawObject->vert_points[i].point_index >= dm->drawObject->tot_loop_verts) {
1379                         copy_v3_v3(&varray[j], mvert[i].co);
1380                         j += 3;
1381                 }
1382         }
1383 }
1384
1385 static void cdDM_buffer_copy_normal(
1386         DerivedMesh *dm, short *varray)
1387 {
1388         CDDerivedMesh *cddm = (CDDerivedMesh *)dm;
1389         int i, j, totpoly;
1390         int start;
1391
1392         const float (*nors)[3] = dm->getPolyDataArray(dm, CD_NORMAL);
1393         const float (*lnors)[3] = dm->getLoopDataArray(dm, CD_NORMAL);
1394
1395         const MVert *mvert;
1396         const MPoly *mpoly;
1397         const MLoop *mloop;
1398
1399         mvert = dm->getVertArray(dm);
1400         mpoly = dm->getPolyArray(dm);
1401         mloop = dm->getLoopArray(dm);
1402         totpoly = dm->getNumPolys(dm);
1403
1404         /* we are in sculpt mode, disable loop normals (since they won't get updated) */
1405         if (cddm->pbvh)
1406                 lnors = NULL;
1407
1408         start = 0;
1409         for (i = 0; i < totpoly; i++, mpoly++) {
1410                 const bool smoothnormal = (mpoly->flag & ME_SMOOTH) != 0;
1411
1412                 if (lnors) {
1413                         /* Copy loop normals */
1414                         for (j = 0; j < mpoly->totloop; j++, start += 4) {
1415                                 normal_float_to_short_v3(&varray[start], lnors[mpoly->loopstart + j]);
1416                         }
1417                 }
1418                 else if (smoothnormal) {
1419                         /* Copy vertex normal */
1420                         for (j = 0; j < mpoly->totloop; j++, start += 4) {
1421                                 copy_v3_v3_short(&varray[start], mvert[mloop[mpoly->loopstart + j].v].no);
1422                         }
1423                 }
1424                 else {
1425                         /* Copy cached OR calculated face normal */
1426                         short f_no_s[3];
1427
1428                         if (nors) {
1429                                 normal_float_to_short_v3(f_no_s, nors[i]);
1430                         }
1431                         else {
1432                                 float f_no[3];
1433                                 BKE_mesh_calc_poly_normal(mpoly, &mloop[mpoly->loopstart], mvert, f_no);
1434                                 normal_float_to_short_v3(f_no_s, f_no);
1435                         }
1436
1437                         for (j = 0; j < mpoly->totloop; j++, start += 4) {
1438                                 copy_v3_v3_short(&varray[start], f_no_s);
1439                         }
1440                 }
1441         }
1442 }
1443
1444 static void cdDM_buffer_copy_uv(
1445         DerivedMesh *dm, float *varray)
1446 {
1447         int i, j, totpoly;
1448         int start;
1449
1450         const MPoly *mpoly;
1451         const MLoopUV *mloopuv;
1452
1453         if ((mloopuv = DM_get_loop_data_layer(dm, CD_MLOOPUV)) == NULL) {
1454                 return;
1455         }
1456
1457         mpoly = dm->getPolyArray(dm);
1458         totpoly = dm->getNumPolys(dm);
1459
1460         start = 0;
1461         for (i = 0; i < totpoly; i++, mpoly++) {
1462                 for (j = 0; j < mpoly->totloop; j++) {
1463                         copy_v2_v2(&varray[start], mloopuv[mpoly->loopstart + j].uv);
1464                         start += 2;
1465                 }
1466         }
1467 }
1468
1469 static void cdDM_buffer_copy_uv_texpaint(
1470         DerivedMesh *dm, float *varray)
1471 {
1472         int i, j, totpoly;
1473         int start;
1474
1475         const MPoly *mpoly;
1476
1477         int totmaterial = dm->totmat;
1478         const MLoopUV **uv_base;
1479         const MLoopUV  *uv_stencil_base;
1480         int stencil;
1481
1482         totpoly = dm->getNumPolys(dm);
1483
1484         /* should have been checked for before, reassert */
1485         BLI_assert(DM_get_loop_data_layer(dm, CD_MLOOPUV));
1486         uv_base = MEM_mallocN(totmaterial * sizeof(*uv_base), "texslots");
1487
1488         for (i = 0; i < totmaterial; i++) {
1489                 uv_base[i] = DM_paint_uvlayer_active_get(dm, i);
1490         }
1491
1492         stencil = CustomData_get_stencil_layer(&dm->loopData, CD_MLOOPUV);
1493         uv_stencil_base = CustomData_get_layer_n(&dm->loopData, CD_MLOOPUV, stencil);
1494
1495         mpoly = dm->getPolyArray(dm);
1496         start = 0;
1497
1498         for (i = 0; i < totpoly; i++, mpoly++) {
1499                 int mat_i = mpoly->mat_nr;
1500
1501                 for (j = 0; j < mpoly->totloop; j++) {
1502                         copy_v2_v2(&varray[start], uv_base[mat_i][mpoly->loopstart + j].uv);
1503                         copy_v2_v2(&varray[start + 2], uv_stencil_base[mpoly->loopstart + j].uv);
1504                         start += 4;
1505                 }
1506         }
1507
1508         MEM_freeN((void *)uv_base);
1509 }
1510
1511 /* treat varray_ as an array of MCol, four MCol's per face */
1512 static void cdDM_buffer_copy_mcol(
1513         DerivedMesh *dm, unsigned char *varray,
1514         const void *user_data)
1515 {
1516         int i, j, totpoly;
1517         int start;
1518
1519         const MLoopCol *mloopcol = user_data;
1520         const MPoly *mpoly = dm->getPolyArray(dm);
1521
1522         totpoly = dm->getNumPolys(dm);
1523
1524         start = 0;
1525
1526         for (i = 0; i < totpoly; i++, mpoly++) {
1527                 for (j = 0; j < mpoly->totloop; j++) {
1528                         copy_v3_v3_uchar(&varray[start], &mloopcol[mpoly->loopstart + j].r);
1529                         start += 3;
1530                 }
1531         }
1532 }
1533
1534 static void cdDM_buffer_copy_edge(
1535         DerivedMesh *dm, unsigned int *varray)
1536 {
1537         MEdge *medge, *medge_base;
1538         int i, totedge, iloose, inorm, iloosehidden, inormhidden;
1539         int tot_loose_hidden = 0, tot_loose = 0;
1540         int tot_hidden = 0, tot = 0;
1541
1542         medge_base = medge = dm->getEdgeArray(dm);
1543         totedge = dm->getNumEdges(dm);
1544
1545         for (i = 0; i < totedge; i++, medge++) {
1546                 if (medge->flag & ME_EDGEDRAW) {
1547                         if (medge->flag & ME_LOOSEEDGE) tot_loose++;
1548                         else tot++;
1549                 }
1550                 else {
1551                         if (medge->flag & ME_LOOSEEDGE) tot_loose_hidden++;
1552                         else tot_hidden++;
1553                 }
1554         }
1555
1556         inorm = 0;
1557         inormhidden = tot;
1558         iloose = tot + tot_hidden;
1559         iloosehidden = iloose + tot_loose;
1560
1561         medge = medge_base;
1562         for (i = 0; i < totedge; i++, medge++) {
1563                 if (medge->flag & ME_EDGEDRAW) {
1564                         if (medge->flag & ME_LOOSEEDGE) {
1565                                 varray[iloose * 2] = dm->drawObject->vert_points[medge->v1].point_index;
1566                                 varray[iloose * 2 + 1] = dm->drawObject->vert_points[medge->v2].point_index;
1567                                 iloose++;
1568                         }
1569                         else {
1570                                 varray[inorm * 2] = dm->drawObject->vert_points[medge->v1].point_index;
1571                                 varray[inorm * 2 + 1] = dm->drawObject->vert_points[medge->v2].point_index;
1572                                 inorm++;
1573                         }
1574                 }
1575                 else {
1576                         if (medge->flag & ME_LOOSEEDGE) {
1577                                 varray[iloosehidden * 2] = dm->drawObject->vert_points[medge->v1].point_index;
1578                                 varray[iloosehidden * 2 + 1] = dm->drawObject->vert_points[medge->v2].point_index;
1579                                 iloosehidden++;
1580                         }
1581                         else {
1582                                 varray[inormhidden * 2] = dm->drawObject->vert_points[medge->v1].point_index;
1583                                 varray[inormhidden * 2 + 1] = dm->drawObject->vert_points[medge->v2].point_index;
1584                                 inormhidden++;
1585                         }
1586                 }
1587         }
1588
1589         dm->drawObject->tot_loose_edge_drawn = tot_loose;
1590         dm->drawObject->loose_edge_offset = tot + tot_hidden;
1591         dm->drawObject->tot_edge_drawn = tot;
1592 }
1593
1594 static void cdDM_buffer_copy_uvedge(
1595         DerivedMesh *dm, float *varray)
1596 {
1597         int i, j, totpoly;
1598         int start;
1599         const MLoopUV *mloopuv;
1600         const MPoly *mpoly = dm->getPolyArray(dm);
1601
1602         if ((mloopuv = DM_get_loop_data_layer(dm, CD_MLOOPUV)) == NULL) {
1603                 return;
1604         }
1605
1606         totpoly = dm->getNumPolys(dm);
1607         start = 0;
1608
1609         for (i = 0; i < totpoly; i++, mpoly++) {
1610                 for (j = 0; j < mpoly->totloop; j++) {
1611                         copy_v2_v2(&varray[start], mloopuv[mpoly->loopstart + j].uv);
1612                         copy_v2_v2(&varray[start + 2], mloopuv[mpoly->loopstart + (j + 1) % mpoly->totloop].uv);
1613                         start += 4;
1614                 }
1615         }
1616 }
1617
1618 static void cdDM_copy_gpu_data(
1619         DerivedMesh *dm, int type, void *varray_p,
1620         const int *mat_orig_to_new, const void *user_data)
1621 {
1622         /* 'varray_p' cast is redundant but include for self-documentation */
1623         switch (type) {
1624                 case GPU_BUFFER_VERTEX:
1625                         cdDM_buffer_copy_vertex(dm, (float *)varray_p);
1626                         break;
1627                 case GPU_BUFFER_NORMAL:
1628                         cdDM_buffer_copy_normal(dm, (short *)varray_p);
1629                         break;
1630                 case GPU_BUFFER_COLOR:
1631                         cdDM_buffer_copy_mcol(dm, (unsigned char *)varray_p, user_data);
1632                         break;
1633                 case GPU_BUFFER_UV:
1634                         cdDM_buffer_copy_uv(dm, (float *)varray_p);
1635                         break;
1636                 case GPU_BUFFER_UV_TEXPAINT:
1637                         cdDM_buffer_copy_uv_texpaint(dm, (float *)varray_p);
1638                         break;
1639                 case GPU_BUFFER_EDGE:
1640                         cdDM_buffer_copy_edge(dm, (unsigned int *)varray_p);
1641                         break;
1642                 case GPU_BUFFER_UVEDGE:
1643                         cdDM_buffer_copy_uvedge(dm, (float *)varray_p);
1644                         break;
1645                 case GPU_BUFFER_TRIANGLES:
1646                         cdDM_buffer_copy_triangles(dm, (unsigned int *)varray_p, mat_orig_to_new);
1647                         break;
1648                 default:
1649                         break;
1650         }
1651 }
1652
1653 /* add a new point to the list of points related to a particular
1654  * vertex */
1655 #ifdef USE_GPU_POINT_LINK
1656
1657 static void cdDM_drawobject_add_vert_point(GPUDrawObject *gdo, int vert_index, int point_index)
1658 {
1659         GPUVertPointLink *lnk;
1660
1661         lnk = &gdo->vert_points[vert_index];
1662
1663         /* if first link is in use, add a new link at the end */
1664         if (lnk->point_index != -1) {
1665                 /* get last link */
1666                 for (; lnk->next; lnk = lnk->next) ;
1667
1668                 /* add a new link from the pool */
1669                 lnk = lnk->next = &gdo->vert_points_mem[gdo->vert_points_usage];
1670                 gdo->vert_points_usage++;
1671         }
1672
1673         lnk->point_index = point_index;
1674 }
1675
1676 #else
1677
1678 static void cdDM_drawobject_add_vert_point(GPUDrawObject *gdo, int vert_index, int point_index)
1679 {
1680         GPUVertPointLink *lnk;
1681         lnk = &gdo->vert_points[vert_index];
1682         if (lnk->point_index == -1) {
1683                 lnk->point_index = point_index;
1684         }
1685 }
1686
1687 #endif  /* USE_GPU_POINT_LINK */
1688
1689 /* for each vertex, build a list of points related to it; these lists
1690  * are stored in an array sized to the number of vertices */
1691 static void cdDM_drawobject_init_vert_points(
1692         GPUDrawObject *gdo,
1693         const MPoly *mpoly, const MLoop *mloop,
1694         int tot_poly)
1695 {
1696         int i;
1697         int tot_loops = 0;
1698
1699         /* allocate the array and space for links */
1700         gdo->vert_points = MEM_mallocN(sizeof(GPUVertPointLink) * gdo->totvert,
1701                                        "GPUDrawObject.vert_points");
1702 #ifdef USE_GPU_POINT_LINK
1703         gdo->vert_points_mem = MEM_callocN(sizeof(GPUVertPointLink) * gdo->totvert,
1704                                            "GPUDrawObject.vert_points_mem");
1705         gdo->vert_points_usage = 0;
1706 #endif
1707
1708         /* -1 indicates the link is not yet used */
1709         for (i = 0; i < gdo->totvert; i++) {
1710 #ifdef USE_GPU_POINT_LINK
1711                 gdo->vert_points[i].link = NULL;
1712 #endif
1713                 gdo->vert_points[i].point_index = -1;
1714         }
1715
1716         for (i = 0; i < tot_poly; i++) {
1717                 int j;
1718                 const MPoly *mp = &mpoly[i];
1719
1720                 /* assign unique indices to vertices of the mesh */
1721                 for (j = 0; j < mp->totloop; j++) {
1722                         cdDM_drawobject_add_vert_point(gdo, mloop[mp->loopstart + j].v, tot_loops + j);
1723                 }
1724                 tot_loops += mp->totloop;
1725         }
1726
1727         /* map any unused vertices to loose points */
1728         for (i = 0; i < gdo->totvert; i++) {
1729                 if (gdo->vert_points[i].point_index == -1) {
1730                         gdo->vert_points[i].point_index = gdo->tot_loop_verts + gdo->tot_loose_point;
1731                         gdo->tot_loose_point++;
1732                 }
1733         }
1734 }
1735
1736 /* see GPUDrawObject's structure definition for a description of the
1737  * data being initialized here */
1738 static GPUDrawObject *cdDM_GPUobject_new(DerivedMesh *dm)
1739 {
1740         GPUDrawObject *gdo;
1741         const MPoly *mpoly;
1742         const MLoop *mloop;
1743         const short dm_totmat = dm->totmat;
1744         GPUBufferMaterial *mat_info;
1745         int i, totloops, totpolys;
1746
1747         /* object contains at least one material (default included) so zero means uninitialized dm */
1748         BLI_assert(dm_totmat != 0);
1749
1750         mpoly = dm->getPolyArray(dm);
1751         mloop = dm->getLoopArray(dm);
1752
1753         totpolys = dm->getNumPolys(dm);
1754         totloops = dm->getNumLoops(dm);
1755
1756         /* get the number of points used by each material, treating
1757          * each quad as two triangles */
1758         mat_info = MEM_callocN(sizeof(*mat_info) * dm_totmat, "GPU_drawobject_new.mat_orig_to_new");
1759
1760         for (i = 0; i < totpolys; i++) {
1761                 const short mat_nr = ME_MAT_NR_TEST(mpoly[i].mat_nr, dm_totmat);
1762                 mat_info[mat_nr].totpolys++;
1763                 mat_info[mat_nr].totelements += 3 * ME_POLY_TRI_TOT(&mpoly[i]);
1764                 mat_info[mat_nr].totloops += mpoly[i].totloop;
1765         }
1766         /* create the GPUDrawObject */
1767         gdo = MEM_callocN(sizeof(GPUDrawObject), "GPUDrawObject");
1768         gdo->totvert = dm->getNumVerts(dm);
1769         gdo->totedge = dm->getNumEdges(dm);
1770
1771         GPU_buffer_material_finalize(gdo, mat_info, dm_totmat);
1772
1773         gdo->tot_loop_verts = totloops;
1774
1775         /* store total number of points used for triangles */
1776         gdo->tot_triangle_point = poly_to_tri_count(totpolys, totloops) * 3;
1777
1778         cdDM_drawobject_init_vert_points(gdo, mpoly, mloop, totpolys);
1779
1780         return gdo;
1781 }
1782
1783 static void cdDM_foreachMappedVert(
1784         DerivedMesh *dm,
1785         void (*func)(void *userData, int index, const float co[3], const float no_f[3], const short no_s[3]),
1786         void *userData,
1787         DMForeachFlag flag)
1788 {
1789         MVert *mv = CDDM_get_verts(dm);
1790         const int *index = DM_get_vert_data_layer(dm, CD_ORIGINDEX);
1791         int i;
1792
1793         if (index) {
1794                 for (i = 0; i < dm->numVertData; i++, mv++) {
1795                         const short *no = (flag & DM_FOREACH_USE_NORMAL) ? mv->no : NULL;
1796                         const int orig = *index++;
1797                         if (orig == ORIGINDEX_NONE) continue;
1798                         func(userData, orig, mv->co, NULL, no);
1799                 }
1800         }
1801         else {
1802                 for (i = 0; i < dm->numVertData; i++, mv++) {
1803                         const short *no = (flag & DM_FOREACH_USE_NORMAL) ? mv->no : NULL;
1804                         func(userData, i, mv->co, NULL, no);
1805                 }
1806         }
1807 }
1808
1809 static void cdDM_foreachMappedEdge(
1810         DerivedMesh *dm,
1811         void (*func)(void *userData, int index, const float v0co[3], const float v1co[3]),
1812         void *userData)
1813 {
1814         CDDerivedMesh *cddm = (CDDerivedMesh *) dm;
1815         MVert *mv = cddm->mvert;
1816         MEdge *med = cddm->medge;
1817         int i, orig, *index = DM_get_edge_data_layer(dm, CD_ORIGINDEX);
1818
1819         for (i = 0; i < dm->numEdgeData; i++, med++) {
1820                 if (index) {
1821                         orig = *index++;
1822                         if (orig == ORIGINDEX_NONE) continue;
1823                         func(userData, orig, mv[med->v1].co, mv[med->v2].co);
1824                 }
1825                 else
1826                         func(userData, i, mv[med->v1].co, mv[med->v2].co);
1827         }
1828 }
1829
1830 static void cdDM_foreachMappedLoop(
1831         DerivedMesh *dm,
1832         void (*func)(void *userData, int vertex_index, int face_index, const float co[3], const float no[3]),
1833         void *userData,
1834         DMForeachFlag flag)
1835 {
1836         /* We can't use dm->getLoopDataLayout(dm) here, we want to always access dm->loopData, EditDerivedBMesh would
1837          * return loop data from bmesh itself. */
1838         const float (*lnors)[3] = (flag & DM_FOREACH_USE_NORMAL) ? DM_get_loop_data_layer(dm, CD_NORMAL) : NULL;
1839
1840         const MVert *mv = CDDM_get_verts(dm);
1841         const MLoop *ml = CDDM_get_loops(dm);
1842         const MPoly *mp = CDDM_get_polys(dm);
1843         const int *v_index = DM_get_vert_data_layer(dm, CD_ORIGINDEX);
1844         const int *f_index = DM_get_poly_data_layer(dm, CD_ORIGINDEX);
1845         int p_idx, i;
1846
1847         for (p_idx = 0; p_idx < dm->numPolyData; ++p_idx, ++mp) {
1848                 for (i = 0; i < mp->totloop; ++i, ++ml) {
1849                         const int v_idx = v_index ? v_index[ml->v] : ml->v;
1850                         const int f_idx = f_index ? f_index[p_idx] : p_idx;
1851                         const float *no = lnors ? *lnors++ : NULL;
1852                         if (!ELEM(ORIGINDEX_NONE, v_idx, f_idx)) {
1853                                 func(userData, v_idx, f_idx, mv[ml->v].co, no);
1854                         }
1855                 }
1856         }
1857 }
1858
1859 static void cdDM_foreachMappedFaceCenter(
1860         DerivedMesh *dm,
1861         void (*func)(void *userData, int index, const float cent[3], const float no[3]),
1862         void *userData,
1863         DMForeachFlag flag)
1864 {
1865         CDDerivedMesh *cddm = (CDDerivedMesh *)dm;
1866         MVert *mvert = cddm->mvert;
1867         MPoly *mp;
1868         MLoop *ml;
1869         int i, orig, *index;
1870
1871         index = CustomData_get_layer(&dm->polyData, CD_ORIGINDEX);
1872         mp = cddm->mpoly;
1873         for (i = 0; i < dm->numPolyData; i++, mp++) {
1874                 float cent[3];
1875                 float *no, _no[3];
1876
1877                 if (index) {
1878                         orig = *index++;
1879                         if (orig == ORIGINDEX_NONE) continue;
1880                 }
1881                 else {
1882                         orig = i;
1883                 }
1884                 
1885                 ml = &cddm->mloop[mp->loopstart];
1886                 BKE_mesh_calc_poly_center(mp, ml, mvert, cent);
1887
1888                 if (flag & DM_FOREACH_USE_NORMAL) {
1889                         BKE_mesh_calc_poly_normal(mp, ml, mvert, (no = _no));
1890                 }
1891                 else {
1892                         no = NULL;
1893                 }
1894
1895                 func(userData, orig, cent, no);
1896         }
1897
1898 }
1899
1900 void CDDM_recalc_tessellation_ex(DerivedMesh *dm, const bool do_face_nor_cpy)
1901 {
1902         CDDerivedMesh *cddm = (CDDerivedMesh *)dm;
1903
1904         dm->numTessFaceData = BKE_mesh_recalc_tessellation(
1905                 &dm->faceData, &dm->loopData, &dm->polyData,
1906                 cddm->mvert,
1907                 dm->numTessFaceData, dm->numLoopData, dm->numPolyData,
1908                 do_face_nor_cpy);
1909
1910         cddm->mface = CustomData_get_layer(&dm->faceData, CD_MFACE);
1911
1912         /* Tessellation recreated faceData, and the active layer indices need to get re-propagated
1913          * from loops and polys to faces */
1914         CustomData_bmesh_update_active_layers(&dm->faceData, &dm->polyData, &dm->loopData);
1915 }
1916
1917 void CDDM_recalc_tessellation(DerivedMesh *dm)
1918 {
1919         CDDM_recalc_tessellation_ex(dm, true);
1920 }
1921
1922 void CDDM_recalc_looptri(DerivedMesh *dm)
1923 {
1924         CDDerivedMesh *cddm = (CDDerivedMesh *)dm;
1925         const unsigned int totpoly = dm->numPolyData;
1926         const unsigned int totloop = dm->numLoopData;
1927
1928         DM_ensure_looptri_data(dm);
1929         BLI_assert(totpoly == 0 || cddm->dm.looptris.array_wip != NULL);
1930
1931         BKE_mesh_recalc_looptri(
1932                 cddm->mloop, cddm->mpoly,
1933                 cddm->mvert,
1934                 totloop, totpoly,
1935                 cddm->dm.looptris.array_wip);
1936
1937         BLI_assert(cddm->dm.looptris.array == NULL);
1938         atomic_cas_ptr((void **)&cddm->dm.looptris.array, cddm->dm.looptris.array, cddm->dm.looptris.array_wip);
1939         cddm->dm.looptris.array_wip = NULL;
1940 }
1941
1942 static void cdDM_free_internal(CDDerivedMesh *cddm)
1943 {
1944         if (cddm->pmap) MEM_freeN(cddm->pmap);
1945         if (cddm->pmap_mem) MEM_freeN(cddm->pmap_mem);
1946 }
1947
1948 static void cdDM_release(DerivedMesh *dm)
1949 {
1950         CDDerivedMesh *cddm = (CDDerivedMesh *)dm;
1951
1952         if (DM_release(dm)) {
1953                 cdDM_free_internal(cddm);
1954                 MEM_freeN(cddm);
1955         }
1956 }
1957
1958 /**************** CDDM interface functions ****************/
1959 static CDDerivedMesh *cdDM_create(const char *desc)
1960 {
1961         CDDerivedMesh *cddm;
1962         DerivedMesh *dm;
1963
1964         cddm = MEM_callocN(sizeof(*cddm), desc);
1965         dm = &cddm->dm;
1966
1967         dm->getMinMax = cdDM_getMinMax;
1968
1969         dm->getNumVerts = cdDM_getNumVerts;
1970         dm->getNumEdges = cdDM_getNumEdges;
1971         dm->getNumTessFaces = cdDM_getNumTessFaces;
1972         dm->getNumLoops = cdDM_getNumLoops;
1973         dm->getNumPolys = cdDM_getNumPolys;
1974
1975         dm->getVert = cdDM_getVert;
1976         dm->getEdge = cdDM_getEdge;
1977         dm->getTessFace = cdDM_getTessFace;
1978
1979         dm->copyVertArray = cdDM_copyVertArray;
1980         dm->copyEdgeArray = cdDM_copyEdgeArray;
1981         dm->copyTessFaceArray = cdDM_copyTessFaceArray;
1982         dm->copyLoopArray = cdDM_copyLoopArray;
1983         dm->copyPolyArray = cdDM_copyPolyArray;
1984
1985         dm->getVertData = DM_get_vert_data;
1986         dm->getEdgeData = DM_get_edge_data;
1987         dm->getTessFaceData = DM_get_tessface_data;
1988         dm->getVertDataArray = DM_get_vert_data_layer;
1989         dm->getEdgeDataArray = DM_get_edge_data_layer;
1990         dm->getTessFaceDataArray = DM_get_tessface_data_layer;
1991
1992         dm->calcNormals = CDDM_calc_normals;
1993         dm->calcLoopNormals = CDDM_calc_loop_normals;
1994         dm->calcLoopNormalsSpaceArray = CDDM_calc_loop_normals_spacearr;
1995         dm->calcLoopTangents = DM_calc_loop_tangents;
1996         dm->recalcTessellation = CDDM_recalc_tessellation;
1997         dm->recalcLoopTri = CDDM_recalc_looptri;
1998
1999         dm->getVertCos = cdDM_getVertCos;
2000         dm->getVertCo = cdDM_getVertCo;
2001         dm->getVertNo = cdDM_getVertNo;
2002
2003         dm->getPBVH = cdDM_getPBVH;
2004         dm->getPolyMap = cdDM_getPolyMap;
2005
2006         dm->drawVerts = cdDM_drawVerts;
2007
2008         dm->drawUVEdges = cdDM_drawUVEdges;
2009         dm->drawEdges = cdDM_drawEdges;
2010         dm->drawLooseEdges = cdDM_drawLooseEdges;
2011         dm->drawMappedEdges = cdDM_drawMappedEdges;
2012
2013         dm->drawFacesSolid = cdDM_drawFacesSolid;
2014         dm->drawFacesTex = cdDM_drawFacesTex;
2015         dm->drawFacesGLSL = cdDM_drawFacesGLSL;
2016         dm->drawMappedFaces = cdDM_drawMappedFaces;
2017         dm->drawMappedFacesTex = cdDM_drawMappedFacesTex;
2018         dm->drawMappedFacesGLSL = cdDM_drawMappedFacesGLSL;
2019         dm->drawMappedFacesMat = cdDM_drawMappedFacesMat;
2020
2021         dm->gpuObjectNew = cdDM_GPUobject_new;
2022         dm->copy_gpu_data = cdDM_copy_gpu_data;
2023
2024         dm->foreachMappedVert = cdDM_foreachMappedVert;
2025         dm->foreachMappedEdge = cdDM_foreachMappedEdge;
2026         dm->foreachMappedLoop = cdDM_foreachMappedLoop;
2027         dm->foreachMappedFaceCenter = cdDM_foreachMappedFaceCenter;
2028
2029         dm->release = cdDM_release;
2030
2031         return cddm;
2032 }
2033
2034 DerivedMesh *CDDM_new(int numVerts, int numEdges, int numTessFaces, int numLoops, int numPolys)
2035 {
2036         CDDerivedMesh *cddm = cdDM_create("CDDM_new dm");
2037         DerivedMesh *dm = &cddm->dm;
2038
2039         DM_init(dm, DM_TYPE_CDDM, numVerts, numEdges, numTessFaces, numLoops, numPolys);
2040
2041         CustomData_add_layer(&dm->vertData, CD_ORIGINDEX, CD_CALLOC, NULL, numVerts);
2042         CustomData_add_layer(&dm->edgeData, CD_ORIGINDEX, CD_CALLOC, NULL, numEdges);
2043         CustomData_add_layer(&dm->faceData, CD_ORIGINDEX, CD_CALLOC, NULL, numTessFaces);
2044         CustomData_add_layer(&dm->polyData, CD_ORIGINDEX, CD_CALLOC, NULL, numPolys);
2045
2046         CustomData_add_layer(&dm->vertData, CD_MVERT, CD_CALLOC, NULL, numVerts);
2047         CustomData_add_layer(&dm->edgeData, CD_MEDGE, CD_CALLOC, NULL, numEdges);
2048         CustomData_add_layer(&dm->faceData, CD_MFACE, CD_CALLOC, NULL, numTessFaces);
2049         CustomData_add_layer(&dm->loopData, CD_MLOOP, CD_CALLOC, NULL, numLoops);
2050         CustomData_add_layer(&dm->polyData, CD_MPOLY, CD_CALLOC, NULL, numPolys);
2051
2052         cddm->mvert = CustomData_get_layer(&dm->vertData, CD_MVERT);
2053         cddm->medge = CustomData_get_layer(&dm->edgeData, CD_MEDGE);
2054         cddm->mface = CustomData_get_layer(&dm->faceData, CD_MFACE);
2055         cddm->mloop = CustomData_get_layer(&dm->loopData, CD_MLOOP);
2056         cddm->mpoly = CustomData_get_layer(&dm->polyData, CD_MPOLY);
2057
2058         return dm;
2059 }
2060
2061 DerivedMesh *CDDM_from_mesh(Mesh *mesh)
2062 {
2063         CDDerivedMesh *cddm = cdDM_create(__func__);
2064         DerivedMesh *dm = &cddm->dm;
2065         CustomDataMask mask = CD_MASK_MESH & (~CD_MASK_MDISPS);
2066         int alloctype;
2067
2068         /* this does a referenced copy, with an exception for fluidsim */
2069
2070         DM_init(dm, DM_TYPE_CDDM, mesh->totvert, mesh->totedge, 0 /* mesh->totface */,
2071                 mesh->totloop, mesh->totpoly);
2072
2073         dm->deformedOnly = 1;
2074         dm->cd_flag = mesh->cd_flag;
2075
2076         alloctype = CD_REFERENCE;
2077
2078         CustomData_merge(&mesh->vdata, &dm->vertData, mask, alloctype,
2079                          mesh->totvert);
2080         CustomData_merge(&mesh->edata, &dm->edgeData, mask, alloctype,
2081                          mesh->totedge);
2082         CustomData_merge(&mesh->fdata, &dm->faceData, mask | CD_MASK_ORIGINDEX, alloctype,
2083                          0 /* mesh->totface */);
2084         CustomData_merge(&mesh->ldata, &dm->loopData, mask, alloctype,
2085                          mesh->totloop);
2086         CustomData_merge(&mesh->pdata, &dm->polyData, mask, alloctype,
2087                          mesh->totpoly);
2088
2089         cddm->mvert = CustomData_get_layer(&dm->vertData, CD_MVERT);
2090         cddm->medge = CustomData_get_layer(&dm->edgeData, CD_MEDGE);
2091         cddm->mloop = CustomData_get_layer(&dm->loopData, CD_MLOOP);
2092         cddm->mpoly = CustomData_get_layer(&dm->polyData, CD_MPOLY);
2093 #if 0
2094         cddm->mface = CustomData_get_layer(&dm->faceData, CD_MFACE);
2095 #else
2096         cddm->mface = NULL;
2097 #endif
2098
2099         /* commented since even when CD_ORIGINDEX was first added this line fails
2100          * on the default cube, (after editmode toggle too) - campbell */
2101 #if 0
2102         BLI_assert(CustomData_has_layer(&cddm->dm.faceData, CD_ORIGINDEX));
2103 #endif
2104
2105         return dm;
2106 }
2107
2108 DerivedMesh *CDDM_from_curve(Object *ob)
2109 {
2110         ListBase disp = {NULL, NULL};
2111
2112         if (ob->curve_cache) {
2113                 disp = ob->curve_cache->disp;
2114         }
2115
2116         return CDDM_from_curve_displist(ob, &disp);
2117 }
2118
2119 DerivedMesh *CDDM_from_curve_displist(Object *ob, ListBase *dispbase)
2120 {
2121         Curve *cu = (Curve *) ob->data;
2122         DerivedMesh *dm;
2123         CDDerivedMesh *cddm;
2124         MVert *allvert;
2125         MEdge *alledge;
2126         MLoop *allloop;
2127         MPoly *allpoly;
2128         MLoopUV *alluv = NULL;
2129         int totvert, totedge, totloop, totpoly;
2130         bool use_orco_uv = (cu->flag & CU_UV_ORCO) != 0;
2131
2132         if (BKE_mesh_nurbs_displist_to_mdata(
2133                 ob, dispbase, &allvert, &totvert, &alledge,
2134                 &totedge, &allloop, &allpoly, (use_orco_uv) ? &alluv : NULL,
2135                 &totloop, &totpoly) != 0)
2136         {
2137                 /* Error initializing mdata. This often happens when curve is empty */
2138                 return CDDM_new(0, 0, 0, 0, 0);
2139         }
2140
2141         dm = CDDM_new(totvert, totedge, 0, totloop, totpoly);
2142         dm->deformedOnly = 1;
2143         dm->dirty |= DM_DIRTY_NORMALS;
2144
2145         cddm = (CDDerivedMesh *)dm;
2146
2147         memcpy(cddm->mvert, allvert, totvert * sizeof(MVert));
2148         memcpy(cddm->medge, alledge, totedge * sizeof(MEdge));
2149         memcpy(cddm->mloop, allloop, totloop * sizeof(MLoop));
2150         memcpy(cddm->mpoly, allpoly, totpoly * sizeof(MPoly));
2151
2152         if (alluv) {
2153                 const char *uvname = "Orco";
2154                 CustomData_add_layer_named(&cddm->dm.polyData, CD_MTEXPOLY, CD_DEFAULT, NULL, totpoly, uvname);
2155                 CustomData_add_layer_named(&cddm->dm.loopData, CD_MLOOPUV, CD_ASSIGN, alluv, totloop, uvname);
2156         }
2157
2158         MEM_freeN(allvert);
2159         MEM_freeN(alledge);
2160         MEM_freeN(allloop);
2161         MEM_freeN(allpoly);
2162
2163         return dm;
2164 }
2165
2166 static void loops_to_customdata_corners(
2167         BMesh *bm, CustomData *facedata,
2168         int cdindex, const BMLoop *l3[3],
2169         int numCol, int numTex)
2170 {
2171         const BMLoop *l;
2172         BMFace *f = l3[0]->f;
2173         MTFace *texface;
2174         MTexPoly *texpoly;
2175         MCol *mcol;
2176         MLoopCol *mloopcol;
2177         MLoopUV *mloopuv;
2178         int i, j, hasPCol = CustomData_has_layer(&bm->ldata, CD_PREVIEW_MLOOPCOL);
2179
2180         for (i = 0; i < numTex; i++) {
2181                 texface = CustomData_get_n(facedata, CD_MTFACE, cdindex, i);
2182                 texpoly = CustomData_bmesh_get_n(&bm->pdata, f->head.data, CD_MTEXPOLY, i);
2183                 
2184                 ME_MTEXFACE_CPY(texface, texpoly);
2185         
2186                 for (j = 0; j < 3; j++) {
2187                         l = l3[j];
2188                         mloopuv = CustomData_bmesh_get_n(&bm->ldata, l->head.data, CD_MLOOPUV, i);
2189                         copy_v2_v2(texface->uv[j], mloopuv->uv);
2190                 }
2191         }
2192
2193         for (i = 0; i < numCol; i++) {
2194                 mcol = CustomData_get_n(facedata, CD_MCOL, cdindex, i);
2195                 
2196                 for (j = 0; j < 3; j++) {
2197                         l = l3[j];
2198                         mloopcol = CustomData_bmesh_get_n(&bm->ldata, l->head.data, CD_MLOOPCOL, i);
2199                         MESH_MLOOPCOL_TO_MCOL(mloopcol, &mcol[j]);
2200                 }
2201         }
2202
2203         if (hasPCol) {
2204                 mcol = CustomData_get(facedata, cdindex, CD_PREVIEW_MCOL);
2205
2206                 for (j = 0; j < 3; j++) {
2207                         l = l3[j];
2208                         mloopcol = CustomData_bmesh_get(&bm->ldata, l->head.data, CD_PREVIEW_MLOOPCOL);
2209                         MESH_MLOOPCOL_TO_MCOL(mloopcol, &mcol[j]);
2210                 }
2211         }
2212 }
2213
2214 /* used for both editbmesh and bmesh */
2215 static DerivedMesh *cddm_from_bmesh_ex(
2216         struct BMesh *bm, const bool use_mdisps,
2217         /* EditBMesh vars for use_tessface */
2218         const bool use_tessface,
2219         const int em_tottri, const BMLoop *(*em_looptris)[3])
2220 {
2221         DerivedMesh *dm = CDDM_new(bm->totvert,
2222                                    bm->totedge,
2223                                    use_tessface ? em_tottri : 0,
2224                                    bm->totloop,
2225                                    bm->totface);
2226
2227         CDDerivedMesh *cddm = (CDDerivedMesh *)dm;
2228         BMIter iter;
2229         BMVert *eve;
2230         BMEdge *eed;
2231         BMFace *efa;
2232         MVert *mvert = cddm->mvert;
2233         MEdge *medge = cddm->medge;
2234         MFace *mface = cddm->mface;
2235         MLoop *mloop = cddm->mloop;
2236         MPoly *mpoly = cddm->mpoly;
2237         int numCol = CustomData_number_of_layers(&bm->ldata, CD_MLOOPCOL);
2238         int numTex = CustomData_number_of_layers(&bm->pdata, CD_MTEXPOLY);
2239         int *index, add_orig;
2240         CustomDataMask mask;
2241         unsigned int i, j;
2242         
2243         const int cd_vert_bweight_offset = CustomData_get_offset(&bm->vdata, CD_BWEIGHT);
2244         const int cd_edge_bweight_offset = CustomData_get_offset(&bm->edata, CD_BWEIGHT);
2245         const int cd_edge_crease_offset  = CustomData_get_offset(&bm->edata, CD_CREASE);
2246         
2247         dm->deformedOnly = 1;
2248         
2249         /* don't add origindex layer if one already exists */
2250         add_orig = !CustomData_has_layer(&bm->pdata, CD_ORIGINDEX);
2251
2252         mask = use_mdisps ? CD_MASK_DERIVEDMESH | CD_MASK_MDISPS : CD_MASK_DERIVEDMESH;
2253         
2254         /* don't process shapekeys, we only feed them through the modifier stack as needed,
2255          * e.g. for applying modifiers or the like*/
2256         mask &= ~CD_MASK_SHAPEKEY;
2257         CustomData_merge(&bm->vdata, &dm->vertData, mask,
2258                          CD_CALLOC, dm->numVertData);
2259         CustomData_merge(&bm->edata, &dm->edgeData, mask,
2260                          CD_CALLOC, dm->numEdgeData);
2261         CustomData_merge(&bm->ldata, &dm->loopData, mask,
2262                          CD_CALLOC, dm->numLoopData);
2263         CustomData_merge(&bm->pdata, &dm->polyData, mask,
2264                          CD_CALLOC, dm->numPolyData);
2265
2266         /* add tessellation mface layers */
2267         if (use_tessface) {
2268                 CustomData_from_bmeshpoly(&dm->faceData, &dm->polyData, &dm->loopData, em_tottri);
2269         }
2270
2271         index = dm->getVertDataArray(dm, CD_ORIGINDEX);
2272
2273         BM_ITER_MESH_INDEX (eve, &iter, bm, BM_VERTS_OF_MESH, i) {
2274                 MVert *mv = &mvert[i];
2275
2276                 copy_v3_v3(mv->co, eve->co);
2277
2278                 BM_elem_index_set(eve, i); /* set_inline */
2279
2280                 normal_float_to_short_v3(mv->no, eve->no);
2281
2282                 mv->flag = BM_vert_flag_to_mflag(eve);
2283
2284                 if (cd_vert_bweight_offset != -1) mv->bweight = BM_ELEM_CD_GET_FLOAT_AS_UCHAR(eve, cd_vert_bweight_offset);
2285
2286                 if (add_orig) *index++ = i;
2287
2288                 CustomData_from_bmesh_block(&bm->vdata, &dm->vertData, eve->head.data, i);
2289         }
2290         bm->elem_index_dirty &= ~BM_VERT;
2291
2292         index = dm->getEdgeDataArray(dm, CD_ORIGINDEX);
2293         BM_ITER_MESH_INDEX (eed, &iter, bm, BM_EDGES_OF_MESH, i) {
2294                 MEdge *med = &medge[i];
2295
2296                 BM_elem_index_set(eed, i); /* set_inline */
2297
2298                 med->v1 = BM_elem_index_get(eed->v1);
2299                 med->v2 = BM_elem_index_get(eed->v2);
2300
2301                 med->flag = BM_edge_flag_to_mflag(eed);
2302
2303                 /* handle this differently to editmode switching,
2304                  * only enable draw for single user edges rather then calculating angle */
2305                 if ((med->flag & ME_EDGEDRAW) == 0) {
2306                         if (eed->l && eed->l == eed->l->radial_next) {
2307                                 med->flag |= ME_EDGEDRAW;
2308                         }
2309                 }
2310
2311                 if (cd_edge_crease_offset  != -1) med->crease  = BM_ELEM_CD_GET_FLOAT_AS_UCHAR(eed, cd_edge_crease_offset);
2312                 if (cd_edge_bweight_offset != -1) med->bweight = BM_ELEM_CD_GET_FLOAT_AS_UCHAR(eed, cd_edge_bweight_offset);
2313
2314                 CustomData_from_bmesh_block(&bm->edata, &dm->edgeData, eed->head.data, i);
2315                 if (add_orig) *index++ = i;
2316         }
2317         bm->elem_index_dirty &= ~BM_EDGE;
2318
2319         /* avoid this where possiblem, takes extra memory */
2320         if (use_tessface) {
2321
2322                 BM_mesh_elem_index_ensure(bm, BM_FACE);
2323
2324                 index = dm->getTessFaceDataArray(dm, CD_ORIGINDEX);
2325                 for (i = 0; i < dm->numTessFaceData; i++) {
2326                         MFace *mf = &mface[i];
2327                         const BMLoop **l = em_looptris[i];
2328                         efa = l[0]->f;
2329
2330                         mf->v1 = BM_elem_index_get(l[0]->v);
2331                         mf->v2 = BM_elem_index_get(l[1]->v);
2332                         mf->v3 = BM_elem_index_get(l[2]->v);
2333                         mf->v4 = 0;
2334                         mf->mat_nr = efa->mat_nr;
2335                         mf->flag = BM_face_flag_to_mflag(efa);
2336
2337                         /* map mfaces to polygons in the same cddm intentionally */
2338                         *index++ = BM_elem_index_get(efa);
2339
2340                         loops_to_customdata_corners(bm, &dm->faceData, i, l, numCol, numTex);
2341                         test_index_face(mf, &dm->faceData, i, 3);
2342                 }
2343         }
2344         
2345         index = CustomData_get_layer(&dm->polyData, CD_ORIGINDEX);
2346         j = 0;
2347         BM_ITER_MESH_INDEX (efa, &iter, bm, BM_FACES_OF_MESH, i) {
2348                 BMLoop *l_iter;
2349                 BMLoop *l_first;
2350                 MPoly *mp = &mpoly[i];
2351
2352                 BM_elem_index_set(efa, i); /* set_inline */
2353
2354                 mp->totloop = efa->len;
2355                 mp->flag = BM_face_flag_to_mflag(efa);
2356                 mp->loopstart = j;
2357                 mp->mat_nr = efa->mat_nr;
2358
2359                 l_iter = l_first = BM_FACE_FIRST_LOOP(efa);
2360                 do {
2361                         mloop->v = BM_elem_index_get(l_iter->v);
2362                         mloop->e = BM_elem_index_get(l_iter->e);
2363                         CustomData_from_bmesh_block(&bm->ldata, &dm->loopData, l_iter->head.data, j);
2364
2365                         BM_elem_index_set(l_iter, j); /* set_inline */
2366
2367                         j++;
2368                         mloop++;
2369                 } while ((l_iter = l_iter->next) != l_first);
2370
2371                 CustomData_from_bmesh_block(&bm->pdata, &dm->polyData, efa->head.data, i);
2372
2373                 if (add_orig) *index++ = i;
2374         }
2375         bm->elem_index_dirty &= ~(BM_FACE | BM_LOOP);
2376
2377         dm->cd_flag = BM_mesh_cd_flag_from_bmesh(bm);
2378
2379         return dm;
2380 }
2381
2382 struct DerivedMesh *CDDM_from_bmesh(struct BMesh *bm, const bool use_mdisps)
2383 {
2384         return cddm_from_bmesh_ex(
2385                 bm, use_mdisps, false,
2386                 /* these vars are for editmesh only */
2387                 0, NULL);
2388 }
2389
2390 DerivedMesh *CDDM_from_editbmesh(BMEditMesh *em, const bool use_mdisps, const bool use_tessface)
2391 {
2392         return cddm_from_bmesh_ex(
2393                 em->bm, use_mdisps,
2394                 /* editmesh */
2395                 use_tessface, em->tottri, (const BMLoop *(*)[3])em->looptris);
2396 }
2397
2398 static DerivedMesh *cddm_copy_ex(DerivedMesh *source,
2399                                  const bool need_tessface_data,
2400                                  const bool faces_from_tessfaces)
2401 {
2402         const bool copy_tessface_data = (faces_from_tessfaces || need_tessface_data);
2403         CDDerivedMesh *cddm = cdDM_create("CDDM_copy cddm");
2404         DerivedMesh *dm = &cddm->dm;
2405         int numVerts = source->numVertData;
2406         int numEdges = source->numEdgeData;
2407         int numTessFaces = copy_tessface_data ? source->numTessFaceData : 0;
2408         int numLoops = source->numLoopData;
2409         int numPolys = source->numPolyData;
2410
2411         /* NOTE: Don't copy tessellation faces if not requested explicitly. */
2412
2413         /* ensure these are created if they are made on demand */
2414         source->getVertDataArray(source, CD_ORIGINDEX);
2415         source->getEdgeDataArray(source, CD_ORIGINDEX);
2416         source->getPolyDataArray(source, CD_ORIGINDEX);
2417         if (copy_tessface_data) {
2418                 source->getTessFaceDataArray(source, CD_ORIGINDEX);
2419         }
2420
2421         /* this initializes dm, and copies all non mvert/medge/mface layers */
2422         DM_from_template(dm, source, DM_TYPE_CDDM, numVerts, numEdges, numTessFaces,
2423                          numLoops, numPolys);
2424         dm->deformedOnly = source->deformedOnly;
2425         dm->cd_flag = source->cd_flag;
2426         dm->dirty = source->dirty;
2427
2428         /* Tessellation data is never copied, so tag it here.
2429          * Only tag dirty layers if we really ignored tessellation faces.
2430          */
2431         if (!copy_tessface_data) {
2432                 dm->dirty |= DM_DIRTY_TESS_CDLAYERS;
2433         }
2434
2435         CustomData_copy_data(&source->vertData, &dm->vertData, 0, 0, numVerts);
2436         CustomData_copy_data(&source->edgeData, &dm->edgeData, 0, 0, numEdges);
2437         if (copy_tessface_data) {
2438                 CustomData_copy_data(&source->faceData, &dm->faceData, 0, 0, numTessFaces);
2439         }
2440
2441         /* now add mvert/medge/mface layers */
2442         cddm->mvert = source->dupVertArray(source);
2443         cddm->medge = source->dupEdgeArray(source);
2444
2445         CustomData_add_layer(&dm->vertData, CD_MVERT, CD_ASSIGN, cddm->mvert, numVerts);
2446         CustomData_add_layer(&dm->edgeData, CD_MEDGE, CD_ASSIGN, cddm->medge, numEdges);
2447
2448         if (faces_from_tessfaces || copy_tessface_data) {
2449                 cddm->mface = source->dupTessFaceArray(source);
2450                 CustomData_add_layer(&dm->faceData, CD_MFACE, CD_ASSIGN, cddm->mface, numTessFaces);
2451         }
2452
2453         if (!faces_from_tessfaces) {
2454                 DM_DupPolys(source, dm);
2455         }
2456         else {
2457                 CDDM_tessfaces_to_faces(dm);
2458         }
2459
2460         cddm->mloop = CustomData_get_layer(&dm->loopData, CD_MLOOP);
2461         cddm->mpoly = CustomData_get_layer(&dm->polyData, CD_MPOLY);
2462
2463         return dm;
2464 }
2465
2466 DerivedMesh *CDDM_copy(DerivedMesh *source)
2467 {
2468         return cddm_copy_ex(source, false, false);
2469 }
2470
2471 DerivedMesh *CDDM_copy_from_tessface(DerivedMesh *source)
2472 {
2473         return cddm_copy_ex(source, false, true);
2474 }
2475
2476 DerivedMesh *CDDM_copy_with_tessface(DerivedMesh *source)
2477 {
2478         return cddm_copy_ex(source, true, false);
2479 }
2480
2481 /* note, the CD_ORIGINDEX layers are all 0, so if there is a direct
2482  * relationship between mesh data this needs to be set by the caller. */
2483 DerivedMesh *CDDM_from_template_ex(
2484         DerivedMesh *source,
2485         int numVerts, int numEdges, int numTessFaces,
2486         int numLoops, int numPolys,
2487         CustomDataMask mask)
2488 {
2489         CDDerivedMesh *cddm = cdDM_create("CDDM_from_template dest");
2490         DerivedMesh *dm = &cddm->dm;
2491
2492         /* ensure these are created if they are made on demand */
2493         source->getVertDataArray(source, CD_ORIGINDEX);
2494         source->getEdgeDataArray(source, CD_ORIGINDEX);
2495         source->getTessFaceDataArray(source, CD_ORIGINDEX);
2496         source->getPolyDataArray(source, CD_ORIGINDEX);
2497
2498         /* this does a copy of all non mvert/medge/mface layers */
2499         DM_from_template_ex(
2500                 dm, source, DM_TYPE_CDDM,
2501                 numVerts, numEdges, numTessFaces,
2502                 numLoops, numPolys,
2503                 mask);
2504
2505         /* now add mvert/medge/mface layers */
2506         CustomData_add_layer(&dm->vertData, CD_MVERT, CD_CALLOC, NULL, numVerts);
2507         CustomData_add_layer(&dm->edgeData, CD_MEDGE, CD_CALLOC, NULL, numEdges);
2508         CustomData_add_layer(&dm->faceData, CD_MFACE, CD_CALLOC, NULL, numTessFaces);
2509         CustomData_add_layer(&dm->loopData, CD_MLOOP, CD_CALLOC, NULL, numLoops);
2510         CustomData_add_layer(&dm->polyData, CD_MPOLY, CD_CALLOC, NULL, numPolys);
2511
2512         if (!CustomData_get_layer(&dm->vertData, CD_ORIGINDEX))
2513                 CustomData_add_layer(&dm->vertData, CD_ORIGINDEX, CD_CALLOC, NULL, numVerts);
2514         if (!CustomData_get_layer(&dm->edgeData, CD_ORIGINDEX))
2515                 CustomData_add_layer(&dm->edgeData, CD_ORIGINDEX, CD_CALLOC, NULL, numEdges);
2516         if (!CustomData_get_layer(&dm->faceData, CD_ORIGINDEX))
2517                 CustomData_add_layer(&dm->faceData, CD_ORIGINDEX, CD_CALLOC, NULL, numTessFaces);
2518
2519         cddm->mvert = CustomData_get_layer(&dm->vertData, CD_MVERT);
2520         cddm->medge = CustomData_get_layer(&dm->edgeData, CD_MEDGE);
2521         cddm->mface = CustomData_get_layer(&dm->faceData, CD_MFACE);
2522         cddm->mloop = CustomData_get_layer(&dm->loopData, CD_MLOOP);
2523         cddm->mpoly = CustomData_get_layer(&dm->polyData, CD_MPOLY);
2524
2525         return dm;
2526 }
2527 DerivedMesh *CDDM_from_template(
2528         DerivedMesh *source,
2529         int numVerts, int numEdges, int numTessFaces,
2530         int numLoops, int numPolys)
2531 {
2532         return CDDM_from_template_ex(
2533                 source, numVerts, numEdges, numTessFaces,
2534                 numLoops, numPolys,
2535                 CD_MASK_DERIVEDMESH);
2536 }
2537
2538 void CDDM_apply_vert_coords(DerivedMesh *dm, float (*vertCoords)[3])
2539 {
2540         CDDerivedMesh *cddm = (CDDerivedMesh *)dm;
2541         MVert *vert;
2542         int i;
2543
2544         /* this will just return the pointer if it wasn't a referenced layer */
2545         vert = CustomData_duplicate_referenced_layer(&dm->vertData, CD_MVERT, dm->numVertData);
2546         cddm->mvert = vert;
2547
2548         for (i = 0; i < dm->numVertData; ++i, ++vert)
2549                 copy_v3_v3(vert->co, vertCoords[i]);
2550
2551         cddm->dm.dirty |= DM_DIRTY_NORMALS;
2552 }
2553
2554 void CDDM_apply_vert_normals(DerivedMesh *dm, short (*vertNormals)[3])
2555 {
2556         CDDerivedMesh *cddm = (CDDerivedMesh *)dm;
2557         MVert *vert;
2558         int i;
2559
2560         /* this will just return the pointer if it wasn't a referenced layer */
2561         vert = CustomData_duplicate_referenced_layer(&dm->vertData, CD_MVERT, dm->numVertData);
2562         cddm->mvert = vert;
2563
2564         for (i = 0; i < dm->numVertData; ++i, ++vert)
2565                 copy_v3_v3_short(vert->no, vertNormals[i]);
2566
2567         cddm->dm.dirty &= ~DM_DIRTY_NORMALS;
2568 }
2569
2570 void CDDM_calc_normals_mapping_ex(DerivedMesh *dm, const bool only_face_normals)
2571 {
2572         CDDerivedMesh *cddm = (CDDerivedMesh *)dm;
2573         float (*face_nors)[3] = NULL;
2574
2575         if (dm->numVertData == 0) {
2576                 cddm->dm.dirty &= ~DM_DIRTY_NORMALS;
2577                 return;
2578         }
2579
2580         /* now we skip calculating vertex normals for referenced layer,
2581          * no need to duplicate verts.
2582          * WATCH THIS, bmesh only change!,
2583          * need to take care of the side effects here - campbell */
2584 #if 0
2585         /* we don't want to overwrite any referenced layers */
2586         cddm->mvert = CustomData_duplicate_referenced_layer(&dm->vertData, CD_MVERT, dm->numVertData);
2587 #endif
2588
2589 #if 0
2590         if (dm->numTessFaceData == 0) {
2591                 /* No tessellation on this mesh yet, need to calculate one.
2592                  *
2593                  * Important not to update face normals from polys since it
2594                  * interferes with assigning the new normal layer in the following code.
2595                  */
2596                 CDDM_recalc_tessellation_ex(dm, false);
2597         }
2598         else {
2599                 /* A tessellation already exists, it should always have a CD_ORIGINDEX */
2600                 BLI_assert(CustomData_has_layer(&dm->faceData, CD_ORIGINDEX));
2601                 CustomData_free_layers(&dm->faceData, CD_NORMAL, dm->numTessFaceData);
2602         }
2603 #endif
2604
2605         face_nors = MEM_mallocN(sizeof(*face_nors) * dm->numPolyData, "face_nors");
2606
2607         /* calculate face normals */
2608         BKE_mesh_calc_normals_poly(
2609                 cddm->mvert, NULL, dm->numVertData, CDDM_get_loops(dm), CDDM_get_polys(dm),
2610                 dm->numLoopData, dm->numPolyData, face_nors,
2611                 only_face_normals);
2612
2613         CustomData_add_layer(&dm->polyData, CD_NORMAL, CD_ASSIGN, face_nors, dm->numPolyData);
2614
2615         cddm->dm.dirty &= ~DM_DIRTY_NORMALS;
2616 }
2617
2618 void CDDM_calc_normals_mapping(DerivedMesh *dm)
2619 {
2620         /* use this to skip calculating normals on original vert's, this may need to be changed */
2621         const bool only_face_normals = CustomData_is_referenced_layer(&dm->vertData, CD_MVERT);
2622
2623         CDDM_calc_normals_mapping_ex(dm, only_face_normals);
2624 }
2625
2626 #if 0
2627 /* bmesh note: this matches what we have in trunk */
2628 void CDDM_calc_normals(DerivedMesh *dm)
2629 {
2630         CDDerivedMesh *cddm = (CDDerivedMesh *)dm;
2631         float (*poly_nors)[3];
2632
2633         if (dm->numVertData == 0) return;
2634
2635         /* we don't want to overwrite any referenced layers */
2636         cddm->mvert = CustomData_duplicate_referenced_layer(&dm->vertData, CD_MVERT, dm->numVertData);
2637
2638         /* fill in if it exists */
2639         poly_nors = CustomData_get_layer(&dm->polyData, CD_NORMAL);
2640         if (!poly_nors) {
2641                 poly_nors = CustomData_add_layer(&dm->polyData, CD_NORMAL, CD_CALLOC, NULL, dm->numPolyData);
2642         }
2643
2644         BKE_mesh_calc_normals_poly(cddm->mvert, dm->numVertData, CDDM_get_loops(dm), CDDM_get_polys(dm),
2645                                        dm->numLoopData, dm->numPolyData, poly_nors, false);
2646
2647         cddm->dm.dirty &= ~DM_DIRTY_NORMALS;
2648 }
2649 #else
2650
2651 /* poly normal layer is now only for final display */
2652 void CDDM_calc_normals(DerivedMesh *dm)
2653 {
2654         CDDerivedMesh *cddm = (CDDerivedMesh *)dm;
2655
2656         /* we don't want to overwrite any referenced layers */
2657         cddm->mvert = CustomData_duplicate_referenced_layer(&dm->vertData, CD_MVERT, dm->numVertData);
2658
2659         BKE_mesh_calc_normals_poly(cddm->mvert, NULL, dm->numVertData, CDDM_get_loops(dm), CDDM_get_polys(dm),
2660                                    dm->numLoopData, dm->numPolyData, NULL, false);
2661
2662         cddm->dm.dirty &= ~DM_DIRTY_NORMALS;
2663 }
2664
2665 #endif
2666
2667 void CDDM_calc_loop_normals(DerivedMesh *dm, const bool use_split_normals, const float split_angle)
2668 {
2669         CDDM_calc_loop_normals_spacearr(dm, use_split_normals, split_angle, NULL);
2670 }
2671
2672 /* #define DEBUG_CLNORS */
2673 #ifdef DEBUG_CLNORS
2674 #  include "BLI_linklist.h"
2675 #endif
2676
2677 void CDDM_calc_loop_normals_spacearr(
2678         DerivedMesh *dm, const bool use_split_normals, const float split_angle, MLoopNorSpaceArray *r_lnors_spacearr)
2679 {
2680         MVert *mverts = dm->getVertArray(dm);
2681         MEdge *medges = dm->getEdgeArray(dm);
2682         MLoop *mloops = dm->getLoopArray(dm);
2683         MPoly *mpolys = dm->getPolyArray(dm);
2684
2685         CustomData *ldata, *pdata;
2686
2687         float (*lnors)[3];
2688         short (*clnor_data)[2];
2689         float (*pnors)[3];
2690
2691         const int numVerts = dm->getNumVerts(dm);
2692         const int numEdges = dm->getNumEdges(dm);
2693         const int numLoops = dm->getNumLoops(dm);
2694         const int numPolys = dm->getNumPolys(dm);
2695
2696         ldata = dm->getLoopDataLayout(dm);
2697         if (CustomData_has_layer(ldata, CD_NORMAL)) {
2698                 lnors = CustomData_get_layer(ldata, CD_NORMAL);
2699         }
2700         else {
2701                 lnors = CustomData_add_layer(ldata, CD_NORMAL, CD_CALLOC, NULL, numLoops);
2702         }
2703
2704         /* Compute poly (always needed) and vert normals. */
2705         /* Note we can't use DM_ensure_normals, since it won't keep computed poly nors... */
2706         pdata = dm->getPolyDataLayout(dm);
2707         pnors = CustomData_get_layer(pdata, CD_NORMAL);
2708         if (!pnors) {
2709                 pnors = CustomData_add_layer(pdata, CD_NORMAL, CD_CALLOC, NULL, numPolys);
2710         }
2711         BKE_mesh_calc_normals_poly(mverts, NULL, numVerts, mloops, mpolys, numLoops, numPolys, pnors,
2712                                    (dm->dirty & DM_DIRTY_NORMALS) ? false : true);
2713
2714         dm->dirty &= ~DM_DIRTY_NORMALS;
2715
2716         clnor_data = CustomData_get_layer(ldata, CD_CUSTOMLOOPNORMAL);
2717
2718         BKE_mesh_normals_loop_split(mverts, numVerts, medges, numEdges, mloops, lnors, numLoops,
2719                                     mpolys, (const float (*)[3])pnors, numPolys,
2720                                     use_split_normals, split_angle,
2721                                     r_lnors_spacearr, clnor_data, NULL);
2722 #ifdef DEBUG_CLNORS
2723         if (r_lnors_spacearr) {
2724                 int i;
2725                 for (i = 0; i < numLoops; i++) {
2726                         if (r_lnors_spacearr->lspacearr[i]->ref_alpha != 0.0f) {
2727                                 LinkNode *loops = r_lnors_spacearr->lspacearr[i]->loops;
2728                                 printf("Loop %d uses lnor space %p:\n", i, r_lnors_spacearr->lspacearr[i]);
2729                                 print_v3("\tfinal lnor", lnors[i]);
2730                                 print_v3("\tauto lnor", r_lnors_spacearr->lspacearr[i]->vec_lnor);
2731                                 print_v3("\tref_vec", r_lnors_spacearr->lspacearr[i]->vec_ref);
2732                                 printf("\talpha: %f\n\tbeta: %f\n\tloops: %p\n", r_lnors_spacearr->lspacearr[i]->ref_alpha,
2733                                        r_lnors_spacearr->lspacearr[i]->ref_beta, r_lnors_spacearr->lspacearr[i]->loops);
2734                                 printf("\t\t(shared with loops");
2735                                 while (loops) {
2736                                         printf(" %d", GET_INT_FROM_POINTER(loops->link));
2737                                         loops = loops->next;
2738                                 }
2739                                 printf(")\n");
2740                         }
2741                         else {
2742                                 printf("Loop %d has no lnor space\n", i);
2743                         }
2744                 }
2745         }
2746 #endif
2747 }
2748
2749
2750 void CDDM_calc_normals_tessface(DerivedMesh *dm)
2751 {
2752         CDDerivedMesh *cddm = (CDDerivedMesh *)dm;
2753         float (*face_nors)[3];
2754
2755         if (dm->numVertData == 0) return;
2756
2757         /* we don't want to overwrite any referenced layers */
2758         cddm->mvert = CustomData_duplicate_referenced_layer(&dm->vertData, CD_MVERT, dm->numVertData);
2759
2760         /* fill in if it exists */
2761         face_nors = CustomData_get_layer(&dm->faceData, CD_NORMAL);
2762         if (!face_nors) {
2763                 face_nors = CustomData_add_layer(&dm->faceData, CD_NORMAL, CD_CALLOC, NULL, dm->numTessFaceData);
2764         }
2765
2766         BKE_mesh_calc_normals_tessface(cddm->mvert, dm->numVertData,
2767                                        cddm->mface, dm->numTessFaceData, face_nors);
2768
2769         cddm->dm.dirty &= ~DM_DIRTY_NORMALS;
2770 }
2771
2772 #if 1
2773
2774 /**
2775  * Poly compare with vtargetmap
2776  * Function used by #CDDM_merge_verts.
2777  * The function compares poly_source after applying vtargetmap, with poly_target.
2778  * The two polys are identical if they share the same vertices in the same order, or in reverse order,
2779  * but starting position loopstart may be different.
2780  * The function is called with direct_reverse=1 for same order (i.e. same normal),
2781  * and may be called again with direct_reverse=-1 for reverse order.
2782  * \return 1 if polys are identical,  0 if polys are different.
2783  */
2784 static int cddm_poly_compare(
2785         MLoop *mloop_array,
2786         MPoly *mpoly_source, MPoly *mpoly_target,
2787         const int *vtargetmap, const int direct_reverse)
2788 {
2789         int vert_source, first_vert_source, vert_target;
2790         int i_loop_source;
2791         int i_loop_target, i_loop_target_start, i_loop_target_offset, i_loop_target_adjusted;
2792         bool compare_completed = false;
2793         bool same_loops = false;
2794
2795         MLoop *mloop_source, *mloop_target;
2796
2797         BLI_assert(direct_reverse == 1 || direct_reverse == -1);
2798
2799         i_loop_source = 0;
2800         mloop_source = mloop_array + mpoly_source->loopstart;
2801         vert_source = mloop_source->v;
2802
2803         if (vtargetmap[vert_source] != -1) {
2804                 vert_source = vtargetmap[vert_source];
2805         }
2806         else {
2807                 /* All source loop vertices should be mapped */
2808                 BLI_assert(false);
2809         }
2810
2811         /* Find same vertex within mpoly_target's loops */
2812         mloop_target = mloop_array + mpoly_target->loopstart;
2813         for (i_loop_target = 0; i_loop_target < mpoly_target->totloop; i_loop_target++, mloop_target++) {
2814                 if (mloop_target->v == vert_source) {
2815                         break;
2816                 }
2817         }
2818
2819         /* If same vertex not found, then polys cannot be equal */
2820         if (i_loop_target >= mpoly_target->totloop) {
2821                 return false;
2822         }
2823
2824         /* Now mloop_source and m_loop_target have one identical vertex */
2825         /* mloop_source is at position 0, while m_loop_target has advanced to find identical vertex */
2826         /* Go around the loop and check that all vertices match in same order */
2827         /* Skipping source loops when consecutive source vertices are mapped to same target vertex */
2828
2829         i_loop_target_start = i_loop_target;
2830         i_loop_target_offset = 0;
2831         first_vert_source = vert_source;
2832
2833         compare_completed = false;
2834         same_loops = false;
2835
2836         while (!compare_completed) {
2837
2838                 vert_target = mloop_target->v;
2839
2840                 /* First advance i_loop_source, until it points to different vertex, after mapping applied */
2841                 do {
2842                         i_loop_source++;
2843
2844                         if (i_loop_source == mpoly_source->totloop) {
2845                                 /* End of loops for source, must match end of loop for target.  */
2846                                 if (i_loop_target_offset == mpoly_target->totloop - 1) {
2847                                         compare_completed = true;
2848                                         same_loops = true;
2849                                         break;  /* Polys are identical */
2850                                 }
2851                                 else {
2852                                         compare_completed = true;
2853                                         same_loops = false;
2854                                         break;  /* Polys are different */
2855                                 }
2856                         }
2857
2858                         mloop_source++;
2859                         vert_source = mloop_source->v;
2860
2861                         if (vtargetmap[vert_source] != -1) {
2862                                 vert_source = vtargetmap[vert_source];
2863                         }
2864                         else {
2865                                 /* All source loop vertices should be mapped */
2866                                 BLI_assert(false);
2867                         }
2868
2869                 } while (vert_source == vert_target);
2870
2871                 if (compare_completed) {
2872                         break;
2873                 }
2874
2875                 /* Now advance i_loop_target as well */
2876                 i_loop_target_offset++;
2877
2878                 if (i_loop_target_offset == mpoly_target->totloop) {
2879                         /* End of loops for target only, that means no match */
2880                         /* except if all remaining source vertices are mapped to first target */
2881                         for (; i_loop_source < mpoly_source->totloop; i_loop_source++, mloop_source++) {
2882                                 vert_source = vtargetmap[mloop_source->v];
2883                                 if (vert_source != first_vert_source) {
2884                                         compare_completed = true;
2885                                         same_loops = false;
2886                                         break;
2887                                 }
2888                         }
2889                         if (!compare_completed) {
2890                                 same_loops = true;
2891                         }
2892                         break;
2893                 }
2894
2895                 /* Adjust i_loop_target for cycling around and for direct/reverse order defined by delta = +1 or -1 */
2896                 i_loop_target_adjusted = (i_loop_target_start + direct_reverse * i_loop_target_offset) % mpoly_target->totloop;
2897                 if (i_loop_target_adjusted < 0) {
2898                         i_loop_target_adjusted += mpoly_target->totloop;
2899                 }
2900                 mloop_target = mloop_array + mpoly_target->loopstart + i_loop_target_adjusted;
2901                 vert_target = mloop_target->v;
2902
2903                 if (vert_target != vert_source) {
2904                         same_loops = false;  /* Polys are different */
2905                         break;
2906                 }
2907         }
2908         return same_loops;
2909 }
2910
2911 /* Utility stuff for using GHash with polys */
2912
2913 typedef struct PolyKey {
2914         int poly_index;   /* index of the MPoly within the derived mesh */
2915         int totloops;     /* number of loops in the poly */
2916         unsigned int hash_sum;  /* Sum of all vertices indices */
2917         unsigned int hash_xor;  /* Xor of all vertices indices */
2918 } PolyKey;
2919
2920
2921 static unsigned int poly_gset_hash_fn(const void *key)
2922 {
2923         const PolyKey *pk = key;
2924         return pk->hash_sum;
2925 }
2926
2927 static bool poly_gset_compare_fn(const void *k1, const void *k2)
2928 {
2929         const PolyKey *pk1 = k1;
2930         const PolyKey *pk2 = k2;
2931         if ((pk1->hash_sum == pk2->hash_sum) &&
2932             (pk1->hash_xor == pk2->hash_xor) &&
2933             (pk1->totloops == pk2->totloops))
2934         {
2935                 /* Equality - note that this does not mean equality of polys */
2936                 return false;
2937         }
2938         else {
2939                 return true;
2940         }
2941 }
2942
2943 /**
2944  * Merge Verts
2945  *
2946  * This frees dm, and returns a new one.
2947  *
2948  * \param vtargetmap  The table that maps vertices to target vertices.  a value of -1
2949  * indicates a vertex is a target, and is to be kept.
2950  * This array is aligned with 'dm->numVertData'
2951  * \warning \a vtergatmap must **not** contain any chained mapping (v1 -> v2 -> v3 etc.), this is not supported
2952  * and will likely generate corrupted geometry.
2953  *
2954  * \param tot_vtargetmap  The number of non '-1' values in vtargetmap. (not the size)
2955  *
2956  * \param merge_mode enum with two modes.
2957  * - #CDDM_MERGE_VERTS_DUMP_IF_MAPPED
2958  * When called by the Mirror Modifier,
2959  * In this mode it skips any faces that have all vertices merged (to avoid creating pairs
2960  * of faces sharing the same set of vertices)
2961  * - #CDDM_MERGE_VERTS_DUMP_IF_EQUAL
2962  * When called by the Array Modifier,
2963  * In this mode, faces where all vertices are merged are double-checked,
2964  * to see whether all target vertices actually make up a poly already.
2965  * Indeed it could be that all of a poly's vertices are merged,
2966  * but merged to vertices that do not make up a single poly,
2967  * in which case the original poly should not be dumped.
2968  * Actually this later behavior could apply to the Mirror Modifier as well, but the additional checks are
2969  * costly and not necessary in the case of mirror, because each vertex is only merged to its own mirror.
2970  *
2971  * \note #CDDM_recalc_tessellation has to run on the returned DM if you want to access tessfaces.
2972  */
2973 DerivedMesh *CDDM_merge_verts(DerivedMesh *dm, const int *vtargetmap, const int tot_vtargetmap, const int merge_mode)
2974 {
2975 // #define USE_LOOPS
2976         CDDerivedMesh *cddm = (CDDerivedMesh *)dm;
2977         CDDerivedMesh *cddm2 = NULL;
2978
2979         const int totvert = dm->numVertData;
2980         const int totedge = dm->numEdgeData;
2981         const int totloop = dm->numLoopData;
2982         const int totpoly = dm->numPolyData;
2983
2984         const int totvert_final = totvert - tot_vtargetmap;
2985
2986         MVert *mv, *mvert = MEM_mallocN(sizeof(*mvert) * totvert_final, __func__);
2987         int *oldv         = MEM_mallocN(sizeof(*oldv)  * totvert_final, __func__);
2988         int *newv         = MEM_mallocN(sizeof(*newv)  * totvert, __func__);
2989         STACK_DECLARE(mvert);
2990         STACK_DECLARE(oldv);
2991
2992         /* Note: create (totedge + totloop) elements because partially invalid polys due to merge may require
2993          * generating new edges, and while in 99% cases we'll still end with less final edges than totedge,
2994          * cases can be forged that would end requiring more... */
2995         MEdge *med, *medge = MEM_mallocN(sizeof(*medge) * (totedge + totloop), __func__);
2996         int *olde          = MEM_mallocN(sizeof(*olde)  * (totedge + totloop), __func__);
2997         int *newe          = MEM_mallocN(sizeof(*newe)  * (totedge + totloop), __func__);
2998         STACK_DECLARE(medge);
2999         STACK_DECLARE(olde);
3000
3001         MLoop *ml, *mloop = MEM_mallocN(sizeof(*mloop) * totloop, __func__);
3002         int *oldl         = MEM_mallocN(sizeof(*oldl)  * totloop, __func__);
3003 #ifdef USE_LOOPS
3004         int newl          = MEM_mallocN(sizeof(*newl)  * totloop, __func__);
3005 #endif
3006         STACK_DECLARE(mloop);
3007         STACK_DECLARE(oldl);
3008
3009         MPoly *mp, *mpoly = MEM_mallocN(sizeof(*medge) * totpoly, __func__);
3010         int *oldp         = MEM_mallocN(sizeof(*oldp)  * totpoly, __func__);
3011         STACK_DECLARE(mpoly);
3012         STACK_DECLARE(oldp);
3013
3014         EdgeHash *ehash = BLI_edgehash_new_ex(__func__, totedge);
3015
3016         int i, j, c;
3017
3018         PolyKey *poly_keys;
3019         GSet *poly_gset = NULL;
3020
3021         STACK_INIT(oldv, totvert_final);
3022         STACK_INIT(olde, totedge);
3023         STACK_INIT(oldl, totloop);
3024         STACK_INIT(oldp, totpoly);
3025
3026         STACK_INIT(mvert, totvert_final);
3027         STACK_INIT(medge, totedge);
3028         STACK_INIT(mloop, totloop);
3029         STACK_INIT(mpoly, totpoly);
3030
3031         /* fill newv with destination vertex indices */
3032         mv = cddm->mvert;
3033         c = 0;
3034         for (i = 0; i < totvert; i++, mv++) {
3035                 if (vtargetmap[i] == -1) {
3036                         STACK_PUSH(oldv, i);
3037                         STACK_PUSH(mvert, *mv);
3038                         newv[i] = c++;
3039                 }
3040                 else {
3041                         /* dummy value */
3042                         newv[i] = 0;
3043                 }
3044         }
3045         
3046         /* now link target vertices to destination indices */
3047         for (i = 0; i < totvert; i++) {
3048                 if (vtargetmap[i] != -1) {
3049                         newv[i] = newv[vtargetmap[i]];
3050                 }
3051         }
3052
3053         /* Don't remap vertices in cddm->mloop, because we need to know the original
3054          * indices in order to skip faces with all vertices merged.
3055          * The "update loop indices..." section further down remaps vertices in mloop.
3056          */
3057
3058         /* now go through and fix edges and faces */
3059         med = cddm->medge;
3060         c = 0;
3061         for (i = 0; i < totedge; i++, med++) {
3062                 const unsigned int v1 = (vtargetmap[med->v1] != -1) ? vtargetmap[med->v1] : med->v1;
3063                 const unsigned int v2 = (vtargetmap[med->v2] != -1) ? vtargetmap[med->v2] : med->v2;
3064                 if (LIKELY(v1 != v2)) {
3065                         void **val_p;
3066
3067                         if (BLI_edgehash_ensure_p(ehash, v1, v2, &val_p)) {
3068                                 newe[i] = GET_INT_FROM_POINTER(*val_p);
3069                         }
3070                         else {
3071                                 STACK_PUSH(olde, i);
3072                                 STACK_PUSH(medge, *med);
3073                                 newe[i] = c;
3074                                 *val_p = SET_INT_IN_POINTER(c);
3075                                 c++;
3076                         }
3077                 }
3078                 else {
3079                         newe[i] = -1;
3080                 }
3081         }
3082         
3083         if (merge_mode == CDDM_MERGE_VERTS_DUMP_IF_EQUAL) {
3084                 /* In this mode, we need to determine,  whenever a poly' vertices are all mapped */
3085                 /* if the targets already make up a poly, in which case the new poly is dropped */
3086                 /* This poly equality check is rather complex.   We use a BLI_ghash to speed it up with a first level check */
3087                 PolyKey *mpgh;
3088                 poly_keys = MEM_mallocN(sizeof(PolyKey) * totpoly, __func__);
3089                 poly_gset = BLI_gset_new_ex(poly_gset_hash_fn, poly_gset_compare_fn, __func__, totpoly);
3090                 /* Duplicates allowed because our compare function is not pure equality */
3091                 BLI_gset_flag_set(poly_gset, GHASH_FLAG_ALLOW_DUPES);
3092
3093                 mp = cddm->mpoly;
3094                 mpgh = poly_keys;
3095                 for (i = 0; i < totpoly; i++, mp++, mpgh++)&nb