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