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