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