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