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