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