Cleanup: fixes for building with recent clang
[blender.git] / source / blender / blenkernel / intern / DerivedMesh.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) 2005 Blender Foundation.
19  * All rights reserved.
20  *
21  * The Original Code is: all of this file.
22  *
23  * Contributor(s): none yet.
24  *
25  * ***** END GPL LICENSE BLOCK *****
26  */
27
28 /** \file blender/blenkernel/intern/DerivedMesh.c
29  *  \ingroup bke
30  */
31
32
33 #include <string.h>
34 #include <limits.h>
35
36 #include "MEM_guardedalloc.h"
37
38 #include "DNA_cloth_types.h"
39 #include "DNA_key_types.h"
40 #include "DNA_material_types.h"
41 #include "DNA_mesh_types.h"
42 #include "DNA_meshdata_types.h"
43 #include "DNA_object_types.h"
44 #include "DNA_scene_types.h"
45
46 #include "BLI_blenlib.h"
47 #include "BLI_bitmap.h"
48 #include "BLI_math.h"
49 #include "BLI_utildefines.h"
50 #include "BLI_linklist.h"
51
52 #include "BKE_cdderivedmesh.h"
53 #include "BKE_editmesh.h"
54 #include "BKE_key.h"
55 #include "BKE_material.h"
56 #include "BKE_modifier.h"
57 #include "BKE_mesh.h"
58 #include "BKE_mesh_mapping.h"
59 #include "BKE_object.h"
60 #include "BKE_object_deform.h"
61 #include "BKE_paint.h"
62 #include "BKE_texture.h"
63 #include "BKE_multires.h"
64 #include "BKE_bvhutils.h"
65 #include "BKE_deform.h"
66 #include "BKE_global.h" /* For debug flag, DM_update_tessface_data() func. */
67
68 #ifdef WITH_GAMEENGINE
69 #include "BKE_navmesh_conversion.h"
70 static DerivedMesh *navmesh_dm_createNavMeshForVisualization(DerivedMesh *dm);
71 #endif
72
73 #include "BLI_sys_types.h" /* for intptr_t support */
74
75 #include "GPU_buffers.h"
76 #include "GPU_extensions.h"
77 #include "GPU_glew.h"
78
79 /* very slow! enable for testing only! */
80 //#define USE_MODIFIER_VALIDATE
81
82 #ifdef USE_MODIFIER_VALIDATE
83 #  define ASSERT_IS_VALID_DM(dm) (BLI_assert((dm == NULL) || (DM_is_valid(dm) == true)))
84 #else
85 #  define ASSERT_IS_VALID_DM(dm)
86 #endif
87
88 static void add_shapekey_layers(DerivedMesh *dm, Mesh *me, Object *ob);
89 static void shapekey_layers_to_keyblocks(DerivedMesh *dm, Mesh *me, int actshape_uid);
90
91
92 /* -------------------------------------------------------------------- */
93
94 static MVert *dm_getVertArray(DerivedMesh *dm)
95 {
96         MVert *mvert = CustomData_get_layer(&dm->vertData, CD_MVERT);
97
98         if (!mvert) {
99                 mvert = CustomData_add_layer(&dm->vertData, CD_MVERT, CD_CALLOC, NULL,
100                                              dm->getNumVerts(dm));
101                 CustomData_set_layer_flag(&dm->vertData, CD_MVERT, CD_FLAG_TEMPORARY);
102                 dm->copyVertArray(dm, mvert);
103         }
104
105         return mvert;
106 }
107
108 static MEdge *dm_getEdgeArray(DerivedMesh *dm)
109 {
110         MEdge *medge = CustomData_get_layer(&dm->edgeData, CD_MEDGE);
111
112         if (!medge) {
113                 medge = CustomData_add_layer(&dm->edgeData, CD_MEDGE, CD_CALLOC, NULL,
114                                              dm->getNumEdges(dm));
115                 CustomData_set_layer_flag(&dm->edgeData, CD_MEDGE, CD_FLAG_TEMPORARY);
116                 dm->copyEdgeArray(dm, medge);
117         }
118
119         return medge;
120 }
121
122 static MFace *dm_getTessFaceArray(DerivedMesh *dm)
123 {
124         MFace *mface = CustomData_get_layer(&dm->faceData, CD_MFACE);
125
126         if (!mface) {
127                 int numTessFaces = dm->getNumTessFaces(dm);
128                 
129                 if (!numTessFaces) {
130                         /* Do not add layer if there's no elements in it, this leads to issues later when
131                          * this layer is needed with non-zero size, but currently CD stuff does not check
132                          * for requested layer size on creation and just returns layer which was previously
133                          * added (sergey) */
134                         return NULL;
135                 }
136                 
137                 mface = CustomData_add_layer(&dm->faceData, CD_MFACE, CD_CALLOC, NULL, numTessFaces);
138                 CustomData_set_layer_flag(&dm->faceData, CD_MFACE, CD_FLAG_TEMPORARY);
139                 dm->copyTessFaceArray(dm, mface);
140         }
141
142         return mface;
143 }
144
145 static MLoop *dm_getLoopArray(DerivedMesh *dm)
146 {
147         MLoop *mloop = CustomData_get_layer(&dm->loopData, CD_MLOOP);
148
149         if (!mloop) {
150                 mloop = CustomData_add_layer(&dm->loopData, CD_MLOOP, CD_CALLOC, NULL,
151                                              dm->getNumLoops(dm));
152                 CustomData_set_layer_flag(&dm->loopData, CD_MLOOP, CD_FLAG_TEMPORARY);
153                 dm->copyLoopArray(dm, mloop);
154         }
155
156         return mloop;
157 }
158
159 static MPoly *dm_getPolyArray(DerivedMesh *dm)
160 {
161         MPoly *mpoly = CustomData_get_layer(&dm->polyData, CD_MPOLY);
162
163         if (!mpoly) {
164                 mpoly = CustomData_add_layer(&dm->polyData, CD_MPOLY, CD_CALLOC, NULL,
165                                              dm->getNumPolys(dm));
166                 CustomData_set_layer_flag(&dm->polyData, CD_MPOLY, CD_FLAG_TEMPORARY);
167                 dm->copyPolyArray(dm, mpoly);
168         }
169
170         return mpoly;
171 }
172
173 static MVert *dm_dupVertArray(DerivedMesh *dm)
174 {
175         MVert *tmp = MEM_mallocN(sizeof(*tmp) * dm->getNumVerts(dm),
176                                  "dm_dupVertArray tmp");
177
178         if (tmp) dm->copyVertArray(dm, tmp);
179
180         return tmp;
181 }
182
183 static MEdge *dm_dupEdgeArray(DerivedMesh *dm)
184 {
185         MEdge *tmp = MEM_mallocN(sizeof(*tmp) * dm->getNumEdges(dm),
186                                  "dm_dupEdgeArray tmp");
187
188         if (tmp) dm->copyEdgeArray(dm, tmp);
189
190         return tmp;
191 }
192
193 static MFace *dm_dupFaceArray(DerivedMesh *dm)
194 {
195         MFace *tmp = MEM_mallocN(sizeof(*tmp) * dm->getNumTessFaces(dm),
196                                  "dm_dupFaceArray tmp");
197
198         if (tmp) dm->copyTessFaceArray(dm, tmp);
199
200         return tmp;
201 }
202
203 static MLoop *dm_dupLoopArray(DerivedMesh *dm)
204 {
205         MLoop *tmp = MEM_mallocN(sizeof(*tmp) * dm->getNumLoops(dm),
206                                  "dm_dupLoopArray tmp");
207
208         if (tmp) dm->copyLoopArray(dm, tmp);
209
210         return tmp;
211 }
212
213 static MPoly *dm_dupPolyArray(DerivedMesh *dm)
214 {
215         MPoly *tmp = MEM_mallocN(sizeof(*tmp) * dm->getNumPolys(dm),
216                                  "dm_dupPolyArray tmp");
217
218         if (tmp) dm->copyPolyArray(dm, tmp);
219
220         return tmp;
221 }
222
223 static CustomData *dm_getVertCData(DerivedMesh *dm)
224 {
225         return &dm->vertData;
226 }
227
228 static CustomData *dm_getEdgeCData(DerivedMesh *dm)
229 {
230         return &dm->edgeData;
231 }
232
233 static CustomData *dm_getTessFaceCData(DerivedMesh *dm)
234 {
235         return &dm->faceData;
236 }
237
238 static CustomData *dm_getLoopCData(DerivedMesh *dm)
239 {
240         return &dm->loopData;
241 }
242
243 static CustomData *dm_getPolyCData(DerivedMesh *dm)
244 {
245         return &dm->polyData;
246 }
247
248 void DM_init_funcs(DerivedMesh *dm)
249 {
250         /* default function implementations */
251         dm->getVertArray = dm_getVertArray;
252         dm->getEdgeArray = dm_getEdgeArray;
253         dm->getTessFaceArray = dm_getTessFaceArray;
254         dm->getLoopArray = dm_getLoopArray;
255         dm->getPolyArray = dm_getPolyArray;
256         dm->dupVertArray = dm_dupVertArray;
257         dm->dupEdgeArray = dm_dupEdgeArray;
258         dm->dupTessFaceArray = dm_dupFaceArray;
259         dm->dupLoopArray = dm_dupLoopArray;
260         dm->dupPolyArray = dm_dupPolyArray;
261
262         dm->getVertDataLayout = dm_getVertCData;
263         dm->getEdgeDataLayout = dm_getEdgeCData;
264         dm->getTessFaceDataLayout = dm_getTessFaceCData;
265         dm->getLoopDataLayout = dm_getLoopCData;
266         dm->getPolyDataLayout = dm_getPolyCData;
267
268         dm->getVertData = DM_get_vert_data;
269         dm->getEdgeData = DM_get_edge_data;
270         dm->getTessFaceData = DM_get_tessface_data;
271         dm->getPolyData = DM_get_poly_data;
272         dm->getVertDataArray = DM_get_vert_data_layer;
273         dm->getEdgeDataArray = DM_get_edge_data_layer;
274         dm->getTessFaceDataArray = DM_get_tessface_data_layer;
275         dm->getPolyDataArray = DM_get_poly_data_layer;
276         dm->getLoopDataArray = DM_get_loop_data_layer;
277
278         bvhcache_init(&dm->bvhCache);
279 }
280
281 void DM_init(DerivedMesh *dm, DerivedMeshType type, int numVerts, int numEdges,
282              int numTessFaces, int numLoops, int numPolys)
283 {
284         dm->type = type;
285         dm->numVertData = numVerts;
286         dm->numEdgeData = numEdges;
287         dm->numTessFaceData = numTessFaces;
288         dm->numLoopData = numLoops;
289         dm->numPolyData = numPolys;
290
291         DM_init_funcs(dm);
292         
293         dm->needsFree = 1;
294         dm->auto_bump_scale = -1.0f;
295         dm->dirty = 0;
296
297         /* don't use CustomData_reset(...); because we dont want to touch customdata */
298         fill_vn_i(dm->vertData.typemap, CD_NUMTYPES, -1);
299         fill_vn_i(dm->edgeData.typemap, CD_NUMTYPES, -1);
300         fill_vn_i(dm->faceData.typemap, CD_NUMTYPES, -1);
301         fill_vn_i(dm->loopData.typemap, CD_NUMTYPES, -1);
302         fill_vn_i(dm->polyData.typemap, CD_NUMTYPES, -1);
303 }
304
305 void DM_from_template(DerivedMesh *dm, DerivedMesh *source, DerivedMeshType type,
306                       int numVerts, int numEdges, int numTessFaces,
307                       int numLoops, int numPolys)
308 {
309         CustomData_copy(&source->vertData, &dm->vertData, CD_MASK_DERIVEDMESH,
310                         CD_CALLOC, numVerts);
311         CustomData_copy(&source->edgeData, &dm->edgeData, CD_MASK_DERIVEDMESH,
312                         CD_CALLOC, numEdges);
313         CustomData_copy(&source->faceData, &dm->faceData, CD_MASK_DERIVEDMESH,
314                         CD_CALLOC, numTessFaces);
315         CustomData_copy(&source->loopData, &dm->loopData, CD_MASK_DERIVEDMESH,
316                         CD_CALLOC, numLoops);
317         CustomData_copy(&source->polyData, &dm->polyData, CD_MASK_DERIVEDMESH,
318                         CD_CALLOC, numPolys);
319
320         dm->cd_flag = source->cd_flag;
321
322         dm->type = type;
323         dm->numVertData = numVerts;
324         dm->numEdgeData = numEdges;
325         dm->numTessFaceData = numTessFaces;
326         dm->numLoopData = numLoops;
327         dm->numPolyData = numPolys;
328
329         DM_init_funcs(dm);
330
331         dm->needsFree = 1;
332         dm->dirty = 0;
333 }
334
335 int DM_release(DerivedMesh *dm)
336 {
337         if (dm->needsFree) {
338                 bvhcache_free(&dm->bvhCache);
339                 GPU_drawobject_free(dm);
340                 CustomData_free(&dm->vertData, dm->numVertData);
341                 CustomData_free(&dm->edgeData, dm->numEdgeData);
342                 CustomData_free(&dm->faceData, dm->numTessFaceData);
343                 CustomData_free(&dm->loopData, dm->numLoopData);
344                 CustomData_free(&dm->polyData, dm->numPolyData);
345
346                 if (dm->mat) {
347                         MEM_freeN(dm->mat);
348                         dm->mat = NULL;
349                         dm->totmat = 0;
350                 }
351
352                 return 1;
353         }
354         else {
355                 CustomData_free_temporary(&dm->vertData, dm->numVertData);
356                 CustomData_free_temporary(&dm->edgeData, dm->numEdgeData);
357                 CustomData_free_temporary(&dm->faceData, dm->numTessFaceData);
358                 CustomData_free_temporary(&dm->loopData, dm->numLoopData);
359                 CustomData_free_temporary(&dm->polyData, dm->numPolyData);
360
361                 return 0;
362         }
363 }
364
365 void DM_DupPolys(DerivedMesh *source, DerivedMesh *target)
366 {
367         CustomData_free(&target->loopData, source->numLoopData);
368         CustomData_free(&target->polyData, source->numPolyData);
369
370         CustomData_copy(&source->loopData, &target->loopData, CD_MASK_DERIVEDMESH, CD_DUPLICATE, source->numLoopData);
371         CustomData_copy(&source->polyData, &target->polyData, CD_MASK_DERIVEDMESH, CD_DUPLICATE, source->numPolyData);
372
373         target->numLoopData = source->numLoopData;
374         target->numPolyData = source->numPolyData;
375
376         if (!CustomData_has_layer(&target->polyData, CD_MPOLY)) {
377                 MPoly *mpoly;
378                 MLoop *mloop;
379
380                 mloop = source->dupLoopArray(source);
381                 mpoly = source->dupPolyArray(source);
382                 CustomData_add_layer(&target->loopData, CD_MLOOP, CD_ASSIGN, mloop, source->numLoopData);
383                 CustomData_add_layer(&target->polyData, CD_MPOLY, CD_ASSIGN, mpoly, source->numPolyData);
384         }
385 }
386
387 void DM_ensure_normals(DerivedMesh *dm)
388 {
389         if (dm->dirty & DM_DIRTY_NORMALS) {
390                 dm->calcNormals(dm);
391         }
392         BLI_assert((dm->dirty & DM_DIRTY_NORMALS) == 0);
393 }
394
395 static void DM_calc_loop_normals(DerivedMesh *dm, float split_angle)
396 {
397         dm->calcLoopNormals(dm, split_angle);
398         dm->dirty |= DM_DIRTY_TESS_CDLAYERS;
399 }
400
401 /* note: until all modifiers can take MPoly's as input,
402  * use this at the start of modifiers  */
403 void DM_ensure_tessface(DerivedMesh *dm)
404 {
405         const int numTessFaces = dm->getNumTessFaces(dm);
406         const int numPolys =     dm->getNumPolys(dm);
407
408         if ((numTessFaces == 0) && (numPolys != 0)) {
409                 dm->recalcTessellation(dm);
410
411                 if (dm->getNumTessFaces(dm) != 0) {
412                         /* printf("info %s: polys -> ngons calculated\n", __func__); */
413                 }
414                 else {
415                         printf("warning %s: could not create tessfaces from %d polygons, dm->type=%d\n",
416                                __func__, numPolys, dm->type);
417                 }
418         }
419
420         else if (dm->dirty & DM_DIRTY_TESS_CDLAYERS) {
421                 BLI_assert(CustomData_has_layer(&dm->faceData, CD_ORIGINDEX) || numTessFaces == 0);
422                 DM_update_tessface_data(dm);
423         }
424
425         dm->dirty &= ~DM_DIRTY_TESS_CDLAYERS;
426 }
427
428 /* Update tessface CD data from loop/poly ones. Needed when not retessellating after modstack evaluation. */
429 /* NOTE: Assumes dm has valid tessellated data! */
430 void DM_update_tessface_data(DerivedMesh *dm)
431 {
432         MFace *mf, *mface = dm->getTessFaceArray(dm);
433         MPoly *mp = dm->getPolyArray(dm);
434         MLoop *ml = dm->getLoopArray(dm);
435
436         CustomData *fdata = dm->getTessFaceDataLayout(dm);
437         CustomData *pdata = dm->getPolyDataLayout(dm);
438         CustomData *ldata = dm->getLoopDataLayout(dm);
439
440         const int totface = dm->getNumTessFaces(dm);
441         int mf_idx;
442
443         int *polyindex = CustomData_get_layer(fdata, CD_ORIGINDEX);
444         unsigned int (*loopindex)[4];
445
446         /* Should never occure, but better abort than segfault! */
447         if (!polyindex)
448                 return;
449
450         CustomData_from_bmeshpoly(fdata, pdata, ldata, totface);
451
452         if (CustomData_has_layer(fdata, CD_MTFACE) ||
453             CustomData_has_layer(fdata, CD_MCOL) ||
454             CustomData_has_layer(fdata, CD_PREVIEW_MCOL) ||
455             CustomData_has_layer(fdata, CD_ORIGSPACE) ||
456             CustomData_has_layer(fdata, CD_TESSLOOPNORMAL))
457         {
458                 loopindex = MEM_mallocN(sizeof(*loopindex) * totface, __func__);
459
460                 for (mf_idx = 0, mf = mface; mf_idx < totface; mf_idx++, mf++) {
461                         const int mf_len = mf->v4 ? 4 : 3;
462                         unsigned int *ml_idx = loopindex[mf_idx];
463                         int i, not_done;
464
465                         /* Find out loop indices. */
466                         /* NOTE: This assumes tessface are valid and in sync with loop/poly... Else, most likely, segfault! */
467                         for (i = mp[polyindex[mf_idx]].loopstart, not_done = mf_len; not_done; i++) {
468                                 const int tf_v = BKE_MESH_TESSFACE_VINDEX_ORDER(mf, ml[i].v);
469                                 if (tf_v != -1) {
470                                         ml_idx[tf_v] = i;
471                                         not_done--;
472                                 }
473                         }
474                 }
475
476                 /* NOTE: quad detection issue - forth vertidx vs forth loopidx:
477                  * Here, our tfaces' forth vertex index is never 0 for a quad. However, we know our forth loop index may be
478                  * 0 for quads (because our quads may have been rotated compared to their org poly, see tessellation code).
479                  * So we pass the MFace's, and BKE_mesh_loops_to_tessdata will use MFace->v4 index as quad test.
480                  */
481                 BKE_mesh_loops_to_tessdata(fdata, ldata, pdata, mface, polyindex, loopindex, totface);
482
483                 MEM_freeN(loopindex);
484         }
485
486         if (G.debug & G_DEBUG)
487                 printf("%s: Updated tessellated customdata of dm %p\n", __func__, dm);
488
489         dm->dirty &= ~DM_DIRTY_TESS_CDLAYERS;
490 }
491
492 void DM_update_materials(DerivedMesh *dm, Object *ob)
493 {
494         int i, totmat = ob->totcol + 1; /* materials start from 1, default material is 0 */
495         dm->totmat = totmat;
496
497         /* invalidate old materials */
498         if (dm->mat)
499                 MEM_freeN(dm->mat);
500
501         dm->mat = MEM_callocN(totmat * sizeof(*dm->mat), "DerivedMesh.mat");
502
503         /* we leave last material as empty - rationale here is being able to index
504          * the materials by using the mf->mat_nr directly and leaving the last
505          * material as NULL in case no materials exist on mesh, so indexing will not fail */
506         for (i = 0; i < totmat - 1; i++) {
507                 dm->mat[i] = give_current_material(ob, i + 1);
508         }
509 }
510
511 MTFace *DM_paint_uvlayer_active_get(DerivedMesh *dm, int mat_nr)
512 {
513         MTFace *tf_base;
514
515         BLI_assert(mat_nr < dm->totmat);
516
517         if (dm->mat[mat_nr] && dm->mat[mat_nr]->texpaintslot &&
518             dm->mat[mat_nr]->texpaintslot[dm->mat[mat_nr]->paint_active_slot].uvname)
519         {
520                 tf_base = CustomData_get_layer_named(&dm->faceData, CD_MTFACE,
521                                                      dm->mat[mat_nr]->texpaintslot[dm->mat[mat_nr]->paint_active_slot].uvname);
522                 /* This can fail if we have changed the name in the UV layer list and have assigned the old name in the material
523                  * texture slot.*/
524                 if (!tf_base)
525                         tf_base = CustomData_get_layer(&dm->faceData, CD_MTFACE);
526         }
527         else {
528                 tf_base = CustomData_get_layer(&dm->faceData, CD_MTFACE);
529         }
530
531         return tf_base;
532 }
533
534 void DM_to_mesh(DerivedMesh *dm, Mesh *me, Object *ob, CustomDataMask mask)
535 {
536         /* dm might depend on me, so we need to do everything with a local copy */
537         Mesh tmp = *me;
538         int totvert, totedge /*, totface */ /* UNUSED */, totloop, totpoly;
539         int did_shapekeys = 0;
540         
541         CustomData_reset(&tmp.vdata);
542         CustomData_reset(&tmp.edata);
543         CustomData_reset(&tmp.fdata);
544         CustomData_reset(&tmp.ldata);
545         CustomData_reset(&tmp.pdata);
546
547         DM_ensure_normals(dm);
548
549         totvert = tmp.totvert = dm->getNumVerts(dm);
550         totedge = tmp.totedge = dm->getNumEdges(dm);
551         totloop = tmp.totloop = dm->getNumLoops(dm);
552         totpoly = tmp.totpoly = dm->getNumPolys(dm);
553         tmp.totface = 0;
554
555         CustomData_copy(&dm->vertData, &tmp.vdata, mask, CD_DUPLICATE, totvert);
556         CustomData_copy(&dm->edgeData, &tmp.edata, mask, CD_DUPLICATE, totedge);
557         CustomData_copy(&dm->loopData, &tmp.ldata, mask, CD_DUPLICATE, totloop);
558         CustomData_copy(&dm->polyData, &tmp.pdata, mask, CD_DUPLICATE, totpoly);
559         tmp.cd_flag = dm->cd_flag;
560
561         if (CustomData_has_layer(&dm->vertData, CD_SHAPEKEY)) {
562                 KeyBlock *kb;
563                 int uid;
564                 
565                 if (ob) {
566                         kb = BLI_findlink(&me->key->block, ob->shapenr - 1);
567                         if (kb) {
568                                 uid = kb->uid;
569                         }
570                         else {
571                                 printf("%s: error - could not find active shapekey %d!\n",
572                                        __func__, ob->shapenr - 1);
573
574                                 uid = INT_MAX;
575                         }
576                 }
577                 else {
578                         /* if no object, set to INT_MAX so we don't mess up any shapekey layers */
579                         uid = INT_MAX;
580                 }
581
582                 shapekey_layers_to_keyblocks(dm, me, uid);
583                 did_shapekeys = 1;
584         }
585
586         /* copy texture space */
587         if (ob) {
588                 BKE_mesh_texspace_copy_from_object(&tmp, ob);
589         }
590         
591         /* not all DerivedMeshes store their verts/edges/faces in CustomData, so
592          * we set them here in case they are missing */
593         if (!CustomData_has_layer(&tmp.vdata, CD_MVERT))
594                 CustomData_add_layer(&tmp.vdata, CD_MVERT, CD_ASSIGN, dm->dupVertArray(dm), totvert);
595         if (!CustomData_has_layer(&tmp.edata, CD_MEDGE))
596                 CustomData_add_layer(&tmp.edata, CD_MEDGE, CD_ASSIGN, dm->dupEdgeArray(dm), totedge);
597         if (!CustomData_has_layer(&tmp.pdata, CD_MPOLY)) {
598                 tmp.mloop = dm->dupLoopArray(dm);
599                 tmp.mpoly = dm->dupPolyArray(dm);
600
601                 CustomData_add_layer(&tmp.ldata, CD_MLOOP, CD_ASSIGN, tmp.mloop, tmp.totloop);
602                 CustomData_add_layer(&tmp.pdata, CD_MPOLY, CD_ASSIGN, tmp.mpoly, tmp.totpoly);
603         }
604
605         /* object had got displacement layer, should copy this layer to save sculpted data */
606         /* NOTE: maybe some other layers should be copied? nazgul */
607         if (CustomData_has_layer(&me->ldata, CD_MDISPS)) {
608                 if (totloop == me->totloop) {
609                         MDisps *mdisps = CustomData_get_layer(&me->ldata, CD_MDISPS);
610                         CustomData_add_layer(&tmp.ldata, CD_MDISPS, CD_DUPLICATE, mdisps, totloop);
611                 }
612         }
613
614         /* yes, must be before _and_ after tessellate */
615         BKE_mesh_update_customdata_pointers(&tmp, false);
616
617         /* since 2.65 caller must do! */
618         // BKE_mesh_tessface_calc(&tmp);
619
620         CustomData_free(&me->vdata, me->totvert);
621         CustomData_free(&me->edata, me->totedge);
622         CustomData_free(&me->fdata, me->totface);
623         CustomData_free(&me->ldata, me->totloop);
624         CustomData_free(&me->pdata, me->totpoly);
625
626         /* ok, this should now use new CD shapekey data,
627          * which should be fed through the modifier
628          * stack*/
629         if (tmp.totvert != me->totvert && !did_shapekeys && me->key) {
630                 printf("%s: YEEK! this should be recoded! Shape key loss!: ID '%s'\n", __func__, tmp.id.name);
631                 if (tmp.key) tmp.key->id.us--;
632                 tmp.key = NULL;
633         }
634
635         /* Clear selection history */
636         tmp.mselect = NULL;
637         tmp.totselect = 0;
638         if (me->mselect) {
639                 MEM_freeN(me->mselect);
640         }
641
642         /* skip the listbase */
643         MEMCPY_STRUCT_OFS(me, &tmp, id.prev);
644 }
645
646 void DM_to_meshkey(DerivedMesh *dm, Mesh *me, KeyBlock *kb)
647 {
648         int a, totvert = dm->getNumVerts(dm);
649         float *fp;
650         MVert *mvert;
651         
652         if (totvert == 0 || me->totvert == 0 || me->totvert != totvert) return;
653         
654         if (kb->data) MEM_freeN(kb->data);
655         kb->data = MEM_mallocN(me->key->elemsize * me->totvert, "kb->data");
656         kb->totelem = totvert;
657         
658         fp = kb->data;
659         mvert = dm->getVertDataArray(dm, CD_MVERT);
660         
661         for (a = 0; a < kb->totelem; a++, fp += 3, mvert++) {
662                 copy_v3_v3(fp, mvert->co);
663         }
664 }
665
666 void DM_set_only_copy(DerivedMesh *dm, CustomDataMask mask)
667 {
668         CustomData_set_only_copy(&dm->vertData, mask);
669         CustomData_set_only_copy(&dm->edgeData, mask);
670         CustomData_set_only_copy(&dm->faceData, mask);
671         /* this wasn't in 2.63 and is disabled for 2.64 because it gives problems with
672          * weight paint mode when there are modifiers applied, needs further investigation,
673          * see replies to r50969, Campbell */
674 #if 0
675         CustomData_set_only_copy(&dm->loopData, mask);
676         CustomData_set_only_copy(&dm->polyData, mask);
677 #endif
678 }
679
680 void DM_add_vert_layer(DerivedMesh *dm, int type, int alloctype, void *layer)
681 {
682         CustomData_add_layer(&dm->vertData, type, alloctype, layer, dm->numVertData);
683 }
684
685 void DM_add_edge_layer(DerivedMesh *dm, int type, int alloctype, void *layer)
686 {
687         CustomData_add_layer(&dm->edgeData, type, alloctype, layer, dm->numEdgeData);
688 }
689
690 void DM_add_tessface_layer(DerivedMesh *dm, int type, int alloctype, void *layer)
691 {
692         CustomData_add_layer(&dm->faceData, type, alloctype, layer, dm->numTessFaceData);
693 }
694
695 void DM_add_loop_layer(DerivedMesh *dm, int type, int alloctype, void *layer)
696 {
697         CustomData_add_layer(&dm->loopData, type, alloctype, layer, dm->numLoopData);
698 }
699
700 void DM_add_poly_layer(DerivedMesh *dm, int type, int alloctype, void *layer)
701 {
702         CustomData_add_layer(&dm->polyData, type, alloctype, layer, dm->numPolyData);
703 }
704
705 void *DM_get_vert_data(DerivedMesh *dm, int index, int type)
706 {
707         BLI_assert(index >= 0 && index < dm->getNumVerts(dm));
708         return CustomData_get(&dm->vertData, index, type);
709 }
710
711 void *DM_get_edge_data(DerivedMesh *dm, int index, int type)
712 {
713         BLI_assert(index >= 0 && index < dm->getNumEdges(dm));
714         return CustomData_get(&dm->edgeData, index, type);
715 }
716
717 void *DM_get_tessface_data(DerivedMesh *dm, int index, int type)
718 {
719         BLI_assert(index >= 0 && index < dm->getNumTessFaces(dm));
720         return CustomData_get(&dm->faceData, index, type);
721 }
722
723 void *DM_get_poly_data(DerivedMesh *dm, int index, int type)
724 {
725         BLI_assert(index >= 0 && index < dm->getNumPolys(dm));
726         return CustomData_get(&dm->polyData, index, type);
727 }
728
729
730 void *DM_get_vert_data_layer(DerivedMesh *dm, int type)
731 {
732         if (type == CD_MVERT)
733                 return dm->getVertArray(dm);
734
735         return CustomData_get_layer(&dm->vertData, type);
736 }
737
738 void *DM_get_edge_data_layer(DerivedMesh *dm, int type)
739 {
740         if (type == CD_MEDGE)
741                 return dm->getEdgeArray(dm);
742
743         return CustomData_get_layer(&dm->edgeData, type);
744 }
745
746 void *DM_get_tessface_data_layer(DerivedMesh *dm, int type)
747 {
748         if (type == CD_MFACE)
749                 return dm->getTessFaceArray(dm);
750
751         return CustomData_get_layer(&dm->faceData, type);
752 }
753
754 void *DM_get_poly_data_layer(DerivedMesh *dm, int type)
755 {
756         return CustomData_get_layer(&dm->polyData, type);
757 }
758
759 void *DM_get_loop_data_layer(DerivedMesh *dm, int type)
760 {
761         return CustomData_get_layer(&dm->loopData, type);
762 }
763
764 void DM_set_vert_data(DerivedMesh *dm, int index, int type, void *data)
765 {
766         CustomData_set(&dm->vertData, index, type, data);
767 }
768
769 void DM_set_edge_data(DerivedMesh *dm, int index, int type, void *data)
770 {
771         CustomData_set(&dm->edgeData, index, type, data);
772 }
773
774 void DM_set_tessface_data(DerivedMesh *dm, int index, int type, void *data)
775 {
776         CustomData_set(&dm->faceData, index, type, data);
777 }
778
779 void DM_copy_vert_data(DerivedMesh *source, DerivedMesh *dest,
780                        int source_index, int dest_index, int count)
781 {
782         CustomData_copy_data(&source->vertData, &dest->vertData,
783                              source_index, dest_index, count);
784 }
785
786 void DM_copy_edge_data(DerivedMesh *source, DerivedMesh *dest,
787                        int source_index, int dest_index, int count)
788 {
789         CustomData_copy_data(&source->edgeData, &dest->edgeData,
790                              source_index, dest_index, count);
791 }
792
793 void DM_copy_tessface_data(DerivedMesh *source, DerivedMesh *dest,
794                            int source_index, int dest_index, int count)
795 {
796         CustomData_copy_data(&source->faceData, &dest->faceData,
797                              source_index, dest_index, count);
798 }
799
800 void DM_copy_loop_data(DerivedMesh *source, DerivedMesh *dest,
801                        int source_index, int dest_index, int count)
802 {
803         CustomData_copy_data(&source->loopData, &dest->loopData,
804                              source_index, dest_index, count);
805 }
806
807 void DM_copy_poly_data(DerivedMesh *source, DerivedMesh *dest,
808                        int source_index, int dest_index, int count)
809 {
810         CustomData_copy_data(&source->polyData, &dest->polyData,
811                              source_index, dest_index, count);
812 }
813
814 void DM_free_vert_data(struct DerivedMesh *dm, int index, int count)
815 {
816         CustomData_free_elem(&dm->vertData, index, count);
817 }
818
819 void DM_free_edge_data(struct DerivedMesh *dm, int index, int count)
820 {
821         CustomData_free_elem(&dm->edgeData, index, count);
822 }
823
824 void DM_free_tessface_data(struct DerivedMesh *dm, int index, int count)
825 {
826         CustomData_free_elem(&dm->faceData, index, count);
827 }
828
829 void DM_free_loop_data(struct DerivedMesh *dm, int index, int count)
830 {
831         CustomData_free_elem(&dm->loopData, index, count);
832 }
833
834 void DM_free_poly_data(struct DerivedMesh *dm, int index, int count)
835 {
836         CustomData_free_elem(&dm->polyData, index, count);
837 }
838
839 void DM_interp_vert_data(DerivedMesh *source, DerivedMesh *dest,
840                          int *src_indices, float *weights,
841                          int count, int dest_index)
842 {
843         CustomData_interp(&source->vertData, &dest->vertData, src_indices,
844                           weights, NULL, count, dest_index);
845 }
846
847 void DM_interp_edge_data(DerivedMesh *source, DerivedMesh *dest,
848                          int *src_indices,
849                          float *weights, EdgeVertWeight *vert_weights,
850                          int count, int dest_index)
851 {
852         CustomData_interp(&source->edgeData, &dest->edgeData, src_indices,
853                           weights, (float *)vert_weights, count, dest_index);
854 }
855
856 void DM_interp_tessface_data(DerivedMesh *source, DerivedMesh *dest,
857                              int *src_indices,
858                              float *weights, FaceVertWeight *vert_weights,
859                              int count, int dest_index)
860 {
861         CustomData_interp(&source->faceData, &dest->faceData, src_indices,
862                           weights, (float *)vert_weights, count, dest_index);
863 }
864
865 void DM_swap_tessface_data(DerivedMesh *dm, int index, const int *corner_indices)
866 {
867         CustomData_swap(&dm->faceData, index, corner_indices);
868 }
869
870 void DM_interp_loop_data(DerivedMesh *source, DerivedMesh *dest,
871                          int *src_indices,
872                          float *weights, int count, int dest_index)
873 {
874         CustomData_interp(&source->loopData, &dest->loopData, src_indices,
875                           weights, NULL, count, dest_index);
876 }
877
878 void DM_interp_poly_data(DerivedMesh *source, DerivedMesh *dest,
879                          int *src_indices,
880                          float *weights, int count, int dest_index)
881 {
882         CustomData_interp(&source->polyData, &dest->polyData, src_indices,
883                           weights, NULL, count, dest_index);
884 }
885
886 ///
887 DerivedMesh *mesh_create_derived(Mesh *me, float (*vertCos)[3])
888 {
889         DerivedMesh *dm = CDDM_from_mesh(me);
890         
891         if (!dm)
892                 return NULL;
893         
894         if (vertCos) {
895                 CDDM_apply_vert_coords(dm, vertCos);
896         }
897
898         return dm;
899 }
900
901 DerivedMesh *mesh_create_derived_for_modifier(Scene *scene, Object *ob, 
902                                               ModifierData *md, int build_shapekey_layers)
903 {
904         Mesh *me = ob->data;
905         ModifierTypeInfo *mti = modifierType_getInfo(md->type);
906         DerivedMesh *dm;
907         KeyBlock *kb;
908
909         md->scene = scene;
910         
911         if (!(md->mode & eModifierMode_Realtime)) return NULL;
912         if (mti->isDisabled && mti->isDisabled(md, 0)) return NULL;
913         
914         if (build_shapekey_layers && me->key && (kb = BLI_findlink(&me->key->block, ob->shapenr - 1))) {
915                 BKE_keyblock_convert_to_mesh(kb, me);
916         }
917         
918         if (mti->type == eModifierTypeType_OnlyDeform) {
919                 int numVerts;
920                 float (*deformedVerts)[3] = BKE_mesh_vertexCos_get(me, &numVerts);
921
922                 modwrap_deformVerts(md, ob, NULL, deformedVerts, numVerts, 0);
923                 dm = mesh_create_derived(me, deformedVerts);
924
925                 if (build_shapekey_layers)
926                         add_shapekey_layers(dm, me, ob);
927                 
928                 MEM_freeN(deformedVerts);
929         }
930         else {
931                 DerivedMesh *tdm = mesh_create_derived(me, NULL);
932
933                 if (build_shapekey_layers)
934                         add_shapekey_layers(tdm, me, ob);
935                 
936                 dm = modwrap_applyModifier(md, ob, tdm, 0);
937                 ASSERT_IS_VALID_DM(dm);
938
939                 if (tdm != dm) tdm->release(tdm);
940         }
941
942         return dm;
943 }
944
945 static float (*get_editbmesh_orco_verts(BMEditMesh *em))[3]
946 {
947         BMIter iter;
948         BMVert *eve;
949         float (*orco)[3];
950         int i;
951
952         /* these may not really be the orco's, but it's only for preview.
953          * could be solver better once, but isn't simple */
954         
955         orco = MEM_mallocN(sizeof(float) * 3 * em->bm->totvert, "BMEditMesh Orco");
956
957         BM_ITER_MESH_INDEX (eve, &iter, em->bm, BM_VERTS_OF_MESH, i) {
958                 copy_v3_v3(orco[i], eve->co);
959         }
960         
961         return orco;
962 }
963
964 /* orco custom data layer */
965 static float (*get_orco_coords_dm(Object *ob, BMEditMesh *em, int layer, int *free))[3]
966 {
967         *free = 0;
968
969         if (layer == CD_ORCO) {
970                 /* get original coordinates */
971                 *free = 1;
972
973                 if (em)
974                         return get_editbmesh_orco_verts(em);
975                 else
976                         return BKE_mesh_orco_verts_get(ob);
977         }
978         else if (layer == CD_CLOTH_ORCO) {
979                 /* apply shape key for cloth, this should really be solved
980                  * by a more flexible customdata system, but not simple */
981                 if (!em) {
982                         ClothModifierData *clmd = (ClothModifierData *)modifiers_findByType(ob, eModifierType_Cloth);
983                         KeyBlock *kb = BKE_keyblock_from_key(BKE_key_from_object(ob), clmd->sim_parms->shapekey_rest);
984
985                         if (kb->data)
986                                 return kb->data;
987                 }
988
989                 return NULL;
990         }
991
992         return NULL;
993 }
994
995 static DerivedMesh *create_orco_dm(Object *ob, Mesh *me, BMEditMesh *em, int layer)
996 {
997         DerivedMesh *dm;
998         float (*orco)[3];
999         int free;
1000
1001         if (em) dm = CDDM_from_editbmesh(em, false, false);
1002         else dm = CDDM_from_mesh(me);
1003
1004         orco = get_orco_coords_dm(ob, em, layer, &free);
1005
1006         if (orco) {
1007                 CDDM_apply_vert_coords(dm, orco);
1008                 if (free) MEM_freeN(orco);
1009         }
1010
1011         return dm;
1012 }
1013
1014 static void add_orco_dm(Object *ob, BMEditMesh *em, DerivedMesh *dm,
1015                         DerivedMesh *orcodm, int layer)
1016 {
1017         float (*orco)[3], (*layerorco)[3];
1018         int totvert, free;
1019
1020         totvert = dm->getNumVerts(dm);
1021
1022         if (orcodm) {
1023                 orco = MEM_callocN(sizeof(float[3]) * totvert, "dm orco");
1024                 free = 1;
1025
1026                 if (orcodm->getNumVerts(orcodm) == totvert)
1027                         orcodm->getVertCos(orcodm, orco);
1028                 else
1029                         dm->getVertCos(dm, orco);
1030         }
1031         else
1032                 orco = get_orco_coords_dm(ob, em, layer, &free);
1033
1034         if (orco) {
1035                 if (layer == CD_ORCO)
1036                         BKE_mesh_orco_verts_transform(ob->data, orco, totvert, 0);
1037
1038                 if (!(layerorco = DM_get_vert_data_layer(dm, layer))) {
1039                         DM_add_vert_layer(dm, layer, CD_CALLOC, NULL);
1040                         layerorco = DM_get_vert_data_layer(dm, layer);
1041                 }
1042
1043                 memcpy(layerorco, orco, sizeof(float) * 3 * totvert);
1044                 if (free) MEM_freeN(orco);
1045         }
1046 }
1047
1048 /* weight paint colors */
1049
1050 /* Something of a hack, at the moment deal with weightpaint
1051  * by tucking into colors during modifier eval, only in
1052  * wpaint mode. Works ok but need to make sure recalc
1053  * happens on enter/exit wpaint.
1054  */
1055
1056 void weight_to_rgb(float r_rgb[3], const float weight)
1057 {
1058         const float blend = ((weight / 2.0f) + 0.5f);
1059
1060         if (weight <= 0.25f) {    /* blue->cyan */
1061                 r_rgb[0] = 0.0f;
1062                 r_rgb[1] = blend * weight * 4.0f;
1063                 r_rgb[2] = blend;
1064         }
1065         else if (weight <= 0.50f) {  /* cyan->green */
1066                 r_rgb[0] = 0.0f;
1067                 r_rgb[1] = blend;
1068                 r_rgb[2] = blend * (1.0f - ((weight - 0.25f) * 4.0f));
1069         }
1070         else if (weight <= 0.75f) {  /* green->yellow */
1071                 r_rgb[0] = blend * ((weight - 0.50f) * 4.0f);
1072                 r_rgb[1] = blend;
1073                 r_rgb[2] = 0.0f;
1074         }
1075         else if (weight <= 1.0f) {  /* yellow->red */
1076                 r_rgb[0] = blend;
1077                 r_rgb[1] = blend * (1.0f - ((weight - 0.75f) * 4.0f));
1078                 r_rgb[2] = 0.0f;
1079         }
1080         else {
1081                 /* exceptional value, unclamped or nan,
1082                  * avoid uninitialized memory use */
1083                 r_rgb[0] = 1.0f;
1084                 r_rgb[1] = 0.0f;
1085                 r_rgb[2] = 1.0f;
1086         }
1087 }
1088
1089 /* draw_flag's for calc_weightpaint_vert_color */
1090 enum {
1091         /* only one of these should be set, keep first (for easy bit-shifting) */
1092         CALC_WP_GROUP_USER_ACTIVE   = (1 << 1),
1093         CALC_WP_GROUP_USER_ALL      = (1 << 2),
1094
1095         CALC_WP_MULTIPAINT          = (1 << 3),
1096         CALC_WP_AUTO_NORMALIZE      = (1 << 4)
1097 };
1098
1099 typedef struct DMWeightColorInfo {
1100         const ColorBand *coba;
1101         const char *alert_color;
1102 } DMWeightColorInfo;
1103
1104
1105 static int dm_drawflag_calc(ToolSettings *ts)
1106 {
1107         return ((ts->multipaint ? CALC_WP_MULTIPAINT :
1108                                   /* CALC_WP_GROUP_USER_ACTIVE or CALC_WP_GROUP_USER_ALL*/
1109                                   (1 << ts->weightuser)) |
1110                 (ts->auto_normalize ? CALC_WP_AUTO_NORMALIZE : 0));
1111 }
1112
1113 static void weightpaint_color(unsigned char r_col[4], DMWeightColorInfo *dm_wcinfo, const float input)
1114 {
1115         float colf[4];
1116
1117         if (dm_wcinfo && dm_wcinfo->coba) {
1118                 do_colorband(dm_wcinfo->coba, input, colf);
1119         }
1120         else {
1121                 weight_to_rgb(colf, input);
1122         }
1123
1124         /* don't use rgb_float_to_uchar() here because
1125          * the resulting float doesn't need 0-1 clamp check */
1126         r_col[0] = (unsigned char)(colf[0] * 255.0f);
1127         r_col[1] = (unsigned char)(colf[1] * 255.0f);
1128         r_col[2] = (unsigned char)(colf[2] * 255.0f);
1129         r_col[3] = 255;
1130 }
1131
1132
1133 static void calc_weightpaint_vert_color(
1134         unsigned char r_col[4],
1135         const MDeformVert *dv,
1136         DMWeightColorInfo *dm_wcinfo,
1137         const int defbase_tot, const int defbase_act,
1138         const bool *defbase_sel, const int defbase_sel_tot,
1139         const int draw_flag)
1140 {
1141         float input = 0.0f;
1142         
1143         bool show_alert_color = false;
1144
1145         if ((defbase_sel_tot > 1) && (draw_flag & CALC_WP_MULTIPAINT)) {
1146                 /* Multi-Paint feature */
1147                 bool was_a_nonzero = false;
1148                 unsigned int i;
1149
1150                 const MDeformWeight *dw = dv->dw;
1151                 for (i = dv->totweight; i != 0; i--, dw++) {
1152                         /* in multipaint, get the average if auto normalize is inactive
1153                          * get the sum if it is active */
1154                         if (dw->def_nr < defbase_tot) {
1155                                 if (defbase_sel[dw->def_nr]) {
1156                                         if (dw->weight) {
1157                                                 input += dw->weight;
1158                                                 was_a_nonzero = true;
1159                                         }
1160                                 }
1161                         }
1162                 }
1163
1164                 /* make it black if the selected groups have no weight on a vertex */
1165                 if (was_a_nonzero == false) {
1166                         show_alert_color = true;
1167                 }
1168                 else if ((draw_flag & CALC_WP_AUTO_NORMALIZE) == false) {
1169                         input /= defbase_sel_tot; /* get the average */
1170                 }
1171         }
1172         else {
1173                 /* default, non tricky behavior */
1174                 input = defvert_find_weight(dv, defbase_act);
1175
1176                 if (draw_flag & CALC_WP_GROUP_USER_ACTIVE) {
1177                         if (input == 0.0f) {
1178                                 show_alert_color = true;
1179                         }
1180                 }
1181                 else if (draw_flag & CALC_WP_GROUP_USER_ALL) {
1182                         if (input == 0.0f) {
1183                                 show_alert_color = defvert_is_weight_zero(dv, defbase_tot);
1184                         }
1185                 }
1186         }
1187
1188         if (show_alert_color == false) {
1189                 CLAMP(input, 0.0f, 1.0f);
1190                 weightpaint_color(r_col, dm_wcinfo, input);
1191         }
1192         else {
1193                 copy_v3_v3_char((char *)r_col, dm_wcinfo->alert_color);
1194                 r_col[3] = 255;
1195         }
1196 }
1197
1198 static DMWeightColorInfo G_dm_wcinfo;
1199
1200 void vDM_ColorBand_store(const ColorBand *coba, const char alert_color[4])
1201 {
1202         G_dm_wcinfo.coba        = coba;
1203         G_dm_wcinfo.alert_color = alert_color;
1204 }
1205
1206 /* return an array of vertex weight colors, caller must free.
1207  *
1208  * note that we could save some memory and allocate RGB only but then we'd need to
1209  * re-arrange the colors when copying to the face since MCol has odd ordering,
1210  * so leave this as is - campbell */
1211 static void calc_weightpaint_vert_array(Object *ob, DerivedMesh *dm, int const draw_flag, DMWeightColorInfo *dm_wcinfo,
1212                                         unsigned char (*r_wtcol_v)[4])
1213 {
1214         MDeformVert *dv = DM_get_vert_data_layer(dm, CD_MDEFORMVERT);
1215         int numVerts = dm->getNumVerts(dm);
1216
1217         if (dv) {
1218                 unsigned char (*wc)[4] = r_wtcol_v;
1219                 unsigned int i;
1220
1221                 /* variables for multipaint */
1222                 const int defbase_tot = BLI_listbase_count(&ob->defbase);
1223                 const int defbase_act = ob->actdef - 1;
1224
1225                 int defbase_sel_tot = 0;
1226                 bool *defbase_sel = NULL;
1227
1228                 if (draw_flag & CALC_WP_MULTIPAINT) {
1229                         defbase_sel = BKE_object_defgroup_selected_get(ob, defbase_tot, &defbase_sel_tot);
1230                 }
1231
1232                 for (i = numVerts; i != 0; i--, wc++, dv++) {
1233                         calc_weightpaint_vert_color((unsigned char *)wc, dv, dm_wcinfo, defbase_tot, defbase_act, defbase_sel, defbase_sel_tot, draw_flag);
1234                 }
1235
1236                 if (defbase_sel) {
1237                         MEM_freeN(defbase_sel);
1238                 }
1239         }
1240         else {
1241                 unsigned char col[4];
1242                 if (draw_flag & (CALC_WP_GROUP_USER_ACTIVE | CALC_WP_GROUP_USER_ALL)) {
1243                         copy_v3_v3_char((char *)col, dm_wcinfo->alert_color);
1244                         col[3] = 255;
1245                 }
1246                 else {
1247                         weightpaint_color(col, dm_wcinfo, 0.0f);
1248                 }
1249                 fill_vn_i((int *)r_wtcol_v, numVerts, *((int *)col));
1250         }
1251 }
1252
1253 /* return an array of vertex weight colors from given weights, caller must free.
1254  *
1255  * note that we could save some memory and allocate RGB only but then we'd need to
1256  * re-arrange the colors when copying to the face since MCol has odd ordering,
1257  * so leave this as is - campbell */
1258 static void calc_colors_from_weights_array(const int num, const float *weights,
1259                                            unsigned char (*r_wtcol_v)[4])
1260 {
1261         unsigned char (*wc)[4] = r_wtcol_v;
1262         int i;
1263
1264         for (i = 0; i < num; i++, wc++, weights++) {
1265                 weightpaint_color((unsigned char *)wc, NULL, *weights);
1266         }
1267 }
1268
1269 void DM_update_weight_mcol(Object *ob, DerivedMesh *dm, int const draw_flag,
1270                            float *weights, int num, const int *indices)
1271 {
1272         BMEditMesh *em = (dm->type == DM_TYPE_EDITBMESH) ? BKE_editmesh_from_object(ob) : NULL;
1273         unsigned char (*wtcol_v)[4];
1274         int numVerts = dm->getNumVerts(dm);
1275         int i;
1276
1277         if (em) {
1278                 BKE_editmesh_color_ensure(em, BM_VERT);
1279                 wtcol_v = em->derivedVertColor;
1280         }
1281         else {
1282                 wtcol_v = MEM_mallocN(sizeof(*wtcol_v) * numVerts, __func__);
1283         }
1284
1285         /* Weights are given by caller. */
1286         if (weights) {
1287                 float *w = weights;
1288                 /* If indices is not NULL, it means we do not have weights for all vertices,
1289                  * so we must create them (and set them to zero)... */
1290                 if (indices) {
1291                         w = MEM_callocN(sizeof(float) * numVerts, "Temp weight array DM_update_weight_mcol");
1292                         i = num;
1293                         while (i--)
1294                                 w[indices[i]] = weights[i];
1295                 }
1296
1297                 /* Convert float weights to colors. */
1298                 calc_colors_from_weights_array(numVerts, w, wtcol_v);
1299
1300                 if (indices)
1301                         MEM_freeN(w);
1302         }
1303         else {
1304                 /* No weights given, take them from active vgroup(s). */
1305                 calc_weightpaint_vert_array(ob, dm, draw_flag, &G_dm_wcinfo, wtcol_v);
1306         }
1307
1308         if (dm->type == DM_TYPE_EDITBMESH) {
1309                 /* editmesh draw function checks specifically for this */
1310         }
1311         else {
1312                 const int dm_totpoly = dm->getNumPolys(dm);
1313                 const int dm_totloop = dm->getNumLoops(dm);
1314                 unsigned char(*wtcol_l)[4] = CustomData_get_layer(dm->getLoopDataLayout(dm), CD_PREVIEW_MLOOPCOL);
1315                 MLoop *mloop = dm->getLoopArray(dm), *ml;
1316                 MPoly *mp = dm->getPolyArray(dm);
1317                 int l_index;
1318                 int j;
1319
1320                 /* now add to loops, so the data can be passed through the modifier stack */
1321                 /* If no CD_PREVIEW_MLOOPCOL existed yet, we have to add a new one! */
1322                 if (!wtcol_l) {
1323                         wtcol_l = MEM_mallocN(sizeof(*wtcol_l) * dm_totloop, __func__);
1324                         CustomData_add_layer(&dm->loopData, CD_PREVIEW_MLOOPCOL, CD_ASSIGN, wtcol_l, dm_totloop);
1325                 }
1326
1327                 l_index = 0;
1328                 for (i = 0; i < dm_totpoly; i++, mp++) {
1329                         ml = mloop + mp->loopstart;
1330
1331                         for (j = 0; j < mp->totloop; j++, ml++, l_index++) {
1332                                 copy_v4_v4_char((char *)&wtcol_l[l_index],
1333                                                 (char *)&wtcol_v[ml->v]);
1334                         }
1335                 }
1336                 MEM_freeN(wtcol_v);
1337
1338                 dm->dirty |= DM_DIRTY_TESS_CDLAYERS;
1339         }
1340 }
1341
1342 static void DM_update_statvis_color(Scene *scene, Object *ob, DerivedMesh *dm)
1343 {
1344         BMEditMesh *em = BKE_editmesh_from_object(ob);
1345
1346         BKE_editmesh_statvis_calc(em, dm, &scene->toolsettings->statvis);
1347 }
1348
1349 static void shapekey_layers_to_keyblocks(DerivedMesh *dm, Mesh *me, int actshape_uid)
1350 {
1351         KeyBlock *kb;
1352         int i, j, tot;
1353         
1354         if (!me->key)
1355                 return;
1356         
1357         tot = CustomData_number_of_layers(&dm->vertData, CD_SHAPEKEY);
1358         for (i = 0; i < tot; i++) {
1359                 CustomDataLayer *layer = &dm->vertData.layers[CustomData_get_layer_index_n(&dm->vertData, CD_SHAPEKEY, i)];
1360                 float (*cos)[3], (*kbcos)[3];
1361                 
1362                 for (kb = me->key->block.first; kb; kb = kb->next) {
1363                         if (kb->uid == layer->uid)
1364                                 break;
1365                 }
1366                 
1367                 if (!kb) {
1368                         kb = BKE_keyblock_add(me->key, layer->name);
1369                         kb->uid = layer->uid;
1370                 }
1371                 
1372                 if (kb->data)
1373                         MEM_freeN(kb->data);
1374                 
1375                 cos = CustomData_get_layer_n(&dm->vertData, CD_SHAPEKEY, i);
1376                 kb->totelem = dm->numVertData;
1377
1378                 kb->data = kbcos = MEM_mallocN(sizeof(float) * 3 * kb->totelem, "kbcos DerivedMesh.c");
1379                 if (kb->uid == actshape_uid) {
1380                         MVert *mvert = dm->getVertArray(dm);
1381                         
1382                         for (j = 0; j < dm->numVertData; j++, kbcos++, mvert++) {
1383                                 copy_v3_v3(*kbcos, mvert->co);
1384                         }
1385                 }
1386                 else {
1387                         for (j = 0; j < kb->totelem; j++, cos++, kbcos++) {
1388                                 copy_v3_v3(*kbcos, *cos);
1389                         }
1390                 }
1391         }
1392         
1393         for (kb = me->key->block.first; kb; kb = kb->next) {
1394                 if (kb->totelem != dm->numVertData) {
1395                         if (kb->data)
1396                                 MEM_freeN(kb->data);
1397                         
1398                         kb->totelem = dm->numVertData;
1399                         kb->data = MEM_callocN(sizeof(float) * 3 * kb->totelem, "kb->data derivedmesh.c");
1400                         fprintf(stderr, "%s: lost a shapekey layer: '%s'! (bmesh internal error)\n", __func__, kb->name);
1401                 }
1402         }
1403 }
1404
1405 static void add_shapekey_layers(DerivedMesh *dm, Mesh *me, Object *UNUSED(ob))
1406 {
1407         KeyBlock *kb;
1408         Key *key = me->key;
1409         int i;
1410         const size_t shape_alloc_len = sizeof(float) * 3 * me->totvert;
1411
1412         if (!me->key)
1413                 return;
1414
1415         /* ensure we can use mesh vertex count for derived mesh custom data */
1416         if (me->totvert != dm->getNumVerts(dm)) {
1417                 fprintf(stderr,
1418                         "%s: vertex size mismatch (mesh/dm) '%s' (%d != %d)\n",
1419                         __func__, me->id.name + 2, me->totvert, dm->getNumVerts(dm));
1420                 return;
1421         }
1422
1423         for (i = 0, kb = key->block.first; kb; kb = kb->next, i++) {
1424                 int ci;
1425                 float *array;
1426
1427                 if (me->totvert != kb->totelem) {
1428                         fprintf(stderr,
1429                                 "%s: vertex size mismatch (Mesh '%s':%d != KeyBlock '%s':%d)\n",
1430                                 __func__, me->id.name + 2, me->totvert, kb->name, kb->totelem);
1431                         array = MEM_callocN(shape_alloc_len, __func__);
1432                 }
1433                 else {
1434                         array = MEM_mallocN(shape_alloc_len, __func__);
1435                         memcpy(array, kb->data, shape_alloc_len);
1436                 }
1437
1438                 CustomData_add_layer_named(&dm->vertData, CD_SHAPEKEY, CD_ASSIGN, array, dm->numVertData, kb->name);
1439                 ci = CustomData_get_layer_index_n(&dm->vertData, CD_SHAPEKEY, i);
1440
1441                 dm->vertData.layers[ci].uid = kb->uid;
1442         }
1443 }
1444
1445 /**
1446  * Called after calculating all modifiers.
1447  *
1448  * \note tessfaces should already be calculated.
1449  */
1450 static void dm_ensure_display_normals(DerivedMesh *dm)
1451 {
1452         /* Note: dm *may* have a poly CD_NORMAL layer (generated by a modifier needing poly normals e.g.).
1453          *       We do not use it here, though. And it should be tagged as temp!
1454          */
1455         /* BLI_assert((CustomData_has_layer(&dm->polyData, CD_NORMAL) == false)); */
1456
1457         if ((dm->type == DM_TYPE_CDDM) &&
1458             ((dm->dirty & DM_DIRTY_NORMALS) || CustomData_has_layer(&dm->faceData, CD_NORMAL) == false))
1459         {
1460                 /* if normals are dirty we want to calculate vertex normals too */
1461                 CDDM_calc_normals_mapping_ex(dm, (dm->dirty & DM_DIRTY_NORMALS) ? false : true);
1462         }
1463 }
1464 /* new value for useDeform -1  (hack for the gameengine):
1465  * - apply only the modifier stack of the object, skipping the virtual modifiers,
1466  * - don't apply the key
1467  * - apply deform modifiers and input vertexco
1468  */
1469 static void mesh_calc_modifiers(Scene *scene, Object *ob, float (*inputVertexCos)[3],
1470                                 DerivedMesh **deform_r, DerivedMesh **final_r,
1471                                 int useRenderParams, int useDeform,
1472                                 int needMapping, CustomDataMask dataMask,
1473                                 int index, int useCache, int build_shapekey_layers)
1474 {
1475         Mesh *me = ob->data;
1476         ModifierData *firstmd, *md, *previewmd = NULL;
1477         CDMaskLink *datamasks, *curr;
1478         /* XXX Always copying POLYINDEX, else tessellated data are no more valid! */
1479         CustomDataMask mask, nextmask, previewmask = 0, append_mask = CD_MASK_ORIGINDEX;
1480         float (*deformedVerts)[3] = NULL;
1481         DerivedMesh *dm = NULL, *orcodm, *clothorcodm, *finaldm;
1482         int numVerts = me->totvert;
1483         int required_mode;
1484         bool isPrevDeform = false;
1485         const bool skipVirtualArmature = (useDeform < 0);
1486         MultiresModifierData *mmd = get_multires_modifier(scene, ob, 0);
1487         const bool has_multires = (mmd && mmd->sculptlvl != 0);
1488         bool multires_applied = false;
1489         const bool sculpt_mode = ob->mode & OB_MODE_SCULPT && ob->sculpt && !useRenderParams;
1490         const bool sculpt_dyntopo = (sculpt_mode && ob->sculpt->bm)  && !useRenderParams;
1491         const int draw_flag = dm_drawflag_calc(scene->toolsettings);
1492
1493         /* Generic preview only in object mode! */
1494         const bool do_mod_mcol = (ob->mode == OB_MODE_OBJECT);
1495 #if 0 /* XXX Will re-enable this when we have global mod stack options. */
1496         const bool do_final_wmcol = (scene->toolsettings->weights_preview == WP_WPREVIEW_FINAL) && do_wmcol;
1497 #endif
1498         const bool do_final_wmcol = false;
1499         const bool do_init_wmcol = ((dataMask & CD_MASK_PREVIEW_MCOL) && (ob->mode & OB_MODE_WEIGHT_PAINT) && !do_final_wmcol);
1500         /* XXX Same as above... For now, only weights preview in WPaint mode. */
1501         const bool do_mod_wmcol = do_init_wmcol;
1502
1503         const bool do_loop_normals = (me->flag & ME_AUTOSMOOTH);
1504         const float loop_normals_split_angle = me->smoothresh;
1505
1506         VirtualModifierData virtualModifierData;
1507
1508         ModifierApplyFlag app_flags = useRenderParams ? MOD_APPLY_RENDER : 0;
1509         ModifierApplyFlag deform_app_flags = app_flags;
1510         if (useCache)
1511                 app_flags |= MOD_APPLY_USECACHE;
1512         if (useDeform)
1513                 deform_app_flags |= MOD_APPLY_USECACHE;
1514
1515         if (!skipVirtualArmature) {
1516                 firstmd = modifiers_getVirtualModifierList(ob, &virtualModifierData);
1517         }
1518         else {
1519                 /* game engine exception */
1520                 firstmd = ob->modifiers.first;
1521                 if (firstmd && firstmd->type == eModifierType_Armature)
1522                         firstmd = firstmd->next;
1523         }
1524
1525         md = firstmd;
1526
1527         modifiers_clearErrors(ob);
1528
1529         if (useRenderParams) required_mode = eModifierMode_Render;
1530         else required_mode = eModifierMode_Realtime;
1531
1532         if (do_mod_wmcol || do_mod_mcol) {
1533                 /* Find the last active modifier generating a preview, or NULL if none. */
1534                 /* XXX Currently, DPaint modifier just ignores this.
1535                  *     Needs a stupid hack...
1536                  *     The whole "modifier preview" thing has to be (re?)designed, anyway! */
1537                 previewmd = modifiers_getLastPreview(scene, md, required_mode);
1538
1539                 /* even if the modifier doesn't need the data, to make a preview it may */
1540                 if (previewmd) {
1541                         if (do_mod_wmcol) {
1542                                 previewmask = CD_MASK_MDEFORMVERT;
1543                         }
1544                 }
1545         }
1546
1547         datamasks = modifiers_calcDataMasks(scene, ob, md, dataMask, required_mode, previewmd, previewmask);
1548         curr = datamasks;
1549
1550         if (deform_r) *deform_r = NULL;
1551         *final_r = NULL;
1552
1553         if (useDeform) {
1554                 if (inputVertexCos)
1555                         deformedVerts = inputVertexCos;
1556                 
1557                 /* Apply all leading deforming modifiers */
1558                 for (; md; md = md->next, curr = curr->next) {
1559                         ModifierTypeInfo *mti = modifierType_getInfo(md->type);
1560
1561                         md->scene = scene;
1562                         
1563                         if (!modifier_isEnabled(scene, md, required_mode)) continue;
1564                         if (useDeform < 0 && mti->dependsOnTime && mti->dependsOnTime(md)) continue;
1565
1566                         if (mti->type == eModifierTypeType_OnlyDeform && !sculpt_dyntopo) {
1567                                 if (!deformedVerts)
1568                                         deformedVerts = BKE_mesh_vertexCos_get(me, &numVerts);
1569
1570                                 modwrap_deformVerts(md, ob, NULL, deformedVerts, numVerts, deform_app_flags);
1571                         }
1572                         else {
1573                                 break;
1574                         }
1575                         
1576                         /* grab modifiers until index i */
1577                         if ((index >= 0) && (BLI_findindex(&ob->modifiers, md) >= index))
1578                                 break;
1579                 }
1580
1581                 /* Result of all leading deforming modifiers is cached for
1582                  * places that wish to use the original mesh but with deformed
1583                  * coordinates (vpaint, etc.)
1584                  */
1585                 if (deform_r) {
1586                         *deform_r = CDDM_from_mesh(me);
1587
1588                         if (build_shapekey_layers)
1589                                 add_shapekey_layers(dm, me, ob);
1590                         
1591                         if (deformedVerts) {
1592                                 CDDM_apply_vert_coords(*deform_r, deformedVerts);
1593                         }
1594                 }
1595         }
1596         else {
1597                 /* default behavior for meshes */
1598                 if (inputVertexCos)
1599                         deformedVerts = inputVertexCos;
1600                 else
1601                         deformedVerts = BKE_mesh_vertexCos_get(me, &numVerts);
1602         }
1603
1604
1605         /* Now apply all remaining modifiers. If useDeform is off then skip
1606          * OnlyDeform ones. 
1607          */
1608         dm = NULL;
1609         orcodm = NULL;
1610         clothorcodm = NULL;
1611
1612         for (; md; md = md->next, curr = curr->next) {
1613                 ModifierTypeInfo *mti = modifierType_getInfo(md->type);
1614
1615                 md->scene = scene;
1616
1617                 if (!modifier_isEnabled(scene, md, required_mode)) continue;
1618                 if (mti->type == eModifierTypeType_OnlyDeform && !useDeform) continue;
1619                 if ((mti->flags & eModifierTypeFlag_RequiresOriginalData) && dm) {
1620                         modifier_setError(md, "Modifier requires original data, bad stack position");
1621                         continue;
1622                 }
1623                 if (sculpt_mode &&
1624                     (!has_multires || multires_applied || sculpt_dyntopo))
1625                 {
1626                         bool unsupported = false;
1627
1628                         if (md->type == eModifierType_Multires && ((MultiresModifierData *)md)->sculptlvl == 0) {
1629                                 /* If multires is on level 0 skip it silently without warning message. */
1630                                 if (!sculpt_dyntopo)
1631                                         continue;
1632                         }
1633
1634                         if (sculpt_dyntopo && !useRenderParams)
1635                                 unsupported = true;
1636
1637                         if (scene->toolsettings->sculpt->flags & SCULPT_ONLY_DEFORM)
1638                                 unsupported |= (mti->type != eModifierTypeType_OnlyDeform);
1639
1640                         unsupported |= multires_applied;
1641
1642                         if (unsupported) {
1643                                 if (sculpt_dyntopo)
1644                                         modifier_setError(md, "Not supported in dyntopo");
1645                                 else
1646                                         modifier_setError(md, "Not supported in sculpt mode");
1647                                 continue;
1648                         }
1649                         else {
1650                                 modifier_setError(md, "Hide, Mask and optimized display disabled");
1651                         }
1652                 }
1653                 if (needMapping && !modifier_supportsMapping(md)) continue;
1654                 if (useDeform < 0 && mti->dependsOnTime && mti->dependsOnTime(md)) continue;
1655
1656                 /* add an orco layer if needed by this modifier */
1657                 if (mti->requiredDataMask)
1658                         mask = mti->requiredDataMask(ob, md);
1659                 else
1660                         mask = 0;
1661
1662                 if (dm && (mask & CD_MASK_ORCO))
1663                         add_orco_dm(ob, NULL, dm, orcodm, CD_ORCO);
1664
1665                 /* How to apply modifier depends on (a) what we already have as
1666                  * a result of previous modifiers (could be a DerivedMesh or just
1667                  * deformed vertices) and (b) what type the modifier is.
1668                  */
1669
1670                 if (mti->type == eModifierTypeType_OnlyDeform) {
1671                         /* No existing verts to deform, need to build them. */
1672                         if (!deformedVerts) {
1673                                 if (dm) {
1674                                         /* Deforming a derived mesh, read the vertex locations
1675                                          * out of the mesh and deform them. Once done with this
1676                                          * run of deformers verts will be written back.
1677                                          */
1678                                         numVerts = dm->getNumVerts(dm);
1679                                         deformedVerts =
1680                                             MEM_mallocN(sizeof(*deformedVerts) * numVerts, "dfmv");
1681                                         dm->getVertCos(dm, deformedVerts);
1682                                 }
1683                                 else {
1684                                         deformedVerts = BKE_mesh_vertexCos_get(me, &numVerts);
1685                                 }
1686                         }
1687
1688                         /* if this is not the last modifier in the stack then recalculate the normals
1689                          * to avoid giving bogus normals to the next modifier see: [#23673] */
1690                         if (isPrevDeform && mti->dependsOnNormals && mti->dependsOnNormals(md)) {
1691                                 /* XXX, this covers bug #23673, but we may need normal calc for other types */
1692                                 if (dm && dm->type == DM_TYPE_CDDM) {
1693                                         CDDM_apply_vert_coords(dm, deformedVerts);
1694                                 }
1695                         }
1696
1697                         modwrap_deformVerts(md, ob, dm, deformedVerts, numVerts, deform_app_flags);
1698                 }
1699                 else {
1700                         DerivedMesh *ndm;
1701
1702                         /* determine which data layers are needed by following modifiers */
1703                         if (curr->next)
1704                                 nextmask = curr->next->mask;
1705                         else
1706                                 nextmask = dataMask;
1707
1708                         /* apply vertex coordinates or build a DerivedMesh as necessary */
1709                         if (dm) {
1710                                 if (deformedVerts) {
1711                                         DerivedMesh *tdm = CDDM_copy(dm);
1712                                         dm->release(dm);
1713                                         dm = tdm;
1714
1715                                         CDDM_apply_vert_coords(dm, deformedVerts);
1716                                 }
1717                         }
1718                         else {
1719                                 dm = CDDM_from_mesh(me);
1720                                 ASSERT_IS_VALID_DM(dm);
1721
1722                                 if (build_shapekey_layers)
1723                                         add_shapekey_layers(dm, me, ob);
1724
1725                                 if (deformedVerts) {
1726                                         CDDM_apply_vert_coords(dm, deformedVerts);
1727                                 }
1728
1729                                 if (do_init_wmcol)
1730                                         DM_update_weight_mcol(ob, dm, draw_flag, NULL, 0, NULL);
1731
1732                                 /* Constructive modifiers need to have an origindex
1733                                  * otherwise they wont have anywhere to copy the data from.
1734                                  *
1735                                  * Also create ORIGINDEX data if any of the following modifiers
1736                                  * requests it, this way Mirror, Solidify etc will keep ORIGINDEX
1737                                  * data by using generic DM_copy_vert_data() functions.
1738                                  */
1739                                 if (needMapping || (nextmask & CD_MASK_ORIGINDEX)) {
1740                                         /* calc */
1741                                         DM_add_vert_layer(dm, CD_ORIGINDEX, CD_CALLOC, NULL);
1742                                         DM_add_edge_layer(dm, CD_ORIGINDEX, CD_CALLOC, NULL);
1743                                         DM_add_poly_layer(dm, CD_ORIGINDEX, CD_CALLOC, NULL);
1744
1745 #pragma omp parallel sections if (dm->numVertData + dm->numEdgeData + dm->numPolyData >= BKE_MESH_OMP_LIMIT)
1746                                         {
1747 #pragma omp section
1748                                                 { range_vn_i(DM_get_vert_data_layer(dm, CD_ORIGINDEX), dm->numVertData, 0); }
1749 #pragma omp section
1750                                                 { range_vn_i(DM_get_edge_data_layer(dm, CD_ORIGINDEX), dm->numEdgeData, 0); }
1751 #pragma omp section
1752                                                 { range_vn_i(DM_get_poly_data_layer(dm, CD_ORIGINDEX), dm->numPolyData, 0); }
1753                                         }
1754                                 }
1755                         }
1756
1757                         
1758                         /* set the DerivedMesh to only copy needed data */
1759                         mask = curr->mask;
1760                         /* needMapping check here fixes bug [#28112], otherwise its
1761                          * possible that it wont be copied */
1762                         mask |= append_mask;
1763                         DM_set_only_copy(dm, mask | (needMapping ? CD_MASK_ORIGINDEX : 0));
1764                         
1765                         /* add cloth rest shape key if need */
1766                         if (mask & CD_MASK_CLOTH_ORCO)
1767                                 add_orco_dm(ob, NULL, dm, clothorcodm, CD_CLOTH_ORCO);
1768
1769                         /* add an origspace layer if needed */
1770                         if ((curr->mask) & CD_MASK_ORIGSPACE_MLOOP) {
1771                                 if (!CustomData_has_layer(&dm->loopData, CD_ORIGSPACE_MLOOP)) {
1772                                         DM_add_loop_layer(dm, CD_ORIGSPACE_MLOOP, CD_CALLOC, NULL);
1773                                         DM_init_origspace(dm);
1774                                 }
1775                         }
1776
1777                         ndm = modwrap_applyModifier(md, ob, dm, app_flags);
1778                         ASSERT_IS_VALID_DM(ndm);
1779
1780                         if (ndm) {
1781                                 /* if the modifier returned a new dm, release the old one */
1782                                 if (dm && dm != ndm) dm->release(dm);
1783
1784                                 dm = ndm;
1785
1786                                 if (deformedVerts) {
1787                                         if (deformedVerts != inputVertexCos)
1788                                                 MEM_freeN(deformedVerts);
1789
1790                                         deformedVerts = NULL;
1791                                 }
1792                         }
1793
1794                         /* create an orco derivedmesh in parallel */
1795                         if (nextmask & CD_MASK_ORCO) {
1796                                 if (!orcodm)
1797                                         orcodm = create_orco_dm(ob, me, NULL, CD_ORCO);
1798
1799                                 nextmask &= ~CD_MASK_ORCO;
1800                                 DM_set_only_copy(orcodm, nextmask | CD_MASK_ORIGINDEX |
1801                                                  (mti->requiredDataMask ?
1802                                                   mti->requiredDataMask(ob, md) : 0));
1803
1804                                 ndm = modwrap_applyModifier(md, ob, orcodm, (app_flags & ~MOD_APPLY_USECACHE) | MOD_APPLY_ORCO);
1805                                 ASSERT_IS_VALID_DM(ndm);
1806
1807                                 if (ndm) {
1808                                         /* if the modifier returned a new dm, release the old one */
1809                                         if (orcodm && orcodm != ndm) orcodm->release(orcodm);
1810                                         orcodm = ndm;
1811                                 }
1812                         }
1813
1814                         /* create cloth orco derivedmesh in parallel */
1815                         if (nextmask & CD_MASK_CLOTH_ORCO) {
1816                                 if (!clothorcodm)
1817                                         clothorcodm = create_orco_dm(ob, me, NULL, CD_CLOTH_ORCO);
1818
1819                                 nextmask &= ~CD_MASK_CLOTH_ORCO;
1820                                 DM_set_only_copy(clothorcodm, nextmask | CD_MASK_ORIGINDEX);
1821
1822                                 ndm = modwrap_applyModifier(md, ob, clothorcodm, (app_flags & ~MOD_APPLY_USECACHE) | MOD_APPLY_ORCO);
1823                                 ASSERT_IS_VALID_DM(ndm);
1824
1825                                 if (ndm) {
1826                                         /* if the modifier returned a new dm, release the old one */
1827                                         if (clothorcodm && clothorcodm != ndm) clothorcodm->release(clothorcodm);
1828                                         clothorcodm = ndm;
1829                                 }
1830                         }
1831
1832                         /* in case of dynamic paint, make sure preview mask remains for following modifiers */
1833                         /* XXX Temp and hackish solution! */
1834                         if (md->type == eModifierType_DynamicPaint)
1835                                 append_mask |= CD_MASK_PREVIEW_MLOOPCOL;
1836                         /* In case of active preview modifier, make sure preview mask remains for following modifiers. */
1837                         else if ((md == previewmd) && (do_mod_wmcol)) {
1838                                 DM_update_weight_mcol(ob, dm, draw_flag, NULL, 0, NULL);
1839                                 append_mask |= CD_MASK_PREVIEW_MLOOPCOL;
1840                         }
1841                 }
1842
1843                 isPrevDeform = (mti->type == eModifierTypeType_OnlyDeform);
1844
1845                 /* grab modifiers until index i */
1846                 if ((index >= 0) && (BLI_findindex(&ob->modifiers, md) >= index))
1847                         break;
1848
1849                 if (sculpt_mode && md->type == eModifierType_Multires) {
1850                         multires_applied = true;
1851                 }
1852         }
1853
1854         for (md = firstmd; md; md = md->next)
1855                 modifier_freeTemporaryData(md);
1856
1857         /* Yay, we are done. If we have a DerivedMesh and deformed vertices
1858          * need to apply these back onto the DerivedMesh. If we have no
1859          * DerivedMesh then we need to build one.
1860          */
1861         if (dm && deformedVerts) {
1862                 finaldm = CDDM_copy(dm);
1863
1864                 dm->release(dm);
1865
1866                 CDDM_apply_vert_coords(finaldm, deformedVerts);
1867
1868 #if 0 /* For later nice mod preview! */
1869                 /* In case we need modified weights in CD_PREVIEW_MCOL, we have to re-compute it. */
1870                 if (do_final_wmcol)
1871                         DM_update_weight_mcol(ob, finaldm, draw_flag, NULL, 0, NULL);
1872 #endif
1873         }
1874         else if (dm) {
1875                 finaldm = dm;
1876
1877 #if 0 /* For later nice mod preview! */
1878                 /* In case we need modified weights in CD_PREVIEW_MCOL, we have to re-compute it. */
1879                 if (do_final_wmcol)
1880                         DM_update_weight_mcol(ob, finaldm, draw_flag, NULL, 0, NULL);
1881 #endif
1882         }
1883         else {
1884                 finaldm = CDDM_from_mesh(me);
1885                 
1886                 if (build_shapekey_layers) {
1887                         add_shapekey_layers(finaldm, me, ob);
1888                 }
1889                 
1890                 if (deformedVerts) {
1891                         CDDM_apply_vert_coords(finaldm, deformedVerts);
1892                 }
1893
1894                 /* In this case, we should never have weight-modifying modifiers in stack... */
1895                 if (do_init_wmcol)
1896                         DM_update_weight_mcol(ob, finaldm, draw_flag, NULL, 0, NULL);
1897         }
1898
1899         /* add an orco layer if needed */
1900         if (dataMask & CD_MASK_ORCO) {
1901                 add_orco_dm(ob, NULL, finaldm, orcodm, CD_ORCO);
1902
1903                 if (deform_r && *deform_r)
1904                         add_orco_dm(ob, NULL, *deform_r, NULL, CD_ORCO);
1905         }
1906
1907         if (do_loop_normals) {
1908                 /* Compute loop normals (note: will compute poly and vert normals as well, if needed!) */
1909                 DM_calc_loop_normals(finaldm, loop_normals_split_angle);
1910         }
1911
1912         {
1913                 DM_ensure_tessface(finaldm);
1914
1915                 /* without this, drawing ngon tri's faces will show ugly tessellated face
1916                  * normals and will also have to calculate normals on the fly, try avoid
1917                  * this where possible since calculating polygon normals isn't fast,
1918                  * note that this isn't a problem for subsurf (only quads) or editmode
1919                  * which deals with drawing differently.
1920                  *
1921                  * Only calc vertex normals if they are flagged as dirty.
1922                  * If using loop normals, poly nors have already been computed.
1923                  */
1924                 if (!do_loop_normals) {
1925                         dm_ensure_display_normals(finaldm);
1926                 }
1927         }
1928
1929 #ifdef WITH_GAMEENGINE
1930         /* NavMesh - this is a hack but saves having a NavMesh modifier */
1931         if ((ob->gameflag & OB_NAVMESH) && (finaldm->type == DM_TYPE_CDDM)) {
1932                 DerivedMesh *tdm;
1933                 tdm = navmesh_dm_createNavMeshForVisualization(finaldm);
1934                 if (finaldm != tdm) {
1935                         finaldm->release(finaldm);
1936                         finaldm = tdm;
1937                 }
1938         }
1939 #endif /* WITH_GAMEENGINE */
1940
1941         *final_r = finaldm;
1942
1943         if (orcodm)
1944                 orcodm->release(orcodm);
1945         if (clothorcodm)
1946                 clothorcodm->release(clothorcodm);
1947
1948         if (deformedVerts && deformedVerts != inputVertexCos)
1949                 MEM_freeN(deformedVerts);
1950
1951         BLI_linklist_free((LinkNode *)datamasks, NULL);
1952 }
1953
1954 float (*editbmesh_get_vertex_cos(BMEditMesh *em, int *r_numVerts))[3]
1955 {
1956         BMIter iter;
1957         BMVert *eve;
1958         float (*cos)[3];
1959         int i;
1960
1961         *r_numVerts = em->bm->totvert;
1962
1963         cos = MEM_mallocN(sizeof(float) * 3 * em->bm->totvert, "vertexcos");
1964
1965         BM_ITER_MESH_INDEX (eve, &iter, em->bm, BM_VERTS_OF_MESH, i) {
1966                 copy_v3_v3(cos[i], eve->co);
1967         }
1968
1969         return cos;
1970 }
1971
1972 bool editbmesh_modifier_is_enabled(Scene *scene, ModifierData *md, DerivedMesh *dm)
1973 {
1974         ModifierTypeInfo *mti = modifierType_getInfo(md->type);
1975         int required_mode = eModifierMode_Realtime | eModifierMode_Editmode;
1976
1977         if (!modifier_isEnabled(scene, md, required_mode)) return 0;
1978         if ((mti->flags & eModifierTypeFlag_RequiresOriginalData) && dm) {
1979                 modifier_setError(md, "Modifier requires original data, bad stack position");
1980                 return false;
1981         }
1982         
1983         return true;
1984 }
1985
1986 static void editbmesh_calc_modifiers(Scene *scene, Object *ob, BMEditMesh *em, DerivedMesh **cage_r,
1987                                      DerivedMesh **final_r,
1988                                      CustomDataMask dataMask)
1989 {
1990         ModifierData *md, *previewmd = NULL;
1991         float (*deformedVerts)[3] = NULL;
1992         CustomDataMask mask, previewmask = 0, append_mask = 0;
1993         DerivedMesh *dm = NULL, *orcodm = NULL;
1994         int i, numVerts = 0, cageIndex = modifiers_getCageIndex(scene, ob, NULL, 1);
1995         CDMaskLink *datamasks, *curr;
1996         int required_mode = eModifierMode_Realtime | eModifierMode_Editmode;
1997         int draw_flag = dm_drawflag_calc(scene->toolsettings);
1998
1999         // const bool do_mod_mcol = true; // (ob->mode == OB_MODE_OBJECT);
2000 #if 0 /* XXX Will re-enable this when we have global mod stack options. */
2001         const bool do_final_wmcol = (scene->toolsettings->weights_preview == WP_WPREVIEW_FINAL) && do_wmcol;
2002 #endif
2003         const bool do_final_wmcol = false;
2004         const bool do_init_wmcol = ((((Mesh *)ob->data)->drawflag & ME_DRAWEIGHT) && !do_final_wmcol);
2005         const bool do_init_statvis = ((((Mesh *)ob->data)->drawflag & ME_DRAW_STATVIS) && !do_init_wmcol);
2006         const bool do_mod_wmcol = do_init_wmcol;
2007         VirtualModifierData virtualModifierData;
2008
2009         const bool do_loop_normals = (((Mesh *)(ob->data))->flag & ME_AUTOSMOOTH);
2010         const float loop_normals_split_angle = ((Mesh *)(ob->data))->smoothresh;
2011
2012         modifiers_clearErrors(ob);
2013
2014         if (cage_r && cageIndex == -1) {
2015                 *cage_r = getEditDerivedBMesh(em, ob, NULL);
2016         }
2017
2018         md = modifiers_getVirtualModifierList(ob, &virtualModifierData);
2019
2020         /* copied from mesh_calc_modifiers */
2021         if (do_mod_wmcol) {
2022                 previewmd = modifiers_getLastPreview(scene, md, required_mode);
2023                 /* even if the modifier doesn't need the data, to make a preview it may */
2024                 if (previewmd) {
2025                         previewmask = CD_MASK_MDEFORMVERT;
2026                 }
2027         }
2028
2029         datamasks = modifiers_calcDataMasks(scene, ob, md, dataMask, required_mode, previewmd, previewmask);
2030
2031         curr = datamasks;
2032         for (i = 0; md; i++, md = md->next, curr = curr->next) {
2033                 ModifierTypeInfo *mti = modifierType_getInfo(md->type);
2034
2035                 md->scene = scene;
2036                 
2037                 if (!editbmesh_modifier_is_enabled(scene, md, dm))
2038                         continue;
2039
2040                 /* add an orco layer if needed by this modifier */
2041                 if (dm && mti->requiredDataMask) {
2042                         mask = mti->requiredDataMask(ob, md);
2043                         if (mask & CD_MASK_ORCO)
2044                                 add_orco_dm(ob, em, dm, orcodm, CD_ORCO);
2045                 }
2046
2047                 /* How to apply modifier depends on (a) what we already have as
2048                  * a result of previous modifiers (could be a DerivedMesh or just
2049                  * deformed vertices) and (b) what type the modifier is.
2050                  */
2051
2052                 if (mti->type == eModifierTypeType_OnlyDeform) {
2053                         /* No existing verts to deform, need to build them. */
2054                         if (!deformedVerts) {
2055                                 if (dm) {
2056                                         /* Deforming a derived mesh, read the vertex locations
2057                                          * out of the mesh and deform them. Once done with this
2058                                          * run of deformers verts will be written back.
2059                                          */
2060                                         numVerts = dm->getNumVerts(dm);
2061                                         deformedVerts =
2062                                             MEM_mallocN(sizeof(*deformedVerts) * numVerts, "dfmv");
2063                                         dm->getVertCos(dm, deformedVerts);
2064                                 }
2065                                 else {
2066                                         deformedVerts = editbmesh_get_vertex_cos(em, &numVerts);
2067                                 }
2068                         }
2069
2070                         if (mti->deformVertsEM)
2071                                 modwrap_deformVertsEM(md, ob, em, dm, deformedVerts, numVerts);
2072                         else
2073                                 modwrap_deformVerts(md, ob, dm, deformedVerts, numVerts, 0);
2074                 }
2075                 else {
2076                         DerivedMesh *ndm;
2077
2078                         /* apply vertex coordinates or build a DerivedMesh as necessary */
2079                         if (dm) {
2080                                 if (deformedVerts) {
2081                                         DerivedMesh *tdm = CDDM_copy(dm);
2082                                         if (!(cage_r && dm == *cage_r)) dm->release(dm);
2083                                         dm = tdm;
2084
2085                                         CDDM_apply_vert_coords(dm, deformedVerts);
2086                                 }
2087                                 else if (cage_r && dm == *cage_r) {
2088                                         /* dm may be changed by this modifier, so we need to copy it
2089                                          */
2090                                         dm = CDDM_copy(dm);
2091                                 }
2092
2093                         }
2094                         else {
2095                                 dm = CDDM_from_editbmesh(em, false, false);
2096                                 ASSERT_IS_VALID_DM(dm);
2097
2098                                 if (deformedVerts) {
2099                                         CDDM_apply_vert_coords(dm, deformedVerts);
2100                                 }
2101
2102                                 if (do_init_wmcol) {
2103                                         DM_update_weight_mcol(ob, dm, draw_flag, NULL, 0, NULL);
2104                                 }
2105                         }
2106
2107                         /* create an orco derivedmesh in parallel */
2108                         mask = curr->mask;
2109                         if (mask & CD_MASK_ORCO) {
2110                                 if (!orcodm)
2111                                         orcodm = create_orco_dm(ob, ob->data, em, CD_ORCO);
2112
2113                                 mask &= ~CD_MASK_ORCO;
2114                                 DM_set_only_copy(orcodm, mask | CD_MASK_ORIGINDEX);
2115
2116                                 if (mti->applyModifierEM) {
2117                                         ndm = modwrap_applyModifierEM(md, ob, em, orcodm, MOD_APPLY_ORCO);
2118                                 }
2119                                 else {
2120                                         ndm = modwrap_applyModifier(md, ob, orcodm, MOD_APPLY_ORCO);
2121                                 }
2122                                 ASSERT_IS_VALID_DM(ndm);
2123
2124                                 if (ndm) {
2125                                         /* if the modifier returned a new dm, release the old one */
2126                                         if (orcodm && orcodm != ndm) orcodm->release(orcodm);
2127                                         orcodm = ndm;
2128                                 }
2129                         }
2130
2131                         /* set the DerivedMesh to only copy needed data */
2132                         mask |= append_mask;
2133                         mask = curr->mask; /* CD_MASK_ORCO may have been cleared above */
2134
2135                         DM_set_only_copy(dm, mask | CD_MASK_ORIGINDEX);
2136
2137                         if (mask & CD_MASK_ORIGSPACE_MLOOP) {
2138                                 if (!CustomData_has_layer(&dm->loopData, CD_ORIGSPACE_MLOOP)) {
2139                                         DM_add_loop_layer(dm, CD_ORIGSPACE_MLOOP, CD_CALLOC, NULL);
2140                                         DM_init_origspace(dm);
2141                                 }
2142                         }
2143
2144                         if (mti->applyModifierEM)
2145                                 ndm = modwrap_applyModifierEM(md, ob, em, dm, MOD_APPLY_USECACHE);
2146                         else
2147                                 ndm = modwrap_applyModifier(md, ob, dm, MOD_APPLY_USECACHE);
2148                         ASSERT_IS_VALID_DM(ndm);
2149
2150                         if (ndm) {
2151                                 if (dm && dm != ndm)
2152                                         dm->release(dm);
2153
2154                                 dm = ndm;
2155
2156                                 if (deformedVerts) {
2157                                         MEM_freeN(deformedVerts);
2158                                         deformedVerts = NULL;
2159                                 }
2160                         }
2161                 }
2162
2163                 /* In case of active preview modifier, make sure preview mask remains for following modifiers. */
2164                 if ((md == previewmd) && (do_mod_wmcol)) {
2165                         DM_update_weight_mcol(ob, dm, draw_flag, NULL, 0, NULL);
2166                         append_mask |= CD_MASK_PREVIEW_MLOOPCOL;
2167                 }
2168
2169                 if (cage_r && i == cageIndex) {
2170                         if (dm && deformedVerts) {
2171                                 *cage_r = CDDM_copy(dm);
2172                                 CDDM_apply_vert_coords(*cage_r, deformedVerts);
2173                         }
2174                         else if (dm) {
2175                                 *cage_r = dm;
2176                         }
2177                         else {
2178                                 *cage_r =
2179                                     getEditDerivedBMesh(em, ob,
2180                                                         deformedVerts ? MEM_dupallocN(deformedVerts) : NULL);
2181                         }
2182                 }
2183         }
2184
2185         BLI_linklist_free((LinkNode *)datamasks, NULL);
2186
2187         /* Yay, we are done. If we have a DerivedMesh and deformed vertices need
2188          * to apply these back onto the DerivedMesh. If we have no DerivedMesh
2189          * then we need to build one.
2190          */
2191         if (dm && deformedVerts) {
2192                 *final_r = CDDM_copy(dm);
2193
2194                 if (!(cage_r && dm == *cage_r)) dm->release(dm);
2195
2196                 CDDM_apply_vert_coords(*final_r, deformedVerts);
2197         }
2198         else if (dm) {
2199                 *final_r = dm;
2200         }
2201         else if (!deformedVerts && cage_r && *cage_r) {
2202                 /* cage should already have up to date normals */
2203                 *final_r = *cage_r;
2204
2205                 /* In this case, we should never have weight-modifying modifiers in stack... */
2206                 if (do_init_wmcol)
2207                         DM_update_weight_mcol(ob, *final_r, draw_flag, NULL, 0, NULL);
2208                 if (do_init_statvis)
2209                         DM_update_statvis_color(scene, ob, *final_r);
2210         }
2211         else {
2212                 /* this is just a copy of the editmesh, no need to calc normals */
2213                 *final_r = getEditDerivedBMesh(em, ob, deformedVerts);
2214                 deformedVerts = NULL;
2215
2216                 /* In this case, we should never have weight-modifying modifiers in stack... */
2217                 if (do_init_wmcol)
2218                         DM_update_weight_mcol(ob, *final_r, draw_flag, NULL, 0, NULL);
2219                 if (do_init_statvis)
2220                         DM_update_statvis_color(scene, ob, *final_r);
2221         }
2222
2223         if (do_loop_normals) {
2224                 /* Compute loop normals */
2225                 DM_calc_loop_normals(*final_r, loop_normals_split_angle);
2226                 if (cage_r && *cage_r && (*cage_r != *final_r)) {
2227                         DM_calc_loop_normals(*cage_r, loop_normals_split_angle);
2228                 }
2229         }
2230
2231         /* --- */
2232         /* BMESH_ONLY, ensure tessface's used for drawing,
2233          * but don't recalculate if the last modifier in the stack gives us tessfaces
2234          * check if the derived meshes are DM_TYPE_EDITBMESH before calling, this isn't essential
2235          * but quiets annoying error messages since tessfaces wont be created. */
2236         if ((*final_r)->type != DM_TYPE_EDITBMESH) {
2237                 DM_ensure_tessface(*final_r);
2238         }
2239         if (cage_r && *cage_r) {
2240                 if ((*cage_r)->type != DM_TYPE_EDITBMESH) {
2241                         if (*cage_r != *final_r) {
2242                                 DM_ensure_tessface(*cage_r);
2243                         }
2244                 }
2245         }
2246         /* --- */
2247
2248         /* same as mesh_calc_modifiers (if using loop normals, poly nors have already been computed). */
2249         if (!do_loop_normals) {
2250                 dm_ensure_display_normals(*final_r);
2251         }
2252
2253         /* add an orco layer if needed */
2254         if (dataMask & CD_MASK_ORCO)
2255                 add_orco_dm(ob, em, *final_r, orcodm, CD_ORCO);
2256
2257         if (orcodm)
2258                 orcodm->release(orcodm);
2259
2260         if (deformedVerts)
2261                 MEM_freeN(deformedVerts);
2262 }
2263
2264 static void mesh_build_data(Scene *scene, Object *ob, CustomDataMask dataMask,
2265                             int build_shapekey_layers)
2266 {
2267         Object *obact = scene->basact ? scene->basact->object : NULL;
2268         bool editing = BKE_paint_select_face_test(ob);
2269         /* weight paint and face select need original indices because of selection buffer drawing */
2270         int needMapping = (ob == obact) && (editing || (ob->mode & (OB_MODE_WEIGHT_PAINT | OB_MODE_VERTEX_PAINT | OB_MODE_TEXTURE_PAINT)));
2271
2272         BLI_assert(ob->type == OB_MESH);
2273
2274         BKE_object_free_derived_caches(ob);
2275         BKE_object_sculpt_modifiers_changed(ob);
2276
2277         mesh_calc_modifiers(scene, ob, NULL, &ob->derivedDeform,
2278                             &ob->derivedFinal, 0, 1,
2279                             needMapping, dataMask, -1, 1, build_shapekey_layers);
2280
2281         DM_set_object_boundbox(ob, ob->derivedFinal);
2282
2283         ob->derivedFinal->needsFree = 0;
2284         ob->derivedDeform->needsFree = 0;
2285         ob->lastDataMask = dataMask;
2286
2287         if ((ob->mode & OB_MODE_SCULPT) && ob->sculpt) {
2288                 /* create PBVH immediately (would be created on the fly too,
2289                  * but this avoids waiting on first stroke) */
2290
2291                 BKE_sculpt_update_mesh_elements(scene, scene->toolsettings->sculpt, ob, false, false);
2292         }
2293
2294         BLI_assert(!(ob->derivedFinal->dirty & DM_DIRTY_NORMALS));
2295 }
2296
2297 static void editbmesh_build_data(Scene *scene, Object *obedit, BMEditMesh *em, CustomDataMask dataMask)
2298 {
2299         BKE_object_free_derived_caches(obedit);
2300         BKE_object_sculpt_modifiers_changed(obedit);
2301
2302         BKE_editmesh_free_derivedmesh(em);
2303
2304         editbmesh_calc_modifiers(scene, obedit, em, &em->derivedCage, &em->derivedFinal, dataMask);
2305         DM_set_object_boundbox(obedit, em->derivedFinal);
2306
2307         em->lastDataMask = dataMask;
2308         em->derivedFinal->needsFree = 0;
2309         em->derivedCage->needsFree = 0;
2310
2311         BLI_assert(!(em->derivedFinal->dirty & DM_DIRTY_NORMALS));
2312 }
2313
2314 static CustomDataMask object_get_datamask(Scene *scene, Object *ob)
2315 {
2316         Object *actob = scene->basact ? scene->basact->object : NULL;
2317         CustomDataMask mask = ob->customdata_mask;
2318
2319         if (ob == actob) {
2320                 /* check if we need tfaces & mcols due to face select or texture paint */
2321                 if (BKE_paint_select_face_test(ob) || (ob->mode & OB_MODE_TEXTURE_PAINT)) {
2322                         mask |= CD_MASK_MTFACE | CD_MASK_MCOL;
2323                 }
2324
2325                 /* check if we need mcols due to vertex paint or weightpaint */
2326                 if (ob->mode & OB_MODE_VERTEX_PAINT) {
2327                         mask |= CD_MASK_MCOL;
2328                 }
2329
2330                 if (ob->mode & OB_MODE_WEIGHT_PAINT) {
2331                         mask |= CD_MASK_PREVIEW_MCOL;
2332                 }
2333
2334                 if (ob->mode & OB_MODE_EDIT)
2335                         mask |= CD_MASK_MVERT_SKIN;
2336         }
2337
2338         return mask;
2339 }
2340
2341 void makeDerivedMesh(Scene *scene, Object *ob, BMEditMesh *em,
2342                      CustomDataMask dataMask, int build_shapekey_layers)
2343 {
2344         dataMask |= object_get_datamask(scene, ob);
2345
2346         if (em) {
2347                 editbmesh_build_data(scene, ob, em, dataMask);
2348         }
2349         else {
2350                 mesh_build_data(scene, ob, dataMask, build_shapekey_layers);
2351         }
2352 }
2353
2354 /***/
2355
2356 DerivedMesh *mesh_get_derived_final(Scene *scene, Object *ob, CustomDataMask dataMask)
2357 {
2358         /* if there's no derived mesh or the last data mask used doesn't include
2359          * the data we need, rebuild the derived mesh
2360          */
2361         dataMask |= object_get_datamask(scene, ob);
2362
2363         if (!ob->derivedFinal || (dataMask & ob->lastDataMask) != dataMask)
2364                 mesh_build_data(scene, ob, dataMask, 0);
2365
2366         if (ob->derivedFinal) { BLI_assert(!(ob->derivedFinal->dirty & DM_DIRTY_NORMALS)); }
2367         return ob->derivedFinal;
2368 }
2369
2370 DerivedMesh *mesh_get_derived_deform(Scene *scene, Object *ob, CustomDataMask dataMask)
2371 {
2372         /* if there's no derived mesh or the last data mask used doesn't include
2373          * the data we need, rebuild the derived mesh
2374          */
2375         dataMask |= object_get_datamask(scene, ob);
2376
2377         if (!ob->derivedDeform || (dataMask & ob->lastDataMask) != dataMask)
2378                 mesh_build_data(scene, ob, dataMask, 0);
2379
2380         return ob->derivedDeform;
2381 }
2382
2383 DerivedMesh *mesh_create_derived_render(Scene *scene, Object *ob, CustomDataMask dataMask)
2384 {
2385         DerivedMesh *final;
2386         
2387         mesh_calc_modifiers(scene, ob, NULL, NULL, &final, 1, 1, 0, dataMask, -1, 0, 0);
2388
2389         return final;
2390 }
2391
2392 DerivedMesh *mesh_create_derived_index_render(Scene *scene, Object *ob, CustomDataMask dataMask, int index)
2393 {
2394         DerivedMesh *final;
2395         
2396         mesh_calc_modifiers(scene, ob, NULL, NULL, &final, 1, 1, 0, dataMask, index, 0, 0);
2397
2398         return final;
2399 }
2400
2401 DerivedMesh *mesh_create_derived_view(Scene *scene, Object *ob, CustomDataMask dataMask)
2402 {
2403         DerivedMesh *final;
2404
2405         /* XXX hack
2406          * psys modifier updates particle state when called during dupli-list generation,
2407          * which can lead to wrong transforms. This disables particle system modifier execution.
2408          */
2409         ob->transflag |= OB_NO_PSYS_UPDATE;
2410
2411         mesh_calc_modifiers(scene, ob, NULL, NULL, &final, 0, 1, 0, dataMask, -1, 0, 0);
2412
2413         ob->transflag &= ~OB_NO_PSYS_UPDATE;
2414
2415         return final;
2416 }
2417
2418 DerivedMesh *mesh_create_derived_no_deform(Scene *scene, Object *ob, float (*vertCos)[3],
2419                                            CustomDataMask dataMask)
2420 {
2421         DerivedMesh *final;
2422         
2423         mesh_calc_modifiers(scene, ob, vertCos, NULL, &final, 0, 0, 0, dataMask, -1, 0, 0);
2424
2425         return final;
2426 }
2427
2428 DerivedMesh *mesh_create_derived_no_virtual(Scene *scene, Object *ob, float (*vertCos)[3],
2429                                             CustomDataMask dataMask)
2430 {
2431         DerivedMesh *final;
2432         
2433         mesh_calc_modifiers(scene, ob, vertCos, NULL, &final, 0, -1, 0, dataMask, -1, 0, 0);
2434
2435         return final;
2436 }
2437
2438 DerivedMesh *mesh_create_derived_physics(Scene *scene, Object *ob, float (*vertCos)[3],
2439                                          CustomDataMask dataMask)
2440 {
2441         DerivedMesh *final;
2442         
2443         mesh_calc_modifiers(scene, ob, vertCos, NULL, &final, 0, -1, 1, dataMask, -1, 0, 0);
2444
2445         return final;
2446 }
2447
2448 DerivedMesh *mesh_create_derived_no_deform_render(Scene *scene, Object *ob,
2449                                                   float (*vertCos)[3],
2450                                                   CustomDataMask dataMask)
2451 {
2452         DerivedMesh *final;
2453
2454         mesh_calc_modifiers(scene, ob, vertCos, NULL, &final, 1, 0, 0, dataMask, -1, 0, 0);
2455
2456         return final;
2457 }
2458
2459 /***/
2460
2461 DerivedMesh *editbmesh_get_derived_cage_and_final(Scene *scene, Object *obedit, BMEditMesh *em, DerivedMesh **r_final,
2462                                                   CustomDataMask dataMask)
2463 {
2464         /* if there's no derived mesh or the last data mask used doesn't include
2465          * the data we need, rebuild the derived mesh
2466          */
2467         dataMask |= object_get_datamask(scene, obedit);
2468
2469         if (!em->derivedCage ||
2470             (em->lastDataMask & dataMask) != dataMask)
2471         {
2472                 editbmesh_build_data(scene, obedit, em, dataMask);
2473         }
2474
2475         *r_final = em->derivedFinal;
2476         if (em->derivedFinal) { BLI_assert(!(em->derivedFinal->dirty & DM_DIRTY_NORMALS)); }
2477         return em->derivedCage;
2478 }
2479
2480 DerivedMesh *editbmesh_get_derived_cage(Scene *scene, Object *obedit, BMEditMesh *em, CustomDataMask dataMask)
2481 {
2482         /* if there's no derived mesh or the last data mask used doesn't include
2483          * the data we need, rebuild the derived mesh
2484          */
2485         dataMask |= object_get_datamask(scene, obedit);
2486
2487         if (!em->derivedCage ||
2488             (em->lastDataMask & dataMask) != dataMask)
2489         {
2490                 editbmesh_build_data(scene, obedit, em, dataMask);
2491         }
2492
2493         return em->derivedCage;
2494 }
2495
2496 DerivedMesh *editbmesh_get_derived_base(Object *obedit, BMEditMesh *em)
2497 {
2498         return getEditDerivedBMesh(em, obedit, NULL);
2499 }
2500
2501 /***/
2502
2503 /* get derived mesh from an object, using editbmesh if available. */
2504 DerivedMesh *object_get_derived_final(Object *ob, const bool for_render)
2505 {
2506         Mesh *me = ob->data;
2507         BMEditMesh *em = me->edit_btmesh;
2508
2509         if (for_render) {
2510                 /* TODO(sergey): use proper derived render here in the future. */
2511                 return ob->derivedFinal;
2512         }
2513
2514         /* only return the editmesh if its from this object because
2515          * we don't a mesh from another object's modifier stack: T43122 */
2516         if (em && (em->ob == ob)) {
2517                 DerivedMesh *dm = em->derivedFinal;
2518                 return dm;
2519         }
2520
2521         return ob->derivedFinal;
2522 }
2523
2524
2525 /* UNUSED */
2526 #if 0
2527
2528 /* ********* For those who don't grasp derived stuff! (ton) :) *************** */
2529
2530 static void make_vertexcosnos__mapFunc(void *userData, int index, const float co[3],
2531                                        const float no_f[3], const short no_s[3])
2532 {
2533         DMCoNo *co_no = &((DMCoNo *)userData)[index];
2534
2535         /* check if we've been here before (normal should not be 0) */
2536         if (!is_zero_v3(co_no->no)) {
2537                 return;
2538         }
2539
2540         copy_v3_v3(co_no->co, co);
2541         if (no_f) {
2542                 copy_v3_v3(co_no->no, no_f);
2543         }
2544         else {
2545                 normal_short_to_float_v3(co_no->no, no_s);
2546         }
2547 }
2548
2549 /* always returns original amount me->totvert of vertices and normals, but fully deformed and subsurfered */
2550 /* this is needed for all code using vertexgroups (no subsurf support) */
2551 /* it stores the normals as floats, but they can still be scaled as shorts (32767 = unit) */
2552 /* in use now by vertex/weight paint and particle generating */
2553
2554 DMCoNo *mesh_get_mapped_verts_nors(Scene *scene, Object *ob)
2555 {
2556         Mesh *me = ob->data;
2557         DerivedMesh *dm;
2558         DMCoNo *vertexcosnos;
2559         
2560         /* lets prevent crashing... */
2561         if (ob->type != OB_MESH || me->totvert == 0)
2562                 return NULL;
2563         
2564         dm = mesh_get_derived_final(scene, ob, CD_MASK_BAREMESH | CD_MASK_ORIGINDEX);
2565         
2566         if (dm->foreachMappedVert) {
2567                 vertexcosnos = MEM_callocN(sizeof(DMCoNo) * me->totvert, "vertexcosnos map");
2568                 dm->foreachMappedVert(dm, make_vertexcosnos__mapFunc, vertexcosnos);
2569         }
2570         else {
2571                 DMCoNo *v_co_no = vertexcosnos = MEM_mallocN(sizeof(DMCoNo) * me->totvert, "vertexcosnos map");
2572                 int a;
2573                 for (a = 0; a < me->totvert; a++, v_co_no++) {
2574                         dm->getVertCo(dm, a, v_co_no->co);
2575                         dm->getVertNo(dm, a, v_co_no->no);
2576                 }
2577         }
2578         
2579         dm->release(dm);
2580         return vertexcosnos;
2581 }
2582
2583 #endif
2584
2585 /* same as above but for vert coords */
2586 typedef struct {
2587         float (*vertexcos)[3];
2588         BLI_bitmap *vertex_visit;
2589 } MappedUserData;
2590
2591 static void make_vertexcos__mapFunc(void *userData, int index, const float co[3],
2592                                     const float UNUSED(no_f[3]), const short UNUSED(no_s[3]))
2593 {
2594         MappedUserData *mappedData = (MappedUserData *)userData;
2595
2596         if (BLI_BITMAP_TEST(mappedData->vertex_visit, index) == 0) {
2597                 /* we need coord from prototype vertex, not from copies,
2598                  * assume they stored in the beginning of vertex array stored in DM
2599                  * (mirror modifier for eg does this) */
2600                 copy_v3_v3(mappedData->vertexcos[index], co);
2601                 BLI_BITMAP_ENABLE(mappedData->vertex_visit, index);
2602         }
2603 }
2604
2605 void mesh_get_mapped_verts_coords(DerivedMesh *dm, float (*r_cos)[3], const int totcos)
2606 {
2607         if (dm->foreachMappedVert) {
2608                 MappedUserData userData;
2609                 memset(r_cos, 0, sizeof(*r_cos) * totcos);
2610                 userData.vertexcos = r_cos;
2611                 userData.vertex_visit = BLI_BITMAP_NEW(totcos, "vertexcos flags");
2612                 dm->foreachMappedVert(dm, make_vertexcos__mapFunc, &userData, DM_FOREACH_NOP);
2613                 MEM_freeN(userData.vertex_visit);
2614         }
2615         else {
2616                 int i;
2617                 for (i = 0; i < totcos; i++) {
2618                         dm->getVertCo(dm, i, r_cos[i]);
2619                 }
2620         }
2621 }
2622
2623 /* ******************* GLSL ******************** */
2624
2625 typedef struct {
2626         float (*precomputedFaceNormals)[3];
2627         short (*precomputedLoopNormals)[4][3];
2628         MTFace *mtface;     /* texture coordinates */
2629         MFace *mface;       /* indices */
2630         MVert *mvert;       /* vertices & normals */
2631         float (*orco)[3];
2632         float (*tangent)[4];    /* destination */
2633         int numTessFaces;
2634
2635 } SGLSLMeshToTangent;
2636
2637 /* interface */
2638 #include "mikktspace.h"
2639
2640 static int GetNumFaces(const SMikkTSpaceContext *pContext)
2641 {
2642         SGLSLMeshToTangent *pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
2643         return pMesh->numTessFaces;
2644 }
2645
2646 static int GetNumVertsOfFace(const SMikkTSpaceContext *pContext, const int face_num)
2647 {
2648         SGLSLMeshToTangent *pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
2649         return pMesh->mface[face_num].v4 != 0 ? 4 : 3;
2650 }
2651
2652 static void GetPosition(const SMikkTSpaceContext *pContext, float r_co[3], const int face_num, const int vert_index)
2653 {
2654         //assert(vert_index >= 0 && vert_index < 4);
2655         SGLSLMeshToTangent *pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
2656         const float *co = pMesh->mvert[(&pMesh->mface[face_num].v1)[vert_index]].co;
2657         copy_v3_v3(r_co, co);
2658 }
2659
2660 static void GetTextureCoordinate(const SMikkTSpaceContext *pContext, float r_uv[2], const int face_num, const int vert_index)
2661 {
2662         //assert(vert_index >= 0 && vert_index < 4);
2663         SGLSLMeshToTangent *pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
2664
2665         if (pMesh->mtface != NULL) {
2666                 const float *uv = pMesh->mtface[face_num].uv[vert_index];
2667                 copy_v2_v2(r_uv, uv);
2668         }
2669         else {
2670                 const float *orco = pMesh->orco[(&pMesh->mface[face_num].v1)[vert_index]];
2671                 map_to_sphere(&r_uv[0], &r_uv[1], orco[0], orco[1], orco[2]);
2672         }
2673 }
2674
2675 static void GetNormal(const SMikkTSpaceContext *pContext, float r_no[3], const int face_num, const int vert_index)
2676 {
2677         //assert(vert_index >= 0 && vert_index < 4);
2678         SGLSLMeshToTangent *pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
2679         const bool smoothnormal = (pMesh->mface[face_num].flag & ME_SMOOTH) != 0;
2680
2681         if (pMesh->precomputedLoopNormals) {
2682                 normal_short_to_float_v3(r_no, pMesh->precomputedLoopNormals[face_num][vert_index]);
2683         }
2684         else if (!smoothnormal) {    // flat
2685                 if (pMesh->precomputedFaceNormals) {
2686                         copy_v3_v3(r_no, pMesh->precomputedFaceNormals[face_num]);
2687                 }
2688                 else {
2689                         MFace *mf = &pMesh->mface[face_num];
2690                         const float *p0 = pMesh->mvert[mf->v1].co;
2691                         const float *p1 = pMesh->mvert[mf->v2].co;
2692                         const float *p2 = pMesh->mvert[mf->v3].co;
2693
2694                         if (mf->v4) {
2695                                 const float *p3 = pMesh->mvert[mf->v4].co;
2696                                 normal_quad_v3(r_no, p0, p1, p2, p3);
2697                         }
2698                         else {
2699                                 normal_tri_v3(r_no, p0, p1, p2);
2700                         }
2701                 }
2702         }
2703         else {
2704                 const short *no = pMesh->mvert[(&pMesh->mface[face_num].v1)[vert_index]].no;
2705                 normal_short_to_float_v3(r_no, no);
2706         }
2707 }
2708
2709 static void SetTSpace(const SMikkTSpaceContext *pContext, const float fvTangent[3], const float fSign, const int face_num, const int iVert)
2710 {
2711         //assert(vert_index >= 0 && vert_index < 4);
2712         SGLSLMeshToTangent *pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
2713         float *pRes = pMesh->tangent[4 * face_num + iVert];
2714         copy_v3_v3(pRes, fvTangent);
2715         pRes[3] = fSign;
2716 }
2717
2718 void DM_add_tangent_layer(DerivedMesh *dm)
2719 {
2720         /* mesh vars */
2721         MVert *mvert;
2722         MTFace *mtface;
2723         MFace *mface;
2724         float (*orco)[3] = NULL, (*tangent)[4];
2725         int /* totvert, */ totface;
2726         float (*fnors)[3];
2727         short (*tlnors)[4][3];
2728
2729         if (CustomData_get_layer_index(&dm->faceData, CD_TANGENT) != -1)
2730                 return;
2731
2732         fnors = dm->getTessFaceDataArray(dm, CD_NORMAL);
2733         /* Note, we assume we do have tessellated loop normals at this point (in case it is object-enabled),
2734          * have to check this is valid...
2735          */
2736         tlnors = dm->getTessFaceDataArray(dm, CD_TESSLOOPNORMAL);
2737
2738         /* check we have all the needed layers */
2739         /* totvert = dm->getNumVerts(dm); */ /* UNUSED */
2740         totface = dm->getNumTessFaces(dm);
2741
2742         mvert = dm->getVertArray(dm);
2743         mface = dm->getTessFaceArray(dm);
2744         mtface = dm->getTessFaceDataArray(dm, CD_MTFACE);
2745
2746         if (!mtface) {
2747                 orco = dm->getVertDataArray(dm, CD_ORCO);
2748                 if (!orco)
2749                         return;
2750         }
2751         
2752         /* create tangent layer */
2753         DM_add_tessface_layer(dm, CD_TANGENT, CD_CALLOC, NULL);
2754         tangent = DM_get_tessface_data_layer(dm, CD_TANGENT);
2755         
2756         /* new computation method */
2757         {
2758                 SGLSLMeshToTangent mesh2tangent = {NULL};
2759                 SMikkTSpaceContext sContext = {NULL};
2760                 SMikkTSpaceInterface sInterface = {NULL};
2761
2762                 mesh2tangent.precomputedFaceNormals = fnors;
2763                 mesh2tangent.precomputedLoopNormals = tlnors;
2764                 mesh2tangent.mtface = mtface;
2765                 mesh2tangent.mface = mface;
2766                 mesh2tangent.mvert = mvert;
2767                 mesh2tangent.orco = orco;
2768                 mesh2tangent.tangent = tangent;
2769                 mesh2tangent.numTessFaces = totface;
2770
2771                 sContext.m_pUserData = &mesh2tangent;
2772                 sContext.m_pInterface = &sInterface;
2773                 sInterface.m_getNumFaces = GetNumFaces;
2774                 sInterface.m_getNumVerticesOfFace = GetNumVertsOfFace;
2775                 sInterface.m_getPosition = GetPosition;
2776                 sInterface.m_getTexCoord = GetTextureCoordinate;
2777                 sInterface.m_getNormal = GetNormal;
2778                 sInterface.m_setTSpaceBasic = SetTSpace;
2779
2780                 /* 0 if failed */
2781                 genTangSpaceDefault(&sContext);
2782         }
2783 }
2784
2785 void DM_calc_auto_bump_scale(DerivedMesh *dm)
2786 {
2787         /* int totvert = dm->getNumVerts(dm); */ /* UNUSED */
2788         int totface = dm->getNumTessFaces(dm);
2789
2790         MVert *mvert = dm->getVertArray(dm);
2791         MFace *mface = dm->getTessFaceArray(dm);
2792         MTFace *mtface = dm->getTessFaceDataArray(dm, CD_MTFACE);
2793
2794         if (mtface) {
2795                 double dsum = 0.0;
2796                 int nr_accumulated = 0;
2797                 int f;
2798
2799                 for (f = 0; f < totface; f++) {
2800                         {
2801                                 float *verts[4], *tex_coords[4];
2802                                 const int nr_verts = mface[f].v4 != 0 ? 4 : 3;
2803                                 bool is_degenerate;
2804                                 int i;
2805
2806                                 verts[0] = mvert[mface[f].v1].co; verts[1] = mvert[mface[f].v2].co; verts[2] = mvert[mface[f].v3].co;
2807                                 tex_coords[0] = mtface[f].uv[0]; tex_coords[1] = mtface[f].uv[1]; tex_coords[2] = mtface[f].uv[2];
2808                                 if (nr_verts == 4) {
2809                                         verts[3] = mvert[mface[f].v4].co;
2810                                         tex_coords[3] = mtface[f].uv[3];
2811                                 }
2812
2813                                 /* discard degenerate faces */
2814                                 is_degenerate = 0;
2815                                 if (equals_v3v3(verts[0], verts[1]) || equals_v3v3(verts[0], verts[2]) || equals_v3v3(verts[1], verts[2]) ||
2816                                     equals_v2v2(tex_coords[0], tex_coords[1]) || equals_v2v2(tex_coords[0], tex_coords[2]) || equals_v2v2(tex_coords[1], tex_coords[2]))
2817                                 {
2818                                         is_degenerate = 1;
2819                                 }
2820
2821                                 /* verify last vertex as well if this is a quad */
2822                                 if (is_degenerate == 0 && nr_verts == 4) {
2823                                         if (equals_v3v3(verts[3], verts[0]) || equals_v3v3(verts[3], verts[1]) || equals_v3v3(verts[3], verts[2]) ||
2824                                             equals_v2v2(tex_coords[3], tex_coords[0]) || equals_v2v2(tex_coords[3], tex_coords[1]) || equals_v2v2(tex_coords[3], tex_coords[2]))
2825                                         {
2826                                                 is_degenerate = 1;
2827                                         }
2828
2829                                         /* verify the winding is consistent */
2830                                         if (is_degenerate == 0) {
2831                                                 float prev_edge[2];
2832                                                 bool is_signed = 0;
2833                                                 sub_v2_v2v2(prev_edge, tex_coords[0], tex_coords[3]);
2834
2835                                                 i = 0;
2836                                                 while (is_degenerate == 0 && i < 4) {
2837                                                         float cur_edge[2], signed_area;
2838                                                         sub_v2_v2v2(cur_edge, tex_coords[(i + 1) & 0x3], tex_coords[i]);
2839                                                         signed_area = prev_edge[0] * cur_edge[1] - prev_edge[1] * cur_edge[0];
2840
2841                                                         if (i == 0) {
2842                                                                 is_signed = (signed_area < 0.0f) ? 1 : 0;
2843                                                         }
2844                                                         else if ((is_signed != 0) != (signed_area < 0.0f)) {
2845                                                                 is_degenerate = 1;
2846                                                         }
2847
2848                                                         if (is_degenerate == 0) {
2849                                                                 copy_v2_v2(prev_edge, cur_edge);
2850                                                                 i++;
2851                                                         }
2852                                                 }
2853                                         }
2854                                 }
2855
2856                                 /* proceed if not a degenerate face */
2857                                 if (is_degenerate == 0) {
2858                                         int nr_tris_to_pile = 0;
2859                                         /* quads split at shortest diagonal */
2860                                         int offs = 0;  /* initial triangulation is 0,1,2 and 0, 2, 3 */
2861                                         if (nr_verts == 4) {
2862                                                 float pos_len_diag0, pos_len_diag1;
2863
2864                                                 pos_len_diag0 = len_squared_v3v3(verts[2], verts[0]);
2865                                                 pos_len_diag1 = len_squared_v3v3(verts[3], verts[1]);
2866
2867                                                 if (pos_len_diag1 < pos_len_diag0) {
2868                                                         offs = 1;     // alter split
2869                                                 }
2870                                                 else if (pos_len_diag0 == pos_len_diag1) { /* do UV check instead */
2871                                                         float tex_len_diag0, tex_len_diag1;
2872
2873                                                         tex_len_diag0 = len_squared_v2v2(tex_coords[2], tex_coords[0]);
2874                                                         tex_len_diag1 = len_squared_v2v2(tex_coords[3], tex_coords[1]);
2875
2876                                                         if (tex_len_diag1 < tex_len_diag0) {
2877                                                                 offs = 1; /* alter split */
2878                                                         }
2879                                                 }
2880                                         }
2881                                         nr_tris_to_pile = nr_verts - 2;
2882                                         if (nr_tris_to_pile == 1 || nr_tris_to_pile == 2) {
2883                                                 const int indices[6] = {offs + 0, offs + 1, offs + 2, offs + 0, offs + 2, (offs + 3) & 0x3 };
2884                                                 int t;
2885                                                 for (t = 0; t < nr_tris_to_pile; t++) {
2886                                                         float f2x_area_uv;
2887                                                         const float *p0 = verts[indices[t * 3 + 0]];
2888                                                         const float *p1 = verts[indices[t * 3 + 1]];
2889                                                         const float *p2 = verts[indices[t * 3 + 2]];
2890
2891                                                         float edge_t0[2], edge_t1[2];
2892                                                         sub_v2_v2v2(edge_t0, tex_coords[indices[t * 3 + 1]], tex_coords[indices[t * 3 + 0]]);
2893                                                         sub_v2_v2v2(edge_t1, tex_coords[indices[t * 3 + 2]], tex_coords[indices[t * 3 + 0]]);
2894
2895                                                         f2x_area_uv = fabsf(edge_t0[0] * edge_t1[1] - edge_t0[1] * edge_t1[0]);
2896                                                         if (f2x_area_uv > FLT_EPSILON) {
2897                                                                 float norm[3], v0[3], v1[3], f2x_surf_area, fsurf_ratio;
2898                                                                 sub_v3_v3v3(v0, p1, p0);
2899                                                                 sub_v3_v3v3(v1, p2, p0);
2900                                                                 cross_v3_v3v3(norm, v0, v1);
2901
2902                                                                 f2x_surf_area = len_v3(norm);
2903                                                                 fsurf_ratio = f2x_surf_area / f2x_area_uv;  /* tri area divided by texture area */
2904
2905                                                                 nr_accumulated++;
2906                                                                 dsum += (double)(fsurf_ratio);
2907                                                         }
2908                                                 }
2909                                         }
2910                                 }
2911                         }
2912                 }
2913
2914                 /* finalize */
2915                 {
2916                         const float avg_area_ratio = (nr_accumulated > 0) ? ((float)(dsum / nr_accumulated)) : 1.0f;
2917                         const float use_as_render_bump_scale = sqrtf(avg_area_ratio);       // use width of average surface ratio as your bump scale
2918                         dm->auto_bump_scale = use_as_render_bump_scale;
2919                 }
2920         }
2921         else {
2922                 dm->auto_bump_scale = 1.0f;
2923         }
2924 }
2925
2926 void DM_vertex_attributes_from_gpu(DerivedMesh *dm, GPUVertexAttribs *gattribs, DMVertexAttribs *attribs)
2927 {
2928         CustomData *vdata, *fdata, *tfdata = NULL;
2929         int a, b, layer;
2930
2931         /* From the layers requested by the GLSL shader, figure out which ones are
2932          * actually available for this derivedmesh, and retrieve the pointers */
2933
2934         memset(attribs, 0, sizeof(DMVertexAttribs));
2935
2936         vdata = &dm->vertData;
2937         fdata = tfdata = dm->getTessFaceDataLayout(dm);
2938         
2939         /* calc auto bump scale if necessary */
2940         if (dm->auto_bump_scale <= 0.0f)
2941                 DM_calc_auto_bump_scale(dm);
2942
2943         /* add a tangent layer if necessary */
2944         for (b = 0; b < gattribs->totlayer; b++)
2945                 if (gattribs->layer[b].type == CD_TANGENT)
2946                         if (CustomData_get_layer_index(fdata, CD_TANGENT) == -1)
2947                                 DM_add_tangent_layer(dm);
2948
2949         for (b = 0; b < gattribs->totlayer; b++) {
2950                 if (gattribs->layer[b].type == CD_MTFACE) {
2951                         /* uv coordinates */
2952                         if (dm->type == DM_TYPE_EDITBMESH) {
2953                                 /* exception .. */
2954                                 CustomData *ldata = dm->getLoopDataLayout(dm);
2955
2956                                 if (gattribs->layer[b].name[0])
2957                                         layer = CustomData_get_named_layer_index(ldata, CD_MLOOPUV,
2958                                                                                  gattribs->layer[b].name);
2959                                 else
2960                                         layer = CustomData_get_active_layer_index(ldata, CD_MLOOPUV);
2961
2962                                 a = attribs->tottface++;
2963
2964                                 if (layer != -1) {
2965                                         attribs->tface[a].array = NULL;
2966                                         attribs->tface[a].em_offset = ldata->layers[layer].offset;
2967                                 }
2968                                 else {
2969                                         attribs->tface[a].array = NULL;
2970                                         attribs->tface[a].em_offset = -1;
2971                                 }
2972
2973                                 attribs->tface[a].gl_index = gattribs->layer[b].glindex;
2974                                 attribs->tface[a].gl_texco = gattribs->layer[b].gltexco;
2975                         }
2976                         else {
2977                                 if (gattribs->layer[b].name[0])
2978                                         layer = CustomData_get_named_layer_index(tfdata, CD_MTFACE,
2979                                                                                  gattribs->layer[b].name);
2980                                 else
2981                                         layer = CustomData_get_active_layer_index(tfdata, CD_MTFACE);
2982
2983                                 a = attribs->tottface++;
2984
2985                                 if (layer != -1) {
2986                                         attribs->tface[a].array = tfdata->layers[layer].data;
2987                                         attribs->tface[a].em_offset = tfdata->layers[layer].offset;
2988                                 }
2989                                 else {
2990                                         attribs->tface[a].array = NULL;
2991                                         attribs->tface[a].em_offset = -1;
2992                                 }
2993
2994                                 attribs->tface[a].gl_index = gattribs->layer[b].glindex;
2995                                 attribs->tface[a].gl_texco = gattribs->layer[b].gltexco;
2996                         }
2997                 }
2998                 else if (gattribs->layer[b].type == CD_MCOL) {
2999                         if (dm->type == DM_TYPE_EDITBMESH) {
3000                                 /* exception .. */
3001                                 CustomData *ldata = dm->getLoopDataLayout(dm);
3002
3003                                 if (gattribs->layer[b].name[0])
3004                                         layer = CustomData_get_named_layer_index(ldata, CD_MLOOPCOL,
3005                                                                                  gattribs->layer[b].name);
3006                                 else
3007                                         layer = CustomData_get_active_layer_index(ldata, CD_MLOOPCOL);
3008
3009                                 a = attribs->totmcol++;
3010
3011                                 if (layer != -1) {
3012                                         attribs->mcol[a].array = NULL;
3013                                         /* odd, store the offset for a different layer type here, but editmode draw code expects it */
3014                                         attribs->mcol[a].em_offset = ldata->layers[layer].offset;
3015                                 }
3016                                 else {
3017                                         attribs->mcol[a].array = NULL;
3018                                         attribs->mcol[a].em_offset = -1;
3019                                 }
3020
3021                                 attribs->mcol[a].gl_index = gattribs->layer[b].glindex;
3022                         }
3023                         else {
3024                                 /* vertex colors */
3025                                 if (gattribs->layer[b].name[0])
3026                                         layer = CustomData_get_named_layer_index(tfdata, CD_MCOL,
3027                                                                                  gattribs->layer[b].name);
3028                                 else
3029                                         layer = CustomData_get_active_layer_index(tfdata, CD_MCOL);
3030
3031                                 a = attribs->totmcol++;
3032
3033                                 if (layer != -1) {
3034                                         attribs->mcol[a].array = tfdata->layers[layer].data;
3035                                         /* odd, store the offset for a different layer type here, but editmode draw code expects it */
3036                                         attribs->mcol[a].em_offset = tfdata->layers[layer].offset;
3037                                 }
3038                                 else {
3039                                         attribs->mcol[a].array = NULL;
3040                                         attribs->mcol[a].em_offset = -1;
3041                                 }
3042
3043                                 attribs->mcol[a].gl_index = gattribs->layer[b].glindex;
3044                         }
3045                 }
3046                 else if (gattribs->layer[b].type == CD_TANGENT) {
3047                         /* tangents */
3048                         layer = CustomData_get_layer_index(fdata, CD_TANGENT);
3049
3050                         attribs->tottang = 1;
3051
3052                         if (layer != -1) {
3053                                 attribs->tang.array = fdata->layers[layer].data;
3054                                 attribs->tang.em_offset = fdata->layers[layer].offset;
3055                         }
3056                         else {
3057                                 attribs->tang.array = NULL;
3058                                 attribs->tang.em_offset = -1;
3059                         }
3060
3061                         attribs->tang.gl_index = gattribs->layer[b].glindex;
3062                 }
3063                 else if (gattribs->layer[b].type == CD_ORCO) {
3064                         /* original coordinates */
3065                         layer = CustomData_get_layer_index(vdata, CD_ORCO);
3066                         attribs->totorco = 1;
3067
3068                         if (layer != -1) {
3069                                 attribs->orco.array = vdata->layers[layer].data;
3070                                 attribs->orco.em_offset = vdata->layers[layer].offset;
3071                         }
3072                         else {
3073                                 attribs->orco.array = NULL;
3074                                 attribs->orco.em_offset = -1;
3075                         }
3076
3077                         attribs->orco.gl_index = gattribs->layer[b].glindex;
3078                         attribs->orco.gl_texco = gattribs->layer[b].gltexco;
3079                 }