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