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