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