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