Merging r57816 through r57896 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         return CustomData_get(&dm->vertData, index, type);
660 }
661
662 void *DM_get_edge_data(DerivedMesh *dm, int index, int type)
663 {
664         return CustomData_get(&dm->edgeData, index, type);
665 }
666
667 void *DM_get_tessface_data(DerivedMesh *dm, int index, int type)
668 {
669         return CustomData_get(&dm->faceData, index, type);
670 }
671
672 void *DM_get_poly_data(DerivedMesh *dm, int index, int type)
673 {
674         return CustomData_get(&dm->polyData, index, type);
675 }
676
677
678 void *DM_get_vert_data_layer(DerivedMesh *dm, int type)
679 {
680         if (type == CD_MVERT)
681                 return dm->getVertArray(dm);
682
683         return CustomData_get_layer(&dm->vertData, type);
684 }
685
686 void *DM_get_edge_data_layer(DerivedMesh *dm, int type)
687 {
688         if (type == CD_MEDGE)
689                 return dm->getEdgeArray(dm);
690
691         return CustomData_get_layer(&dm->edgeData, type);
692 }
693
694 void *DM_get_tessface_data_layer(DerivedMesh *dm, int type)
695 {
696         if (type == CD_MFACE)
697                 return dm->getTessFaceArray(dm);
698
699         return CustomData_get_layer(&dm->faceData, type);
700 }
701
702 void *DM_get_poly_data_layer(DerivedMesh *dm, int type)
703 {
704         return CustomData_get_layer(&dm->polyData, type);
705 }
706
707 void *DM_get_loop_data_layer(DerivedMesh *dm, int type)
708 {
709         return CustomData_get_layer(&dm->loopData, type);
710 }
711
712 void DM_set_vert_data(DerivedMesh *dm, int index, int type, void *data)
713 {
714         CustomData_set(&dm->vertData, index, type, data);
715 }
716
717 void DM_set_edge_data(DerivedMesh *dm, int index, int type, void *data)
718 {
719         CustomData_set(&dm->edgeData, index, type, data);
720 }
721
722 void DM_set_tessface_data(DerivedMesh *dm, int index, int type, void *data)
723 {
724         CustomData_set(&dm->faceData, index, type, data);
725 }
726
727 void DM_copy_vert_data(DerivedMesh *source, DerivedMesh *dest,
728                        int source_index, int dest_index, int count)
729 {
730         CustomData_copy_data(&source->vertData, &dest->vertData,
731                              source_index, dest_index, count);
732 }
733
734 void DM_copy_edge_data(DerivedMesh *source, DerivedMesh *dest,
735                        int source_index, int dest_index, int count)
736 {
737         CustomData_copy_data(&source->edgeData, &dest->edgeData,
738                              source_index, dest_index, count);
739 }
740
741 void DM_copy_tessface_data(DerivedMesh *source, DerivedMesh *dest,
742                            int source_index, int dest_index, int count)
743 {
744         CustomData_copy_data(&source->faceData, &dest->faceData,
745                              source_index, dest_index, count);
746 }
747
748 void DM_copy_loop_data(DerivedMesh *source, DerivedMesh *dest,
749                        int source_index, int dest_index, int count)
750 {
751         CustomData_copy_data(&source->loopData, &dest->loopData,
752                              source_index, dest_index, count);
753 }
754
755 void DM_copy_poly_data(DerivedMesh *source, DerivedMesh *dest,
756                        int source_index, int dest_index, int count)
757 {
758         CustomData_copy_data(&source->polyData, &dest->polyData,
759                              source_index, dest_index, count);
760 }
761
762 void DM_free_vert_data(struct DerivedMesh *dm, int index, int count)
763 {
764         CustomData_free_elem(&dm->vertData, index, count);
765 }
766
767 void DM_free_edge_data(struct DerivedMesh *dm, int index, int count)
768 {
769         CustomData_free_elem(&dm->edgeData, index, count);
770 }
771
772 void DM_free_tessface_data(struct DerivedMesh *dm, int index, int count)
773 {
774         CustomData_free_elem(&dm->faceData, index, count);
775 }
776
777 void DM_free_loop_data(struct DerivedMesh *dm, int index, int count)
778 {
779         CustomData_free_elem(&dm->loopData, index, count);
780 }
781
782 void DM_free_poly_data(struct DerivedMesh *dm, int index, int count)
783 {
784         CustomData_free_elem(&dm->polyData, index, count);
785 }
786
787 void DM_interp_vert_data(DerivedMesh *source, DerivedMesh *dest,
788                          int *src_indices, float *weights,
789                          int count, int dest_index)
790 {
791         CustomData_interp(&source->vertData, &dest->vertData, src_indices,
792                           weights, NULL, count, dest_index);
793 }
794
795 void DM_interp_edge_data(DerivedMesh *source, DerivedMesh *dest,
796                          int *src_indices,
797                          float *weights, EdgeVertWeight *vert_weights,
798                          int count, int dest_index)
799 {
800         CustomData_interp(&source->edgeData, &dest->edgeData, src_indices,
801                           weights, (float *)vert_weights, count, dest_index);
802 }
803
804 void DM_interp_tessface_data(DerivedMesh *source, DerivedMesh *dest,
805                              int *src_indices,
806                              float *weights, FaceVertWeight *vert_weights,
807                              int count, int dest_index)
808 {
809         CustomData_interp(&source->faceData, &dest->faceData, src_indices,
810                           weights, (float *)vert_weights, count, dest_index);
811 }
812
813 void DM_swap_tessface_data(DerivedMesh *dm, int index, const int *corner_indices)
814 {
815         CustomData_swap(&dm->faceData, index, corner_indices);
816 }
817
818 void DM_interp_loop_data(DerivedMesh *source, DerivedMesh *dest,
819                          int *src_indices,
820                          float *weights, int count, int dest_index)
821 {
822         CustomData_interp(&source->loopData, &dest->loopData, src_indices,
823                           weights, NULL, count, dest_index);
824 }
825
826 void DM_interp_poly_data(DerivedMesh *source, DerivedMesh *dest,
827                          int *src_indices,
828                          float *weights, int count, int dest_index)
829 {
830         CustomData_interp(&source->polyData, &dest->polyData, src_indices,
831                           weights, NULL, count, dest_index);
832 }
833
834 ///
835 DerivedMesh *mesh_create_derived(Mesh *me, Object *ob, float (*vertCos)[3])
836 {
837         DerivedMesh *dm = CDDM_from_mesh(me, ob);
838         
839         if (!dm)
840                 return NULL;
841         
842         if (vertCos) {
843                 CDDM_apply_vert_coords(dm, vertCos);
844         }
845
846         return dm;
847 }
848
849 DerivedMesh *mesh_create_derived_for_modifier(Scene *scene, Object *ob, 
850                                               ModifierData *md, int build_shapekey_layers)
851 {
852         Mesh *me = ob->data;
853         ModifierTypeInfo *mti = modifierType_getInfo(md->type);
854         DerivedMesh *dm;
855         KeyBlock *kb;
856
857         md->scene = scene;
858         
859         if (!(md->mode & eModifierMode_Realtime)) return NULL;
860         if (mti->isDisabled && mti->isDisabled(md, 0)) return NULL;
861         
862         if (build_shapekey_layers && me->key && (kb = BLI_findlink(&me->key->block, ob->shapenr - 1))) {
863                 BKE_key_convert_to_mesh(kb, me);
864         }
865         
866         if (mti->type == eModifierTypeType_OnlyDeform) {
867                 int numVerts;
868                 float (*deformedVerts)[3] = BKE_mesh_vertexCos_get(me, &numVerts);
869
870                 modwrap_deformVerts(md, ob, NULL, deformedVerts, numVerts, 0);
871                 dm = mesh_create_derived(me, ob, deformedVerts);
872
873                 if (build_shapekey_layers)
874                         add_shapekey_layers(dm, me, ob);
875                 
876                 MEM_freeN(deformedVerts);
877         }
878         else {
879                 DerivedMesh *tdm = mesh_create_derived(me, ob, NULL);
880
881                 if (build_shapekey_layers)
882                         add_shapekey_layers(tdm, me, ob);
883                 
884                 dm = modwrap_applyModifier(md, ob, tdm, 0);
885
886                 if (tdm != dm) tdm->release(tdm);
887         }
888
889         return dm;
890 }
891
892 static float (*get_editbmesh_orco_verts(BMEditMesh *em))[3]
893 {
894         BMIter iter;
895         BMVert *eve;
896         float (*orco)[3];
897         int i;
898
899         /* these may not really be the orco's, but it's only for preview.
900          * could be solver better once, but isn't simple */
901         
902         orco = MEM_mallocN(sizeof(float) * 3 * em->bm->totvert, "BMEditMesh Orco");
903
904         BM_ITER_MESH_INDEX (eve, &iter, em->bm, BM_VERTS_OF_MESH, i) {
905                 copy_v3_v3(orco[i], eve->co);
906         }
907         
908         return orco;
909 }
910
911 /* orco custom data layer */
912 static float (*get_orco_coords_dm(Object *ob, BMEditMesh *em, int layer, int *free))[3]
913 {
914         *free = 0;
915
916         if (layer == CD_ORCO) {
917                 /* get original coordinates */
918                 *free = 1;
919
920                 if (em)
921                         return get_editbmesh_orco_verts(em);
922                 else
923                         return BKE_mesh_orco_verts_get(ob);
924         }
925         else if (layer == CD_CLOTH_ORCO) {
926                 /* apply shape key for cloth, this should really be solved
927                  * by a more flexible customdata system, but not simple */
928                 if (!em) {
929                         ClothModifierData *clmd = (ClothModifierData *)modifiers_findByType(ob, eModifierType_Cloth);
930                         KeyBlock *kb = BKE_keyblock_from_key(BKE_key_from_object(ob), clmd->sim_parms->shapekey_rest);
931
932                         if (kb->data)
933                                 return kb->data;
934                 }
935
936                 return NULL;
937         }
938
939         return NULL;
940 }
941
942 static DerivedMesh *create_orco_dm(Object *ob, Mesh *me, BMEditMesh *em, int layer)
943 {
944         DerivedMesh *dm;
945         float (*orco)[3];
946         int free;
947
948         if (em) dm = CDDM_from_editbmesh(em, FALSE, FALSE);
949         else dm = CDDM_from_mesh(me, ob);
950
951         orco = get_orco_coords_dm(ob, em, layer, &free);
952
953         if (orco) {
954                 CDDM_apply_vert_coords(dm, orco);
955                 if (free) MEM_freeN(orco);
956         }
957
958         return dm;
959 }
960
961 static void add_orco_dm(Object *ob, BMEditMesh *em, DerivedMesh *dm,
962                         DerivedMesh *orcodm, int layer)
963 {
964         float (*orco)[3], (*layerorco)[3];
965         int totvert, free;
966
967         totvert = dm->getNumVerts(dm);
968
969         if (orcodm) {
970                 orco = MEM_callocN(sizeof(float) * 3 * totvert, "dm orco");
971                 free = 1;
972
973                 if (orcodm->getNumVerts(orcodm) == totvert)
974                         orcodm->getVertCos(orcodm, orco);
975                 else
976                         dm->getVertCos(dm, orco);
977         }
978         else
979                 orco = get_orco_coords_dm(ob, em, layer, &free);
980
981         if (orco) {
982                 if (layer == CD_ORCO)
983                         BKE_mesh_orco_verts_transform(ob->data, orco, totvert, 0);
984
985                 if (!(layerorco = DM_get_vert_data_layer(dm, layer))) {
986                         DM_add_vert_layer(dm, layer, CD_CALLOC, NULL);
987                         layerorco = DM_get_vert_data_layer(dm, layer);
988                 }
989
990                 memcpy(layerorco, orco, sizeof(float) * 3 * totvert);
991                 if (free) MEM_freeN(orco);
992         }
993 }
994
995 /* weight paint colors */
996
997 /* Something of a hack, at the moment deal with weightpaint
998  * by tucking into colors during modifier eval, only in
999  * wpaint mode. Works ok but need to make sure recalc
1000  * happens on enter/exit wpaint.
1001  */
1002
1003 void weight_to_rgb(float r_rgb[3], const float weight)
1004 {
1005         const float blend = ((weight / 2.0f) + 0.5f);
1006
1007         if (weight <= 0.25f) {    /* blue->cyan */
1008                 r_rgb[0] = 0.0f;
1009                 r_rgb[1] = blend * weight * 4.0f;
1010                 r_rgb[2] = blend;
1011         }
1012         else if (weight <= 0.50f) {  /* cyan->green */
1013                 r_rgb[0] = 0.0f;
1014                 r_rgb[1] = blend;
1015                 r_rgb[2] = blend * (1.0f - ((weight - 0.25f) * 4.0f));
1016         }
1017         else if (weight <= 0.75f) {  /* green->yellow */
1018                 r_rgb[0] = blend * ((weight - 0.50f) * 4.0f);
1019                 r_rgb[1] = blend;
1020                 r_rgb[2] = 0.0f;
1021         }
1022         else if (weight <= 1.0f) {  /* yellow->red */
1023                 r_rgb[0] = blend;
1024                 r_rgb[1] = blend * (1.0f - ((weight - 0.75f) * 4.0f));
1025                 r_rgb[2] = 0.0f;
1026         }
1027         else {
1028                 /* exceptional value, unclamped or nan,
1029                  * avoid uninitialized memory use */
1030                 r_rgb[0] = 1.0f;
1031                 r_rgb[1] = 0.0f;
1032                 r_rgb[2] = 1.0f;
1033         }
1034 }
1035
1036 /* draw_flag's for calc_weightpaint_vert_color */
1037 enum {
1038         /* only one of these should be set, keep first (for easy bit-shifting) */
1039         CALC_WP_GROUP_USER_ACTIVE   = (1 << 1),
1040         CALC_WP_GROUP_USER_ALL      = (1 << 2),
1041
1042         CALC_WP_MULTIPAINT          = (1 << 3),
1043         CALC_WP_AUTO_NORMALIZE      = (1 << 4)
1044 };
1045
1046 typedef struct DMWeightColorInfo {
1047         const ColorBand *coba;
1048         const char *alert_color;
1049 } DMWeightColorInfo;
1050
1051
1052 static int dm_drawflag_calc(ToolSettings *ts)
1053 {
1054         return ((ts->multipaint ? CALC_WP_MULTIPAINT :
1055                                   /* CALC_WP_GROUP_USER_ACTIVE or CALC_WP_GROUP_USER_ALL*/
1056                                   (1 << ts->weightuser)) |
1057                 (ts->auto_normalize ? CALC_WP_AUTO_NORMALIZE : 0));
1058 }
1059
1060 static void weightpaint_color(unsigned char r_col[4], DMWeightColorInfo *dm_wcinfo, const float input)
1061 {
1062         float colf[4];
1063
1064         if (dm_wcinfo && dm_wcinfo->coba) {
1065                 do_colorband(dm_wcinfo->coba, input, colf);
1066         }
1067         else {
1068                 weight_to_rgb(colf, input);
1069         }
1070
1071         /* don't use rgb_float_to_uchar() here because
1072          * the resulting float doesn't need 0-1 clamp check */
1073         r_col[0] = (unsigned char)(colf[0] * 255.0f);
1074         r_col[1] = (unsigned char)(colf[1] * 255.0f);
1075         r_col[2] = (unsigned char)(colf[2] * 255.0f);
1076         r_col[3] = 255;
1077 }
1078
1079
1080 static void calc_weightpaint_vert_color(
1081         unsigned char r_col[4],
1082         MDeformVert *dv, 
1083         DMWeightColorInfo *dm_wcinfo,
1084         const int defbase_tot, const int defbase_act,
1085         const bool *defbase_sel, const int defbase_sel_tot,
1086         const int draw_flag)
1087 {
1088         float input = 0.0f;
1089         
1090         bool show_alert_color = false;
1091
1092         if ((defbase_sel_tot > 1) && (draw_flag & CALC_WP_MULTIPAINT)) {
1093                 /* Multi-Paint feature */
1094                 bool was_a_nonzero = false;
1095                 unsigned int i;
1096
1097                 MDeformWeight *dw = dv->dw;
1098                 for (i = dv->totweight; i != 0; i--, dw++) {
1099                         /* in multipaint, get the average if auto normalize is inactive
1100                          * get the sum if it is active */
1101                         if (dw->def_nr < defbase_tot) {
1102                                 if (defbase_sel[dw->def_nr]) {
1103                                         if (dw->weight) {
1104                                                 input += dw->weight;
1105                                                 was_a_nonzero = true;
1106                                         }
1107                                 }
1108                         }
1109                 }
1110
1111                 /* make it black if the selected groups have no weight on a vertex */
1112                 if (was_a_nonzero == false) {
1113                         show_alert_color = true;
1114                 }
1115                 else if ((draw_flag & CALC_WP_AUTO_NORMALIZE) == FALSE) {
1116                         input /= defbase_sel_tot; /* get the average */
1117                 }
1118         }
1119         else {
1120                 /* default, non tricky behavior */
1121                 input = defvert_find_weight(dv, defbase_act);
1122
1123                 if (draw_flag & CALC_WP_GROUP_USER_ACTIVE) {
1124                         if (input == 0.0f) {
1125                                 show_alert_color = true;
1126                         }
1127                 }
1128                 else if (draw_flag & CALC_WP_GROUP_USER_ALL) {
1129                         if (input == 0.0f) {
1130                                 show_alert_color = defvert_is_weight_zero(dv, defbase_tot);
1131                         }
1132                 }
1133         }
1134
1135         if (show_alert_color == false) {
1136                 CLAMP(input, 0.0f, 1.0f);
1137                 weightpaint_color(r_col, dm_wcinfo, input);
1138         }
1139         else {
1140                 copy_v3_v3_char((char *)r_col, dm_wcinfo->alert_color);
1141                 r_col[3] = 255;
1142         }
1143 }
1144
1145 static DMWeightColorInfo G_dm_wcinfo;
1146
1147 void vDM_ColorBand_store(const ColorBand *coba, const char alert_color[4])
1148 {
1149         G_dm_wcinfo.coba        = coba;
1150         G_dm_wcinfo.alert_color = alert_color;
1151 }
1152
1153 /* return an array of vertex weight colors, caller must free.
1154  *
1155  * note that we could save some memory and allocate RGB only but then we'd need to
1156  * re-arrange the colors when copying to the face since MCol has odd ordering,
1157  * so leave this as is - campbell */
1158 static void calc_weightpaint_vert_array(Object *ob, DerivedMesh *dm, int const draw_flag, DMWeightColorInfo *dm_wcinfo,
1159                                         unsigned char (*r_wtcol_v)[4])
1160 {
1161         MDeformVert *dv = DM_get_vert_data_layer(dm, CD_MDEFORMVERT);
1162         int numVerts = dm->getNumVerts(dm);
1163
1164         if (dv) {
1165                 unsigned char (*wc)[4] = r_wtcol_v;
1166                 unsigned int i;
1167
1168                 /* variables for multipaint */
1169                 const int defbase_tot = BLI_countlist(&ob->defbase);
1170                 const int defbase_act = ob->actdef - 1;
1171
1172                 int defbase_sel_tot = 0;
1173                 bool *defbase_sel = NULL;
1174
1175                 if (draw_flag & CALC_WP_MULTIPAINT) {
1176                         defbase_sel = BKE_objdef_selected_get(ob, defbase_tot, &defbase_sel_tot);
1177                 }
1178
1179                 for (i = numVerts; i != 0; i--, wc++, dv++) {
1180                         calc_weightpaint_vert_color((unsigned char *)wc, dv, dm_wcinfo, defbase_tot, defbase_act, defbase_sel, defbase_sel_tot, draw_flag);
1181                 }
1182
1183                 if (defbase_sel) {
1184                         MEM_freeN(defbase_sel);
1185                 }
1186         }
1187         else {
1188                 int col_i;
1189                 if (draw_flag & (CALC_WP_GROUP_USER_ACTIVE | CALC_WP_GROUP_USER_ALL)) {
1190                         col_i = 0;
1191                 }
1192                 else {
1193                         weightpaint_color((unsigned char *)&col_i, dm_wcinfo, 0.0f);
1194                 }
1195                 fill_vn_i((int *)r_wtcol_v, numVerts, col_i);
1196         }
1197 }
1198
1199 /* return an array of vertex weight colors from given weights, caller must free.
1200  *
1201  * note that we could save some memory and allocate RGB only but then we'd need to
1202  * re-arrange the colors when copying to the face since MCol has odd ordering,
1203  * so leave this as is - campbell */
1204 static void calc_colors_from_weights_array(const int num, const float *weights,
1205                                            unsigned char (*r_wtcol_v)[4])
1206 {
1207         unsigned char (*wc)[4] = r_wtcol_v;
1208         int i;
1209
1210         for (i = 0; i < num; i++, wc++, weights++) {
1211                 weightpaint_color((unsigned char *)wc, NULL, *weights);
1212         }
1213 }
1214
1215 void DM_update_weight_mcol(Object *ob, DerivedMesh *dm, int const draw_flag,
1216                            float *weights, int num, const int *indices)
1217 {
1218         BMEditMesh *em = (dm->type == DM_TYPE_EDITBMESH) ? BKE_editmesh_from_object(ob) : NULL;
1219         unsigned char (*wtcol_v)[4];
1220         int numVerts = dm->getNumVerts(dm);
1221         int i;
1222
1223         if (em) {
1224                 BKE_editmesh_color_ensure(em, BM_VERT);
1225                 wtcol_v = em->derivedVertColor;
1226         }
1227         else {
1228                 wtcol_v = MEM_mallocN(sizeof(*wtcol_v) * numVerts, __func__);
1229         }
1230
1231         /* Weights are given by caller. */
1232         if (weights) {
1233                 float *w = weights;
1234                 /* If indices is not NULL, it means we do not have weights for all vertices,
1235                  * so we must create them (and set them to zero)... */
1236                 if (indices) {
1237                         w = MEM_callocN(sizeof(float) * numVerts, "Temp weight array DM_update_weight_mcol");
1238                         i = num;
1239                         while (i--)
1240                                 w[indices[i]] = weights[i];
1241                 }
1242
1243                 /* Convert float weights to colors. */
1244                 calc_colors_from_weights_array(numVerts, w, wtcol_v);
1245
1246                 if (indices)
1247                         MEM_freeN(w);
1248         }
1249         else {
1250                 /* No weights given, take them from active vgroup(s). */
1251                 calc_weightpaint_vert_array(ob, dm, draw_flag, &G_dm_wcinfo, wtcol_v);
1252         }
1253
1254         if (dm->type == DM_TYPE_EDITBMESH) {
1255                 /* editmesh draw function checks spesifically for this */
1256         }
1257         else {
1258                 const int dm_totpoly = dm->getNumPolys(dm);
1259                 const int dm_totloop = dm->getNumLoops(dm);
1260                 unsigned char(*wtcol_l)[4] = CustomData_get_layer(dm->getLoopDataLayout(dm), CD_PREVIEW_MLOOPCOL);
1261                 MLoop *mloop = dm->getLoopArray(dm), *ml;
1262                 MPoly *mp = dm->getPolyArray(dm);
1263                 int l_index;
1264                 int j;
1265
1266                 /* now add to loops, so the data can be passed through the modifier stack */
1267                 /* If no CD_PREVIEW_MLOOPCOL existed yet, we have to add a new one! */
1268                 if (!wtcol_l) {
1269                         wtcol_l = MEM_mallocN(sizeof(*wtcol_l) * dm_totloop, __func__);
1270                         CustomData_add_layer(&dm->loopData, CD_PREVIEW_MLOOPCOL, CD_ASSIGN, wtcol_l, dm_totloop);
1271                 }
1272
1273                 l_index = 0;
1274                 for (i = 0; i < dm_totpoly; i++, mp++) {
1275                         ml = mloop + mp->loopstart;
1276
1277                         for (j = 0; j < mp->totloop; j++, ml++, l_index++) {
1278                                 copy_v4_v4_char((char *)&wtcol_l[l_index],
1279                                                 (char *)&wtcol_v[ml->v]);
1280                         }
1281                 }
1282                 MEM_freeN(wtcol_v);
1283
1284                 dm->dirty |= DM_DIRTY_TESS_CDLAYERS;
1285         }
1286 }
1287
1288 static void DM_update_statvis_color(Scene *scene, Object *ob, DerivedMesh *dm)
1289 {
1290         BMEditMesh *em = BKE_editmesh_from_object(ob);
1291
1292         BKE_editmesh_statvis_calc(em, dm, &scene->toolsettings->statvis);
1293 }
1294
1295 static void shapekey_layers_to_keyblocks(DerivedMesh *dm, Mesh *me, int actshape_uid)
1296 {
1297         KeyBlock *kb;
1298         int i, j, tot;
1299         
1300         if (!me->key)
1301                 return;
1302         
1303         tot = CustomData_number_of_layers(&dm->vertData, CD_SHAPEKEY);
1304         for (i = 0; i < tot; i++) {
1305                 CustomDataLayer *layer = &dm->vertData.layers[CustomData_get_layer_index_n(&dm->vertData, CD_SHAPEKEY, i)];
1306                 float (*cos)[3], (*kbcos)[3];
1307                 
1308                 for (kb = me->key->block.first; kb; kb = kb->next) {
1309                         if (kb->uid == layer->uid)
1310                                 break;
1311                 }
1312                 
1313                 if (!kb) {
1314                         kb = BKE_keyblock_add(me->key, layer->name);
1315                         kb->uid = layer->uid;
1316                 }
1317                 
1318                 if (kb->data)
1319                         MEM_freeN(kb->data);
1320                 
1321                 cos = CustomData_get_layer_n(&dm->vertData, CD_SHAPEKEY, i);
1322                 kb->totelem = dm->numVertData;
1323
1324                 kb->data = kbcos = MEM_mallocN(sizeof(float) * 3 * kb->totelem, "kbcos DerivedMesh.c");
1325                 if (kb->uid == actshape_uid) {
1326                         MVert *mvert = dm->getVertArray(dm);
1327                         
1328                         for (j = 0; j < dm->numVertData; j++, kbcos++, mvert++) {
1329                                 copy_v3_v3(*kbcos, mvert->co);
1330                         }
1331                 }
1332                 else {
1333                         for (j = 0; j < kb->totelem; j++, cos++, kbcos++) {
1334                                 copy_v3_v3(*kbcos, *cos);
1335                         }
1336                 }
1337         }
1338         
1339         for (kb = me->key->block.first; kb; kb = kb->next) {
1340                 if (kb->totelem != dm->numVertData) {
1341                         if (kb->data)
1342                                 MEM_freeN(kb->data);
1343                         
1344                         kb->totelem = dm->numVertData;
1345                         kb->data = MEM_callocN(sizeof(float) * 3 * kb->totelem, "kb->data derivedmesh.c");
1346                         fprintf(stderr, "%s: lost a shapekey layer: '%s'! (bmesh internal error)\n", __func__, kb->name);
1347                 }
1348         }
1349 }
1350
1351 static void add_shapekey_layers(DerivedMesh *dm, Mesh *me, Object *UNUSED(ob))
1352 {
1353         KeyBlock *kb;
1354         Key *key = me->key;
1355         int i;
1356         const size_t shape_alloc_len = sizeof(float) * 3 * me->totvert;
1357
1358         if (!me->key)
1359                 return;
1360
1361         /* ensure we can use mesh vertex count for derived mesh custom data */
1362         if (me->totvert != dm->getNumVerts(dm)) {
1363                 fprintf(stderr,
1364                         "%s: vertex size mismatch (mesh/dm) '%s' (%d != %d)\n",
1365                         __func__, me->id.name + 2, me->totvert, dm->getNumVerts(dm));
1366                 return;
1367         }
1368
1369         for (i = 0, kb = key->block.first; kb; kb = kb->next, i++) {
1370                 int ci;
1371                 float *array;
1372
1373                 if (me->totvert != kb->totelem) {
1374                         fprintf(stderr,
1375                                 "%s: vertex size mismatch (Mesh '%s':%d != KeyBlock '%s':%d)\n",
1376                                 __func__, me->id.name + 2, me->totvert, kb->name, kb->totelem);
1377                         array = MEM_callocN(shape_alloc_len, __func__);
1378                 }
1379                 else {
1380                         array = MEM_mallocN(shape_alloc_len, __func__);
1381                         memcpy(array, kb->data, shape_alloc_len);
1382                 }
1383
1384                 CustomData_add_layer_named(&dm->vertData, CD_SHAPEKEY, CD_ASSIGN, array, dm->numVertData, kb->name);
1385                 ci = CustomData_get_layer_index_n(&dm->vertData, CD_SHAPEKEY, i);
1386
1387                 dm->vertData.layers[ci].uid = kb->uid;
1388         }
1389 }
1390
1391 /**
1392  * Called after calculating all modifiers.
1393  *
1394  * \note tessfaces should already be calculated.
1395  */
1396 static void dm_ensure_display_normals(DerivedMesh *dm)
1397 {
1398         /* this is for final output only, up until now this layer should be missing */
1399         BLI_assert(CustomData_has_layer(&dm->polyData, CD_NORMAL) == false);
1400
1401         if ((dm->type == DM_TYPE_CDDM) &&
1402             ((dm->dirty & DM_DIRTY_NORMALS) || CustomData_has_layer(&dm->faceData, CD_NORMAL) == FALSE))
1403         {
1404                 /* if normals are dirty we want to calculate vertex normals too */
1405                 CDDM_calc_normals_mapping_ex(dm, (dm->dirty & DM_DIRTY_NORMALS) ? false : true);
1406         }
1407 }
1408 /* new value for useDeform -1  (hack for the gameengine):
1409  * - apply only the modifier stack of the object, skipping the virtual modifiers,
1410  * - don't apply the key
1411  * - apply deform modifiers and input vertexco
1412  */
1413 static void mesh_calc_modifiers(Scene *scene, Object *ob, float (*inputVertexCos)[3],
1414                                 DerivedMesh **deform_r, DerivedMesh **final_r,
1415                                 int useRenderParams, int useDeform,
1416                                 int needMapping, CustomDataMask dataMask,
1417                                 int index, int useCache, int build_shapekey_layers)
1418 {
1419         Mesh *me = ob->data;
1420         ModifierData *firstmd, *md, *previewmd = NULL;
1421         CDMaskLink *datamasks, *curr;
1422         /* XXX Always copying POLYINDEX, else tessellated data are no more valid! */
1423         CustomDataMask mask, nextmask, previewmask = 0, append_mask = CD_MASK_ORIGINDEX;
1424         float (*deformedVerts)[3] = NULL;
1425         DerivedMesh *dm = NULL, *orcodm, *clothorcodm, *finaldm;
1426         int numVerts = me->totvert;
1427         int required_mode;
1428         int isPrevDeform = FALSE;
1429         int skipVirtualArmature = (useDeform < 0);
1430         MultiresModifierData *mmd = get_multires_modifier(scene, ob, 0);
1431         int has_multires = mmd != NULL, multires_applied = 0;
1432         int sculpt_mode = ob->mode & OB_MODE_SCULPT && ob->sculpt;
1433         int sculpt_dyntopo = (sculpt_mode && ob->sculpt->bm);
1434         int draw_flag = dm_drawflag_calc(scene->toolsettings);
1435
1436         /* Generic preview only in object mode! */
1437         const int do_mod_mcol = (ob->mode == OB_MODE_OBJECT);
1438 #if 0 /* XXX Will re-enable this when we have global mod stack options. */
1439         const int do_final_wmcol = (scene->toolsettings->weights_preview == WP_WPREVIEW_FINAL) && do_wmcol;
1440 #endif
1441         const int do_final_wmcol = FALSE;
1442         int do_init_wmcol = ((dataMask & CD_MASK_PREVIEW_MCOL) && (ob->mode & OB_MODE_WEIGHT_PAINT) && !do_final_wmcol);
1443         /* XXX Same as above... For now, only weights preview in WPaint mode. */
1444         const int do_mod_wmcol = do_init_wmcol;
1445
1446         ModifierApplyFlag app_flags = useRenderParams ? MOD_APPLY_RENDER : 0;
1447         ModifierApplyFlag deform_app_flags = app_flags;
1448         if (useCache)
1449                 app_flags |= MOD_APPLY_USECACHE;
1450         if (useDeform)
1451                 deform_app_flags |= MOD_APPLY_USECACHE;
1452
1453         if (mmd && !mmd->sculptlvl)
1454                 has_multires = 0;
1455
1456         if (!skipVirtualArmature) {
1457                 firstmd = modifiers_getVirtualModifierList(ob);
1458         }
1459         else {
1460                 /* game engine exception */
1461                 firstmd = ob->modifiers.first;
1462                 if (firstmd && firstmd->type == eModifierType_Armature)
1463                         firstmd = firstmd->next;
1464         }
1465
1466         md = firstmd;
1467
1468         modifiers_clearErrors(ob);
1469
1470         if (useRenderParams) required_mode = eModifierMode_Render;
1471         else required_mode = eModifierMode_Realtime;
1472
1473         if (do_mod_wmcol || do_mod_mcol) {
1474                 /* Find the last active modifier generating a preview, or NULL if none. */
1475                 /* XXX Currently, DPaint modifier just ignores this.
1476                  *     Needs a stupid hack...
1477                  *     The whole "modifier preview" thing has to be (re?)designed, anyway! */
1478                 previewmd = modifiers_getLastPreview(scene, md, required_mode);
1479
1480                 /* even if the modifier doesn't need the data, to make a preview it may */
1481                 if (previewmd) {
1482                         if (do_mod_wmcol) {
1483                                 previewmask = CD_MASK_MDEFORMVERT;
1484                         }
1485                 }
1486         }
1487
1488         datamasks = modifiers_calcDataMasks(scene, ob, md, dataMask, required_mode, previewmd, previewmask);
1489         curr = datamasks;
1490
1491         if (deform_r) *deform_r = NULL;
1492         *final_r = NULL;
1493
1494         if (useDeform) {
1495                 if (inputVertexCos)
1496                         deformedVerts = inputVertexCos;
1497                 
1498                 /* Apply all leading deforming modifiers */
1499                 for (; md; md = md->next, curr = curr->next) {
1500                         ModifierTypeInfo *mti = modifierType_getInfo(md->type);
1501
1502                         md->scene = scene;
1503                         
1504                         if (!modifier_isEnabled(scene, md, required_mode)) continue;
1505                         if (useDeform < 0 && mti->dependsOnTime && mti->dependsOnTime(md)) continue;
1506
1507                         if (mti->type == eModifierTypeType_OnlyDeform && !sculpt_dyntopo) {
1508                                 if (!deformedVerts)
1509                                         deformedVerts = BKE_mesh_vertexCos_get(me, &numVerts);
1510
1511                                 modwrap_deformVerts(md, ob, NULL, deformedVerts, numVerts, deform_app_flags);
1512                         }
1513                         else {
1514                                 break;
1515                         }
1516                         
1517                         /* grab modifiers until index i */
1518                         if ((index >= 0) && (BLI_findindex(&ob->modifiers, md) >= index))
1519                                 break;
1520                 }
1521
1522                 /* Result of all leading deforming modifiers is cached for
1523                  * places that wish to use the original mesh but with deformed
1524                  * coordinates (vpaint, etc.)
1525                  */
1526                 if (deform_r) {
1527                         *deform_r = CDDM_from_mesh(me, ob);
1528                          
1529                         if (build_shapekey_layers)
1530                                 add_shapekey_layers(dm, me, ob);
1531                         
1532                         if (deformedVerts) {
1533                                 CDDM_apply_vert_coords(*deform_r, deformedVerts);
1534                         }
1535                 }
1536         }
1537         else {
1538                 /* default behavior for meshes */
1539                 if (inputVertexCos)
1540                         deformedVerts = inputVertexCos;
1541                 else
1542                         deformedVerts = BKE_mesh_vertexCos_get(me, &numVerts);
1543         }
1544
1545
1546         /* Now apply all remaining modifiers. If useDeform is off then skip
1547          * OnlyDeform ones. 
1548          */
1549         dm = NULL;
1550         orcodm = NULL;
1551         clothorcodm = NULL;
1552
1553         for (; md; md = md->next, curr = curr->next) {
1554                 ModifierTypeInfo *mti = modifierType_getInfo(md->type);
1555
1556                 md->scene = scene;
1557
1558                 if (!modifier_isEnabled(scene, md, required_mode)) continue;
1559                 if (mti->type == eModifierTypeType_OnlyDeform && !useDeform) continue;
1560                 if ((mti->flags & eModifierTypeFlag_RequiresOriginalData) && dm) {
1561                         modifier_setError(md, "Modifier requires original data, bad stack position");
1562                         continue;
1563                 }
1564                 if (sculpt_mode &&
1565                         (!has_multires || multires_applied || ob->sculpt->bm))
1566                 {
1567                         int unsupported = 0;
1568
1569                         if (md->type == eModifierType_Multires && ((MultiresModifierData *)md)->sculptlvl == 0) {
1570                                 /* If multires is on level 0 skip it silently without warning message. */
1571                                 continue;
1572                         }
1573
1574                         if (sculpt_dyntopo && !useRenderParams)
1575                                 unsupported = TRUE;
1576
1577                         if (scene->toolsettings->sculpt->flags & SCULPT_ONLY_DEFORM)
1578                                 unsupported |= mti->type != eModifierTypeType_OnlyDeform;
1579
1580                         unsupported |= multires_applied;
1581
1582                         if (unsupported) {
1583                                 modifier_setError(md, "Not supported in sculpt mode");
1584                                 continue;
1585                         }
1586                 }
1587                 if (needMapping && !modifier_supportsMapping(md)) continue;
1588                 if (useDeform < 0 && mti->dependsOnTime && mti->dependsOnTime(md)) continue;
1589
1590                 /* add an orco layer if needed by this modifier */
1591                 if (mti->requiredDataMask)
1592                         mask = mti->requiredDataMask(ob, md);
1593                 else
1594                         mask = 0;
1595
1596                 if (dm && (mask & CD_MASK_ORCO))
1597                         add_orco_dm(ob, NULL, dm, orcodm, CD_ORCO);
1598
1599                 /* How to apply modifier depends on (a) what we already have as
1600                  * a result of previous modifiers (could be a DerivedMesh or just
1601                  * deformed vertices) and (b) what type the modifier is.
1602                  */
1603
1604                 if (mti->type == eModifierTypeType_OnlyDeform) {
1605                         /* No existing verts to deform, need to build them. */
1606                         if (!deformedVerts) {
1607                                 if (dm) {
1608                                         /* Deforming a derived mesh, read the vertex locations
1609                                          * out of the mesh and deform them. Once done with this
1610                                          * run of deformers verts will be written back.
1611                                          */
1612                                         numVerts = dm->getNumVerts(dm);
1613                                         deformedVerts =
1614                                             MEM_mallocN(sizeof(*deformedVerts) * numVerts, "dfmv");
1615                                         dm->getVertCos(dm, deformedVerts);
1616                                 }
1617                                 else {
1618                                         deformedVerts = BKE_mesh_vertexCos_get(me, &numVerts);
1619                                 }
1620                         }
1621
1622                         /* if this is not the last modifier in the stack then recalculate the normals
1623                          * to avoid giving bogus normals to the next modifier see: [#23673] */
1624                         if (isPrevDeform && mti->dependsOnNormals && mti->dependsOnNormals(md)) {
1625                                 /* XXX, this covers bug #23673, but we may need normal calc for other types */
1626                                 if (dm && dm->type == DM_TYPE_CDDM) {
1627                                         CDDM_apply_vert_coords(dm, deformedVerts);
1628                                 }
1629                         }
1630
1631                         modwrap_deformVerts(md, ob, dm, deformedVerts, numVerts, deform_app_flags);
1632                 }
1633                 else {
1634                         DerivedMesh *ndm;
1635
1636                         /* determine which data layers are needed by following modifiers */
1637                         if (curr->next)
1638                                 nextmask = curr->next->mask;
1639                         else
1640                                 nextmask = dataMask;
1641
1642                         /* apply vertex coordinates or build a DerivedMesh as necessary */
1643                         if (dm) {
1644                                 if (deformedVerts) {
1645                                         DerivedMesh *tdm = CDDM_copy(dm);
1646                                         dm->release(dm);
1647                                         dm = tdm;
1648
1649                                         CDDM_apply_vert_coords(dm, deformedVerts);
1650                                 }
1651                         }
1652                         else {
1653                                 dm = CDDM_from_mesh(me, ob);
1654
1655                                 if (build_shapekey_layers)
1656                                         add_shapekey_layers(dm, me, ob);
1657
1658                                 if (deformedVerts) {
1659                                         CDDM_apply_vert_coords(dm, deformedVerts);
1660                                 }
1661
1662                                 if (do_init_wmcol)
1663                                         DM_update_weight_mcol(ob, dm, draw_flag, NULL, 0, NULL);
1664
1665                                 /* Constructive modifiers need to have an origindex
1666                                  * otherwise they wont have anywhere to copy the data from.
1667                                  *
1668                                  * Also create ORIGINDEX data if any of the following modifiers
1669                                  * requests it, this way Mirror, Solidify etc will keep ORIGINDEX
1670                                  * data by using generic DM_copy_vert_data() functions.
1671                                  */
1672                                 if (needMapping || (nextmask & CD_MASK_ORIGINDEX)) {
1673                                         /* calc */
1674                                         DM_add_vert_layer(dm, CD_ORIGINDEX, CD_CALLOC, NULL);
1675                                         DM_add_edge_layer(dm, CD_ORIGINDEX, CD_CALLOC, NULL);
1676                                         DM_add_poly_layer(dm, CD_ORIGINDEX, CD_CALLOC, NULL);
1677
1678 #pragma omp parallel sections if (dm->numVertData + dm->numEdgeData + dm->numPolyData >= DM_OMP_LIMIT)
1679                                         {
1680 #pragma omp section
1681                                                 { range_vn_i(DM_get_vert_data_layer(dm, CD_ORIGINDEX), dm->numVertData, 0); }
1682 #pragma omp section
1683                                                 { range_vn_i(DM_get_edge_data_layer(dm, CD_ORIGINDEX), dm->numEdgeData, 0); }
1684 #pragma omp section
1685                                                 { range_vn_i(DM_get_poly_data_layer(dm, CD_ORIGINDEX), dm->numPolyData, 0); }
1686                                         }
1687                                 }
1688                         }
1689
1690                         
1691                         /* set the DerivedMesh to only copy needed data */
1692                         mask = curr->mask;
1693                         /* needMapping check here fixes bug [#28112], otherwise its
1694                          * possible that it wont be copied */
1695                         mask |= append_mask;
1696                         DM_set_only_copy(dm, mask | (needMapping ? CD_MASK_ORIGINDEX : 0));
1697                         
1698                         /* add cloth rest shape key if need */
1699                         if (mask & CD_MASK_CLOTH_ORCO)
1700                                 add_orco_dm(ob, NULL, dm, clothorcodm, CD_CLOTH_ORCO);
1701
1702                         /* add an origspace layer if needed */
1703                         if ((curr->mask) & CD_MASK_ORIGSPACE_MLOOP) {
1704                                 if (!CustomData_has_layer(&dm->loopData, CD_ORIGSPACE_MLOOP)) {
1705                                         DM_add_loop_layer(dm, CD_ORIGSPACE_MLOOP, CD_CALLOC, NULL);
1706                                         DM_init_origspace(dm);
1707                                 }
1708                         }
1709
1710                         ndm = modwrap_applyModifier(md, ob, dm, app_flags);
1711
1712                         if (ndm) {
1713                                 /* if the modifier returned a new dm, release the old one */
1714                                 if (dm && dm != ndm) dm->release(dm);
1715
1716                                 dm = ndm;
1717
1718                                 if (deformedVerts) {
1719                                         if (deformedVerts != inputVertexCos)
1720                                                 MEM_freeN(deformedVerts);
1721
1722                                         deformedVerts = NULL;
1723                                 }
1724                         }
1725
1726                         /* create an orco derivedmesh in parallel */
1727                         if (nextmask & CD_MASK_ORCO) {
1728                                 if (!orcodm)
1729                                         orcodm = create_orco_dm(ob, me, NULL, CD_ORCO);
1730
1731                                 nextmask &= ~CD_MASK_ORCO;
1732                                 DM_set_only_copy(orcodm, nextmask | CD_MASK_ORIGINDEX |
1733                                                  (mti->requiredDataMask ?
1734                                                   mti->requiredDataMask(ob, md) : 0));
1735
1736                                 ndm = modwrap_applyModifier(md, ob, orcodm, (app_flags & ~MOD_APPLY_USECACHE) | MOD_APPLY_ORCO);
1737
1738                                 if (ndm) {
1739                                         /* if the modifier returned a new dm, release the old one */
1740                                         if (orcodm && orcodm != ndm) orcodm->release(orcodm);
1741                                         orcodm = ndm;
1742                                 }
1743                         }
1744
1745                         /* create cloth orco derivedmesh in parallel */
1746                         if (nextmask & CD_MASK_CLOTH_ORCO) {
1747                                 if (!clothorcodm)
1748                                         clothorcodm = create_orco_dm(ob, me, NULL, CD_CLOTH_ORCO);
1749
1750                                 nextmask &= ~CD_MASK_CLOTH_ORCO;
1751                                 DM_set_only_copy(clothorcodm, nextmask | CD_MASK_ORIGINDEX);
1752
1753                                 ndm = modwrap_applyModifier(md, ob, clothorcodm, (app_flags & ~MOD_APPLY_USECACHE) | MOD_APPLY_ORCO);
1754
1755                                 if (ndm) {
1756                                         /* if the modifier returned a new dm, release the old one */
1757                                         if (clothorcodm && clothorcodm != ndm) clothorcodm->release(clothorcodm);
1758                                         clothorcodm = ndm;
1759                                 }
1760                         }
1761
1762                         /* in case of dynamic paint, make sure preview mask remains for following modifiers */
1763                         /* XXX Temp and hackish solution! */
1764                         if (md->type == eModifierType_DynamicPaint)
1765                                 append_mask |= CD_MASK_PREVIEW_MLOOPCOL;
1766                         /* In case of active preview modifier, make sure preview mask remains for following modifiers. */
1767                         else if ((md == previewmd) && (do_mod_wmcol)) {
1768                                 DM_update_weight_mcol(ob, dm, draw_flag, NULL, 0, NULL);
1769                                 append_mask |= CD_MASK_PREVIEW_MLOOPCOL;
1770                         }
1771                 }
1772
1773                 isPrevDeform = (mti->type == eModifierTypeType_OnlyDeform);
1774
1775                 /* grab modifiers until index i */
1776                 if ((index >= 0) && (BLI_findindex(&ob->modifiers, md) >= index))
1777                         break;
1778
1779                 if (sculpt_mode && md->type == eModifierType_Multires)
1780                         multires_applied = 1;
1781         }
1782
1783         for (md = firstmd; md; md = md->next)
1784                 modifier_freeTemporaryData(md);
1785
1786         /* Yay, we are done. If we have a DerivedMesh and deformed vertices
1787          * need to apply these back onto the DerivedMesh. If we have no
1788          * DerivedMesh then we need to build one.
1789          */
1790         if (dm && deformedVerts) {
1791                 finaldm = CDDM_copy(dm);
1792
1793                 dm->release(dm);
1794
1795                 CDDM_apply_vert_coords(finaldm, deformedVerts);
1796
1797 #if 0 /* For later nice mod preview! */
1798                 /* In case we need modified weights in CD_PREVIEW_MCOL, we have to re-compute it. */
1799                 if (do_final_wmcol)
1800                         DM_update_weight_mcol(ob, finaldm, draw_flag, NULL, 0, NULL);
1801 #endif
1802         }
1803         else if (dm) {
1804                 finaldm = dm;
1805
1806 #if 0 /* For later nice mod preview! */
1807                 /* In case we need modified weights in CD_PREVIEW_MCOL, we have to re-compute it. */
1808                 if (do_final_wmcol)
1809                         DM_update_weight_mcol(ob, finaldm, draw_flag, NULL, 0, NULL);
1810 #endif
1811         }
1812         else {
1813                 finaldm = CDDM_from_mesh(me, ob);
1814                 
1815                 if (build_shapekey_layers) {
1816                         add_shapekey_layers(finaldm, me, ob);
1817                 }
1818                 
1819                 if (deformedVerts) {
1820                         CDDM_apply_vert_coords(finaldm, deformedVerts);
1821                 }
1822
1823                 /* In this case, we should never have weight-modifying modifiers in stack... */
1824                 if (do_init_wmcol)
1825                         DM_update_weight_mcol(ob, finaldm, draw_flag, NULL, 0, NULL);
1826         }
1827
1828         /* add an orco layer if needed */
1829         if (dataMask & CD_MASK_ORCO) {
1830                 add_orco_dm(ob, NULL, finaldm, orcodm, CD_ORCO);
1831
1832                 if (deform_r && *deform_r)
1833                         add_orco_dm(ob, NULL, *deform_r, NULL, CD_ORCO);
1834         }
1835
1836         {
1837                 /* calculating normals can re-calculate tessfaces in some cases */
1838 #if 0
1839                 int num_tessface = finaldm->getNumTessFaces(finaldm);
1840 #endif
1841                 /* --------------------------------------------------------------------- */
1842                 /* First calculate the polygon and vertex normals, re-tessellation
1843                  * copies these into the tessface's normal layer */
1844
1845
1846                 /* comment because this causes a bug when deform is applied after a
1847                  * bug when applied after a subsurf modifier (SubSurf -> Cast) for eg,
1848                  * it also looks like this isn't even needed since code above recalc's
1849                  * normals - campbell */
1850 #if 0
1851                 finaldm->calcNormals(finaldm);
1852 #endif
1853
1854                 /* Re-tessellation is necessary to push render data (uvs, textures, colors)
1855                  * from loops and polys onto the tessfaces. This may be currently be
1856                  * redundant in cases where the render mode doesn't use these inputs, but
1857                  * ideally eventually tessellation would happen on-demand, and this is one
1858                  * of the primary places it would be needed. */
1859 #if 0
1860                 if (num_tessface == 0 && finaldm->getNumTessFaces(finaldm) == 0)
1861 #else
1862                 if (finaldm->getNumTessFaces(finaldm) == 0) /* || !CustomData_has_layer(&finaldm->faceData, CD_ORIGINDEX)) */
1863 #endif
1864                 {
1865                         finaldm->recalcTessellation(finaldm);
1866                 }
1867                 /* Even if tessellation is not needed, some modifiers might have modified CD layers
1868                  * (like mloopcol or mloopuv), hence we have to update those. */
1869                 else if (finaldm->dirty & DM_DIRTY_TESS_CDLAYERS) {
1870                         /* A tessellation already exists, it should always have a CD_ORIGINDEX. */
1871                         BLI_assert(CustomData_has_layer(&finaldm->faceData, CD_ORIGINDEX));
1872                         DM_update_tessface_data(finaldm);
1873                 }
1874                 /* Need to watch this, it can cause issues, see bug [#29338]             */
1875                 /* take care with this block, we really need testing frameworks          */
1876                 /* --------------------------------------------------------------------- */
1877
1878                 /* without this, drawing ngon tri's faces will show ugly tessellated face
1879                  * normals and will also have to calculate normals on the fly, try avoid
1880                  * this where possible since calculating polygon normals isn't fast,
1881                  * note that this isn't a problem for subsurf (only quads) or editmode
1882                  * which deals with drawing differently.
1883                  *
1884                  * Only calc vertex normals if they are flagged as dirty.
1885                  */
1886                 dm_ensure_display_normals(finaldm);
1887         }
1888
1889 #ifdef WITH_GAMEENGINE
1890         /* NavMesh - this is a hack but saves having a NavMesh modifier */
1891         if ((ob->gameflag & OB_NAVMESH) && (finaldm->type == DM_TYPE_CDDM)) {
1892                 DerivedMesh *tdm;
1893                 tdm = navmesh_dm_createNavMeshForVisualization(finaldm);
1894                 if (finaldm != tdm) {
1895                         finaldm->release(finaldm);
1896                         finaldm = tdm;
1897                 }
1898         }
1899 #endif /* WITH_GAMEENGINE */
1900
1901         *final_r = finaldm;
1902
1903         if (orcodm)
1904                 orcodm->release(orcodm);
1905         if (clothorcodm)
1906                 clothorcodm->release(clothorcodm);
1907
1908         if (deformedVerts && deformedVerts != inputVertexCos)
1909                 MEM_freeN(deformedVerts);
1910
1911         BLI_linklist_free((LinkNode *)datamasks, NULL);
1912 }
1913
1914 float (*editbmesh_get_vertex_cos(BMEditMesh *em, int *numVerts_r))[3]
1915 {
1916         BMIter iter;
1917         BMVert *eve;
1918         float (*cos)[3];
1919         int i;
1920
1921         *numVerts_r = em->bm->totvert;
1922
1923         cos = MEM_mallocN(sizeof(float) * 3 * em->bm->totvert, "vertexcos");
1924
1925         BM_ITER_MESH_INDEX (eve, &iter, em->bm, BM_VERTS_OF_MESH, i) {
1926                 copy_v3_v3(cos[i], eve->co);
1927         }
1928
1929         return cos;
1930 }
1931
1932 int editbmesh_modifier_is_enabled(Scene *scene, ModifierData *md, DerivedMesh *dm)
1933 {
1934         ModifierTypeInfo *mti = modifierType_getInfo(md->type);
1935         int required_mode = eModifierMode_Realtime | eModifierMode_Editmode;
1936
1937         if (!modifier_isEnabled(scene, md, required_mode)) return 0;
1938         if ((mti->flags & eModifierTypeFlag_RequiresOriginalData) && dm) {
1939                 modifier_setError(md, "Modifier requires original data, bad stack position");
1940                 return 0;
1941         }
1942         
1943         return 1;
1944 }
1945
1946 static void editbmesh_calc_modifiers(Scene *scene, Object *ob, BMEditMesh *em, DerivedMesh **cage_r,
1947                                      DerivedMesh **final_r,
1948                                      CustomDataMask dataMask)
1949 {
1950         ModifierData *md, *previewmd = NULL;
1951         float (*deformedVerts)[3] = NULL;
1952         CustomDataMask mask, previewmask = 0;
1953         DerivedMesh *dm, *orcodm = NULL;
1954         int i, numVerts = 0, cageIndex = modifiers_getCageIndex(scene, ob, NULL, 1);
1955         CDMaskLink *datamasks, *curr;
1956         int required_mode = eModifierMode_Realtime | eModifierMode_Editmode;
1957         int draw_flag = dm_drawflag_calc(scene->toolsettings);
1958
1959         // const int do_mod_mcol = true; // (ob->mode == OB_MODE_OBJECT);
1960 #if 0 /* XXX Will re-enable this when we have global mod stack options. */
1961         const int do_final_wmcol = (scene->toolsettings->weights_preview == WP_WPREVIEW_FINAL) && do_wmcol;
1962 #endif
1963         const int do_final_wmcol = FALSE;
1964         int do_init_wmcol = ((((Mesh *)ob->data)->drawflag & ME_DRAWEIGHT) && !do_final_wmcol);
1965         int do_init_statvis = ((((Mesh *)ob->data)->drawflag & ME_DRAW_STATVIS) && !do_init_wmcol);
1966         const int do_mod_wmcol = do_init_wmcol;
1967
1968         modifiers_clearErrors(ob);
1969
1970         if (cage_r && cageIndex == -1) {
1971                 *cage_r = getEditDerivedBMesh(em, ob, NULL);
1972         }
1973
1974         dm = NULL;
1975         md = modifiers_getVirtualModifierList(ob);
1976
1977         /* copied from mesh_calc_modifiers */
1978         if (do_mod_wmcol) {
1979                 previewmd = modifiers_getLastPreview(scene, md, required_mode);
1980                 /* even if the modifier doesn't need the data, to make a preview it may */
1981                 if (previewmd) {
1982                         if (do_mod_wmcol) {
1983                                 previewmask = CD_MASK_MDEFORMVERT;
1984                         }
1985                 }
1986         }
1987
1988         datamasks = modifiers_calcDataMasks(scene, ob, md, dataMask, required_mode, previewmd, previewmask);
1989
1990         curr = datamasks;
1991         for (i = 0; md; i++, md = md->next, curr = curr->next) {
1992                 ModifierTypeInfo *mti = modifierType_getInfo(md->type);
1993
1994                 md->scene = scene;
1995                 
1996                 if (!editbmesh_modifier_is_enabled(scene, md, dm))
1997                         continue;
1998
1999                 /* add an orco layer if needed by this modifier */
2000                 if (dm && mti->requiredDataMask) {
2001                         mask = mti->requiredDataMask(ob, md);
2002                         if (mask & CD_MASK_ORCO)
2003                                 add_orco_dm(ob, em, dm, orcodm, CD_ORCO);
2004                 }
2005
2006                 /* How to apply modifier depends on (a) what we already have as
2007                  * a result of previous modifiers (could be a DerivedMesh or just
2008                  * deformed vertices) and (b) what type the modifier is.
2009                  */
2010
2011                 if (mti->type == eModifierTypeType_OnlyDeform) {
2012                         /* No existing verts to deform, need to build them. */
2013                         if (!deformedVerts) {
2014                                 if (dm) {
2015                                         /* Deforming a derived mesh, read the vertex locations
2016                                          * out of the mesh and deform them. Once done with this
2017                                          * run of deformers verts will be written back.
2018                                          */
2019                                         numVerts = dm->getNumVerts(dm);
2020                                         deformedVerts =
2021                                             MEM_mallocN(sizeof(*deformedVerts) * numVerts, "dfmv");
2022                                         dm->getVertCos(dm, deformedVerts);
2023                                 }
2024                                 else {
2025                                         deformedVerts = editbmesh_get_vertex_cos(em, &numVerts);
2026                                 }
2027                         }
2028
2029                         if (mti->deformVertsEM)
2030                                 modwrap_deformVertsEM(md, ob, em, dm, deformedVerts, numVerts);
2031                         else
2032                                 modwrap_deformVerts(md, ob, dm, deformedVerts, numVerts, 0);
2033                 }
2034                 else {
2035                         DerivedMesh *ndm;
2036
2037                         /* apply vertex coordinates or build a DerivedMesh as necessary */
2038                         if (dm) {
2039                                 if (deformedVerts) {
2040                                         DerivedMesh *tdm = CDDM_copy(dm);
2041                                         if (!(cage_r && dm == *cage_r)) dm->release(dm);
2042                                         dm = tdm;
2043
2044                                         CDDM_apply_vert_coords(dm, deformedVerts);
2045                                 }
2046                                 else if (cage_r && dm == *cage_r) {
2047                                         /* dm may be changed by this modifier, so we need to copy it
2048                                          */
2049                                         dm = CDDM_copy(dm);
2050                                 }
2051
2052                         }
2053                         else {
2054                                 dm = CDDM_from_editbmesh(em, FALSE, FALSE);
2055
2056                                 if (deformedVerts) {
2057                                         CDDM_apply_vert_coords(dm, deformedVerts);
2058                                 }
2059
2060                                 if (do_init_wmcol) {
2061                                         DM_update_weight_mcol(ob, dm, draw_flag, NULL, 0, NULL);
2062                                 }
2063                         }
2064
2065                         /* create an orco derivedmesh in parallel */
2066                         mask = curr->mask;
2067                         if (mask & CD_MASK_ORCO) {
2068                                 if (!orcodm)
2069                                         orcodm = create_orco_dm(ob, ob->data, em, CD_ORCO);
2070
2071                                 mask &= ~CD_MASK_ORCO;
2072                                 DM_set_only_copy(orcodm, mask | CD_MASK_ORIGINDEX);
2073
2074                                 if (mti->applyModifierEM)
2075                                         ndm = modwrap_applyModifierEM(md, ob, em, orcodm, MOD_APPLY_ORCO);
2076                                 else
2077                                         ndm = modwrap_applyModifier(md, ob, orcodm, MOD_APPLY_ORCO);
2078
2079                                 if (ndm) {
2080                                         /* if the modifier returned a new dm, release the old one */
2081                                         if (orcodm && orcodm != ndm) orcodm->release(orcodm);
2082                                         orcodm = ndm;
2083                                 }
2084                         }
2085
2086                         /* set the DerivedMesh to only copy needed data */
2087                         mask = curr->mask; /* CD_MASK_ORCO may have been cleared above */
2088
2089                         DM_set_only_copy(dm, mask | CD_MASK_ORIGINDEX);
2090
2091                         if (mask & CD_MASK_ORIGSPACE_MLOOP) {
2092                                 if (!CustomData_has_layer(&dm->loopData, CD_ORIGSPACE_MLOOP)) {
2093                                         DM_add_loop_layer(dm, CD_ORIGSPACE_MLOOP, CD_CALLOC, NULL);
2094                                         DM_init_origspace(dm);
2095                                 }
2096                         }
2097
2098                         if (mti->applyModifierEM)
2099                                 ndm = modwrap_applyModifierEM(md, ob, em, dm, MOD_APPLY_USECACHE);
2100                         else
2101                                 ndm = modwrap_applyModifier(md, ob, dm, MOD_APPLY_USECACHE);
2102
2103                         if (ndm) {
2104                                 if (dm && dm != ndm)
2105                                         dm->release(dm);
2106
2107                                 dm = ndm;
2108
2109                                 if (deformedVerts) {
2110                                         MEM_freeN(deformedVerts);
2111                                         deformedVerts = NULL;
2112                                 }
2113                         }
2114                 }
2115
2116                 if (cage_r && i == cageIndex) {
2117                         if (dm && deformedVerts) {
2118                                 *cage_r = CDDM_copy(dm);
2119                                 CDDM_apply_vert_coords(*cage_r, deformedVerts);
2120                         }
2121                         else if (dm) {
2122                                 *cage_r = dm;
2123                         }
2124                         else {
2125                                 *cage_r =
2126                                     getEditDerivedBMesh(em, ob,
2127                                                         deformedVerts ? MEM_dupallocN(deformedVerts) : NULL);
2128                         }
2129                 }
2130         }
2131
2132         BLI_linklist_free((LinkNode *)datamasks, NULL);
2133
2134         /* Yay, we are done. If we have a DerivedMesh and deformed vertices need
2135          * to apply these back onto the DerivedMesh. If we have no DerivedMesh
2136          * then we need to build one.
2137          */
2138         if (dm && deformedVerts) {
2139                 *final_r = CDDM_copy(dm);
2140
2141                 if (!(cage_r && dm == *cage_r)) dm->release(dm);
2142
2143                 CDDM_apply_vert_coords(*final_r, deformedVerts);
2144         }
2145         else if (dm) {
2146                 *final_r = dm;
2147         }
2148         else if (!deformedVerts && cage_r && *cage_r) {
2149                 /* cage should already have up to date normals */
2150                 *final_r = *cage_r;
2151
2152                 /* In this case, we should never have weight-modifying modifiers in stack... */
2153                 if (do_init_wmcol)
2154                         DM_update_weight_mcol(ob, *final_r, draw_flag, NULL, 0, NULL);
2155                 if (do_init_statvis)
2156                         DM_update_statvis_color(scene, ob, *final_r);
2157         }
2158         else {
2159                 /* this is just a copy of the editmesh, no need to calc normals */
2160                 *final_r = getEditDerivedBMesh(em, ob, deformedVerts);
2161                 deformedVerts = NULL;
2162
2163                 /* In this case, we should never have weight-modifying modifiers in stack... */
2164                 if (do_init_wmcol)
2165                         DM_update_weight_mcol(ob, *final_r, draw_flag, NULL, 0, NULL);
2166                 if (do_init_statvis)
2167                         DM_update_statvis_color(scene, ob, *final_r);
2168         }
2169
2170         /* --- */
2171         /* BMESH_ONLY, ensure tessface's used for drawing,
2172          * but don't recalculate if the last modifier in the stack gives us tessfaces
2173          * check if the derived meshes are DM_TYPE_EDITBMESH before calling, this isn't essential
2174          * but quiets annoying error messages since tessfaces wont be created. */
2175         if ((*final_r)->type != DM_TYPE_EDITBMESH) {
2176                 DM_ensure_tessface(*final_r);
2177         }
2178         if (cage_r && *cage_r) {
2179                 if ((*cage_r)->type != DM_TYPE_EDITBMESH) {
2180                         if (*cage_r != *final_r) {
2181                                 DM_ensure_tessface(*cage_r);
2182                         }
2183                 }
2184         }
2185         /* --- */
2186
2187         /* same as mesh_calc_modifiers */
2188         dm_ensure_display_normals(*final_r);
2189
2190         /* add an orco layer if needed */
2191         if (dataMask & CD_MASK_ORCO)
2192                 add_orco_dm(ob, em, *final_r, orcodm, CD_ORCO);
2193
2194         if (orcodm)
2195                 orcodm->release(orcodm);
2196
2197         if (deformedVerts)
2198                 MEM_freeN(deformedVerts);
2199 }
2200
2201 static void mesh_build_data(Scene *scene, Object *ob, CustomDataMask dataMask,
2202                             int build_shapekey_layers)
2203 {
2204         Object *obact = scene->basact ? scene->basact->object : NULL;
2205         int editing = paint_facesel_test(ob);
2206         /* weight paint and face select need original indices because of selection buffer drawing */
2207         int needMapping = (ob == obact) && (editing || (ob->mode & (OB_MODE_WEIGHT_PAINT | OB_MODE_VERTEX_PAINT | OB_MODE_TEXTURE_PAINT)));
2208
2209         BLI_assert(ob->type == OB_MESH);
2210
2211         BKE_object_free_derived_caches(ob);
2212         BKE_object_sculpt_modifiers_changed(ob);
2213
2214         mesh_calc_modifiers(scene, ob, NULL, &ob->derivedDeform,
2215                             &ob->derivedFinal, 0, 1,
2216                             needMapping, dataMask, -1, 1, build_shapekey_layers);
2217
2218         DM_set_object_boundbox(ob, ob->derivedFinal);
2219
2220         ob->derivedFinal->needsFree = 0;
2221         ob->derivedDeform->needsFree = 0;
2222         ob->lastDataMask = dataMask;
2223
2224         if ((ob->mode & OB_MODE_SCULPT) && ob->sculpt) {
2225                 /* create PBVH immediately (would be created on the fly too,
2226                  * but this avoids waiting on first stroke) */
2227                 ob->sculpt->pbvh = ob->derivedFinal->getPBVH(ob, ob->derivedFinal);
2228         }
2229
2230         BLI_assert(!(ob->derivedFinal->dirty & DM_DIRTY_NORMALS));
2231 }
2232
2233 static void editbmesh_build_data(Scene *scene, Object *obedit, BMEditMesh *em, CustomDataMask dataMask)
2234 {
2235         BKE_object_free_derived_caches(obedit);
2236         BKE_object_sculpt_modifiers_changed(obedit);
2237
2238         if (em->derivedFinal) {
2239                 if (em->derivedFinal != em->derivedCage) {
2240                         em->derivedFinal->needsFree = 1;
2241                         em->derivedFinal->release(em->derivedFinal);
2242                 }
2243                 em->derivedFinal = NULL;
2244         }
2245         if (em->derivedCage) {
2246                 em->derivedCage->needsFree = 1;
2247                 em->derivedCage->release(em->derivedCage);
2248                 em->derivedCage = NULL;
2249         }
2250
2251         editbmesh_calc_modifiers(scene, obedit, em, &em->derivedCage, &em->derivedFinal, dataMask);
2252         DM_set_object_boundbox(obedit, em->derivedFinal);
2253
2254         em->lastDataMask = dataMask;
2255         em->derivedFinal->needsFree = 0;
2256         em->derivedCage->needsFree = 0;
2257
2258         BLI_assert(!(em->derivedFinal->dirty & DM_DIRTY_NORMALS));
2259 }
2260
2261 static CustomDataMask object_get_datamask(Scene *scene, Object *ob)
2262 {
2263         Object *actob = scene->basact ? scene->basact->object : NULL;
2264         CustomDataMask mask = ob->customdata_mask;
2265
2266         if (ob == actob) {
2267                 /* check if we need tfaces & mcols due to face select or texture paint */
2268                 if (paint_facesel_test(ob) || (ob->mode & OB_MODE_TEXTURE_PAINT)) {
2269                         mask |= CD_MASK_MTFACE | CD_MASK_MCOL;
2270                 }
2271
2272                 /* check if we need mcols due to vertex paint or weightpaint */
2273                 if (ob->mode & OB_MODE_VERTEX_PAINT) {
2274                         mask |= CD_MASK_MCOL;
2275                 }
2276
2277                 if (ob->mode & OB_MODE_WEIGHT_PAINT) {
2278                         mask |= CD_MASK_PREVIEW_MCOL;
2279                 }
2280
2281                 if (ob->mode & OB_MODE_EDIT)
2282                         mask |= CD_MASK_MVERT_SKIN;
2283         }
2284
2285         return mask;
2286 }
2287
2288 void makeDerivedMesh(Scene *scene, Object *ob, BMEditMesh *em,
2289                      CustomDataMask dataMask, int build_shapekey_layers)
2290 {
2291         dataMask |= object_get_datamask(scene, ob);
2292
2293         if (em) {
2294                 editbmesh_build_data(scene, ob, em, dataMask);
2295         }
2296         else {
2297                 mesh_build_data(scene, ob, dataMask, build_shapekey_layers);
2298         }
2299 }
2300
2301 /***/
2302
2303 DerivedMesh *mesh_get_derived_final(Scene *scene, Object *ob, CustomDataMask dataMask)
2304 {
2305         /* if there's no derived mesh or the last data mask used doesn't include
2306          * the data we need, rebuild the derived mesh
2307          */
2308         dataMask |= object_get_datamask(scene, ob);
2309
2310         if (!ob->derivedFinal || (dataMask & ob->lastDataMask) != dataMask)
2311                 mesh_build_data(scene, ob, dataMask, 0);
2312
2313         if (ob->derivedFinal) { BLI_assert(!(ob->derivedFinal->dirty & DM_DIRTY_NORMALS)); }
2314         return ob->derivedFinal;
2315 }
2316
2317 DerivedMesh *mesh_get_derived_deform(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->derivedDeform || (dataMask & ob->lastDataMask) != dataMask)
2325                 mesh_build_data(scene, ob, dataMask, 0);
2326
2327         return ob->derivedDeform;
2328 }
2329
2330 DerivedMesh *mesh_create_derived_render(Scene *scene, Object *ob, CustomDataMask dataMask)
2331 {
2332         DerivedMesh *final;
2333         
2334         mesh_calc_modifiers(scene, ob, NULL, NULL, &final, 1, 1, 0, dataMask, -1, 0, 0);
2335
2336         return final;
2337 }
2338
2339 DerivedMesh *mesh_create_derived_index_render(Scene *scene, Object *ob, CustomDataMask dataMask, int index)
2340 {
2341         DerivedMesh *final;
2342         
2343         mesh_calc_modifiers(scene, ob, NULL, NULL, &final, 1, 1, 0, dataMask, index, 0, 0);
2344
2345         return final;
2346 }
2347
2348 DerivedMesh *mesh_create_derived_view(Scene *scene, Object *ob, CustomDataMask dataMask)
2349 {
2350         DerivedMesh *final;
2351
2352         /* XXX hack
2353          * psys modifier updates particle state when called during dupli-list generation,
2354          * which can lead to wrong transforms. This disables particle system modifier execution.
2355          */
2356         ob->transflag |= OB_NO_PSYS_UPDATE;
2357
2358         mesh_calc_modifiers(scene, ob, NULL, NULL, &final, 0, 1, 0, dataMask, -1, 0, 0);
2359
2360         ob->transflag &= ~OB_NO_PSYS_UPDATE;
2361
2362         return final;
2363 }
2364
2365 DerivedMesh *mesh_create_derived_no_deform(Scene *scene, Object *ob, float (*vertCos)[3],
2366                                            CustomDataMask dataMask)
2367 {
2368         DerivedMesh *final;
2369         
2370         mesh_calc_modifiers(scene, ob, vertCos, NULL, &final, 0, 0, 0, dataMask, -1, 0, 0);
2371
2372         return final;
2373 }
2374
2375 DerivedMesh *mesh_create_derived_no_virtual(Scene *scene, Object *ob, float (*vertCos)[3],
2376                                             CustomDataMask dataMask)
2377 {
2378         DerivedMesh *final;
2379         
2380         mesh_calc_modifiers(scene, ob, vertCos, NULL, &final, 0, -1, 0, dataMask, -1, 0, 0);
2381
2382         return final;
2383 }
2384
2385 DerivedMesh *mesh_create_derived_physics(Scene *scene, Object *ob, float (*vertCos)[3],
2386                                          CustomDataMask dataMask)
2387 {
2388         DerivedMesh *final;
2389         
2390         mesh_calc_modifiers(scene, ob, vertCos, NULL, &final, 0, -1, 1, dataMask, -1, 0, 0);
2391
2392         return final;
2393 }
2394
2395 DerivedMesh *mesh_create_derived_no_deform_render(Scene *scene, Object *ob,
2396                                                   float (*vertCos)[3],
2397                                                   CustomDataMask dataMask)
2398 {
2399         DerivedMesh *final;
2400
2401         mesh_calc_modifiers(scene, ob, vertCos, NULL, &final, 1, 0, 0, dataMask, -1, 0, 0);
2402
2403         return final;
2404 }
2405
2406 /***/
2407
2408 DerivedMesh *editbmesh_get_derived_cage_and_final(Scene *scene, Object *obedit, BMEditMesh *em, DerivedMesh **final_r,
2409                                                   CustomDataMask dataMask)
2410 {
2411         /* if there's no derived mesh or the last data mask used doesn't include
2412          * the data we need, rebuild the derived mesh
2413          */
2414         dataMask |= object_get_datamask(scene, obedit);
2415
2416         if (!em->derivedCage ||
2417             (em->lastDataMask & dataMask) != dataMask)
2418         {
2419                 editbmesh_build_data(scene, obedit, em, dataMask);
2420         }
2421
2422         *final_r = em->derivedFinal;
2423         if (em->derivedFinal) { BLI_assert(!(em->derivedFinal->dirty & DM_DIRTY_NORMALS)); }
2424         return em->derivedCage;
2425 }
2426
2427 DerivedMesh *editbmesh_get_derived_cage(Scene *scene, Object *obedit, BMEditMesh *em, CustomDataMask dataMask)
2428 {
2429         /* if there's no derived mesh or the last data mask used doesn't include
2430          * the data we need, rebuild the derived mesh
2431          */
2432         dataMask |= object_get_datamask(scene, obedit);
2433
2434         if (!em->derivedCage ||
2435             (em->lastDataMask & dataMask) != dataMask)
2436         {
2437                 editbmesh_build_data(scene, obedit, em, dataMask);
2438         }
2439
2440         return em->derivedCage;
2441 }
2442
2443 DerivedMesh *editbmesh_get_derived_base(Object *obedit, BMEditMesh *em)
2444 {
2445         return getEditDerivedBMesh(em, obedit, NULL);
2446 }
2447
2448 /* UNUSED */
2449 #if 0
2450
2451 /* ********* For those who don't grasp derived stuff! (ton) :) *************** */
2452
2453 static void make_vertexcosnos__mapFunc(void *userData, int index, const float co[3],
2454                                        const float no_f[3], const short no_s[3])
2455 {
2456         DMCoNo *co_no = &((DMCoNo *)userData)[index];
2457
2458         /* check if we've been here before (normal should not be 0) */
2459         if (!is_zero_v3(co_no->no)) {
2460                 return;
2461         }
2462
2463         copy_v3_v3(co_no->co, co);
2464         if (no_f) {
2465                 copy_v3_v3(co_no->no, no_f);
2466         }
2467         else {
2468                 normal_short_to_float_v3(co_no->no, no_s);
2469         }
2470 }
2471
2472 /* always returns original amount me->totvert of vertices and normals, but fully deformed and subsurfered */
2473 /* this is needed for all code using vertexgroups (no subsurf support) */
2474 /* it stores the normals as floats, but they can still be scaled as shorts (32767 = unit) */
2475 /* in use now by vertex/weight paint and particle generating */
2476
2477 DMCoNo *mesh_get_mapped_verts_nors(Scene *scene, Object *ob)
2478 {
2479         Mesh *me = ob->data;
2480         DerivedMesh *dm;
2481         DMCoNo *vertexcosnos;
2482         
2483         /* lets prevent crashing... */
2484         if (ob->type != OB_MESH || me->totvert == 0)
2485                 return NULL;
2486         
2487         dm = mesh_get_derived_final(scene, ob, CD_MASK_BAREMESH | CD_MASK_ORIGINDEX);
2488         
2489         if (dm->foreachMappedVert) {
2490                 vertexcosnos = MEM_callocN(sizeof(DMCoNo) * me->totvert, "vertexcosnos map");
2491                 dm->foreachMappedVert(dm, make_vertexcosnos__mapFunc, vertexcosnos);
2492         }
2493         else {
2494                 DMCoNo *v_co_no = vertexcosnos = MEM_mallocN(sizeof(DMCoNo) * me->totvert, "vertexcosnos map");
2495                 int a;
2496                 for (a = 0; a < me->totvert; a++, v_co_no++) {
2497                         dm->getVertCo(dm, a, v_co_no->co);
2498                         dm->getVertNo(dm, a, v_co_no->no);
2499                 }
2500         }
2501         
2502         dm->release(dm);
2503         return vertexcosnos;
2504 }
2505
2506 #endif
2507
2508 /* ******************* GLSL ******************** */
2509
2510 typedef struct {
2511         float *precomputedFaceNormals;
2512         MTFace *mtface;     /* texture coordinates */
2513         MFace *mface;       /* indices */
2514         MVert *mvert;       /* vertices & normals */
2515         float (*orco)[3];
2516         float (*tangent)[4];    /* destination */
2517         int numTessFaces;
2518
2519 } SGLSLMeshToTangent;
2520
2521 /* interface */
2522 #include "mikktspace.h"
2523
2524 static int GetNumFaces(const SMikkTSpaceContext *pContext)
2525 {
2526         SGLSLMeshToTangent *pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
2527         return pMesh->numTessFaces;
2528 }
2529
2530 static int GetNumVertsOfFace(const SMikkTSpaceContext *pContext, const int face_num)
2531 {
2532         SGLSLMeshToTangent *pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
2533         return pMesh->mface[face_num].v4 != 0 ? 4 : 3;
2534 }
2535
2536 static void GetPosition(const SMikkTSpaceContext *pContext, float r_co[3], const int face_num, const int vert_index)
2537 {
2538         //assert(vert_index >= 0 && vert_index < 4);
2539         SGLSLMeshToTangent *pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
2540         const float *co = pMesh->mvert[(&pMesh->mface[face_num].v1)[vert_index]].co;
2541         copy_v3_v3(r_co, co);
2542 }
2543
2544 static void GetTextureCoordinate(const SMikkTSpaceContext *pContext, float r_uv[2], const int face_num, const int vert_index)
2545 {
2546         //assert(vert_index >= 0 && vert_index < 4);
2547         SGLSLMeshToTangent *pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
2548
2549         if (pMesh->mtface != NULL) {
2550                 const float *uv = pMesh->mtface[face_num].uv[vert_index];
2551                 copy_v2_v2(r_uv, uv);
2552         }
2553         else {
2554                 const float *orco = pMesh->orco[(&pMesh->mface[face_num].v1)[vert_index]];
2555                 map_to_sphere(&r_uv[0], &r_uv[1], orco[0], orco[1], orco[2]);
2556         }
2557 }
2558
2559 static void GetNormal(const SMikkTSpaceContext *pContext, float r_no[3], const int face_num, const int vert_index)
2560 {
2561         //assert(vert_index >= 0 && vert_index < 4);
2562         SGLSLMeshToTangent *pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
2563
2564         const int smoothnormal = (pMesh->mface[face_num].flag & ME_SMOOTH);
2565         if (!smoothnormal) {    // flat
2566                 if (pMesh->precomputedFaceNormals) {
2567                         copy_v3_v3(r_no, &pMesh->precomputedFaceNormals[3 * face_num]);
2568                 }
2569                 else {
2570                         MFace *mf = &pMesh->mface[face_num];
2571                         const float *p0 = pMesh->mvert[mf->v1].co;
2572                         const float *p1 = pMesh->mvert[mf->v2].co;
2573                         const float *p2 = pMesh->mvert[mf->v3].co;
2574
2575                         if (mf->v4) {
2576                                 const float *p3 = pMesh->mvert[mf->v4].co;
2577                                 normal_quad_v3(r_no, p0, p1, p2, p3);
2578                         }
2579                         else {
2580                                 normal_tri_v3(r_no, p0, p1, p2);
2581                         }
2582                 }
2583         }
2584         else {
2585                 const short *no = pMesh->mvert[(&pMesh->mface[face_num].v1)[vert_index]].no;
2586                 normal_short_to_float_v3(r_no, no);
2587         }
2588 }
2589 static void SetTSpace(const SMikkTSpaceContext *pContext, const float fvTangent[3], const float fSign, const int face_num, const int iVert)
2590 {
2591         //assert(vert_index >= 0 && vert_index < 4);
2592         SGLSLMeshToTangent *pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
2593         float *pRes = pMesh->tangent[4 * face_num + iVert];
2594         copy_v3_v3(pRes, fvTangent);
2595         pRes[3] = fSign;
2596 }
2597
2598
2599 void DM_add_tangent_layer(DerivedMesh *dm)
2600 {
2601         /* mesh vars */
2602         MVert *mvert;
2603         MTFace *mtface;
2604         MFace *mface;
2605         float (*orco)[3] = NULL, (*tangent)[4];
2606         int /* totvert, */ totface;
2607         float *nors;
2608
2609         if (CustomData_get_layer_index(&dm->faceData, CD_TANGENT) != -1)
2610                 return;
2611
2612         nors = dm->getTessFaceDataArray(dm, CD_NORMAL);
2613
2614         /* check we have all the needed layers */
2615         /* totvert = dm->getNumVerts(dm); */ /* UNUSED */
2616         totface = dm->getNumTessFaces(dm);
2617
2618         mvert = dm->getVertArray(dm);
2619         mface = dm->getTessFaceArray(dm);
2620         mtface = dm->getTessFaceDataArray(dm, CD_MTFACE);
2621
2622         if (!mtface) {
2623                 orco = dm->getVertDataArray(dm, CD_ORCO);
2624                 if (!orco)
2625                         return;
2626         }
2627         
2628         /* create tangent layer */
2629         DM_add_tessface_layer(dm, CD_TANGENT, CD_CALLOC, NULL);
2630         tangent = DM_get_tessface_data_layer(dm, CD_TANGENT);
2631         
2632         /* new computation method */
2633         {
2634                 SGLSLMeshToTangent mesh2tangent = {0};
2635                 SMikkTSpaceContext sContext = {0};
2636                 SMikkTSpaceInterface sInterface = {0};
2637
2638                 mesh2tangent.precomputedFaceNormals = nors;
2639                 mesh2tangent.mtface = mtface;
2640                 mesh2tangent.mface = mface;
2641                 mesh2tangent.mvert = mvert;
2642                 mesh2tangent.orco = orco;
2643                 mesh2tangent.tangent = tangent;
2644                 mesh2tangent.numTessFaces = totface;
2645
2646                 sContext.m_pUserData = &mesh2tangent;
2647                 sContext.m_pInterface = &sInterface;
2648                 sInterface.m_getNumFaces = GetNumFaces;
2649                 sInterface.m_getNumVerticesOfFace = GetNumVertsOfFace;
2650                 sInterface.m_getPosition = GetPosition;
2651                 sInterface.m_getTexCoord = GetTextureCoordinate;
2652                 sInterface.m_getNormal = GetNormal;
2653                 sInterface.m_setTSpaceBasic = SetTSpace;
2654
2655                 /* 0 if failed */
2656                 genTangSpaceDefault(&sContext);
2657         }
2658 }
2659
2660 void DM_calc_auto_bump_scale(DerivedMesh *dm)
2661 {
2662         /* int totvert = dm->getNumVerts(dm); */ /* UNUSED */
2663         int totface = dm->getNumTessFaces(dm);
2664
2665         MVert *mvert = dm->getVertArray(dm);
2666         MFace *mface = dm->getTessFaceArray(dm);
2667         MTFace *mtface = dm->getTessFaceDataArray(dm, CD_MTFACE);
2668
2669         if (mtface) {
2670                 double dsum = 0.0;
2671                 int nr_accumulated = 0;
2672                 int f;
2673
2674                 for (f = 0; f < totface; f++) {
2675                         {
2676                                 float *verts[4], *tex_coords[4];
2677                                 const int nr_verts = mface[f].v4 != 0 ? 4 : 3;
2678                                 int i, is_degenerate;
2679
2680                                 verts[0] = mvert[mface[f].v1].co; verts[1] = mvert[mface[f].v2].co; verts[2] = mvert[mface[f].v3].co;
2681                                 tex_coords[0] = mtface[f].uv[0]; tex_coords[1] = mtface[f].uv[1]; tex_coords[2] = mtface[f].uv[2];
2682                                 if (nr_verts == 4) {
2683                                         verts[3] = mvert[mface[f].v4].co;
2684                                         tex_coords[3] = mtface[f].uv[3];
2685                                 }
2686
2687                                 /* discard degenerate faces */
2688                                 is_degenerate = 0;
2689                                 if (equals_v3v3(verts[0], verts[1]) || equals_v3v3(verts[0], verts[2]) || equals_v3v3(verts[1], verts[2]) ||
2690                                     equals_v2v2(tex_coords[0], tex_coords[1]) || equals_v2v2(tex_coords[0], tex_coords[2]) || equals_v2v2(tex_coords[1], tex_coords[2]))
2691                                 {
2692                                         is_degenerate = 1;
2693                                 }
2694
2695                                 /* verify last vertex as well if this is a quad */
2696                                 if (is_degenerate == 0 && nr_verts == 4) {
2697                                         if (equals_v3v3(verts[3], verts[0]) || equals_v3v3(verts[3], verts[1]) || equals_v3v3(verts[3], verts[2]) ||
2698                                             equals_v2v2(tex_coords[3], tex_coords[0]) || equals_v2v2(tex_coords[3], tex_coords[1]) || equals_v2v2(tex_coords[3], tex_coords[2]))
2699                                         {
2700                                                 is_degenerate = 1;
2701                                         }
2702
2703                                         /* verify the winding is consistent */
2704                                         if (is_degenerate == 0) {
2705                                                 float prev_edge[2];
2706                                                 int is_signed = 0;
2707                                                 sub_v2_v2v2(prev_edge, tex_coords[0], tex_coords[3]);
2708
2709                                                 i = 0;
2710                                                 while (is_degenerate == 0 && i < 4) {
2711                                                         float cur_edge[2], signed_area;
2712                                                         sub_v2_v2v2(cur_edge, tex_coords[(i + 1) & 0x3], tex_coords[i]);
2713                                                         signed_area = prev_edge[0] * cur_edge[1] - prev_edge[1] * cur_edge[0];
2714
2715                                                         if (i == 0) {
2716                                                                 is_signed = (signed_area < 0.0f) ? 1 : 0;
2717                                                         }
2718                                                         else if ((is_signed != 0) != (signed_area < 0.0f)) {
2719                                                                 is_degenerate = 1;
2720                                                         }
2721
2722                                                         if (is_degenerate == 0) {
2723                                                                 copy_v2_v2(prev_edge, cur_edge);
2724                                                                 i++;
2725                                                         }
2726                                                 }
2727                                         }
2728                                 }
2729
2730                                 /* proceed if not a degenerate face */
2731                                 if (is_degenerate == 0) {
2732                                         int nr_tris_to_pile = 0;
2733                                         /* quads split at shortest diagonal */
2734                                         int offs = 0;  /* initial triangulation is 0,1,2 and 0, 2, 3 */
2735                                         if (nr_verts == 4) {
2736                                                 float pos_len_diag0, pos_len_diag1;
2737                                                 float vtmp[3];
2738                                                 sub_v3_v3v3(vtmp, verts[2], verts[0]);
2739                                                 pos_len_diag0 = dot_v3v3(vtmp, vtmp);
2740                                                 sub_v3_v3v3(vtmp, verts[3], verts[1]);
2741                                                 pos_len_diag1 = dot_v3v3(vtmp, vtmp);
2742
2743                                                 if (pos_len_diag1 < pos_len_diag0) {
2744                                                         offs = 1;     // alter split
2745                                                 }
2746                                                 else if (pos_len_diag0 == pos_len_diag1) { /* do UV check instead */
2747                                                         float tex_len_diag0, tex_len_diag1;
2748
2749                                                         sub_v2_v2v2(vtmp, tex_coords[2], tex_coords[0]);
2750                                                         tex_len_diag0 = dot_v2v2(vtmp, vtmp);
2751                                                         sub_v2_v2v2(vtmp, tex_coords[3], tex_coords[1]);
2752                                                         tex_len_diag1 = dot_v2v2(vtmp, vtmp);
2753
2754                                                         if (tex_len_diag1 < tex_len_diag0) {
2755                                                                 offs = 1; /* alter split */
2756                                                         }
2757                                                 }
2758                                         }
2759                                         nr_tris_to_pile = nr_verts - 2;
2760                                         if (nr_tris_to_pile == 1 || nr_tris_to_pile == 2) {
2761                                                 const int indices[] = {offs + 0, offs + 1, offs + 2, offs + 0, offs + 2, (offs + 3) & 0x3 };
2762                                                 int t;
2763                                                 for (t = 0; t < nr_tris_to_pile; t++) {
2764                                                         float f2x_area_uv;
2765                                                         float *p0 = verts[indices[t * 3 + 0]];
2766                                                         float *p1 = verts[indices[t * 3 + 1]];
2767                                                         float *p2 = verts[indices[t * 3 + 2]];
2768
2769                                                         float edge_t0[2], edge_t1[2];
2770                                                         sub_v2_v2v2(edge_t0, tex_coords[indices[t * 3 + 1]], tex_coords[indices[t * 3 + 0]]);
2771                                                         sub_v2_v2v2(edge_t1, tex_coords[indices[t * 3 + 2]], tex_coords[indices[t * 3 + 0]]);
2772
2773                                                         f2x_area_uv = fabsf(edge_t0[0] * edge_t1[1] - edge_t0[1] * edge_t1[0]);
2774                                                         if (f2x_area_uv > FLT_EPSILON) {
2775                                                                 float norm[3], v0[3], v1[3], f2x_surf_area, fsurf_ratio;
2776                                                                 sub_v3_v3v3(v0, p1, p0);
2777                                                                 sub_v3_v3v3(v1, p2, p0);
2778                                                                 cross_v3_v3v3(norm, v0, v1);
2779
2780                                                                 f2x_surf_area = len_v3(norm);
2781                                                                 fsurf_ratio = f2x_surf_area / f2x_area_uv;    // tri area divided by texture area
2782
2783                                                                 nr_accumulated++;
2784                                                                 dsum += (double)(fsurf_ratio);
2785                                                         }
2786                                                 }
2787                                         }
2788                                 }
2789                         }
2790                 }
2791
2792                 /* finalize */
2793                 {
2794                         const float avg_area_ratio = (nr_accumulated > 0) ? ((float)(dsum / nr_accumulated)) : 1.0f;
2795                         const float use_as_render_bump_scale = sqrtf(avg_area_ratio);       // use width of average surface ratio as your bump scale
2796                         dm->auto_bump_scale = use_as_render_bump_scale;
2797                 }
2798         }
2799         else {
2800                 dm->auto_bump_scale = 1.0f;
2801         }
2802 }
2803
2804 void DM_vertex_attributes_from_gpu(DerivedMesh *dm, GPUVertexAttribs *gattribs, DMVertexAttribs *attribs)
2805 {
2806         CustomData *vdata, *fdata, *tfdata = NULL;
2807         int a, b, layer;
2808
2809         /* From the layers requested by the GLSL shader, figure out which ones are
2810          * actually available for this derivedmesh, and retrieve the pointers */
2811
2812         memset(attribs, 0, sizeof(DMVertexAttribs));
2813
2814         vdata = &dm->vertData;
2815         fdata = tfdata = dm->getTessFaceDataLayout(dm);
2816         
2817         /* calc auto bump scale if necessary */
2818         if (dm->auto_bump_scale <= 0.0f)
2819                 DM_calc_auto_bump_scale(dm);
2820
2821         /* add a tangent layer if necessary */
2822         for (b = 0; b < gattribs->totlayer; b++)
2823                 if (gattribs->layer[b].type == CD_TANGENT)
2824                         if (CustomData_get_layer_index(fdata, CD_TANGENT) == -1)
2825                                 DM_add_tangent_layer(dm);
2826
2827         for (b = 0; b < gattribs->totlayer; b++) {
2828                 if (gattribs->layer[b].type == CD_MTFACE) {
2829                         /* uv coordinates */
2830                         if (dm->type == DM_TYPE_EDITBMESH) {
2831                                 /* exception .. */
2832                                 CustomData *ldata = dm->getLoopDataLayout(dm);
2833
2834                                 if (gattribs->layer[b].name[0])
2835                                         layer = CustomData_get_named_layer_index(ldata, CD_MLOOPUV,
2836                                                                                  gattribs->layer[b].name);
2837                                 else
2838                                         layer = CustomData_get_active_layer_index(ldata, CD_MLOOPUV);
2839
2840                                 if (layer != -1) {
2841                                         a = attribs->tottface++;
2842
2843                                         attribs->tface[a].array = tfdata->layers[layer].data;
2844                                         attribs->tface[a].em_offset = ldata->layers[layer].offset;
2845                                         attribs->tface[a].gl_index = gattribs->layer[b].glindex;
2846                                         attribs->tface[a].gl_texco = gattribs->layer[b].gltexco;
2847                                 }
2848                         }
2849                         else {
2850                                 if (gattribs->layer[b].name[0])
2851                                         layer = CustomData_get_named_layer_index(tfdata, CD_MTFACE,
2852                                                                                  gattribs->layer[b].name);
2853                                 else
2854                                         layer = CustomData_get_active_layer_index(tfdata, CD_MTFACE);
2855
2856                                 if (layer != -1) {
2857                                         a = attribs->tottface++;
2858
2859                                         attribs->tface[a].array = tfdata->layers[layer].data;
2860                                         attribs->tface[a].em_offset = tfdata->layers[layer].offset;
2861                                         attribs->tface[a].gl_index = gattribs->layer[b].glindex;
2862                                         attribs->tface[a].gl_texco = gattribs->layer[b].gltexco;
2863                                 }
2864                         }
2865                 }
2866                 else if (gattribs->layer[b].type == CD_MCOL) {
2867                         if (dm->type == DM_TYPE_EDITBMESH) {
2868                                 /* exception .. */
2869                                 CustomData *ldata = dm->getLoopDataLayout(dm);
2870
2871                                 if (gattribs->layer[b].name[0])
2872                                         layer = CustomData_get_named_layer_index(ldata, CD_MLOOPCOL,
2873                                                                                  gattribs->layer[b].name);
2874                                 else
2875                                         layer = CustomData_get_active_layer_index(ldata, CD_MLOOPCOL);
2876
2877                                 if (layer != -1) {
2878                                         a = attribs->totmcol++;
2879
2880                                         attribs->mcol[a].array = tfdata->layers[layer].data;
2881                                         /* odd, store the offset for a different layer type here, but editmode draw code expects it */
2882                                         attribs->mcol[a].em_offset = ldata->layers[layer].offset;
2883                                         attribs->mcol[a].gl_index = gattribs->layer[b].glindex;
2884                                 }
2885                         }
2886                         else {
2887                                 /* vertex colors */
2888                                 if (gattribs->layer[b].name[0])
2889                                         layer = CustomData_get_named_layer_index(tfdata, CD_MCOL,
2890                                                                                  gattribs->layer[b].name);
2891                                 else
2892                                         layer = CustomData_get_active_layer_index(tfdata, CD_MCOL);
2893
2894                                 if (layer != -1) {
2895                                         a = attribs->totmcol++;
2896
2897                                         attribs->mcol[a].array = tfdata->layers[layer].data;
2898                                         /* odd, store the offset for a different layer type here, but editmode draw code expects it */
2899                                         attribs->mcol[a].em_offset = tfdata->layers[layer].offset;
2900                                         attribs->mcol[a].gl_index = gattribs->layer[b].glindex;
2901                                 }
2902                         }
2903                 }
2904                 else if (gattribs->layer[b].type == CD_TANGENT) {
2905                         /* tangents */
2906                         layer = CustomData_get_layer_index(fdata, CD_TANGENT);
2907
2908                         if (layer != -1) {
2909                                 attribs->tottang = 1;
2910
2911                                 attribs->tang.array = fdata->layers[layer].data;
2912                                 attribs->tang.em_offset = fdata->layers[layer].offset;
2913                                 attribs->tang.gl_index = gattribs->layer[b].glindex;
2914                         }
2915                 }
2916                 else if (gattribs->layer[b].type == CD_ORCO) {
2917                         /* original coordinates */
2918                         layer = CustomData_get_layer_index(vdata, CD_ORCO);
2919
2920                         if (layer != -1) {
2921                                 attribs->totorco = 1;
2922
2923                                 attribs->orco.array = vdata->layers[layer].data;
2924                                 attribs->orco.em_offset = vdata->layers[layer].offset;
2925                                 attribs->orco.gl_index = gattribs->layer[b].glindex;
2926                                 attribs->orco.gl_texco = gattribs->layer[b].gltexco;
2927                         }
2928                 }
2929         }
2930 }
2931
2932 /* Set object's bounding box based on DerivedMesh min/max data */
2933 void DM_set_object_boundbox(Object *ob, DerivedMesh *dm)
2934 {
2935         float min[3], max[3];
2936
2937         INIT_MINMAX(min, max);
2938
2939         dm->getMinMax(dm, min, max);
2940
2941         if (!ob->bb)
2942                 ob->bb = MEM_callocN(sizeof(BoundBox), "DM-BoundBox");
2943
2944         BKE_boundbox_init_from_minmax(ob->bb, min, max);
2945 }
2946
2947 /* --- NAVMESH (begin) --- */
2948 #ifdef WITH_GAMEENGINE
2949
2950 /* BMESH_TODO, navmesh is not working right currently
2951  * All tools set this as MPoly data, but derived mesh currently draws from MFace (tessface)
2952  *
2953  * Proposed solution, rather then copy CD_RECAST into the MFace array,
2954  * use ORIGINDEX to get the original poly index and then get the CD_RECAST
2955  * data from the original me->mpoly layer. - campbell
2956  */
2957
2958
2959 BLI_INLINE int navmesh_bit(int a, int b)
2960 {
2961         return (a & (1 << b)) >> b;
2962 }
2963
2964 BLI_INLINE void navmesh_intToCol(int i, float col[3])
2965 {
2966         int r = navmesh_bit(i, 0) + navmesh_bit(i, 3) * 2 + 1;
2967         int g = navmesh_bit(i, 1) + navmesh_bit(i, 4) * 2 + 1;
2968         int b = navmesh_bit(i, 2) + navmesh_bit(i, 5) * 2 + 1;
2969         col[0] = 1 - r * 63.0f / 255.0f;
2970         col[1] = 1 - g * 63.0f / 255.0f;
2971         col[2] = 1 - b * 63.0f / 255.0f;
2972 }
2973
2974 static void navmesh_drawColored(DerivedMesh *dm)
2975 {
2976         int a, glmode;
2977         MVert *mvert = (MVert *)CustomData_get_layer(&dm->vertData, CD_MVERT);
2978         MFace *mface = (MFace *)CustomData_get_layer(&dm->faceData, CD_MFACE);
2979         int *polygonIdx = (int *)CustomData_get_layer(&dm->polyData, CD_RECAST);
2980         float col[3];
2981
2982         if (!polygonIdx)
2983                 return;
2984
2985 #if 0
2986         //UI_ThemeColor(TH_WIRE);
2987         glDisable(GL_LIGHTING);
2988         glLineWidth(2.0);
2989         dm->drawEdges(dm, 0, 1);
2990         glLineWidth(1.0);
2991         glEnable(GL_LIGHTING);
2992 #endif
2993
2994         glDisable(GL_LIGHTING);
2995         /* if (GPU_buffer_legacy(dm) ) */ { /* TODO - VBO draw code, not high priority - campbell */
2996                 DEBUG_VBO("Using legacy code. drawNavMeshColored\n");
2997                 //glShadeModel(GL_SMOOTH);
2998                 glBegin(glmode = GL_QUADS);
2999                 for (a = 0; a < dm->numTessFaceData; a++, mface++) {
3000                         int new_glmode = mface->v4 ? GL_QUADS : GL_TRIANGLES;
3001                         int pi = polygonIdx[a];
3002                         if (pi <= 0) {
3003                                 zero_v3(col);
3004                         }
3005                         else {
3006                                 navmesh_intToCol(pi, col);
3007                         }
3008
3009                         if (new_glmode != glmode) {
3010                                 glEnd();
3011                                 glBegin(glmode = new_glmode);
3012                         }
3013                         glColor3fv(col);
3014                         glVertex3fv(mvert[mface->v1].co);
3015                         glVertex3fv(mvert[mface->v2].co);
3016                         glVertex3fv(mvert[mface->v3].co);
3017                         if (mface->v4) {
3018                                 glVertex3fv(mvert[mface->v4].co);
3019                         }
3020                 }
3021                 glEnd();
3022         }
3023         glEnable(GL_LIGHTING);
3024 }
3025
3026 static void navmesh_DM_drawFacesTex(DerivedMesh *dm,
3027                                     DMSetDrawOptionsTex setDrawOptions,
3028                                     DMCompareDrawOptions compareDrawOptions,
3029                                     void *userData)
3030 {
3031         (void) setDrawOptions;
3032         (void) compareDrawOptions;
3033         (void) userData;
3034
3035         navmesh_drawColored(dm);
3036 }
3037
3038 static void navmesh_DM_drawFacesSolid(DerivedMesh *dm,
3039                                       float (*partial_redraw_planes)[4],
3040                                       int UNUSED(fast), DMSetMaterial setMaterial)
3041 {
3042         (void) partial_redraw_planes;
3043         (void) setMaterial;
3044
3045         //drawFacesSolid_original(dm, partial_redraw_planes, fast, setMaterial);
3046         navmesh_drawColored(dm);
3047 }
3048
3049 static DerivedMesh *navmesh_dm_createNavMeshForVisualization(DerivedMesh *dm)
3050 {
3051         DerivedMesh *result;
3052         int maxFaces = dm->getNumPolys(dm);
3053         int *recastData;
3054         int vertsPerPoly = 0, nverts = 0, ndtris = 0, npolys = 0;
3055         float *verts = NULL;
3056         unsigned short *dtris = NULL, *dmeshes = NULL, *polys = NULL;
3057         int *dtrisToPolysMap = NULL, *dtrisToTrisMap = NULL, *trisToFacesMap = NULL;
3058         int res;
3059
3060         result = CDDM_copy(dm);
3061         if (!CustomData_has_layer(&result->polyData, CD_RECAST)) {
3062                 int *sourceRecastData = (int *)CustomData_get_layer(&dm->polyData, CD_RECAST);
3063                 if (sourceRecastData) {
3064                         CustomData_add_layer_named(&result->polyData, CD_RECAST, CD_DUPLICATE,
3065                                                    sourceRecastData, maxFaces, "recastData");
3066                 }
3067         }
3068         recastData = (int *)CustomData_get_layer(&result->polyData, CD_RECAST);
3069
3070         /* note: This is not good design! - really should not be doing this */
3071         result->drawFacesTex =  navmesh_DM_drawFacesTex;
3072         result->drawFacesSolid = navmesh_DM_drawFacesSolid;
3073
3074
3075         /* process mesh */
3076         res  = buildNavMeshDataByDerivedMesh(dm, &vertsPerPoly, &nverts, &verts, &ndtris, &dtris,
3077                                              &npolys, &dmeshes, &polys, &dtrisToPolysMap, &dtrisToTrisMap,
3078                                              &trisToFacesMap);
3079         if (res) {
3080                 size_t