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