7d5a61181003871145c7a7568793344371c8f8da
[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         rgb_float_to_uchar(r_col, colf);
928         r_col[3] = 255; /* really redundant */
929 }
930
931
932 static void calc_weightpaint_vert_color(
933         unsigned char r_col[4],
934         MDeformVert *dv, ColorBand *coba,
935         const int defbase_tot, const int defbase_act,
936         const char *dg_flags,
937         const int selected, const int draw_flag)
938 {
939         float input = 0.0f;
940         
941         int make_black= FALSE;
942
943         if ((selected > 1) && (draw_flag & CALC_WP_MULTIPAINT)) {
944                 int was_a_nonzero= FALSE;
945                 unsigned int i;
946
947                 MDeformWeight *dw= dv->dw;
948                 for (i = dv->totweight; i != 0; i--, dw++) {
949                         /* in multipaint, get the average if auto normalize is inactive
950                          * get the sum if it is active */
951                         if (dw->def_nr < defbase_tot) {
952                                 if (dg_flags[dw->def_nr]) {
953                                         if (dw->weight) {
954                                                 input += dw->weight;
955                                                 was_a_nonzero= TRUE;
956                                         }
957                                 }
958                         }
959                 }
960
961                 /* make it black if the selected groups have no weight on a vertex */
962                 if (was_a_nonzero == FALSE) {
963                         make_black = TRUE;
964                 }
965                 else if ((draw_flag & CALC_WP_AUTO_NORMALIZE) == FALSE) {
966                         input /= selected; /* get the average */
967                 }
968         }
969         else {
970                 /* default, non tricky behavior */
971                 input= defvert_find_weight(dv, defbase_act);
972         }
973
974         if (make_black) { /* TODO, theme color */
975                 r_col[3] = 0;
976                 r_col[2] = 0;
977                 r_col[1] = 0;
978                 r_col[0] = 255;
979         }
980         else {
981                 CLAMP(input, 0.0f, 1.0f);
982                 weightpaint_color(r_col, coba, input);
983         }
984 }
985
986 static ColorBand *stored_cb= NULL;
987
988 void vDM_ColorBand_store(ColorBand *coba)
989 {
990         stored_cb= coba;
991 }
992
993 /* return an array of vertex weight colors, caller must free.
994  *
995  * note that we could save some memory and allocate RGB only but then we'd need to
996  * re-arrange the colors when copying to the face since MCol has odd ordering,
997  * so leave this as is - campbell */
998 static unsigned char *calc_weightpaint_vert_array(Object *ob, DerivedMesh *dm, int const draw_flag, ColorBand *coba)
999 {
1000         MDeformVert *dv = DM_get_vert_data_layer(dm, CD_MDEFORMVERT);
1001         int numVerts = dm->getNumVerts(dm);
1002         unsigned char *wtcol_v = MEM_mallocN (sizeof(unsigned char) * numVerts * 4, "weightmap_v");
1003
1004         if (dv) {
1005                 unsigned char *wc = wtcol_v;
1006                 unsigned int i;
1007
1008                 /* variables for multipaint */
1009                 const int defbase_tot = BLI_countlist(&ob->defbase);
1010                 const int defbase_act = ob->actdef-1;
1011                 char *dg_flags = MEM_mallocN(defbase_tot * sizeof(char), __func__);
1012                 const int selected = get_selected_defgroups(ob, dg_flags, defbase_tot);
1013
1014                 for (i = numVerts; i != 0; i--, wc += 4, dv++) {
1015                         calc_weightpaint_vert_color(wc, dv, coba, defbase_tot, defbase_act, dg_flags, selected, draw_flag);
1016                 }
1017
1018                 MEM_freeN(dg_flags);
1019         }
1020         else {
1021                 int col_i;
1022                 weightpaint_color((unsigned char *)&col_i, coba, 0.0f);
1023                 fill_vn_i((int *)wtcol_v, numVerts, col_i);
1024         }
1025
1026         return wtcol_v;
1027 }
1028
1029 /* return an array of vertex weight colors from given weights, caller must free.
1030  *
1031  * note that we could save some memory and allocate RGB only but then we'd need to
1032  * re-arrange the colors when copying to the face since MCol has odd ordering,
1033  * so leave this as is - campbell */
1034 static unsigned char *calc_colors_from_weights_array(const int num, float *weights)
1035 {
1036         unsigned char *wtcol_v = MEM_mallocN(sizeof(unsigned char) * num * 4, "weightmap_v");
1037         unsigned char *wc = wtcol_v;
1038         int i;
1039
1040         for (i = 0; i < num; i++, wc += 4, weights++)
1041                 weightpaint_color((unsigned char *) wc, NULL, *weights);
1042
1043         return wtcol_v;
1044 }
1045
1046 void DM_update_weight_mcol(Object *ob, DerivedMesh *dm, int const draw_flag,
1047                            float *weights, int num, const int *indices)
1048 {
1049         ColorBand *coba= stored_cb;     /* warning, not a local var */
1050
1051         unsigned char *wtcol_v;
1052 #if 0 /* See coment below. */
1053         unsigned char *wtcol_f = dm->getTessFaceDataArray(dm, CD_WEIGHT_MCOL);
1054 #endif
1055         unsigned char(*wtcol_l)[4] = CustomData_get_layer(dm->getLoopDataLayout(dm), CD_WEIGHT_MLOOPCOL);
1056 #if 0 /* See coment below. */
1057         MFace *mf = dm->getTessFaceArray(dm);
1058 #endif
1059         MLoop *mloop = dm->getLoopArray(dm), *ml;
1060         MPoly *mp = dm->getPolyArray(dm);
1061         int numFaces = dm->getNumTessFaces(dm);
1062         int numVerts = dm->getNumVerts(dm);
1063         int totloop;
1064         int i, j;
1065
1066 #if 0 /* See comment below */
1067         /* If no CD_WEIGHT_MCOL existed yet, add a new one! */
1068         if (!wtcol_f)
1069                 wtcol_f = CustomData_add_layer(&dm->faceData, CD_WEIGHT_MCOL, CD_CALLOC, NULL, numFaces);
1070
1071         if (wtcol_f) {
1072                 unsigned char *wtcol_f_step = wtcol_f;
1073 # else
1074         /* XXX We have to create a CD_WEIGHT_MCOL, else it might sigsev (after a SubSurf mod, eg)... */
1075         if(!dm->getTessFaceDataArray(dm, CD_WEIGHT_MCOL))
1076                 CustomData_add_layer(&dm->faceData, CD_WEIGHT_MCOL, CD_CALLOC, NULL, numFaces);
1077
1078         {
1079 #endif
1080
1081                 /* Weights are given by caller. */
1082                 if (weights) {
1083                         float *w = weights;
1084                         /* If indices is not NULL, it means we do not have weights for all vertices,
1085                          * so we must create them (and set them to zero)... */
1086                         if(indices) {
1087                                 w = MEM_callocN(sizeof(float)*numVerts, "Temp weight array DM_update_weight_mcol");
1088                                 i = num;
1089                                 while(i--)
1090                                         w[indices[i]] = weights[i];
1091                         }
1092
1093                         /* Convert float weights to colors. */
1094                         wtcol_v = calc_colors_from_weights_array(numVerts, w);
1095
1096                         if(indices)
1097                                 MEM_freeN(w);
1098                 }
1099
1100                 /* No weights given, take them from active vgroup(s). */
1101                 else
1102                         wtcol_v = calc_weightpaint_vert_array(ob, dm, draw_flag, coba);
1103
1104                 /* Now copy colors in all face verts. */
1105                 /*first add colors to the tessellation faces*/
1106                 /* XXX Why update that layer? We have to update WEIGHT_MLOOPCOL anyway, 
1107                  *     and tessellation recreates mface layers from mloop/mpoly ones, so no
1108                  *     need to fill WEIGHT_MCOL here. */
1109 #if 0
1110                 for (i = 0; i < numFaces; i++, mf++, wtcol_f_step += (4 * 4)) {
1111                         /*origindex being NULL means we're operating on original mesh data*/
1112 #if 0
1113                         unsigned int fidx= mf->v4 ? 3:2;
1114
1115 #else   /* better zero out triangles 4th component. else valgrind complains when the buffer's copied */
1116                         unsigned int fidx;
1117                         if (mf->v4) {
1118                                 fidx = 3;
1119                         }
1120                         else {
1121                                 fidx = 2;
1122                                 *(int *)(&wtcol_f_step[3 * 4]) = 0;
1123                         }
1124 #endif
1125
1126                         do {
1127                                 copy_v4_v4_char((char *)&wtcol_f_step[fidx * 4],
1128                                                 (char *)&wtcol_v[4 * (*(&mf->v1 + fidx))]);
1129                         } while (fidx--);
1130                 }
1131 #endif
1132                 /*now add to loops, so the data can be passed through the modifier stack*/
1133                 /* If no CD_WEIGHT_MLOOPCOL existed yet, we have to add a new one! */
1134                 if (!wtcol_l) {
1135                         BLI_array_declare(wtcol_l);
1136                         totloop = 0;
1137                         for (i=0; i<dm->numPolyData; i++, mp++) {
1138                                 ml = mloop + mp->loopstart;
1139
1140                                 BLI_array_growitems(wtcol_l, mp->totloop);
1141                                 for (j = 0; j < mp->totloop; j++, ml++, totloop++) {
1142                                         copy_v4_v4_char((char *)&wtcol_l[totloop],
1143                                                         (char *)&wtcol_v[4 * ml->v]);
1144                                 }
1145                         }
1146                         CustomData_add_layer(&dm->loopData, CD_WEIGHT_MLOOPCOL, CD_ASSIGN, wtcol_l, totloop);
1147                 }
1148                 else {
1149                         totloop = 0;
1150                         for (i=0; i < dm->numPolyData; i++, mp++) {
1151                                 ml = mloop + mp->loopstart;
1152
1153                                 for (j=0; j < mp->totloop; j++, ml++, totloop++) {
1154                                         copy_v4_v4_char((char *)&wtcol_l[totloop],
1155                                                         (char *)&wtcol_v[4 * ml->v]);
1156                                 }
1157                         }
1158                 }
1159                 MEM_freeN(wtcol_v);
1160         }
1161 }
1162
1163
1164 static void shapekey_layers_to_keyblocks(DerivedMesh *dm, Mesh *me, int actshape_uid)
1165 {
1166         KeyBlock *kb;
1167         int i, j, tot;
1168         
1169         if (!me->key)
1170                 return; 
1171         
1172         tot = CustomData_number_of_layers(&dm->vertData, CD_SHAPEKEY);
1173         for (i=0; i<tot; i++) {
1174                 CustomDataLayer *layer = &dm->vertData.layers[CustomData_get_layer_index_n(&dm->vertData, CD_SHAPEKEY, i)];
1175                 float (*cos)[3], (*kbcos)[3];
1176                 
1177                 for (kb=me->key->block.first; kb; kb=kb->next) {
1178                         if (kb->uid == layer->uid)
1179                                 break;
1180                 }
1181                 
1182                 if (!kb) {
1183                         kb = add_keyblock(me->key, layer->name);
1184                         kb->uid = layer->uid;
1185                 }
1186                 
1187                 if (kb->data)
1188                         MEM_freeN(kb->data);
1189                 
1190                 cos = CustomData_get_layer_n(&dm->vertData, CD_SHAPEKEY, i);
1191                 kb->totelem = dm->numVertData;
1192
1193                 kb->data = kbcos = MEM_mallocN(sizeof(float)*3*kb->totelem, "kbcos DerivedMesh.c");
1194                 if (kb->uid == actshape_uid) {
1195                         MVert *mvert = dm->getVertArray(dm);
1196                         
1197                         for (j=0; j<dm->numVertData; j++, kbcos++, mvert++) {
1198                                 copy_v3_v3(*kbcos, mvert->co);
1199                         }
1200                 } else {
1201                         for (j=0; j<kb->totelem; j++, cos++, kbcos++) {
1202                                 copy_v3_v3(*kbcos, *cos);
1203                         }
1204                 }
1205         }
1206         
1207         for (kb=me->key->block.first; kb; kb=kb->next) {
1208                 if (kb->totelem != dm->numVertData) {
1209                         if (kb->data)
1210                                 MEM_freeN(kb->data);
1211                         
1212                         kb->totelem = dm->numVertData;
1213                         kb->data = MEM_callocN(sizeof(float)*3*kb->totelem, "kb->data derivedmesh.c");
1214                         fprintf(stderr, "%s: lost a shapekey layer! (bmesh internal error)\n", __func__);
1215                 }
1216         }
1217 }
1218
1219 static void add_shapekey_layers(DerivedMesh *dm, Mesh *me, Object *UNUSED(ob))
1220 {
1221         KeyBlock *kb;
1222         Key *key = me->key;
1223         int i;
1224         const size_t shape_alloc_len = sizeof(float) * 3 * me->totvert;
1225
1226         if (!me->key)
1227                 return;
1228
1229         /* ensure we can use mesh vertex count for derived mesh custom data */
1230         if (me->totvert != dm->getNumVerts(dm)) {
1231                 fprintf(stderr,
1232                         "%s: vertex size mismatch (mesh/dm) '%s' (%d != %d)\n",
1233                         __func__, me->id.name+2, me->totvert, dm->getNumVerts(dm));
1234                 return;
1235         }
1236
1237         for (i=0, kb=key->block.first; kb; kb=kb->next, i++) {
1238                 int ci;
1239                 float *array;
1240
1241                 if (me->totvert != kb->totelem) {
1242                         fprintf(stderr,
1243                                 "%s: vertex size mismatch (mesh/keyblock) '%s' (%d != %d)\n",
1244                                 __func__, me->id.name+2, me->totvert, kb->totelem);
1245                         array = MEM_callocN(shape_alloc_len, __func__);
1246                 }
1247                 else {
1248                         array = MEM_mallocN(shape_alloc_len, __func__);
1249                         memcpy(array, kb->data, shape_alloc_len);
1250                 }
1251
1252                 CustomData_add_layer_named(&dm->vertData, CD_SHAPEKEY, CD_ASSIGN, array, dm->numVertData, kb->name);
1253                 ci = CustomData_get_layer_index_n(&dm->vertData, CD_SHAPEKEY, i);
1254
1255                 dm->vertData.layers[ci].uid = kb->uid;
1256         }
1257 }
1258
1259 /* new value for useDeform -1  (hack for the gameengine):
1260  * - apply only the modifier stack of the object, skipping the virtual modifiers,
1261  * - don't apply the key
1262  * - apply deform modifiers and input vertexco
1263  */
1264 static void mesh_calc_modifiers(Scene *scene, Object *ob, float (*inputVertexCos)[3],
1265                                                                 DerivedMesh **deform_r, DerivedMesh **final_r,
1266                                                                 int useRenderParams, int useDeform,
1267                                                                 int needMapping, CustomDataMask dataMask, 
1268                                                                 int index, int useCache, int build_shapekey_layers)
1269 {
1270         Mesh *me = ob->data;
1271         ModifierData *firstmd, *md, *previewmd = NULL;
1272         LinkNode *datamasks, *curr;
1273         CustomDataMask mask, nextmask, append_mask = 0;
1274         float (*deformedVerts)[3] = NULL;
1275         DerivedMesh *dm=NULL, *orcodm, *clothorcodm, *finaldm;
1276         int numVerts = me->totvert;
1277         int required_mode;
1278         int isPrevDeform= FALSE;
1279         int skipVirtualArmature = (useDeform < 0);
1280         MultiresModifierData *mmd= get_multires_modifier(scene, ob, 0);
1281         int has_multires = mmd != NULL, multires_applied = 0;
1282         int sculpt_mode = ob->mode & OB_MODE_SCULPT && ob->sculpt;
1283
1284         const int draw_flag= ((scene->toolsettings->multipaint ? CALC_WP_MULTIPAINT : 0) |
1285                               (scene->toolsettings->auto_normalize ? CALC_WP_AUTO_NORMALIZE : 0));
1286         /* Generic preview only in object mode! */
1287         const int do_mod_mcol = (ob->mode == OB_MODE_OBJECT);
1288 #if 0 /* XXX Will re-enable this when we have global mod stack options. */
1289         const int do_final_wmcol = (scene->toolsettings->weights_preview == WP_WPREVIEW_FINAL) && do_wmcol;
1290 #endif
1291         const int do_final_wmcol = FALSE;
1292         int do_init_wmcol = ((dataMask & CD_MASK_WEIGHT_MCOL) && (ob->mode & OB_MODE_WEIGHT_PAINT) && !do_final_wmcol);
1293         /* XXX Same as above... For now, only weights preview in WPaint mode. */
1294         const int do_mod_wmcol = do_init_wmcol;
1295
1296         if(mmd && !mmd->sculptlvl)
1297                 has_multires = 0;
1298
1299         if(!skipVirtualArmature) {
1300                 firstmd = modifiers_getVirtualModifierList(ob);
1301         }
1302         else {
1303                 /* game engine exception */
1304                 firstmd = ob->modifiers.first;
1305                 if(firstmd && firstmd->type == eModifierType_Armature)
1306                         firstmd = firstmd->next;
1307         }
1308
1309         md = firstmd;
1310
1311         modifiers_clearErrors(ob);
1312
1313         if(useRenderParams) required_mode = eModifierMode_Render;
1314         else required_mode = eModifierMode_Realtime;
1315
1316         datamasks = modifiers_calcDataMasks(scene, ob, md, dataMask, required_mode);
1317         curr = datamasks;
1318
1319         if(do_mod_wmcol || do_mod_mcol) {
1320                 /* Find the last active modifier generating a preview, or NULL if none. */
1321                 /* XXX Currently, DPaint modifier just ignores this.
1322                  *     Needs a stupid hack...
1323                  *     The whole "modifier preview" thing has to be (re?)designed, anyway! */
1324                 previewmd = modifiers_getLastPreview(scene, md, required_mode);
1325         }
1326
1327         if(deform_r) *deform_r = NULL;
1328         *final_r = NULL;
1329
1330         if(useDeform) {
1331                 if(inputVertexCos)
1332                         deformedVerts = inputVertexCos;
1333                 
1334                 /* Apply all leading deforming modifiers */
1335                 for(;md; md = md->next, curr = curr->next) {
1336                         ModifierTypeInfo *mti = modifierType_getInfo(md->type);
1337
1338                         md->scene= scene;
1339                         
1340                         if(!modifier_isEnabled(scene, md, required_mode)) continue;
1341                         if(useDeform < 0 && mti->dependsOnTime && mti->dependsOnTime(md)) continue;
1342
1343                         if(mti->type == eModifierTypeType_OnlyDeform) {
1344                                 if(!deformedVerts)
1345                                         deformedVerts = mesh_getVertexCos(me, &numVerts);
1346
1347                                 mti->deformVerts(md, ob, NULL, deformedVerts, numVerts, useRenderParams, useDeform);
1348                         } else {
1349                                 break;
1350                         }
1351                         
1352                         /* grab modifiers until index i */
1353                         if((index >= 0) && (modifiers_indexInObject(ob, md) >= index))
1354                                 break;
1355                 }
1356
1357                 /* Result of all leading deforming modifiers is cached for
1358                  * places that wish to use the original mesh but with deformed
1359                  * coordinates (vpaint, etc.)
1360                  */
1361                 if (deform_r) {
1362                         *deform_r = CDDM_from_mesh(me, ob);
1363                          
1364                         if (build_shapekey_layers)
1365                                 add_shapekey_layers(dm, me, ob);
1366                         
1367                         if(deformedVerts) {
1368                                 CDDM_apply_vert_coords(*deform_r, deformedVerts);
1369                                 CDDM_calc_normals(*deform_r);
1370                         }
1371                 }
1372         } else {
1373                 /* default behavior for meshes */
1374                 if(inputVertexCos)
1375                         deformedVerts = inputVertexCos;
1376                 else
1377                         deformedVerts = mesh_getVertexCos(me, &numVerts);
1378         }
1379
1380
1381         /* Now apply all remaining modifiers. If useDeform is off then skip
1382          * OnlyDeform ones. 
1383          */
1384         dm = NULL;
1385         orcodm = NULL;
1386         clothorcodm = NULL;
1387
1388         for(;md; md = md->next, curr = curr->next) {
1389                 ModifierTypeInfo *mti = modifierType_getInfo(md->type);
1390
1391                 md->scene= scene;
1392
1393                 if(!modifier_isEnabled(scene, md, required_mode)) continue;
1394                 if(mti->type == eModifierTypeType_OnlyDeform && !useDeform) continue;
1395                 if((mti->flags & eModifierTypeFlag_RequiresOriginalData) && dm) {
1396                         modifier_setError(md, TIP_("Modifier requires original data, bad stack position."));
1397                         continue;
1398                 }
1399                 if(sculpt_mode && (!has_multires || multires_applied)) {
1400                         int unsupported= 0;
1401
1402                         if(scene->toolsettings->sculpt->flags & SCULPT_ONLY_DEFORM)
1403                                 unsupported|= mti->type != eModifierTypeType_OnlyDeform;
1404
1405                         unsupported|= md->type == eModifierType_Multires && ((MultiresModifierData*)md)->sculptlvl==0;
1406                         unsupported|= multires_applied;
1407
1408                         if(unsupported) {
1409                                 modifier_setError(md, TIP_("Not supported in sculpt mode."));
1410                                 continue;
1411                         }
1412                 }
1413                 if(needMapping && !modifier_supportsMapping(md)) continue;
1414                 if(useDeform < 0 && mti->dependsOnTime && mti->dependsOnTime(md)) continue;
1415
1416                 /* add an orco layer if needed by this modifier */
1417                 if(mti->requiredDataMask)
1418                         mask = mti->requiredDataMask(ob, md);
1419                 else
1420                         mask = 0;
1421
1422                 if(dm && (mask & CD_MASK_ORCO))
1423                         add_orco_dm(ob, NULL, dm, orcodm, CD_ORCO);
1424
1425                 /* How to apply modifier depends on (a) what we already have as
1426                  * a result of previous modifiers (could be a DerivedMesh or just
1427                  * deformed vertices) and (b) what type the modifier is.
1428                  */
1429
1430                 if(mti->type == eModifierTypeType_OnlyDeform) {
1431                         /* No existing verts to deform, need to build them. */
1432                         if(!deformedVerts) {
1433                                 if(dm) {
1434                                         /* Deforming a derived mesh, read the vertex locations
1435                                          * out of the mesh and deform them. Once done with this
1436                                          * run of deformers verts will be written back.
1437                                          */
1438                                         numVerts = dm->getNumVerts(dm);
1439                                         deformedVerts =
1440                                                 MEM_mallocN(sizeof(*deformedVerts) * numVerts, "dfmv");
1441                                         dm->getVertCos(dm, deformedVerts);
1442                                 } else {
1443                                         deformedVerts = mesh_getVertexCos(me, &numVerts);
1444                                 }
1445                         }
1446
1447                         /* if this is not the last modifier in the stack then recalculate the normals
1448                          * to avoid giving bogus normals to the next modifier see: [#23673] */
1449                         if(isPrevDeform &&  mti->dependsOnNormals && mti->dependsOnNormals(md)) {
1450                                 /* XXX, this covers bug #23673, but we may need normal calc for other types */
1451                                 if(dm && dm->type == DM_TYPE_CDDM) {
1452                                         CDDM_apply_vert_coords(dm, deformedVerts);
1453                                         CDDM_calc_normals(dm);
1454                                 }
1455                         }
1456
1457                         mti->deformVerts(md, ob, dm, deformedVerts, numVerts, useRenderParams, useDeform);
1458                 } else {
1459                         DerivedMesh *ndm;
1460
1461                         /* determine which data layers are needed by following modifiers */
1462                         if(curr->next)
1463                                 nextmask= (CustomDataMask)GET_INT_FROM_POINTER(curr->next->link);
1464                         else
1465                                 nextmask= dataMask;
1466
1467                         /* apply vertex coordinates or build a DerivedMesh as necessary */
1468                         if(dm) {
1469                                 if(deformedVerts) {
1470                                         DerivedMesh *tdm = CDDM_copy(dm);
1471                                         dm->release(dm);
1472                                         dm = tdm;
1473
1474                                         CDDM_apply_vert_coords(dm, deformedVerts);
1475                                         CDDM_calc_normals(dm);
1476                                 }
1477                         } else {
1478                                 dm = CDDM_from_mesh(me, ob);
1479
1480                                 if (build_shapekey_layers)
1481                                         add_shapekey_layers(dm, me, ob);
1482
1483                                 if(deformedVerts) {
1484                                         CDDM_apply_vert_coords(dm, deformedVerts);
1485                                         CDDM_calc_normals(dm);
1486                                 }
1487
1488                                 if(do_init_wmcol)
1489                                         DM_update_weight_mcol(ob, dm, draw_flag, NULL, 0, NULL);
1490
1491                                 /* Constructive modifiers need to have an origindex
1492                                  * otherwise they wont have anywhere to copy the data from.
1493                                  *
1494                                  * Also create ORIGINDEX data if any of the following modifiers
1495                                  * requests it, this way Mirror, Solidify etc will keep ORIGINDEX
1496                                  * data by using generic DM_copy_vert_data() functions.
1497                                  */
1498                                 if(needMapping || (nextmask & CD_MASK_ORIGINDEX)) {
1499                                         /* calc */
1500                                         DM_add_vert_layer(dm, CD_ORIGINDEX, CD_CALLOC, NULL);
1501                                         DM_add_edge_layer(dm, CD_ORIGINDEX, CD_CALLOC, NULL);
1502                                         DM_add_poly_layer(dm, CD_ORIGINDEX, CD_CALLOC, NULL);
1503
1504                                         range_vn_i(DM_get_vert_data_layer(dm, CD_ORIGINDEX), dm->numVertData, 0);
1505                                         range_vn_i(DM_get_edge_data_layer(dm, CD_ORIGINDEX), dm->numEdgeData, 0);
1506                                         range_vn_i(DM_get_poly_data_layer(dm, CD_ORIGINDEX), dm->numPolyData, 0);
1507                                 }
1508                         }
1509
1510                         
1511                         /* set the DerivedMesh to only copy needed data */
1512                         mask= (CustomDataMask)GET_INT_FROM_POINTER(curr->link);
1513                         /* needMapping check here fixes bug [#28112], otherwise its
1514                          * possible that it wont be copied */
1515                         mask |= append_mask;
1516                         DM_set_only_copy(dm, mask | (needMapping ? CD_MASK_ORIGINDEX : 0));
1517                         
1518                         /* add cloth rest shape key if need */
1519                         if(mask & CD_MASK_CLOTH_ORCO)
1520                                 add_orco_dm(ob, NULL, dm, clothorcodm, CD_CLOTH_ORCO);
1521
1522                         /* add an origspace layer if needed */
1523                         if(((CustomDataMask)GET_INT_FROM_POINTER(curr->link)) & CD_MASK_ORIGSPACE_MLOOP) {
1524                                 if(!CustomData_has_layer(&dm->loopData, CD_ORIGSPACE_MLOOP)) {
1525                                         DM_add_loop_layer(dm, CD_ORIGSPACE_MLOOP, CD_CALLOC, NULL);
1526                                         DM_init_origspace(dm);
1527                                 }
1528                         }
1529
1530                         ndm = mti->applyModifier(md, ob, dm, useRenderParams, useCache);
1531
1532                         if(ndm) {
1533                                 /* if the modifier returned a new dm, release the old one */
1534                                 if(dm && dm != ndm) dm->release(dm);
1535
1536                                 dm = ndm;
1537
1538                                 if(deformedVerts) {
1539                                         if(deformedVerts != inputVertexCos)
1540                                                 MEM_freeN(deformedVerts);
1541
1542                                         deformedVerts = NULL;
1543                                 }
1544                         } 
1545
1546                         /* create an orco derivedmesh in parallel */
1547                         if(nextmask & CD_MASK_ORCO) {
1548                                 if(!orcodm)
1549                                         orcodm= create_orco_dm(ob, me, NULL, CD_ORCO);
1550
1551                                 nextmask &= ~CD_MASK_ORCO;
1552                                 DM_set_only_copy(orcodm, nextmask | CD_MASK_ORIGINDEX);
1553                                 ndm = mti->applyModifier(md, ob, orcodm, useRenderParams, 0);
1554
1555                                 if(ndm) {
1556                                         /* if the modifier returned a new dm, release the old one */
1557                                         if(orcodm && orcodm != ndm) orcodm->release(orcodm);
1558                                         orcodm = ndm;
1559                                 }
1560                         }
1561
1562                         /* create cloth orco derivedmesh in parallel */
1563                         if(nextmask & CD_MASK_CLOTH_ORCO) {
1564                                 if(!clothorcodm)
1565                                         clothorcodm= create_orco_dm(ob, me, NULL, CD_CLOTH_ORCO);
1566
1567                                 nextmask &= ~CD_MASK_CLOTH_ORCO;
1568                                 DM_set_only_copy(clothorcodm, nextmask | CD_MASK_ORIGINDEX);
1569                                 ndm = mti->applyModifier(md, ob, clothorcodm, useRenderParams, 0);
1570
1571                                 if(ndm) {
1572                                         /* if the modifier returned a new dm, release the old one */
1573                                         if(clothorcodm && clothorcodm != ndm) clothorcodm->release(clothorcodm);
1574                                         clothorcodm = ndm;
1575                                 }
1576                         }
1577
1578                         /* in case of dynamic paint, make sure preview mask remains for following modifiers */
1579                         /* XXX Temp and hackish solution! */
1580                         if (md->type == eModifierType_DynamicPaint)
1581                                 append_mask |= CD_MASK_WEIGHT_MCOL;
1582                         /* In case of active preview modifier, make sure preview mask remains for following modifiers. */
1583                         else if ((md == previewmd) && (do_mod_wmcol)) {
1584                                 DM_update_weight_mcol(ob, dm, draw_flag, NULL, 0, NULL);
1585                                 append_mask |= CD_MASK_WEIGHT_MCOL;
1586                         }
1587                 }
1588
1589                 isPrevDeform= (mti->type == eModifierTypeType_OnlyDeform);
1590
1591                 /* grab modifiers until index i */
1592                 if((index >= 0) && (modifiers_indexInObject(ob, md) >= index))
1593                         break;
1594
1595                 if(sculpt_mode && md->type == eModifierType_Multires)
1596                         multires_applied = 1;
1597         }
1598
1599         for(md=firstmd; md; md=md->next)
1600                 modifier_freeTemporaryData(md);
1601
1602         /* Yay, we are done. If we have a DerivedMesh and deformed vertices
1603          * need to apply these back onto the DerivedMesh. If we have no
1604          * DerivedMesh then we need to build one.
1605          */
1606         if(dm && deformedVerts) {
1607                 finaldm = CDDM_copy(dm);
1608
1609                 dm->release(dm);
1610
1611                 CDDM_apply_vert_coords(finaldm, deformedVerts);
1612                 CDDM_calc_normals(finaldm);
1613
1614 #if 0 /* For later nice mod preview! */
1615                 /* In case we need modified weights in CD_WEIGHT_MCOL, we have to re-compute it. */
1616                 if(do_final_wmcol)
1617                         DM_update_weight_mcol(ob, finaldm, draw_flag, NULL, 0, NULL);
1618 #endif
1619         } else if(dm) {
1620                 finaldm = dm;
1621
1622 #if 0 /* For later nice mod preview! */
1623                 /* In case we need modified weights in CD_WEIGHT_MCOL, we have to re-compute it. */
1624                 if(do_final_wmcol)
1625                         DM_update_weight_mcol(ob, finaldm, draw_flag, NULL, 0, NULL);
1626 #endif
1627         } else {
1628                 int recalc_normals= 0;
1629
1630                 finaldm = CDDM_from_mesh(me, ob);
1631                 
1632                 if(build_shapekey_layers) {
1633                         add_shapekey_layers(finaldm, me, ob);
1634                         recalc_normals= 1;
1635                 }
1636                 
1637                 if(deformedVerts) {
1638                         CDDM_apply_vert_coords(finaldm, deformedVerts);
1639                         recalc_normals= 1;
1640                 }
1641
1642                 if(recalc_normals) {
1643                         CDDM_calc_normals(finaldm);
1644                 }
1645
1646                 /* In this case, we should never have weight-modifying modifiers in stack... */
1647                 if(do_init_wmcol)
1648                         DM_update_weight_mcol(ob, finaldm, draw_flag, NULL, 0, NULL);
1649         }
1650
1651         /* add an orco layer if needed */
1652         if(dataMask & CD_MASK_ORCO) {
1653                 add_orco_dm(ob, NULL, finaldm, orcodm, CD_ORCO);
1654
1655                 if(deform_r && *deform_r)
1656                         add_orco_dm(ob, NULL, *deform_r, NULL, CD_ORCO);
1657         }
1658
1659 #ifdef WITH_GAMEENGINE
1660         /* NavMesh - this is a hack but saves having a NavMesh modifier */
1661         if ((ob->gameflag & OB_NAVMESH) && (finaldm->type == DM_TYPE_CDDM)) {
1662                 DerivedMesh *tdm;
1663                 tdm= navmesh_dm_createNavMeshForVisualization(finaldm);
1664                 if (finaldm != tdm) {
1665                         finaldm->release(finaldm);
1666                         finaldm= tdm;
1667                 }
1668         }
1669 #endif /* WITH_GAMEENGINE */
1670
1671         {
1672                 /* calculating normals can re-calculate tessfaces in some cases */
1673                 int num_tessface = finaldm->getNumTessFaces(finaldm);
1674                 /* --------------------------------------------------------------------- */
1675                 /* First calculate the polygon and vertex normals, re-tessellation
1676                  * copies these into the tessface's normal layer */
1677
1678
1679                 /* comment because this causes a bug when deform is applied after a
1680                  * bug when applied after a subsurf modifier (SubSurf -> Cast) for eg,
1681                  * it also looks like this isn't even needed since code above recalc's
1682                  * normals - campbell */
1683 #if 0
1684                 finaldm->calcNormals(finaldm);
1685 #endif
1686
1687                 /* Re-tessellation is necessary to push render data (uvs, textures, colors)
1688                  * from loops and polys onto the tessfaces. This may be currently be
1689                  * redundant in cases where the render mode doesn't use these inputs, but
1690                  * ideally eventually tessellation would happen on-demand, and this is one
1691                  * of the primary places it would be needed. */
1692                 if (num_tessface == 0 && finaldm->getNumTessFaces(finaldm) == 0) {
1693                         finaldm->recalcTessellation(finaldm);
1694                 }
1695                 /* Need to watch this, it can cause issues, see bug [#29338]             */
1696                 /* take care with this block, we really need testing frameworks          */
1697                 /* --------------------------------------------------------------------- */
1698         }
1699
1700
1701         *final_r = finaldm;
1702
1703         if(orcodm)
1704                 orcodm->release(orcodm);
1705         if(clothorcodm)
1706                 clothorcodm->release(clothorcodm);
1707
1708         if(deformedVerts && deformedVerts != inputVertexCos)
1709                 MEM_freeN(deformedVerts);
1710
1711         BLI_linklist_free(datamasks, NULL);
1712 }
1713
1714 float (*editbmesh_get_vertex_cos(BMEditMesh *em, int *numVerts_r))[3]
1715 {
1716         int i, numVerts = *numVerts_r = em->bm->totvert;
1717         float (*cos)[3];
1718         BMIter iter;
1719         BMVert *eve;
1720
1721         cos = MEM_mallocN(sizeof(float)*3*numVerts, "vertexcos");
1722
1723         eve = BM_iter_new(&iter, em->bm, BM_VERTS_OF_MESH, NULL);
1724         for (i=0; eve; eve=BM_iter_step(&iter), i++) {
1725                 copy_v3_v3(cos[i], eve->co);
1726         }
1727
1728         return cos;
1729 }
1730
1731 int editbmesh_modifier_is_enabled(Scene *scene, ModifierData *md, DerivedMesh *dm)
1732 {
1733         ModifierTypeInfo *mti = modifierType_getInfo(md->type);
1734         int required_mode = eModifierMode_Realtime | eModifierMode_Editmode;
1735
1736         if(!modifier_isEnabled(scene, md, required_mode)) return 0;
1737         if((mti->flags & eModifierTypeFlag_RequiresOriginalData) && dm) {
1738                 modifier_setError(md, TIP_("Modifier requires original data, bad stack position."));
1739                 return 0;
1740         }
1741         
1742         return 1;
1743 }
1744
1745 static void editbmesh_calc_modifiers(Scene *scene, Object *ob, BMEditMesh *em, DerivedMesh **cage_r,
1746                                                                         DerivedMesh **final_r,
1747                                                                         CustomDataMask dataMask)
1748 {
1749         ModifierData *md;
1750         float (*deformedVerts)[3] = NULL;
1751         CustomDataMask mask;
1752         DerivedMesh *dm, *orcodm = NULL;
1753         int i, numVerts = 0, cageIndex = modifiers_getCageIndex(scene, ob, NULL, 1);
1754         LinkNode *datamasks, *curr;
1755         int required_mode = eModifierMode_Realtime | eModifierMode_Editmode;
1756
1757         modifiers_clearErrors(ob);
1758
1759         if(cage_r && cageIndex == -1) {
1760                 *cage_r = getEditDerivedBMesh(em, ob, NULL);
1761         }
1762
1763         dm = NULL;
1764         md = modifiers_getVirtualModifierList(ob);
1765
1766         datamasks = modifiers_calcDataMasks(scene, ob, md, dataMask, required_mode);
1767
1768         curr = datamasks;
1769         for(i = 0; md; i++, md = md->next, curr = curr->next) {
1770                 ModifierTypeInfo *mti = modifierType_getInfo(md->type);
1771
1772                 md->scene= scene;
1773                 
1774                 if(!editbmesh_modifier_is_enabled(scene, md, dm))
1775                         continue;
1776
1777                 /* add an orco layer if needed by this modifier */
1778                 if(dm && mti->requiredDataMask) {
1779                         mask = mti->requiredDataMask(ob, md);
1780                         if(mask & CD_MASK_ORCO)
1781                                 add_orco_dm(ob, em, dm, orcodm, CD_ORCO);
1782                 }
1783
1784                 /* How to apply modifier depends on (a) what we already have as
1785                  * a result of previous modifiers (could be a DerivedMesh or just
1786                  * deformed vertices) and (b) what type the modifier is.
1787                  */
1788
1789                 if(mti->type == eModifierTypeType_OnlyDeform) {
1790                         /* No existing verts to deform, need to build them. */
1791                         if(!deformedVerts) {
1792                                 if(dm) {
1793                                         /* Deforming a derived mesh, read the vertex locations
1794                                          * out of the mesh and deform them. Once done with this
1795                                          * run of deformers verts will be written back.
1796                                          */
1797                                         numVerts = dm->getNumVerts(dm);
1798                                         deformedVerts =
1799                                                 MEM_mallocN(sizeof(*deformedVerts) * numVerts, "dfmv");
1800                                         dm->getVertCos(dm, deformedVerts);
1801                                 } else {
1802                                         deformedVerts = editbmesh_get_vertex_cos(em, &numVerts);
1803                                 }
1804                         }
1805
1806                         if (mti->deformVertsEM)
1807                                 mti->deformVertsEM(md, ob, em, dm, deformedVerts, numVerts);
1808                         else mti->deformVerts(md, ob, dm, deformedVerts, numVerts, 0, 0);
1809                 } else {
1810                         DerivedMesh *ndm;
1811
1812                         /* apply vertex coordinates or build a DerivedMesh as necessary */
1813                         if(dm) {
1814                                 if(deformedVerts) {
1815                                         DerivedMesh *tdm = CDDM_copy(dm);
1816                                         if(!(cage_r && dm == *cage_r)) dm->release(dm);
1817                                         dm = tdm;
1818
1819                                         CDDM_apply_vert_coords(dm, deformedVerts);
1820                                         CDDM_calc_normals(dm);
1821                                 } else if(cage_r && dm == *cage_r) {
1822                                         /* dm may be changed by this modifier, so we need to copy it
1823                                          */
1824                                         dm = CDDM_copy(dm);
1825                                 }
1826
1827                         } else {
1828                                 dm = CDDM_from_BMEditMesh(em, ob->data, FALSE, FALSE);
1829
1830                                 if(deformedVerts) {
1831                                         CDDM_apply_vert_coords(dm, deformedVerts);
1832                                         CDDM_calc_normals(dm);
1833                                 }
1834                         }
1835
1836                         /* create an orco derivedmesh in parallel */
1837                         mask= (CustomDataMask)GET_INT_FROM_POINTER(curr->link);
1838                         if(mask & CD_MASK_ORCO) {
1839                                 if(!orcodm)
1840                                         orcodm= create_orco_dm(ob, ob->data, em, CD_ORCO);
1841
1842                                 mask &= ~CD_MASK_ORCO;
1843                                 DM_set_only_copy(orcodm, mask | CD_MASK_ORIGINDEX);
1844
1845                                 if (mti->applyModifierEM)
1846                                         ndm = mti->applyModifierEM(md, ob, em, orcodm);
1847                                 else
1848                                         ndm = mti->applyModifier(md, ob, orcodm, 0, 0);
1849
1850                                 if(ndm) {
1851                                         /* if the modifier returned a new dm, release the old one */
1852                                         if(orcodm && orcodm != ndm) orcodm->release(orcodm);
1853                                         orcodm = ndm;
1854                                 }
1855                         }
1856
1857                         /* set the DerivedMesh to only copy needed data */
1858                         mask= (CustomDataMask)GET_INT_FROM_POINTER(curr->link); /* CD_MASK_ORCO may have been cleared above */
1859
1860                         DM_set_only_copy(dm, mask | CD_MASK_ORIGINDEX);
1861
1862                         if(mask & CD_MASK_ORIGSPACE_MLOOP) {
1863                                 if(!CustomData_has_layer(&dm->loopData, CD_ORIGSPACE_MLOOP)) {
1864                                         DM_add_loop_layer(dm, CD_ORIGSPACE_MLOOP, CD_CALLOC, NULL);
1865                                         DM_init_origspace(dm);
1866                                 }
1867                         }
1868                         
1869                         if (mti->applyModifierEM)
1870                                 ndm = mti->applyModifierEM(md, ob, em, dm);
1871                         else
1872                                 ndm = mti->applyModifier(md, ob, dm, 0, 0);
1873
1874                         if (ndm) {
1875                                 if(dm && dm != ndm)
1876                                         dm->release(dm);
1877
1878                                 dm = ndm;
1879
1880                                 if (deformedVerts) {
1881                                         MEM_freeN(deformedVerts);
1882                                         deformedVerts = NULL;
1883                                 }
1884                         }
1885                 }
1886
1887                 if(cage_r && i == cageIndex) {
1888                         if(dm && deformedVerts) {
1889                                 *cage_r = CDDM_copy(dm);
1890                                 CDDM_apply_vert_coords(*cage_r, deformedVerts);
1891                         } else if(dm) {
1892                                 *cage_r = dm;
1893                         } else {
1894                                 *cage_r =
1895                                         getEditDerivedBMesh(em, ob,
1896                                                 deformedVerts ? MEM_dupallocN(deformedVerts) : NULL);
1897                         }
1898                 }
1899         }
1900
1901         BLI_linklist_free(datamasks, NULL);
1902
1903         /* Yay, we are done. If we have a DerivedMesh and deformed vertices need
1904          * to apply these back onto the DerivedMesh. If we have no DerivedMesh
1905          * then we need to build one.
1906          */
1907         if(dm && deformedVerts) {
1908                 *final_r = CDDM_copy(dm);
1909
1910                 if(!(cage_r && dm == *cage_r)) dm->release(dm);
1911
1912                 CDDM_apply_vert_coords(*final_r, deformedVerts);
1913                 CDDM_calc_normals(*final_r); /* was CDDM_calc_normals_mapping - campbell */
1914         }
1915         else if (dm) {
1916                 *final_r = dm;
1917                 (*final_r)->calcNormals(*final_r); /* BMESH_ONLY - BMESH_TODO. check if this is needed */
1918         }
1919         else if (!deformedVerts && cage_r && *cage_r) {
1920                 /* cage should already have up to date normals */
1921                 *final_r = *cage_r;
1922                 (*final_r)->calcNormals(*final_r); /* BMESH_ONLY - BMESH_TODO. check if this is needed */
1923         }
1924         else {
1925                 /* this is just a copy of the editmesh, no need to calc normals */
1926                 *final_r = getEditDerivedBMesh(em, ob, deformedVerts);
1927                 deformedVerts = NULL;
1928         }
1929
1930         /* --- */
1931         /* BMESH_ONLY, ensure tessface's used for drawing,
1932          * but dont recalculate if the last modifier in the stack gives us tessfaces
1933          * check if the derived meshes are DM_TYPE_EDITBMESH before calling, this isnt essential
1934          * but quiets annoying error messages since tessfaces wont be created. */
1935         if ((*final_r)->type != DM_TYPE_EDITBMESH) {
1936                 DM_ensure_tessface(*final_r);
1937         }
1938         if (cage_r) {
1939                 if ((*cage_r)->type != DM_TYPE_EDITBMESH) {
1940                         if (*cage_r != *final_r) {
1941                                 DM_ensure_tessface(*cage_r);
1942                         }
1943                 }
1944         }
1945         /* --- */
1946
1947         /* add an orco layer if needed */
1948         if(dataMask & CD_MASK_ORCO)
1949                 add_orco_dm(ob, em, *final_r, orcodm, CD_ORCO);
1950
1951         if(orcodm)
1952                 orcodm->release(orcodm);
1953
1954         if(deformedVerts)
1955                 MEM_freeN(deformedVerts);
1956 }
1957
1958 static void clear_mesh_caches(Object *ob)
1959 {
1960         Mesh *me= ob->data;
1961
1962                 /* also serves as signal to remake texspace */
1963         if (ob->bb) {
1964                 MEM_freeN(ob->bb);
1965                 ob->bb = NULL;
1966         }
1967         if (me->bb) {
1968                 MEM_freeN(me->bb);
1969                 me->bb = NULL;
1970         }
1971
1972         freedisplist(&ob->disp);
1973
1974         if (ob->derivedFinal) {
1975                 ob->derivedFinal->needsFree = 1;
1976                 ob->derivedFinal->release(ob->derivedFinal);
1977                 ob->derivedFinal= NULL;
1978         }
1979         if (ob->derivedDeform) {
1980                 ob->derivedDeform->needsFree = 1;
1981                 ob->derivedDeform->release(ob->derivedDeform);
1982                 ob->derivedDeform= NULL;
1983         }
1984
1985         if(ob->sculpt) {
1986                 object_sculpt_modifiers_changed(ob);
1987         }
1988 }
1989
1990 static void mesh_build_data(Scene *scene, Object *ob, CustomDataMask dataMask,
1991                             int build_shapekey_layers)
1992 {
1993         Object *obact = scene->basact?scene->basact->object:NULL;
1994         int editing = paint_facesel_test(ob);
1995         /* weight paint and face select need original indices because of selection buffer drawing */
1996         int needMapping = (ob==obact) && (editing || (ob->mode & (OB_MODE_WEIGHT_PAINT|OB_MODE_VERTEX_PAINT|OB_MODE_TEXTURE_PAINT)));
1997
1998         clear_mesh_caches(ob);
1999
2000         mesh_calc_modifiers(scene, ob, NULL, &ob->derivedDeform,
2001                                                 &ob->derivedFinal, 0, 1,
2002                                                 needMapping, dataMask, -1, 1, build_shapekey_layers);
2003
2004         DM_set_object_boundbox (ob, ob->derivedFinal);
2005
2006         ob->derivedFinal->needsFree = 0;
2007         ob->derivedDeform->needsFree = 0;
2008         ob->lastDataMask = dataMask;
2009
2010         if((ob->mode & OB_MODE_SCULPT) && ob->sculpt) {
2011                 /* create PBVH immediately (would be created on the fly too,
2012                    but this avoids waiting on first stroke) */
2013                 ob->sculpt->pbvh= ob->derivedFinal->getPBVH(ob, ob->derivedFinal);
2014         }
2015 }
2016
2017 static void editbmesh_build_data(Scene *scene, Object *obedit, BMEditMesh *em, CustomDataMask dataMask)
2018 {
2019         clear_mesh_caches(obedit);
2020
2021         if (em->derivedFinal) {
2022                 if (em->derivedFinal!=em->derivedCage) {
2023                         em->derivedFinal->needsFree = 1;
2024                         em->derivedFinal->release(em->derivedFinal);
2025                 }
2026                 em->derivedFinal = NULL;
2027         }
2028         if (em->derivedCage) {
2029                 em->derivedCage->needsFree = 1;
2030                 em->derivedCage->release(em->derivedCage);
2031                 em->derivedCage = NULL;
2032         }
2033
2034         editbmesh_calc_modifiers(scene, obedit, em, &em->derivedCage, &em->derivedFinal, dataMask);
2035         DM_set_object_boundbox (obedit, em->derivedFinal);
2036
2037         em->lastDataMask = dataMask;
2038         em->derivedFinal->needsFree = 0;
2039         em->derivedCage->needsFree = 0;
2040 }
2041
2042 void makeDerivedMesh(Scene *scene, Object *ob, BMEditMesh *em,
2043                      CustomDataMask dataMask, int build_shapekey_layers)
2044 {
2045         if (em) {
2046                 editbmesh_build_data(scene, ob, em, dataMask);
2047         } else {
2048                 mesh_build_data(scene, ob, dataMask, build_shapekey_layers);
2049         }
2050 }
2051
2052 /***/
2053
2054 DerivedMesh *mesh_get_derived_final(Scene *scene, Object *ob, CustomDataMask dataMask)
2055 {
2056         /* if there's no derived mesh or the last data mask used doesn't include
2057          * the data we need, rebuild the derived mesh
2058          */
2059         if(!ob->derivedFinal || (dataMask & ob->lastDataMask) != dataMask)
2060                 mesh_build_data(scene, ob, dataMask, 0);
2061
2062         return ob->derivedFinal;
2063 }
2064
2065 DerivedMesh *mesh_get_derived_deform(Scene *scene, Object *ob, CustomDataMask dataMask)
2066 {
2067         /* if there's no derived mesh or the last data mask used doesn't include
2068          * the data we need, rebuild the derived mesh
2069          */
2070         if(!ob->derivedDeform || (dataMask & ob->lastDataMask) != dataMask)
2071                 mesh_build_data(scene, ob, dataMask, 0);
2072
2073         return ob->derivedDeform;
2074 }
2075
2076 DerivedMesh *mesh_create_derived_render(Scene *scene, Object *ob, CustomDataMask dataMask)
2077 {
2078         DerivedMesh *final;
2079         
2080         mesh_calc_modifiers(scene, ob, NULL, NULL, &final, 1, 1, 0, dataMask, -1, 0, 0);
2081
2082         return final;
2083 }
2084
2085 DerivedMesh *mesh_create_derived_index_render(Scene *scene, Object *ob, CustomDataMask dataMask, int index)
2086 {
2087         DerivedMesh *final;
2088         
2089         mesh_calc_modifiers(scene, ob, NULL, NULL, &final, 1, 1, 0, dataMask, index, 0, 0);
2090
2091         return final;
2092 }
2093
2094 DerivedMesh *mesh_create_derived_view(Scene *scene, Object *ob, CustomDataMask dataMask)
2095 {
2096         DerivedMesh *final;
2097
2098         mesh_calc_modifiers(scene, ob, NULL, NULL, &final, 0, 1, 0, dataMask, -1, 0, 0);
2099
2100         return final;
2101 }
2102
2103 DerivedMesh *mesh_create_derived_no_deform(Scene *scene, Object *ob, float (*vertCos)[3],
2104                                                                                    CustomDataMask dataMask)
2105 {
2106         DerivedMesh *final;
2107         
2108         mesh_calc_modifiers(scene, ob, vertCos, NULL, &final, 0, 0, 0, dataMask, -1, 0, 0);
2109
2110         return final;
2111 }
2112
2113 DerivedMesh *mesh_create_derived_no_virtual(Scene *scene, Object *ob, float (*vertCos)[3],
2114                                                                                         CustomDataMask dataMask)
2115 {
2116         DerivedMesh *final;
2117         
2118         mesh_calc_modifiers(scene, ob, vertCos, NULL, &final, 0, -1, 0, dataMask, -1, 0, 0);
2119
2120         return final;
2121 }
2122
2123 DerivedMesh *mesh_create_derived_physics(Scene *scene, Object *ob, float (*vertCos)[3],
2124                                                                                         CustomDataMask dataMask)
2125 {
2126         DerivedMesh *final;
2127         
2128         mesh_calc_modifiers(scene, ob, vertCos, NULL, &final, 0, -1, 1, dataMask, -1, 0, 0);
2129
2130         return final;
2131 }
2132
2133 DerivedMesh *mesh_create_derived_no_deform_render(Scene *scene, Object *ob,
2134                                                                                                   float (*vertCos)[3],
2135                                                                                                   CustomDataMask dataMask)
2136 {
2137         DerivedMesh *final;
2138
2139         mesh_calc_modifiers(scene, ob, vertCos, NULL, &final, 1, 0, 0, dataMask, -1, 0, 0);
2140
2141         return final;
2142 }
2143
2144 /***/
2145
2146 DerivedMesh *editbmesh_get_derived_cage_and_final(Scene *scene, Object *obedit, BMEditMesh *em, DerivedMesh **final_r,
2147                                                                                                  CustomDataMask dataMask)
2148 {
2149         /* if there's no derived mesh or the last data mask used doesn't include
2150          * the data we need, rebuild the derived mesh
2151          */
2152         if(!em->derivedCage ||
2153            (em->lastDataMask & dataMask) != dataMask)
2154                 editbmesh_build_data(scene, obedit, em, dataMask);
2155
2156         *final_r = em->derivedFinal;
2157         return em->derivedCage;
2158 }
2159
2160 DerivedMesh *editbmesh_get_derived_cage(Scene *scene, Object *obedit, BMEditMesh *em, CustomDataMask dataMask)
2161 {
2162         /* if there's no derived mesh or the last data mask used doesn't include
2163          * the data we need, rebuild the derived mesh
2164          */
2165         if(!em->derivedCage ||
2166            (em->lastDataMask & dataMask) != dataMask)
2167                 editbmesh_build_data(scene, obedit, em, dataMask);
2168
2169         return em->derivedCage;
2170 }
2171
2172 DerivedMesh *editbmesh_get_derived_base(Object *obedit, BMEditMesh *em)
2173 {
2174         return getEditDerivedBMesh(em, obedit, NULL);
2175 }
2176
2177
2178 /* ********* For those who don't grasp derived stuff! (ton) :) *************** */
2179
2180 static void make_vertexcosnos__mapFunc(void *userData, int index, float *co, float *no_f, short *no_s)
2181 {
2182         float *vec = userData;
2183         
2184         vec+= 6*index;
2185
2186         /* check if we've been here before (normal should not be 0) */
2187         if(vec[3] || vec[4] || vec[5]) return;
2188
2189         copy_v3_v3(vec, co);
2190         vec+= 3;
2191         if(no_f) {
2192                 copy_v3_v3(vec, no_f);
2193         }
2194         else {
2195                 normal_short_to_float_v3(vec, no_s);
2196         }
2197 }
2198
2199 /* always returns original amount me->totvert of vertices and normals, but fully deformed and subsurfered */
2200 /* this is needed for all code using vertexgroups (no subsurf support) */
2201 /* it stores the normals as floats, but they can still be scaled as shorts (32767 = unit) */
2202 /* in use now by vertex/weight paint and particle generating */
2203
2204 float *mesh_get_mapped_verts_nors(Scene *scene, Object *ob)
2205 {
2206         Mesh *me= ob->data;
2207         DerivedMesh *dm;
2208         float *vertexcosnos;
2209         
2210         /* lets prevent crashing... */
2211         if(ob->type!=OB_MESH || me->totvert==0)
2212                 return NULL;
2213         
2214         dm= mesh_get_derived_final(scene, ob, CD_MASK_BAREMESH|CD_MASK_ORIGINDEX);
2215         vertexcosnos= MEM_callocN(6*sizeof(float)*me->totvert, "vertexcosnos map");
2216         
2217         if(dm->foreachMappedVert) {
2218                 dm->foreachMappedVert(dm, make_vertexcosnos__mapFunc, vertexcosnos);
2219         }
2220         else {
2221                 float *fp= vertexcosnos;
2222                 int a;
2223                 
2224                 for(a=0; a< me->totvert; a++, fp+=6) {
2225                         dm->getVertCo(dm, a, fp);
2226                         dm->getVertNo(dm, a, fp+3);
2227                 }
2228         }
2229         
2230         dm->release(dm);
2231         return vertexcosnos;
2232 }
2233
2234 /* ******************* GLSL ******************** */
2235
2236 typedef struct
2237 {
2238         float * precomputedFaceNormals;
2239         MTFace * mtface;        // texture coordinates
2240         MFace * mface;          // indices
2241         MVert * mvert;          // vertices & normals
2242         float (*orco)[3];
2243         float (*tangent)[4];    // destination
2244         int numTessFaces;
2245
2246 } SGLSLMeshToTangent;
2247
2248 // interface
2249 #include "mikktspace.h"
2250
2251 static int GetNumFaces(const SMikkTSpaceContext * pContext)
2252 {
2253         SGLSLMeshToTangent * pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
2254         return pMesh->numTessFaces;
2255 }
2256
2257 static int GetNumVertsOfFace(const SMikkTSpaceContext * pContext, const int face_num)
2258 {
2259         SGLSLMeshToTangent * pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
2260         return pMesh->mface[face_num].v4!=0 ? 4 : 3;
2261 }
2262
2263 static void GetPosition(const SMikkTSpaceContext * pContext, float fPos[], const int face_num, const int vert_index)
2264 {
2265         //assert(vert_index>=0 && vert_index<4);
2266         SGLSLMeshToTangent * pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
2267         const float *co= pMesh->mvert[(&pMesh->mface[face_num].v1)[vert_index]].co;
2268         copy_v3_v3(fPos, co);
2269 }
2270
2271 static void GetTextureCoordinate(const SMikkTSpaceContext * pContext, float fUV[], const int face_num, const int vert_index)
2272 {
2273         //assert(vert_index>=0 && vert_index<4);
2274         SGLSLMeshToTangent * pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
2275
2276         if(pMesh->mtface!=NULL) {
2277                 float * uv = pMesh->mtface[face_num].uv[vert_index];
2278                 fUV[0]=uv[0]; fUV[1]=uv[1];
2279         }
2280         else {
2281                 const float *orco= pMesh->orco[(&pMesh->mface[face_num].v1)[vert_index]];
2282                 map_to_sphere( &fUV[0], &fUV[1], orco[0], orco[1], orco[2]);
2283         }
2284 }
2285
2286 static void GetNormal(const SMikkTSpaceContext * pContext, float fNorm[], const int face_num, const int vert_index)
2287 {
2288         //assert(vert_index>=0 && vert_index<4);
2289         SGLSLMeshToTangent * pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
2290
2291         const int smoothnormal = (pMesh->mface[face_num].flag & ME_SMOOTH);
2292         if(!smoothnormal) {     // flat
2293                 if(pMesh->precomputedFaceNormals) {
2294                         copy_v3_v3(fNorm, &pMesh->precomputedFaceNormals[3*face_num]);
2295                 }
2296                 else {
2297                         MFace *mf= &pMesh->mface[face_num];
2298                         float *p0= pMesh->mvert[mf->v1].co;
2299                         float *p1= pMesh->mvert[mf->v2].co;
2300                         float *p2= pMesh->mvert[mf->v3].co;
2301
2302                         if(mf->v4) {
2303                                 float *p3 = pMesh->mvert[mf->v4].co;
2304                                 normal_quad_v3(fNorm, p0, p1, p2, p3);
2305                         }
2306                         else {
2307                                 normal_tri_v3(fNorm, p0, p1, p2);
2308                         }
2309                 }
2310         }
2311         else {
2312                 const short *no= pMesh->mvert[(&pMesh->mface[face_num].v1)[vert_index]].no;
2313                 normal_short_to_float_v3(fNorm, no);
2314         }
2315 }
2316 static void SetTSpace(const SMikkTSpaceContext * pContext, const float fvTangent[], const float fSign, const int face_num, const int iVert)
2317 {
2318         //assert(vert_index>=0 && vert_index<4);
2319         SGLSLMeshToTangent * pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
2320         float * pRes = pMesh->tangent[4*face_num+iVert];
2321         copy_v3_v3(pRes, fvTangent);
2322         pRes[3]=fSign;
2323 }
2324
2325
2326 void DM_add_tangent_layer(DerivedMesh *dm)
2327 {
2328         /* mesh vars */
2329         MTFace *mtface, *tf;
2330         MFace *mface, *mf;
2331         MVert *mvert, *v1, *v2, *v3, *v4;
2332         MemArena *arena= NULL;
2333         VertexTangent **vtangents= NULL;
2334         float (*orco)[3]= NULL, (*tangent)[4];
2335         float *uv1, *uv2, *uv3, *uv4, *vtang;
2336         float fno[3], tang[3], uv[4][2];
2337         int i, j, len, mf_vi[4], totvert, totface, iCalcNewMethod;
2338         float *nors;
2339
2340         if(CustomData_get_layer_index(&dm->faceData, CD_TANGENT) != -1)
2341                 return;
2342
2343         nors = dm->getTessFaceDataArray(dm, CD_NORMAL);
2344
2345         /* check we have all the needed layers */
2346         totvert= dm->getNumVerts(dm);
2347         totface= dm->getNumTessFaces(dm);
2348
2349         mvert= dm->getVertArray(dm);
2350         mface= dm->getTessFaceArray(dm);
2351         mtface= dm->getTessFaceDataArray(dm, CD_MTFACE);
2352
2353         if(!mtface) {
2354                 orco= dm->getVertDataArray(dm, CD_ORCO);
2355                 if(!orco)
2356                         return;
2357         }
2358         
2359         /* create tangent layer */
2360         DM_add_tessface_layer(dm, CD_TANGENT, CD_CALLOC, NULL);
2361         tangent= DM_get_tessface_data_layer(dm, CD_TANGENT);
2362         
2363         /* allocate some space */
2364         arena= BLI_memarena_new(BLI_MEMARENA_STD_BUFSIZE, "tangent layer arena");
2365         BLI_memarena_use_calloc(arena);
2366         vtangents= MEM_callocN(sizeof(VertexTangent*)*totvert, "VertexTangent");
2367
2368         // new computation method
2369         iCalcNewMethod = 1;
2370         if(iCalcNewMethod != 0) {
2371                 SGLSLMeshToTangent mesh2tangent= {0};
2372                 SMikkTSpaceContext sContext= {0};
2373                 SMikkTSpaceInterface sInterface= {0};
2374
2375                 mesh2tangent.precomputedFaceNormals = nors;
2376                 mesh2tangent.mtface = mtface;
2377                 mesh2tangent.mface = mface;
2378                 mesh2tangent.mvert = mvert;
2379                 mesh2tangent.orco = orco;
2380                 mesh2tangent.tangent = tangent;
2381                 mesh2tangent.numTessFaces = totface;
2382
2383                 sContext.m_pUserData = &mesh2tangent;
2384                 sContext.m_pInterface = &sInterface;
2385                 sInterface.m_getNumFaces = GetNumFaces;
2386                 sInterface.m_getNumVerticesOfFace = GetNumVertsOfFace;
2387                 sInterface.m_getPosition = GetPosition;
2388                 sInterface.m_getTexCoord = GetTextureCoordinate;
2389                 sInterface.m_getNormal = GetNormal;
2390                 sInterface.m_setTSpaceBasic = SetTSpace;
2391
2392                 // 0 if failed
2393                 iCalcNewMethod = genTangSpaceDefault(&sContext);
2394         }
2395
2396         if(!iCalcNewMethod) {
2397                 /* sum tangents at connected vertices */
2398                 for(i=0, tf=mtface, mf=mface; i < totface; mf++, tf++, i++) {
2399                         v1= &mvert[mf->v1];
2400                         v2= &mvert[mf->v2];
2401                         v3= &mvert[mf->v3];
2402
2403                         if (mf->v4) {
2404                                 v4= &mvert[mf->v4];
2405                                 normal_quad_v3( fno,v4->co, v3->co, v2->co, v1->co);
2406                         }
2407                         else {
2408                                 v4= NULL;
2409                                 normal_tri_v3( fno,v3->co, v2->co, v1->co);
2410                         }
2411                 
2412                         if(mtface) {
2413                                 uv1= tf->uv[0];
2414                                 uv2= tf->uv[1];
2415                                 uv3= tf->uv[2];
2416                                 uv4= tf->uv[3];
2417                         }
2418                         else {
2419                                 uv1= uv[0]; uv2= uv[1]; uv3= uv[2]; uv4= uv[3];
2420                                 map_to_sphere( &uv[0][0], &uv[0][1],orco[mf->v1][0], orco[mf->v1][1], orco[mf->v1][2]);
2421                                 map_to_sphere( &uv[1][0], &uv[1][1],orco[mf->v2][0], orco[mf->v2][1], orco[mf->v2][2]);
2422                                 map_to_sphere( &uv[2][0], &uv[2][1],orco[mf->v3][0], orco[mf->v3][1], orco[mf->v3][2]);
2423                                 if(v4)
2424                                         map_to_sphere( &uv[3][0], &uv[3][1],orco[mf->v4][0], orco[mf->v4][1], orco[mf->v4][2]);
2425                         }
2426                 
2427                         tangent_from_uv(uv1, uv2, uv3, v1->co, v2->co, v3->co, fno, tang);
2428                         sum_or_add_vertex_tangent(arena, &vtangents[mf->v1], tang, uv1);
2429                         sum_or_add_vertex_tangent(arena, &vtangents[mf->v2], tang, uv2);
2430                         sum_or_add_vertex_tangent(arena, &vtangents[mf->v3], tang, uv3);
2431                 
2432                         if(mf->v4) {
2433                                 v4= &mvert[mf->v4];
2434                         
2435                                 tangent_from_uv(uv1, uv3, uv4, v1->co, v3->co, v4->co, fno, tang);
2436                                 sum_or_add_vertex_tangent(arena, &vtangents[mf->v1], tang, uv1);
2437                                 sum_or_add_vertex_tangent(arena, &vtangents[mf->v3], tang, uv3);
2438                                 sum_or_add_vertex_tangent(arena, &vtangents[mf->v4], tang, uv4);
2439                         }
2440                 }
2441         
2442                 /* write tangent to layer */
2443                 for(i=0, tf=mtface, mf=mface; i < totface; mf++, tf++, i++, tangent+=4) {
2444                         len= (mf->v4)? 4 : 3; 
2445
2446                         if(mtface == NULL) {
2447                                 map_to_sphere( &uv[0][0], &uv[0][1],orco[mf->v1][0], orco[mf->v1][1], orco[mf->v1][2]);
2448                                 map_to_sphere( &uv[1][0], &uv[1][1],orco[mf->v2][0], orco[mf->v2][1], orco[mf->v2][2]);
2449                                 map_to_sphere( &uv[2][0], &uv[2][1],orco[mf->v3][0], orco[mf->v3][1], orco[mf->v3][2]);
2450                                 if(len==4)
2451                                         map_to_sphere( &uv[3][0], &uv[3][1],orco[mf->v4][0], orco[mf->v4][1], orco[mf->v4][2]);
2452                         }
2453                 
2454                         mf_vi[0]= mf->v1;
2455                         mf_vi[1]= mf->v2;
2456                         mf_vi[2]= mf->v3;
2457                         mf_vi[3]= mf->v4;
2458                 
2459                         for(j=0; j<len; j++) {
2460                                 vtang= find_vertex_tangent(vtangents[mf_vi[j]], mtface ? tf->uv[j] : uv[j]);
2461                                 normalize_v3_v3(tangent[j], vtang);
2462                                 ((float *) tangent[j])[3]=1.0f;
2463                         }
2464                 }
2465         }
2466         
2467         BLI_memarena_free(arena);
2468         MEM_freeN(vtangents);
2469 }
2470
2471 void DM_calc_auto_bump_scale(DerivedMesh *dm)
2472 {
2473         /* int totvert= dm->getNumVerts(dm); */ /* UNUSED */
2474         int totface= dm->getNumTessFaces(dm);
2475
2476         MVert * mvert = dm->getVertArray(dm);
2477         MFace * mface = dm->getTessFaceArray(dm);
2478         MTFace * mtface = dm->getTessFaceDataArray(dm, CD_MTFACE);
2479
2480         if(mtface) {
2481                 double dsum = 0.0;
2482                 int nr_accumulated = 0;
2483                 int f;
2484
2485                 for ( f=0; f < totface; f++ ) {
2486                         {
2487                                 float * verts[4], * tex_coords[4];
2488                                 const int nr_verts = mface[f].v4!=0 ? 4 : 3;
2489                                 int i, is_degenerate;
2490
2491                                 verts[0]=mvert[mface[f].v1].co; verts[1]=mvert[mface[f].v2].co; verts[2]=mvert[mface[f].v3].co;
2492                                 tex_coords[0]=mtface[f].uv[0]; tex_coords[1]=mtface[f].uv[1]; tex_coords[2]=mtface[f].uv[2];
2493                                 if (nr_verts==4) {
2494                                         verts[3]=mvert[mface[f].v4].co;
2495                                         tex_coords[3]=mtface[f].uv[3];
2496                                 }
2497
2498                                 // discard degenerate faces
2499                                 is_degenerate = 0;
2500                                 if(     equals_v3v3(verts[0], verts[1]) || equals_v3v3(verts[0], verts[2]) || equals_v3v3(verts[1], verts[2]) ||
2501                                         equals_v2v2(tex_coords[0], tex_coords[1]) || equals_v2v2(tex_coords[0], tex_coords[2]) || equals_v2v2(tex_coords[1], tex_coords[2]) )
2502                                 {
2503                                         is_degenerate = 1;
2504                                 }
2505
2506                                 // verify last vertex as well if this is a quad
2507                                 if (is_degenerate == 0 && nr_verts == 4) {
2508                                         if (equals_v3v3(verts[3], verts[0]) || equals_v3v3(verts[3], verts[1]) || equals_v3v3(verts[3], verts[2]) ||
2509                                             equals_v2v2(tex_coords[3], tex_coords[0]) || equals_v2v2(tex_coords[3], tex_coords[1]) || equals_v2v2(tex_coords[3], tex_coords[2]) )
2510                                         {
2511                                                 is_degenerate = 1;
2512                                         }
2513
2514                                         // verify the winding is consistent
2515                                         if (is_degenerate == 0) {
2516                                                 float prev_edge[2];
2517                                                 int is_signed = 0;
2518                                                 sub_v2_v2v2(prev_edge, tex_coords[0], tex_coords[3]);
2519
2520                                                 i = 0;
2521                                                 while (is_degenerate == 0 && i < 4) {
2522                                                         float cur_edge[2], signed_area;
2523                                                         sub_v2_v2v2(cur_edge, tex_coords[(i+1)&0x3], tex_coords[i]);
2524                                                         signed_area = prev_edge[0]*cur_edge[1] - prev_edge[1]*cur_edge[0];
2525
2526                                                         if (i == 0 ) {
2527                                                                 is_signed = (signed_area < 0.0f) ? 1 : 0;
2528                                                         }
2529                                                         else if((is_signed != 0) != (signed_area < 0.0f)) {
2530                                                                 is_degenerate = 1;
2531                                                         }
2532
2533                                                         if (is_degenerate == 0) {
2534                                                                 copy_v2_v2(prev_edge, cur_edge);
2535                                                                 ++i;
2536                                                         }
2537                                                 }
2538                                         }
2539                                 }
2540
2541                                 // proceed if not a degenerate face
2542                                 if (is_degenerate == 0) {
2543                                         int nr_tris_to_pile=0;
2544                                         // quads split at shortest diagonal
2545                                         int offs = 0;           // initial triangulation is 0,1,2 and 0, 2, 3
2546                                         if (nr_verts == 4) {
2547                                                 float pos_len_diag0, pos_len_diag1;
2548                                                 float vtmp[3];
2549                                                 sub_v3_v3v3(vtmp, verts[2], verts[0]);
2550                                                 pos_len_diag0 = dot_v3v3(vtmp, vtmp);
2551                                                 sub_v3_v3v3(vtmp, verts[3], verts[1]);
2552                                                 pos_len_diag1 = dot_v3v3(vtmp, vtmp);
2553
2554                                                 if(pos_len_diag1<pos_len_diag0) {
2555                                                         offs=1;         // alter split
2556                                                 }
2557                                                 else if(pos_len_diag0==pos_len_diag1) { /* do UV check instead */
2558                                                         float tex_len_diag0, tex_len_diag1;
2559
2560                                                         sub_v2_v2v2(vtmp, tex_coords[2], tex_coords[0]);
2561                                                         tex_len_diag0 = dot_v2v2(vtmp, vtmp);
2562                                                         sub_v2_v2v2(vtmp, tex_coords[3], tex_coords[1]);
2563                                                         tex_len_diag1 = dot_v2v2(vtmp, vtmp);
2564
2565                                                         if (tex_len_diag1<tex_len_diag0) {
2566                                                                 offs=1; /* alter split */
2567                                                         }
2568                                                 }
2569                                         }
2570                                         nr_tris_to_pile = nr_verts - 2;
2571                                         if (nr_tris_to_pile==1 || nr_tris_to_pile==2) {
2572                                                 const int indices[] = {offs+0, offs+1, offs+2, offs+0, offs+2, (offs+3)&0x3 };
2573                                                 int t;
2574                                                 for ( t=0; t<nr_tris_to_pile; t++ )
2575                                                 {
2576                                                         float f2x_area_uv;
2577                                                         float * p0 = verts[indices[t*3+0]];
2578                                                         float * p1 = verts[indices[t*3+1]];
2579                                                         float * p2 = verts[indices[t*3+2]];
2580
2581                                                         float edge_t0[2], edge_t1[2];
2582                                                         sub_v2_v2v2(edge_t0, tex_coords[indices[t*3+1]], tex_coords[indices[t*3+0]]);
2583                                                         sub_v2_v2v2(edge_t1, tex_coords[indices[t*3+2]], tex_coords[indices[t*3+0]]);
2584
2585                                                         f2x_area_uv = fabsf(edge_t0[0]*edge_t1[1] - edge_t0[1]*edge_t1[0]);
2586                                                         if (f2x_area_uv>FLT_EPSILON) {
2587                                                                 float norm[3], v0[3], v1[3], f2x_surf_area, fsurf_ratio;
2588                                                                 sub_v3_v3v3(v0, p1, p0);
2589                                                                 sub_v3_v3v3(v1, p2, p0);
2590                                                                 cross_v3_v3v3(norm, v0, v1);
2591
2592                                                                 f2x_surf_area = len_v3(norm);
2593                                                                 fsurf_ratio = f2x_surf_area/f2x_area_uv;        // tri area divided by texture area
2594
2595                                                                 ++nr_accumulated;
2596                                                                 dsum += (double)(fsurf_ratio);
2597                                                         }
2598                                                 }
2599                                         }
2600                                 }
2601                         }
2602                 }
2603
2604                 // finalize
2605                 {
2606                         const float avg_area_ratio = (nr_accumulated>0) ? ((float)(dsum / nr_accumulated)) : 1.0f;
2607                         const float use_as_render_bump_scale = sqrtf(avg_area_ratio);           // use width of average surface ratio as your bump scale
2608                         dm->auto_bump_scale = use_as_render_bump_scale;
2609                 }
2610         }
2611         else {
2612                 dm->auto_bump_scale = 1.0f;
2613         }
2614 }
2615
2616 void DM_vertex_attributes_from_gpu(DerivedMesh *dm, GPUVertexAttribs *gattribs, DMVertexAttribs *attribs)
2617 {
2618         CustomData *vdata, *fdata, *tfdata = NULL;
2619         int a, b, layer;
2620
2621         /* From the layers requested by the GLSL shader, figure out which ones are
2622          * actually available for this derivedmesh, and retrieve the pointers */
2623
2624         memset(attribs, 0, sizeof(DMVertexAttribs));
2625
2626         vdata = &dm->vertData;
2627         fdata = tfdata = dm->getTessFaceDataLayout(dm);
2628         
2629         /* calc auto bump scale if necessary */
2630         if(dm->auto_bump_scale<=0.0f)
2631                 DM_calc_auto_bump_scale(dm);
2632
2633         /* add a tangent layer if necessary */
2634         for(b = 0; b < gattribs->totlayer; b++)
2635                 if(gattribs->layer[b].type == CD_TANGENT)
2636                         if(CustomData_get_layer_index(fdata, CD_TANGENT) == -1)
2637                                 DM_add_tangent_layer(dm);
2638
2639         for(b = 0; b < gattribs->totlayer; b++) {
2640                 if(gattribs->layer[b].type == CD_MTFACE) {
2641                         /* uv coordinates */
2642                         if(gattribs->layer[b].name[0])
2643                                 layer = CustomData_get_named_layer_index(tfdata, CD_MTFACE,
2644                                         gattribs->layer[b].name);
2645                         else
2646                                 layer = CustomData_get_active_layer_index(tfdata, CD_MTFACE);
2647
2648                         if(layer != -1) {
2649                                 a = attribs->tottface++;
2650
2651                                 attribs->tface[a].array = tfdata->layers[layer].data;
2652                                 attribs->tface[a].emOffset = tfdata->layers[layer].offset;
2653                                 attribs->tface[a].glIndex = gattribs->layer[b].glindex;
2654                                 attribs->tface[a].glTexco = gattribs->layer[b].gltexco;
2655                         }
2656                         /* BMESH_TODO - BMESH ONLY, may need to get this working?, otherwise remove */
2657 #if 0
2658                         else {
2659                                 int player;
2660                                 CustomData *pdata = dm->getPolyDataLayout(dm);
2661                                 
2662                                 if(gattribs->layer[b].name[0])
2663                                         player = CustomData_get_named_layer_index(pdata, CD_MTEXPOLY,
2664                                                 gattribs->layer[b].name);
2665                                 else
2666                                         player = CustomData_get_active_layer_index(pdata, CD_MTEXPOLY);
2667                                 
2668                                 if (player != -1) {
2669                                         a = attribs->tottface++;
2670         
2671                                         attribs->tface[a].array = NULL;
2672                                         attribs->tface[a].emOffset = pdata->layers[layer].offset;
2673                                         attribs->tface[a].glIndex = gattribs->layer[b].glindex;
2674                                         attribs->tface[a].glTexco = gattribs->layer[b].gltexco;
2675                                         
2676                                 }
2677                         }
2678 #endif
2679                 }
2680                 else if(gattribs->layer[b].type == CD_MCOL) {
2681                         /* vertex colors */
2682                         if(gattribs->layer[b].name[0])
2683                                 layer = CustomData_get_named_layer_index(tfdata, CD_MCOL,
2684                                         gattribs->layer[b].name);
2685                         else
2686                                 layer = CustomData_get_active_layer_index(tfdata, CD_MCOL);
2687
2688                         if(layer != -1) {
2689                                 a = attribs->totmcol++;
2690
2691                                 attribs->mcol[a].array = tfdata->layers[layer].data;
2692                                 attribs->mcol[a].emOffset = tfdata->layers[layer].offset;
2693                                 attribs->mcol[a].glIndex = gattribs->layer[b].glindex;
2694                         }
2695                 }
2696                 else if(gattribs->layer[b].type == CD_TANGENT) {
2697                         /* tangents */
2698                         layer = CustomData_get_layer_index(fdata, CD_TANGENT);
2699
2700                         if(layer != -1) {
2701                                 attribs->tottang = 1;
2702
2703                                 attribs->tang.array = fdata->layers[layer].data;
2704                                 attribs->tang.emOffset = fdata->layers[layer].offset;
2705                                 attribs->tang.glIndex = gattribs->layer[b].glindex;
2706                         }
2707                 }
2708                 else if(gattribs->layer[b].type == CD_ORCO) {
2709                         /* original coordinates */
2710                         layer = CustomData_get_layer_index(vdata, CD_ORCO);
2711
2712                         if(layer != -1) {
2713                                 attribs->totorco = 1;
2714
2715                                 attribs->orco.array = vdata->layers[layer].data;
2716                                 attribs->orco.emOffset = vdata->layers[layer].offset;
2717                                 attribs->orco.glIndex = gattribs->layer[b].glindex;
2718                                 attribs->orco.glTexco = gattribs->layer[b].gltexco;
2719                         }
2720                 }
2721         }
2722 }
2723
2724 /* Set object's bounding box based on DerivedMesh min/max data */
2725 void DM_set_object_boundbox(Object *ob, DerivedMesh *dm)
2726 {
2727         float min[3], max[3];
2728
2729         INIT_MINMAX(min, max);
2730
2731         dm->getMinMax(dm, min, max);
2732
2733         if(!ob->bb)
2734                 ob->bb= MEM_callocN(sizeof(BoundBox), "DM-BoundBox");
2735
2736         boundbox_set_from_min_max(ob->bb, min, max);
2737 }
2738
2739 /* --- NAVMESH (begin) --- */
2740 #ifdef WITH_GAMEENGINE
2741
2742 /* BMESH_TODO, navmesh is not working right currently
2743  * All tools set this as MPoly data, but derived mesh currently draws from MFace (tessface)
2744  *
2745  * Proposed solution, rather then copy CD_RECAST into the MFace array,
2746  * use ORIGINDEX to get the original poly index and then get the CD_RECAST
2747  * data from the original me->mpoly layer. - campbell
2748  */
2749
2750
2751 BM_INLINE int navmesh_bit(int a, int b)
2752 {
2753         return (a & (1 << b)) >> b;
2754 }
2755
2756 BM_INLINE void navmesh_intToCol(int i, float col[3])
2757 {
2758         int     r = navmesh_bit(i, 0) + navmesh_bit(i, 3) * 2 + 1;
2759         int     g = navmesh_bit(i, 1) + navmesh_bit(i, 4) * 2 + 1;
2760         int     b = navmesh_bit(i, 2) + navmesh_bit(i, 5) * 2 + 1;
2761         col[0] = 1 - r*63.0f/255.0f;
2762         col[1] = 1 - g*63.0f/255.0f;
2763         col[2] = 1 - b*63.0f/255.0f;
2764 }
2765
2766 static void navmesh_drawColored(DerivedMesh *dm)
2767 {
2768         int a, glmode;
2769         MVert *mvert = (MVert *)CustomData_get_layer(&dm->vertData, CD_MVERT);
2770         MFace *mface = (MFace *)CustomData_get_layer(&dm->faceData, CD_MFACE);
2771         int *polygonIdx = (int *)CustomData_get_layer(&dm->faceData, CD_RECAST);
2772         float col[3];
2773
2774         if (!polygonIdx)
2775                 return;
2776
2777 #if 0
2778         //UI_ThemeColor(TH_WIRE);
2779         glDisable(GL_LIGHTING);
2780         glLineWidth(2.0);
2781         dm->drawEdges(dm, 0, 1);
2782         glLineWidth(1.0);
2783         glEnable(GL_LIGHTING);
2784 #endif
2785
2786         glDisable(GL_LIGHTING);
2787         /*  if(GPU_buffer_legacy(dm) ) */ { /* TODO - VBO draw code, not high priority - campbell */
2788                 DEBUG_VBO( "Using legacy code. drawNavMeshColored\n" );
2789                 //glShadeModel(GL_SMOOTH);
2790                 glBegin(glmode = GL_QUADS);
2791                 for(a = 0; a < dm->numTessFaceData; a++, mface++) {
2792                         int new_glmode = mface->v4?GL_QUADS:GL_TRIANGLES;
2793                         int pi = polygonIdx[a];
2794                         if (pi <= 0) {
2795                                 zero_v3(col);
2796                         }
2797                         else {
2798                                 navmesh_intToCol(pi, col);
2799                         }
2800
2801                         if(new_glmode != glmode) {
2802                                 glEnd();
2803                                 glBegin(glmode = new_glmode);
2804                         }
2805                         glColor3fv(col);
2806                         glVertex3fv(mvert[mface->v1].co);
2807                         glVertex3fv(mvert[mface->v2].co);
2808                         glVertex3fv(mvert[mface->v3].co);
2809                         if(mface->v4) {
2810                                 glVertex3fv(mvert[mface->v4].co);
2811                         }
2812                 }
2813                 glEnd();
2814         }
2815         glEnable(GL_LIGHTING);
2816 }
2817
2818 static void navmesh_DM_drawFacesTex(DerivedMesh *dm,
2819                         DMSetDrawOptionsTex setDrawOptions,
2820                         DMCompareDrawOptions compareDrawOptions,
2821                         void *userData)
2822 {
2823         (void) setDrawOptions;
2824         (void) compareDrawOptions;
2825         (void) userData;
2826
2827         navmesh_drawColored(dm);
2828 }
2829
2830 static void navmesh_DM_drawFacesSolid(DerivedMesh *dm,
2831                                       float (*partial_redraw_planes)[4],
2832                                       int UNUSED(fast), DMSetMaterial setMaterial)
2833 {
2834         (void) partial_redraw_planes;
2835         (void) setMaterial;
2836
2837         //drawFacesSolid_original(dm, partial_redraw_planes, fast, setMaterial);
2838         navmesh_drawColored(dm);
2839 }
2840
2841 static DerivedMesh *navmesh_dm_createNavMeshForVisualization(DerivedMesh *dm)
2842 {
2843         DerivedMesh *result;
2844         int maxFaces = dm->getNumPolys(dm);
2845         int *recastData;
2846         int vertsPerPoly=0, nverts=0, ndtris=0, npolys=0;
2847         float* verts=NULL;
2848         unsigned short *dtris=NULL, *dmeshes=NULL, *polys=NULL;
2849         int *dtrisToPolysMap=NULL, *dtrisToTrisMap=NULL, *trisToFacesMap=NULL;
2850         int res;
2851
2852         result = CDDM_copy(dm);
2853         if (!CustomData_has_layer(&result->faceData, CD_RECAST)) {
2854                 int *sourceRecastData = (int*)CustomData_get_layer(&dm->faceData, CD_RECAST);
2855                 if (sourceRecastData) {
2856                         CustomData_add_layer_named(&result->faceData, CD_RECAST, CD_DUPLICATE,
2857                                                    sourceRecastData, maxFaces, "recastData");
2858                 }
2859         }
2860         recastData = (int*)CustomData_get_layer(&result->faceData, CD_RECAST);
2861
2862         /* note: This is not good design! - really should not be doing this */
2863         result->drawFacesTex =  navmesh_DM_drawFacesTex;
2864         result->drawFacesSolid = navmesh_DM_drawFacesSolid;
2865
2866
2867         /* process mesh */
2868         res  = buildNavMeshDataByDerivedMesh(dm, &vertsPerPoly, &nverts, &verts, &ndtris, &dtris,
2869                                              &npolys, &dmeshes, &polys, &dtrisToPolysMap, &dtrisToTrisMap,
2870                                              &trisToFacesMap);
2871         if (res) {
2872                 size_t polyIdx;
2873
2874                 /* invalidate concave polygon */
2875                 for (polyIdx=0; polyIdx<(size_t)npolys; polyIdx++) {
2876                         unsigned short* poly = &polys[polyIdx*2*vertsPerPoly];
2877                         if (!polyIsConvex(poly, vertsPerPoly, verts)) {
2878                                 /* set negative polygon idx to all faces */
2879                                 unsigned short *dmesh = &dmeshes[4*polyIdx];
2880                                 unsigned short tbase = dmesh[2];
2881                                 unsigned short tnum = dmesh[3];
2882                                 unsigned short ti;
2883
2884                                 for (ti=0; ti<tnum; ti++) {
2885                                         unsigned short triidx = dtrisToTrisMap[tbase+ti];
2886                                         unsigned short faceidx = trisToFacesMap[triidx];
2887                                         if (recastData[faceidx] > 0) {
2888                                                 recastData[faceidx] = -recastData[faceidx];
2889                                         }
2890                                 }
2891                         }
2892                 }
2893         }
2894         else {
2895                 printf("Error during creation polygon infos\n");
2896         }
2897
2898         /* clean up */
2899         if (verts!=NULL)
2900                 MEM_freeN(verts);
2901         if (dtris!=NULL)
2902                 MEM_freeN(dtris);
2903         if (dmeshes!=NULL)
2904                 MEM_freeN(dmeshes);
2905         if (polys!=NULL)
2906                 MEM_freeN(polys);
2907         if (dtrisToPolysMap!=NULL)
2908                 MEM_freeN(dtrisToPolysMap);
2909         if (dtrisToTrisMap!=NULL)
2910                 MEM_freeN(dtrisToTrisMap);
2911         if (trisToFacesMap!=NULL)
2912                 MEM_freeN(trisToFacesMap);
2913
2914         return result;
2915 }
2916
2917 #endif /* WITH_GAMEENGINE */
2918
2919 /* --- NAVMESH (end) --- */
2920
2921
2922 void DM_init_origspace(DerivedMesh *dm)
2923 {
2924         static float default_osf[4][2] = {{0, 0}, {1, 0}, {1, 1}, {0, 1}};
2925
2926         OrigSpaceLoop *lof_array = CustomData_get_layer(&dm->loopData, CD_ORIGSPACE_MLOOP);
2927         OrigSpaceLoop *lof;
2928         const int numpoly = dm->getNumPolys(dm);
2929         // const int numloop = dm->getNumLoops(dm);
2930         MPoly *mp = dm->getPolyArray(dm);
2931         int i, j;
2932
2933         for (i = 0; i < numpoly; i++, mp++) {
2934                 /* only quads/tri's for now */
2935                 if (mp->totloop == 3 || mp->totloop == 4) {
2936                         lof = lof_array + mp->loopstart;
2937                         for (j = 0; j < mp->totloop; j++, lof++) {
2938                                 copy_v2_v2(lof->uv, default_osf[j]);
2939                         }
2940                 }
2941         }
2942 }
2943
2944
2945
2946 /* derivedmesh info printing function,
2947  * to help track down differences DM output */
2948
2949 #ifndef NDEBUG
2950 #include "BLI_dynstr.h"
2951
2952 static void dm_debug_info_layers(DynStr *dynstr, DerivedMesh *dm, void *(*getElemDataArray)(DerivedMesh *, int))
2953 {
2954         int type;
2955
2956         for (type = 0; type < CD_NUMTYPES; type++) {
2957                 /* note: doesnt account for multiple layers */
2958                 void *pt = getElemDataArray(dm, type);
2959                 if (pt) {
2960                         const char *name = CustomData_layertype_name(type);
2961                         const int size = CustomData_sizeof(type);
2962                         const char *structname;
2963                         int structnum;
2964                         CustomData_file_write_info(type, &structname, &structnum);
2965                         BLI_dynstr_appendf(dynstr,
2966                                            "        dict(name='%s', struct='%s', type=%d, ptr='%p', elem=%d, length=%d),\n",
2967                                                            name, structname, type, (void *)pt, size, (int)(MEM_allocN_len(pt) / size));
2968                 }
2969         }
2970 }
2971
2972 char *DM_debug_info(DerivedMesh *dm)
2973 {
2974         DynStr *dynstr= BLI_dynstr_new();
2975         char *ret;
2976         const char *tstr;
2977
2978         BLI_dynstr_appendf(dynstr, "{\n");
2979         BLI_dynstr_appendf(dynstr, "    'ptr': '%p',\n", (void *)dm);
2980         switch (dm->type) {
2981                 case DM_TYPE_CDDM:     tstr = "DM_TYPE_CDDM";     break;
2982                 case DM_TYPE_EDITBMESH: tstr = "DM_TYPE_EDITMESH";  break;
2983                 case DM_TYPE_CCGDM:    tstr = "DM_TYPE_CCGDM";     break;
2984                 default:               tstr = "UNKNOWN";           break;
2985         }
2986         BLI_dynstr_appendf(dynstr, "    'type': '%s',\n", tstr);
2987         BLI_dynstr_appendf(dynstr, "    'numVertData': %d,\n", dm->numVertData);
2988         BLI_dynstr_appendf(dynstr, "    'numEdgeData': %d,\n", dm->numEdgeData);
2989         BLI_dynstr_appendf(dynstr, "    'numTessFaceData': %d,\n", dm->numTessFaceData);
2990         BLI_dynstr_appendf(dynstr, "    'numPolyData': %d,\n", dm->numPolyData);
2991         BLI_dynstr_appendf(dynstr, "    'deformedOnly': %d,\n", dm->deformedOnly);
2992
2993         BLI_dynstr_appendf(dynstr, "    'vertexLayers': (\n");
2994         dm_debug_info_layers(dynstr, dm, dm->getVertDataArray);
2995         BLI_dynstr_appendf(dynstr, "    ),\n");
2996
2997         BLI_dynstr_appendf(dynstr, "    'loopLayers': (\n");
2998         dm_debug_info_layers(dynstr, dm, DM_get_loop_data_layer);
2999         BLI_dynstr_appendf(dynstr, "    ),\n");
3000
3001         BLI_dynstr_appendf(dynstr, "    'edgeLayers': (\n");
3002         dm_debug_info_layers(dynstr, dm, dm->getEdgeDataArray);
3003         BLI_dynstr_appendf(dynstr, "    ),\n");
3004
3005         BLI_dynstr_appendf(dynstr, "    'tessFaceLayers': (\n");
3006         dm_debug_info_layers(dynstr, dm, dm->getTessFaceDataArray);
3007         BLI_dynstr_appendf(dynstr, "    ),\n");
3008
3009         BLI_dynstr_appendf(dynstr, "    'polyLayers': (\n");
3010         dm_debug_info_layers(dynstr, dm, DM_get_poly_data_layer);
3011         BLI_dynstr_appendf(dynstr, "    ),\n");
3012
3013         BLI_dynstr_appendf(dynstr, "}\n");
3014
3015         ret = BLI_dynstr_get_cstring(dynstr);
3016         BLI_dynstr_free(dynstr);
3017         return ret;
3018 }
3019
3020 void DM_debug_print(DerivedMesh *dm)
3021 {
3022         char *str = DM_debug_info(dm);
3023         printf("%s", str);
3024         fflush(stdout);
3025         MEM_freeN(str);
3026 }
3027
3028 #endif /* NDEBUG */