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