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