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