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