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