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