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