style cleanup - braces & else / if's
[blender.git] / source / blender / blenkernel / intern / DerivedMesh.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * The Original Code is Copyright (C) 2005 Blender Foundation.
19  * All rights reserved.
20  *
21  * The Original Code is: all of this file.
22  *
23  * Contributor(s): none yet.
24  *
25  * ***** END GPL LICENSE BLOCK *****
26  */
27
28 /** \file blender/blenkernel/intern/DerivedMesh.c
29  *  \ingroup bke
30  */
31
32
33 #include <string.h>
34 #include "limits.h"
35
36 #include "MEM_guardedalloc.h"
37
38 #include "DNA_cloth_types.h"
39 #include "DNA_key_types.h"
40 #include "DNA_mesh_types.h"
41 #include "DNA_meshdata_types.h"
42 #include "DNA_armature_types.h"
43 #include "DNA_object_types.h"
44 #include "DNA_scene_types.h" // N_T
45
46 #include "BLI_blenlib.h"
47 #include "BLI_math.h"
48 #include "BLI_memarena.h"
49 #include "BLI_array.h"
50 #include "BLI_pbvh.h"
51 #include "BLI_utildefines.h"
52 #include "BLI_linklist.h"
53
54 #include "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->recalcTessellation(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, "BMEditMesh 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 tessellation faces*/
1095                 /* XXX Why update that layer? We have to update WEIGHT_MLOOPCOL anyway, 
1096                  *     and tessellation 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 behavior 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-tessellation
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-tessellation is necessary to push render data (uvs, textures, colors)
1677                  * from loops and polys onto the tessfaces. This may be currently be
1678                  * redundant in cases where the render mode doesn't use these inputs, but
1679                  * ideally eventually tessellation 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->recalcTessellation(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         }
1904         else if (dm) {
1905                 *final_r = dm;
1906                 (*final_r)->calcNormals(*final_r); /* BMESH_ONLY - BMESH_TODO. check if this is needed */
1907         }
1908         else if (!deformedVerts && cage_r && *cage_r) {
1909                 /* cage should already have up to date normals */
1910                 *final_r = *cage_r;
1911                 (*final_r)->calcNormals(*final_r); /* BMESH_ONLY - BMESH_TODO. check if this is needed */
1912         }
1913         else {
1914                 /* this is just a copy of the editmesh, no need to calc normals */
1915                 *final_r = getEditDerivedBMesh(em, ob, deformedVerts);
1916                 deformedVerts = NULL;
1917         }
1918
1919         /* --- */
1920         /* BMESH_ONLY, ensure tessface's used for drawing,
1921          * but dont recalculate if the last modifier in the stack gives us tessfaces
1922          * check if the derived meshes are DM_TYPE_EDITBMESH before calling, this isnt essential
1923          * but quiets annoying error messages since tessfaces wont be created. */
1924         if ((*final_r)->type != DM_TYPE_EDITBMESH) {
1925                 DM_ensure_tessface(*final_r);
1926         }
1927         if (cage_r) {
1928                 if ((*cage_r)->type != DM_TYPE_EDITBMESH) {
1929                         if (*cage_r != *final_r) {
1930                                 DM_ensure_tessface(*cage_r);
1931                         }
1932                 }
1933         }
1934         /* --- */
1935
1936         /* add an orco layer if needed */
1937         if(dataMask & CD_MASK_ORCO)
1938                 add_orco_dm(ob, em, *final_r, orcodm, CD_ORCO);
1939
1940         if(orcodm)
1941                 orcodm->release(orcodm);
1942
1943         if(deformedVerts)
1944                 MEM_freeN(deformedVerts);
1945 }
1946
1947 static void clear_mesh_caches(Object *ob)
1948 {
1949         Mesh *me= ob->data;
1950
1951                 /* also serves as signal to remake texspace */
1952         if (ob->bb) {
1953                 MEM_freeN(ob->bb);
1954                 ob->bb = NULL;
1955         }
1956         if (me->bb) {
1957                 MEM_freeN(me->bb);
1958                 me->bb = NULL;
1959         }
1960
1961         freedisplist(&ob->disp);
1962
1963         if (ob->derivedFinal) {
1964                 ob->derivedFinal->needsFree = 1;
1965                 ob->derivedFinal->release(ob->derivedFinal);
1966                 ob->derivedFinal= NULL;
1967         }
1968         if (ob->derivedDeform) {
1969                 ob->derivedDeform->needsFree = 1;
1970                 ob->derivedDeform->release(ob->derivedDeform);
1971                 ob->derivedDeform= NULL;
1972         }
1973
1974         if(ob->sculpt) {
1975                 object_sculpt_modifiers_changed(ob);
1976         }
1977 }
1978
1979 static void mesh_build_data(Scene *scene, Object *ob, CustomDataMask dataMask,
1980                             int build_shapekey_layers)
1981 {
1982         Object *obact = scene->basact?scene->basact->object:NULL;
1983         int editing = paint_facesel_test(ob);
1984         /* weight paint and face select need original indices because of selection buffer drawing */
1985         int needMapping = (ob==obact) && (editing || (ob->mode & (OB_MODE_WEIGHT_PAINT|OB_MODE_VERTEX_PAINT|OB_MODE_TEXTURE_PAINT)));
1986
1987         clear_mesh_caches(ob);
1988
1989         mesh_calc_modifiers(scene, ob, NULL, &ob->derivedDeform,
1990                                                 &ob->derivedFinal, 0, 1,
1991                                                 needMapping, dataMask, -1, 1, build_shapekey_layers);
1992
1993         DM_set_object_boundbox (ob, ob->derivedFinal);
1994
1995         ob->derivedFinal->needsFree = 0;
1996         ob->derivedDeform->needsFree = 0;
1997         ob->lastDataMask = dataMask;
1998 }
1999
2000 static void editbmesh_build_data(Scene *scene, Object *obedit, BMEditMesh *em, CustomDataMask dataMask)
2001 {
2002         clear_mesh_caches(obedit);
2003
2004         if (em->derivedFinal) {
2005                 if (em->derivedFinal!=em->derivedCage) {
2006                         em->derivedFinal->needsFree = 1;
2007                         em->derivedFinal->release(em->derivedFinal);
2008                 }
2009                 em->derivedFinal = NULL;
2010         }
2011         if (em->derivedCage) {
2012                 em->derivedCage->needsFree = 1;
2013                 em->derivedCage->release(em->derivedCage);
2014                 em->derivedCage = NULL;
2015         }
2016
2017         editbmesh_calc_modifiers(scene, obedit, em, &em->derivedCage, &em->derivedFinal, dataMask);
2018         DM_set_object_boundbox (obedit, em->derivedFinal);
2019
2020         em->lastDataMask = dataMask;
2021         em->derivedFinal->needsFree = 0;
2022         em->derivedCage->needsFree = 0;
2023 }
2024
2025 void makeDerivedMesh(Scene *scene, Object *ob, BMEditMesh *em,
2026                      CustomDataMask dataMask, int build_shapekey_layers)
2027 {
2028         if (em) {
2029                 editbmesh_build_data(scene, ob, em, dataMask);
2030         } else {
2031                 mesh_build_data(scene, ob, dataMask, build_shapekey_layers);
2032         }
2033 }
2034
2035 /***/
2036
2037 DerivedMesh *mesh_get_derived_final(Scene *scene, Object *ob, CustomDataMask dataMask)
2038 {
2039         /* if there's no derived mesh or the last data mask used doesn't include
2040          * the data we need, rebuild the derived mesh
2041          */
2042         if(!ob->derivedFinal || (dataMask & ob->lastDataMask) != dataMask)
2043                 mesh_build_data(scene, ob, dataMask, 0);
2044
2045         return ob->derivedFinal;
2046 }
2047
2048 DerivedMesh *mesh_get_derived_deform(Scene *scene, Object *ob, CustomDataMask dataMask)
2049 {
2050         /* if there's no derived mesh or the last data mask used doesn't include
2051          * the data we need, rebuild the derived mesh
2052          */
2053         if(!ob->derivedDeform || (dataMask & ob->lastDataMask) != dataMask)
2054                 mesh_build_data(scene, ob, dataMask, 0);
2055
2056         return ob->derivedDeform;
2057 }
2058
2059 DerivedMesh *mesh_create_derived_render(Scene *scene, Object *ob, CustomDataMask dataMask)
2060 {
2061         DerivedMesh *final;
2062         
2063         mesh_calc_modifiers(scene, ob, NULL, NULL, &final, 1, 1, 0, dataMask, -1, 0, 0);
2064
2065         return final;
2066 }
2067
2068 DerivedMesh *mesh_create_derived_index_render(Scene *scene, Object *ob, CustomDataMask dataMask, int index)
2069 {
2070         DerivedMesh *final;
2071         
2072         mesh_calc_modifiers(scene, ob, NULL, NULL, &final, 1, 1, 0, dataMask, index, 0, 0);
2073
2074         return final;
2075 }
2076
2077 DerivedMesh *mesh_create_derived_view(Scene *scene, Object *ob, CustomDataMask dataMask)
2078 {
2079         DerivedMesh *final;
2080
2081         mesh_calc_modifiers(scene, ob, NULL, NULL, &final, 0, 1, 0, dataMask, -1, 0, 0);
2082
2083         return final;
2084 }
2085
2086 DerivedMesh *mesh_create_derived_no_deform(Scene *scene, Object *ob, float (*vertCos)[3],
2087                                                                                    CustomDataMask dataMask)
2088 {
2089         DerivedMesh *final;
2090         
2091         mesh_calc_modifiers(scene, ob, vertCos, NULL, &final, 0, 0, 0, dataMask, -1, 0, 0);
2092
2093         return final;
2094 }
2095
2096 DerivedMesh *mesh_create_derived_no_virtual(Scene *scene, Object *ob, float (*vertCos)[3],
2097                                                                                         CustomDataMask dataMask)
2098 {
2099         DerivedMesh *final;
2100         
2101         mesh_calc_modifiers(scene, ob, vertCos, NULL, &final, 0, -1, 0, dataMask, -1, 0, 0);
2102
2103         return final;
2104 }
2105
2106 DerivedMesh *mesh_create_derived_physics(Scene *scene, Object *ob, float (*vertCos)[3],
2107                                                                                         CustomDataMask dataMask)
2108 {
2109         DerivedMesh *final;
2110         
2111         mesh_calc_modifiers(scene, ob, vertCos, NULL, &final, 0, -1, 1, dataMask, -1, 0, 0);
2112
2113         return final;
2114 }
2115
2116 DerivedMesh *mesh_create_derived_no_deform_render(Scene *scene, Object *ob,
2117                                                                                                   float (*vertCos)[3],
2118                                                                                                   CustomDataMask dataMask)
2119 {
2120         DerivedMesh *final;
2121
2122         mesh_calc_modifiers(scene, ob, vertCos, NULL, &final, 1, 0, 0, dataMask, -1, 0, 0);
2123
2124         return final;
2125 }
2126
2127 /***/
2128
2129 DerivedMesh *editbmesh_get_derived_cage_and_final(Scene *scene, Object *obedit, BMEditMesh *em, DerivedMesh **final_r,
2130                                                                                                  CustomDataMask dataMask)
2131 {
2132         /* if there's no derived mesh or the last data mask used doesn't include
2133          * the data we need, rebuild the derived mesh
2134          */
2135         if(!em->derivedCage ||
2136            (em->lastDataMask & dataMask) != dataMask)
2137                 editbmesh_build_data(scene, obedit, em, dataMask);
2138
2139         *final_r = em->derivedFinal;
2140         return em->derivedCage;
2141 }
2142
2143 DerivedMesh *editbmesh_get_derived_cage(Scene *scene, Object *obedit, BMEditMesh *em, CustomDataMask dataMask)
2144 {
2145         /* if there's no derived mesh or the last data mask used doesn't include
2146          * the data we need, rebuild the derived mesh
2147          */
2148         if(!em->derivedCage ||
2149            (em->lastDataMask & dataMask) != dataMask)
2150                 editbmesh_build_data(scene, obedit, em, dataMask);
2151
2152         return em->derivedCage;
2153 }
2154
2155 DerivedMesh *editbmesh_get_derived_base(Object *obedit, BMEditMesh *em)
2156 {
2157         return getEditDerivedBMesh(em, obedit, NULL);
2158 }
2159
2160
2161 /* ********* For those who don't grasp derived stuff! (ton) :) *************** */
2162
2163 static void make_vertexcosnos__mapFunc(void *userData, int index, float *co, float *no_f, short *no_s)
2164 {
2165         float *vec = userData;
2166         
2167         vec+= 6*index;
2168
2169         /* check if we've been here before (normal should not be 0) */
2170         if(vec[3] || vec[4] || vec[5]) return;
2171
2172         copy_v3_v3(vec, co);
2173         vec+= 3;
2174         if(no_f) {
2175                 copy_v3_v3(vec, no_f);
2176         }
2177         else {
2178                 normal_short_to_float_v3(vec, no_s);
2179         }
2180 }
2181
2182 /* always returns original amount me->totvert of vertices and normals, but fully deformed and subsurfered */
2183 /* this is needed for all code using vertexgroups (no subsurf support) */
2184 /* it stores the normals as floats, but they can still be scaled as shorts (32767 = unit) */
2185 /* in use now by vertex/weight paint and particle generating */
2186
2187 float *mesh_get_mapped_verts_nors(Scene *scene, Object *ob)
2188 {
2189         Mesh *me= ob->data;
2190         DerivedMesh *dm;
2191         float *vertexcosnos;
2192         
2193         /* lets prevent crashing... */
2194         if(ob->type!=OB_MESH || me->totvert==0)
2195                 return NULL;
2196         
2197         dm= mesh_get_derived_final(scene, ob, CD_MASK_BAREMESH|CD_MASK_ORIGINDEX);
2198         vertexcosnos= MEM_callocN(6*sizeof(float)*me->totvert, "vertexcosnos map");
2199         
2200         if(dm->foreachMappedVert) {
2201                 dm->foreachMappedVert(dm, make_vertexcosnos__mapFunc, vertexcosnos);
2202         }
2203         else {
2204                 float *fp= vertexcosnos;
2205                 int a;
2206                 
2207                 for(a=0; a< me->totvert; a++, fp+=6) {
2208                         dm->getVertCo(dm, a, fp);
2209                         dm->getVertNo(dm, a, fp+3);
2210                 }
2211         }
2212         
2213         dm->release(dm);
2214         return vertexcosnos;
2215 }
2216
2217 /* ******************* GLSL ******************** */
2218
2219 typedef struct
2220 {
2221         float * precomputedFaceNormals;
2222         MTFace * mtface;        // texture coordinates
2223         MFace * mface;          // indices
2224         MVert * mvert;          // vertices & normals
2225         float (*orco)[3];
2226         float (*tangent)[4];    // destination
2227         int numTessFaces;
2228
2229 } SGLSLMeshToTangent;
2230
2231 // interface
2232 #include "mikktspace.h"
2233
2234 static int GetNumFaces(const SMikkTSpaceContext * pContext)
2235 {
2236         SGLSLMeshToTangent * pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
2237         return pMesh->numTessFaces;
2238 }
2239
2240 static int GetNumVertsOfFace(const SMikkTSpaceContext * pContext, const int face_num)
2241 {
2242         SGLSLMeshToTangent * pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
2243         return pMesh->mface[face_num].v4!=0 ? 4 : 3;
2244 }
2245
2246 static void GetPosition(const SMikkTSpaceContext * pContext, float fPos[], const int face_num, const int vert_index)
2247 {
2248         //assert(vert_index>=0 && vert_index<4);
2249         SGLSLMeshToTangent * pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
2250         const float *co= pMesh->mvert[(&pMesh->mface[face_num].v1)[vert_index]].co;
2251         copy_v3_v3(fPos, co);
2252 }
2253
2254 static void GetTextureCoordinate(const SMikkTSpaceContext * pContext, float fUV[], const int face_num, const int vert_index)
2255 {
2256         //assert(vert_index>=0 && vert_index<4);
2257         SGLSLMeshToTangent * pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
2258
2259         if(pMesh->mtface!=NULL) {
2260                 float * uv = pMesh->mtface[face_num].uv[vert_index];
2261                 fUV[0]=uv[0]; fUV[1]=uv[1];
2262         }
2263         else {
2264                 const float *orco= pMesh->orco[(&pMesh->mface[face_num].v1)[vert_index]];
2265                 map_to_sphere( &fUV[0], &fUV[1], orco[0], orco[1], orco[2]);
2266         }
2267 }
2268
2269 static void GetNormal(const SMikkTSpaceContext * pContext, float fNorm[], const int face_num, const int vert_index)
2270 {
2271         //assert(vert_index>=0 && vert_index<4);
2272         SGLSLMeshToTangent * pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
2273
2274         const int smoothnormal = (pMesh->mface[face_num].flag & ME_SMOOTH);
2275         if(!smoothnormal) {     // flat
2276                 if(pMesh->precomputedFaceNormals) {
2277                         copy_v3_v3(fNorm, &pMesh->precomputedFaceNormals[3*face_num]);
2278                 }
2279                 else {
2280                         MFace *mf= &pMesh->mface[face_num];
2281                         float *p0= pMesh->mvert[mf->v1].co;
2282                         float *p1= pMesh->mvert[mf->v2].co;
2283                         float *p2= pMesh->mvert[mf->v3].co;
2284
2285                         if(mf->v4) {
2286                                 float *p3 = pMesh->mvert[mf->v4].co;
2287                                 normal_quad_v3(fNorm, p0, p1, p2, p3);
2288                         }
2289                         else {
2290                                 normal_tri_v3(fNorm, p0, p1, p2);
2291                         }
2292                 }
2293         }
2294         else {
2295                 const short *no= pMesh->mvert[(&pMesh->mface[face_num].v1)[vert_index]].no;
2296                 normal_short_to_float_v3(fNorm, no);
2297         }
2298 }
2299 static void SetTSpace(const SMikkTSpaceContext * pContext, const float fvTangent[], const float fSign, const int face_num, const int iVert)
2300 {
2301         //assert(vert_index>=0 && vert_index<4);
2302         SGLSLMeshToTangent * pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
2303         float * pRes = pMesh->tangent[4*face_num+iVert];
2304         copy_v3_v3(pRes, fvTangent);
2305         pRes[3]=fSign;
2306 }
2307
2308
2309 void DM_add_tangent_layer(DerivedMesh *dm)
2310 {
2311         /* mesh vars */
2312         MTFace *mtface, *tf;
2313         MFace *mface, *mf;
2314         MVert *mvert, *v1, *v2, *v3, *v4;
2315         MemArena *arena= NULL;
2316         VertexTangent **vtangents= NULL;
2317         float (*orco)[3]= NULL, (*tangent)[4];
2318         float *uv1, *uv2, *uv3, *uv4, *vtang;
2319         float fno[3], tang[3], uv[4][2];
2320         int i, j, len, mf_vi[4], totvert, totface, iCalcNewMethod;
2321         float *nors;
2322
2323         if(CustomData_get_layer_index(&dm->faceData, CD_TANGENT) != -1)
2324                 return;
2325
2326         nors = dm->getTessFaceDataArray(dm, CD_NORMAL);
2327
2328         /* check we have all the needed layers */
2329         totvert= dm->getNumVerts(dm);
2330         totface= dm->getNumTessFaces(dm);
2331
2332         mvert= dm->getVertArray(dm);
2333         mface= dm->getTessFaceArray(dm);
2334         mtface= dm->getTessFaceDataArray(dm, CD_MTFACE);
2335
2336         if(!mtface) {
2337                 orco= dm->getVertDataArray(dm, CD_ORCO);
2338                 if(!orco)
2339                         return;
2340         }
2341         
2342         /* create tangent layer */
2343         DM_add_tessface_layer(dm, CD_TANGENT, CD_CALLOC, NULL);
2344         tangent= DM_get_tessface_data_layer(dm, CD_TANGENT);
2345         
2346         /* allocate some space */
2347         arena= BLI_memarena_new(BLI_MEMARENA_STD_BUFSIZE, "tangent layer arena");
2348         BLI_memarena_use_calloc(arena);
2349         vtangents= MEM_callocN(sizeof(VertexTangent*)*totvert, "VertexTangent");
2350
2351         // new computation method
2352         iCalcNewMethod = 1;
2353         if(iCalcNewMethod != 0) {
2354                 SGLSLMeshToTangent mesh2tangent= {0};
2355                 SMikkTSpaceContext sContext= {0};
2356                 SMikkTSpaceInterface sInterface= {0};
2357
2358                 mesh2tangent.precomputedFaceNormals = nors;
2359                 mesh2tangent.mtface = mtface;
2360                 mesh2tangent.mface = mface;
2361                 mesh2tangent.mvert = mvert;
2362                 mesh2tangent.orco = orco;
2363                 mesh2tangent.tangent = tangent;
2364                 mesh2tangent.numTessFaces = totface;
2365
2366                 sContext.m_pUserData = &mesh2tangent;
2367                 sContext.m_pInterface = &sInterface;
2368                 sInterface.m_getNumFaces = GetNumFaces;
2369                 sInterface.m_getNumVerticesOfFace = GetNumVertsOfFace;
2370                 sInterface.m_getPosition = GetPosition;
2371                 sInterface.m_getTexCoord = GetTextureCoordinate;
2372                 sInterface.m_getNormal = GetNormal;
2373                 sInterface.m_setTSpaceBasic = SetTSpace;
2374
2375                 // 0 if failed
2376                 iCalcNewMethod = genTangSpaceDefault(&sContext);
2377         }
2378
2379         if(!iCalcNewMethod) {
2380                 /* sum tangents at connected vertices */
2381                 for(i=0, tf=mtface, mf=mface; i < totface; mf++, tf++, i++) {
2382                         v1= &mvert[mf->v1];
2383                         v2= &mvert[mf->v2];
2384                         v3= &mvert[mf->v3];
2385
2386                         if (mf->v4) {
2387                                 v4= &mvert[mf->v4];
2388                                 normal_quad_v3( fno,v4->co, v3->co, v2->co, v1->co);
2389                         }
2390                         else {
2391                                 v4= NULL;
2392                                 normal_tri_v3( fno,v3->co, v2->co, v1->co);
2393                         }
2394                 
2395                         if(mtface) {
2396                                 uv1= tf->uv[0];
2397                                 uv2= tf->uv[1];
2398                                 uv3= tf->uv[2];
2399                                 uv4= tf->uv[3];
2400                         }
2401                         else {
2402                                 uv1= uv[0]; uv2= uv[1]; uv3= uv[2]; uv4= uv[3];
2403                                 map_to_sphere( &uv[0][0], &uv[0][1],orco[mf->v1][0], orco[mf->v1][1], orco[mf->v1][2]);
2404                                 map_to_sphere( &uv[1][0], &uv[1][1],orco[mf->v2][0], orco[mf->v2][1], orco[mf->v2][2]);
2405                                 map_to_sphere( &uv[2][0], &uv[2][1],orco[mf->v3][0], orco[mf->v3][1], orco[mf->v3][2]);
2406                                 if(v4)
2407                                         map_to_sphere( &uv[3][0], &uv[3][1],orco[mf->v4][0], orco[mf->v4][1], orco[mf->v4][2]);
2408                         }
2409                 
2410                         tangent_from_uv(uv1, uv2, uv3, v1->co, v2->co, v3->co, fno, tang);
2411                         sum_or_add_vertex_tangent(arena, &vtangents[mf->v1], tang, uv1);
2412                         sum_or_add_vertex_tangent(arena, &vtangents[mf->v2], tang, uv2);
2413                         sum_or_add_vertex_tangent(arena, &vtangents[mf->v3], tang, uv3);
2414                 
2415                         if(mf->v4) {
2416                                 v4= &mvert[mf->v4];
2417                         
2418                                 tangent_from_uv(uv1, uv3, uv4, v1->co, v3->co, v4->co, fno, tang);
2419                                 sum_or_add_vertex_tangent(arena, &vtangents[mf->v1], tang, uv1);
2420                                 sum_or_add_vertex_tangent(arena, &vtangents[mf->v3], tang, uv3);
2421                                 sum_or_add_vertex_tangent(arena, &vtangents[mf->v4], tang, uv4);
2422                         }
2423                 }
2424         
2425                 /* write tangent to layer */
2426                 for(i=0, tf=mtface, mf=mface; i < totface; mf++, tf++, i++, tangent+=4) {
2427                         len= (mf->v4)? 4 : 3; 
2428
2429                         if(mtface == NULL) {
2430                                 map_to_sphere( &uv[0][0], &uv[0][1],orco[mf->v1][0], orco[mf->v1][1], orco[mf->v1][2]);
2431                                 map_to_sphere( &uv[1][0], &uv[1][1],orco[mf->v2][0], orco[mf->v2][1], orco[mf->v2][2]);
2432                                 map_to_sphere( &uv[2][0], &uv[2][1],orco[mf->v3][0], orco[mf->v3][1], orco[mf->v3][2]);
2433                                 if(len==4)
2434                                         map_to_sphere( &uv[3][0], &uv[3][1],orco[mf->v4][0], orco[mf->v4][1], orco[mf->v4][2]);
2435                         }
2436                 
2437                         mf_vi[0]= mf->v1;
2438                         mf_vi[1]= mf->v2;
2439                         mf_vi[2]= mf->v3;
2440                         mf_vi[3]= mf->v4;
2441                 
2442                         for(j=0; j<len; j++) {
2443                                 vtang= find_vertex_tangent(vtangents[mf_vi[j]], mtface ? tf->uv[j] : uv[j]);
2444                                 normalize_v3_v3(tangent[j], vtang);
2445                                 ((float *) tangent[j])[3]=1.0f;
2446                         }
2447                 }
2448         }
2449         
2450         BLI_memarena_free(arena);
2451         MEM_freeN(vtangents);
2452 }
2453
2454 void DM_calc_auto_bump_scale(DerivedMesh *dm)
2455 {
2456         /* int totvert= dm->getNumVerts(dm); */ /* UNUSED */
2457         int totface= dm->getNumTessFaces(dm);
2458
2459         MVert * mvert = dm->getVertArray(dm);
2460         MFace * mface = dm->getTessFaceArray(dm);
2461         MTFace * mtface = dm->getTessFaceDataArray(dm, CD_MTFACE);
2462
2463         if(mtface) {
2464                 double dsum = 0.0;
2465                 int nr_accumulated = 0;
2466                 int f;
2467
2468                 for ( f=0; f < totface; f++ ) {
2469                         {
2470                                 float * verts[4], * tex_coords[4];
2471                                 const int nr_verts = mface[f].v4!=0 ? 4 : 3;
2472                                 int i, is_degenerate;
2473
2474                                 verts[0]=mvert[mface[f].v1].co; verts[1]=mvert[mface[f].v2].co; verts[2]=mvert[mface[f].v3].co;
2475                                 tex_coords[0]=mtface[f].uv[0]; tex_coords[1]=mtface[f].uv[1]; tex_coords[2]=mtface[f].uv[2];
2476                                 if (nr_verts==4) {
2477                                         verts[3]=mvert[mface[f].v4].co;
2478                                         tex_coords[3]=mtface[f].uv[3];
2479                                 }
2480
2481                                 // discard degenerate faces
2482                                 is_degenerate = 0;
2483                                 if(     equals_v3v3(verts[0], verts[1]) || equals_v3v3(verts[0], verts[2]) || equals_v3v3(verts[1], verts[2]) ||
2484                                         equals_v2v2(tex_coords[0], tex_coords[1]) || equals_v2v2(tex_coords[0], tex_coords[2]) || equals_v2v2(tex_coords[1], tex_coords[2]) )
2485                                 {
2486                                         is_degenerate = 1;
2487                                 }
2488
2489                                 // verify last vertex as well if this is a quad
2490                                 if (is_degenerate == 0 && nr_verts == 4) {
2491                                         if (equals_v3v3(verts[3], verts[0]) || equals_v3v3(verts[3], verts[1]) || equals_v3v3(verts[3], verts[2]) ||
2492                                             equals_v2v2(tex_coords[3], tex_coords[0]) || equals_v2v2(tex_coords[3], tex_coords[1]) || equals_v2v2(tex_coords[3], tex_coords[2]) )
2493                                         {
2494                                                 is_degenerate = 1;
2495                                         }
2496
2497                                         // verify the winding is consistent
2498                                         if (is_degenerate == 0) {
2499                                                 float prev_edge[2];
2500                                                 int is_signed = 0;
2501                                                 sub_v2_v2v2(prev_edge, tex_coords[0], tex_coords[3]);
2502
2503                                                 i = 0;
2504                                                 while (is_degenerate == 0 && i < 4) {
2505                                                         float cur_edge[2], signed_area;
2506                                                         sub_v2_v2v2(cur_edge, tex_coords[(i+1)&0x3], tex_coords[i]);
2507                                                         signed_area = prev_edge[0]*cur_edge[1] - prev_edge[1]*cur_edge[0];
2508
2509                                                         if (i == 0 ) {
2510                                                                 is_signed = (signed_area < 0.0f) ? 1 : 0;
2511                                                         }
2512                                                         else if((is_signed != 0) != (signed_area < 0.0f)) {
2513                                                                 is_degenerate = 1;
2514                                                         }
2515
2516                                                         if (is_degenerate == 0) {
2517                                                                 copy_v2_v2(prev_edge, cur_edge);
2518                                                                 ++i;
2519                                                         }
2520                                                 }
2521                                         }
2522                                 }
2523
2524                                 // proceed if not a degenerate face
2525                                 if (is_degenerate == 0) {
2526                                         int nr_tris_to_pile=0;
2527                                         // quads split at shortest diagonal
2528                                         int offs = 0;           // initial triangulation is 0,1,2 and 0, 2, 3
2529                                         if (nr_verts == 4) {
2530                                                 float pos_len_diag0, pos_len_diag1;
2531                                                 float vtmp[3];
2532                                                 sub_v3_v3v3(vtmp, verts[2], verts[0]);
2533                                                 pos_len_diag0 = dot_v3v3(vtmp, vtmp);
2534                                                 sub_v3_v3v3(vtmp, verts[3], verts[1]);
2535                                                 pos_len_diag1 = dot_v3v3(vtmp, vtmp);
2536
2537                                                 if(pos_len_diag1<pos_len_diag0) {
2538                                                         offs=1;         // alter split
2539                                                 }
2540                                                 else if(pos_len_diag0==pos_len_diag1) { /* do UV check instead */
2541                                                         float tex_len_diag0, tex_len_diag1;
2542
2543                                                         sub_v2_v2v2(vtmp, tex_coords[2], tex_coords[0]);
2544                                                         tex_len_diag0 = dot_v2v2(vtmp, vtmp);
2545                                                         sub_v2_v2v2(vtmp, tex_coords[3], tex_coords[1]);
2546                                                         tex_len_diag1 = dot_v2v2(vtmp, vtmp);
2547
2548                                                         if (tex_len_diag1<tex_len_diag0) {
2549                                                                 offs=1; /* alter split */
2550                                                         }
2551                                                 }
2552                                         }
2553                                         nr_tris_to_pile = nr_verts - 2;
2554                                         if (nr_tris_to_pile==1 || nr_tris_to_pile==2) {
2555                                                 const int indices[] = {offs+0, offs+1, offs+2, offs+0, offs+2, (offs+3)&0x3 };
2556                                                 int t;
2557                                                 for ( t=0; t<nr_tris_to_pile; t++ )
2558                                                 {
2559                                                         float f2x_area_uv;
2560                                                         float * p0 = verts[indices[t*3+0]];
2561                                                         float * p1 = verts[indices[t*3+1]];
2562                                                         float * p2 = verts[indices[t*3+2]];
2563
2564                                                         float edge_t0[2], edge_t1[2];
2565                                                         sub_v2_v2v2(edge_t0, tex_coords[indices[t*3+1]], tex_coords[indices[t*3+0]]);
2566                                                         sub_v2_v2v2(edge_t1, tex_coords[indices[t*3+2]], tex_coords[indices[t*3+0]]);
2567
2568                                                         f2x_area_uv = fabsf(edge_t0[0]*edge_t1[1] - edge_t0[1]*edge_t1[0]);
2569                                                         if (f2x_area_uv>FLT_EPSILON) {
2570                                                                 float norm[3], v0[3], v1[3], f2x_surf_area, fsurf_ratio;
2571                                                                 sub_v3_v3v3(v0, p1, p0);
2572                                                                 sub_v3_v3v3(v1, p2, p0);
2573                                                                 cross_v3_v3v3(norm, v0, v1);
2574
2575                                                                 f2x_surf_area = len_v3(norm);
2576                                                                 fsurf_ratio = f2x_surf_area/f2x_area_uv;        // tri area divided by texture area
2577
2578                                                                 ++nr_accumulated;
2579                                                                 dsum += (double)(fsurf_ratio);
2580                                                         }
2581                                                 }
2582                                         }
2583                                 }
2584                         }
2585                 }
2586
2587                 // finalize
2588                 {
2589                         const float avg_area_ratio = (nr_accumulated>0) ? ((float)(dsum / nr_accumulated)) : 1.0f;
2590                         const float use_as_render_bump_scale = sqrtf(avg_area_ratio);           // use width of average surface ratio as your bump scale
2591                         dm->auto_bump_scale = use_as_render_bump_scale;
2592                 }
2593         }
2594         else {
2595                 dm->auto_bump_scale = 1.0f;
2596         }
2597 }
2598
2599 void DM_vertex_attributes_from_gpu(DerivedMesh *dm, GPUVertexAttribs *gattribs, DMVertexAttribs *attribs)
2600 {
2601         CustomData *vdata, *fdata, *tfdata = NULL;
2602         int a, b, layer;
2603
2604         /* From the layers requested by the GLSL shader, figure out which ones are
2605          * actually available for this derivedmesh, and retrieve the pointers */
2606
2607         memset(attribs, 0, sizeof(DMVertexAttribs));
2608
2609         vdata = &dm->vertData;
2610         fdata = tfdata = dm->getTessFaceDataLayout(dm);
2611         
2612         /* calc auto bump scale if necessary */
2613         if(dm->auto_bump_scale<=0.0f)
2614                 DM_calc_auto_bump_scale(dm);
2615
2616         /* add a tangent layer if necessary */
2617         for(b = 0; b < gattribs->totlayer; b++)
2618                 if(gattribs->layer[b].type == CD_TANGENT)
2619                         if(CustomData_get_layer_index(fdata, CD_TANGENT) == -1)
2620                                 DM_add_tangent_layer(dm);
2621
2622         for(b = 0; b < gattribs->totlayer; b++) {
2623                 if(gattribs->layer[b].type == CD_MTFACE) {
2624                         /* uv coordinates */
2625                         if(gattribs->layer[b].name[0])
2626                                 layer = CustomData_get_named_layer_index(tfdata, CD_MTFACE,
2627                                         gattribs->layer[b].name);
2628                         else
2629                                 layer = CustomData_get_active_layer_index(tfdata, CD_MTFACE);
2630
2631                         if(layer != -1) {
2632                                 a = attribs->tottface++;
2633
2634                                 attribs->tface[a].array = tfdata->layers[layer].data;
2635                                 attribs->tface[a].emOffset = tfdata->layers[layer].offset;
2636                                 attribs->tface[a].glIndex = gattribs->layer[b].glindex;
2637                                 attribs->tface[a].glTexco = gattribs->layer[b].gltexco;
2638                         }
2639                         /* BMESH ONLY, may need to get this working?, otherwise remove */
2640                         /* else {
2641                                 int player;
2642                                 CustomData *pdata = dm->getPolyDataLayout(dm);
2643                                 
2644                                 if(gattribs->layer[b].name[0])
2645                                         player = CustomData_get_named_layer_index(pdata, CD_MTEXPOLY,
2646                                                 gattribs->layer[b].name);
2647                                 else
2648                                         player = CustomData_get_active_layer_index(pdata, CD_MTEXPOLY);
2649                                 
2650                                 if (player != -1) {
2651                                         a = attribs->tottface++;
2652         
2653                                         attribs->tface[a].array = NULL;
2654                                         attribs->tface[a].emOffset = pdata->layers[layer].offset;
2655                                         attribs->tface[a].glIndex = gattribs->layer[b].glindex;
2656                                         attribs->tface[a].glTexco = gattribs->layer[b].gltexco;
2657                                         
2658                                 }
2659                         }
2660                         */
2661                 }
2662                 else if(gattribs->layer[b].type == CD_MCOL) {
2663                         /* vertex colors */
2664                         if(gattribs->layer[b].name[0])
2665                                 layer = CustomData_get_named_layer_index(tfdata, CD_MCOL,
2666                                         gattribs->layer[b].name);
2667                         else
2668                                 layer = CustomData_get_active_layer_index(tfdata, CD_MCOL);
2669
2670                         if(layer != -1) {
2671                                 a = attribs->totmcol++;
2672
2673                                 attribs->mcol[a].array = tfdata->layers[layer].data;
2674                                 attribs->mcol[a].emOffset = tfdata->layers[layer].offset;
2675                                 attribs->mcol[a].glIndex = gattribs->layer[b].glindex;
2676                         }
2677                 }
2678                 else if(gattribs->layer[b].type == CD_TANGENT) {
2679                         /* tangents */
2680                         layer = CustomData_get_layer_index(fdata, CD_TANGENT);
2681
2682                         if(layer != -1) {
2683                                 attribs->tottang = 1;
2684
2685                                 attribs->tang.array = fdata->layers[layer].data;
2686                                 attribs->tang.emOffset = fdata->layers[layer].offset;
2687                                 attribs->tang.glIndex = gattribs->layer[b].glindex;
2688                         }
2689                 }
2690                 else if(gattribs->layer[b].type == CD_ORCO) {
2691                         /* original coordinates */
2692                         layer = CustomData_get_layer_index(vdata, CD_ORCO);
2693
2694                         if(layer != -1) {
2695                                 attribs->totorco = 1;
2696
2697                                 attribs->orco.array = vdata->layers[layer].data;
2698                                 attribs->orco.emOffset = vdata->layers[layer].offset;
2699                                 attribs->orco.glIndex = gattribs->layer[b].glindex;
2700                                 attribs->orco.glTexco = gattribs->layer[b].gltexco;
2701                         }
2702                 }
2703         }
2704 }
2705
2706 /* Set object's bounding box based on DerivedMesh min/max data */
2707 void DM_set_object_boundbox(Object *ob, DerivedMesh *dm)
2708 {
2709         float min[3], max[3];
2710
2711         INIT_MINMAX(min, max);
2712
2713         dm->getMinMax(dm, min, max);
2714
2715         if(!ob->bb)
2716                 ob->bb= MEM_callocN(sizeof(BoundBox), "DM-BoundBox");
2717
2718         boundbox_set_from_min_max(ob->bb, min, max);
2719 }
2720
2721 /* --- NAVMESH (begin) --- */
2722 #ifdef WITH_GAMEENGINE
2723
2724 /* BMESH_TODO, navmesh is not working right currently
2725  * All tools set this as MPoly data, but derived mesh currently draws from MFace (tessface)
2726  *
2727  * Proposed solution, rather then copy CD_RECAST into the MFace array,
2728  * use ORIGINDEX to get the original poly index and then get the CD_RECAST
2729  * data from the original me->mpoly layer. - campbell
2730  */
2731
2732
2733 BM_INLINE int navmesh_bit(int a, int b)
2734 {
2735         return (a & (1 << b)) >> b;
2736 }
2737
2738 BM_INLINE void navmesh_intToCol(int i, float col[3])
2739 {
2740         int     r = navmesh_bit(i, 0) + navmesh_bit(i, 3) * 2 + 1;
2741         int     g = navmesh_bit(i, 1) + navmesh_bit(i, 4) * 2 + 1;
2742         int     b = navmesh_bit(i, 2) + navmesh_bit(i, 5) * 2 + 1;
2743         col[0] = 1 - r*63.0f/255.0f;
2744         col[1] = 1 - g*63.0f/255.0f;
2745         col[2] = 1 - b*63.0f/255.0f;
2746 }
2747
2748 static void navmesh_drawColored(DerivedMesh *dm)
2749 {
2750         int a, glmode;
2751         MVert *mvert = (MVert *)CustomData_get_layer(&dm->vertData, CD_MVERT);
2752         MFace *mface = (MFace *)CustomData_get_layer(&dm->faceData, CD_MFACE);
2753         int *polygonIdx = (int *)CustomData_get_layer(&dm->faceData, CD_RECAST);
2754         float col[3];
2755
2756         if (!polygonIdx)
2757                 return;
2758
2759         /*
2760         //UI_ThemeColor(TH_WIRE);
2761         glDisable(GL_LIGHTING);
2762         glLineWidth(2.0);
2763         dm->drawEdges(dm, 0, 1);
2764         glLineWidth(1.0);
2765         glEnable(GL_LIGHTING);*/
2766
2767         glDisable(GL_LIGHTING);
2768         /*  if(GPU_buffer_legacy(dm) ) */ { /* TODO - VBO draw code, not high priority - campbell */
2769                 DEBUG_VBO( "Using legacy code. drawNavMeshColored\n" );
2770                 //glShadeModel(GL_SMOOTH);
2771                 glBegin(glmode = GL_QUADS);
2772                 for(a = 0; a < dm->numTessFaceData; a++, mface++) {
2773                         int new_glmode = mface->v4?GL_QUADS:GL_TRIANGLES;
2774                         int pi = polygonIdx[a];
2775                         if (pi <= 0) {
2776                                 zero_v3(col);
2777                         }
2778                         else {
2779                                 navmesh_intToCol(pi, col);
2780                         }
2781
2782                         if(new_glmode != glmode) {
2783                                 glEnd();
2784                                 glBegin(glmode = new_glmode);
2785                         }
2786                         glColor3fv(col);
2787                         glVertex3fv(mvert[mface->v1].co);
2788                         glVertex3fv(mvert[mface->v2].co);
2789                         glVertex3fv(mvert[mface->v3].co);
2790                         if(mface->v4) {
2791                                 glVertex3fv(mvert[mface->v4].co);
2792                         }
2793                 }
2794                 glEnd();
2795         }
2796         glEnable(GL_LIGHTING);
2797 }
2798
2799 static void navmesh_DM_drawFacesTex(DerivedMesh *dm,
2800                         int (*setDrawOptions)(MTFace *tface, int has_mcol, int matnr),
2801                         int (*compareDrawOptions)(void *userData, int cur_index, int next_index),
2802                         void *userData)
2803 {
2804         (void) setDrawOptions;
2805         (void) compareDrawOptions;
2806         (void) userData;
2807
2808         navmesh_drawColored(dm);
2809 }
2810
2811 static void navmesh_DM_drawFacesSolid(DerivedMesh *dm,
2812                                       float (*partial_redraw_planes)[4],
2813                                       int UNUSED(fast), int (*setMaterial)(int, void *attribs))
2814 {
2815         (void) partial_redraw_planes;
2816         (void) setMaterial;
2817
2818         //drawFacesSolid_original(dm, partial_redraw_planes, fast, setMaterial);
2819         navmesh_drawColored(dm);
2820 }
2821
2822 static DerivedMesh *navmesh_dm_createNavMeshForVisualization(DerivedMesh *dm)
2823 {
2824         DerivedMesh *result;
2825         int maxFaces = dm->getNumPolys(dm);
2826         int *recastData;
2827         int vertsPerPoly=0, nverts=0, ndtris=0, npolys=0;
2828         float* verts=NULL;
2829         unsigned short *dtris=NULL, *dmeshes=NULL, *polys=NULL;
2830         int *dtrisToPolysMap=NULL, *dtrisToTrisMap=NULL, *trisToFacesMap=NULL;
2831         int res;
2832
2833         result = CDDM_copy(dm);
2834         if (!CustomData_has_layer(&result->faceData, CD_RECAST)) {
2835                 int *sourceRecastData = (int*)CustomData_get_layer(&dm->faceData, CD_RECAST);
2836                 if (sourceRecastData) {
2837                         CustomData_add_layer_named(&result->faceData, CD_RECAST, CD_DUPLICATE,
2838                                                    sourceRecastData, maxFaces, "recastData");
2839                 }
2840         }
2841         recastData = (int*)CustomData_get_layer(&result->faceData, CD_RECAST);
2842
2843         /* note: This is not good design! - really should not be doing this */
2844         result->drawFacesTex =  navmesh_DM_drawFacesTex;
2845         result->drawFacesSolid = navmesh_DM_drawFacesSolid;
2846
2847
2848         /* process mesh */
2849         res  = buildNavMeshDataByDerivedMesh(dm, &vertsPerPoly, &nverts, &verts, &ndtris, &dtris,
2850                                              &npolys, &dmeshes, &polys, &dtrisToPolysMap, &dtrisToTrisMap,
2851                                              &trisToFacesMap);
2852         if (res) {
2853                 size_t polyIdx;
2854
2855                 /* invalidate concave polygon */
2856                 for (polyIdx=0; polyIdx<(size_t)npolys; polyIdx++) {
2857                         unsigned short* poly = &polys[polyIdx*2*vertsPerPoly];
2858                         if (!polyIsConvex(poly, vertsPerPoly, verts)) {
2859                                 /* set negative polygon idx to all faces */
2860                                 unsigned short *dmesh = &dmeshes[4*polyIdx];
2861                                 unsigned short tbase = dmesh[2];
2862                                 unsigned short tnum = dmesh[3];
2863                                 unsigned short ti;
2864
2865                                 for (ti=0; ti<tnum; ti++) {
2866                                         unsigned short triidx = dtrisToTrisMap[tbase+ti];
2867                                         unsigned short faceidx = trisToFacesMap[triidx];
2868                                         if (recastData[faceidx] > 0) {
2869                                                 recastData[faceidx] = -recastData[faceidx];
2870                                         }
2871                                 }
2872                         }
2873                 }
2874         }
2875         else {
2876                 printf("Error during creation polygon infos\n");
2877         }
2878
2879         /* clean up */
2880         if (verts!=NULL)
2881                 MEM_freeN(verts);
2882         if (dtris!=NULL)
2883                 MEM_freeN(dtris);
2884         if (dmeshes!=NULL)
2885                 MEM_freeN(dmeshes);
2886         if (polys!=NULL)
2887                 MEM_freeN(polys);
2888         if (dtrisToPolysMap!=NULL)
2889                 MEM_freeN(dtrisToPolysMap);
2890         if (dtrisToTrisMap!=NULL)
2891                 MEM_freeN(dtrisToTrisMap);
2892         if (trisToFacesMap!=NULL)
2893                 MEM_freeN(trisToFacesMap);
2894
2895         return result;
2896 }
2897
2898 #endif /* WITH_GAMEENGINE */
2899
2900 /* --- NAVMESH (end) --- */
2901
2902
2903 void DM_init_origspace(DerivedMesh *dm)
2904 {
2905         static float default_osf[4][2] = {{0, 0}, {1, 0}, {1, 1}, {0, 1}};
2906
2907         OrigSpaceLoop *lof_array = CustomData_get_layer(&dm->loopData, CD_ORIGSPACE_MLOOP);
2908         OrigSpaceLoop *lof;
2909         const int numpoly = dm->getNumPolys(dm);
2910         // const int numloop = dm->getNumLoops(dm);
2911         MPoly *mp = dm->getPolyArray(dm);
2912         int i, j;
2913
2914         for (i = 0; i < numpoly; i++, mp++) {
2915                 /* only quads/tri's for now */
2916                 if (mp->totloop == 3 || mp->totloop == 4) {
2917                         lof = lof_array + mp->loopstart;
2918                         for (j = 0; j < mp->totloop; j++, lof++) {
2919                                 copy_v2_v2(lof->uv, default_osf[j]);
2920                         }
2921                 }
2922         }
2923 }
2924
2925
2926
2927 /* derivedmesh info printing function,
2928  * to help track down differences DM output */
2929
2930 #ifndef NDEBUG
2931 #include "BLI_dynstr.h"
2932
2933 static void dm_debug_info_layers(DynStr *dynstr, DerivedMesh *dm, void *(*getElemDataArray)(DerivedMesh *, int))
2934 {
2935         int type;
2936
2937         for (type = 0; type < CD_NUMTYPES; type++) {
2938                 /* note: doesnt account for multiple layers */
2939                 void *pt = getElemDataArray(dm, type);
2940                 if (pt) {
2941                         const char *name = CustomData_layertype_name(type);
2942                         const int size = CustomData_sizeof(type);
2943                         const char *structname;
2944                         int structnum;
2945                         CustomData_file_write_info(type, &structname, &structnum);
2946                         BLI_dynstr_appendf(dynstr,
2947                                            "        dict(name='%s', struct='%s', type=%d, ptr='%p', elem=%d, length=%d),\n",
2948                                                            name, structname, type, (void *)pt, size, (int)(MEM_allocN_len(pt) / size));
2949                 }
2950         }
2951 }
2952
2953 char *DM_debug_info(DerivedMesh *dm)
2954 {
2955         DynStr *dynstr= BLI_dynstr_new();
2956         char *ret;
2957         const char *tstr;
2958
2959         BLI_dynstr_appendf(dynstr, "{\n");
2960         BLI_dynstr_appendf(dynstr, "    'ptr': '%p',\n", (void *)dm);
2961         switch (dm->type) {
2962                 case DM_TYPE_CDDM:     tstr = "DM_TYPE_CDDM";     break;
2963                 case DM_TYPE_EDITBMESH: tstr = "DM_TYPE_EDITMESH";  break;
2964                 case DM_TYPE_CCGDM:    tstr = "DM_TYPE_CCGDM";     break;
2965                 default:               tstr = "UNKNOWN";           break;
2966         }
2967         BLI_dynstr_appendf(dynstr, "    'type': '%s',\n", tstr);
2968         BLI_dynstr_appendf(dynstr, "    'numVertData': %d,\n", dm->numVertData);
2969         BLI_dynstr_appendf(dynstr, "    'numEdgeData': %d,\n", dm->numEdgeData);
2970         BLI_dynstr_appendf(dynstr, "    'numTessFaceData': %d,\n", dm->numTessFaceData);
2971         BLI_dynstr_appendf(dynstr, "    'numPolyData': %d,\n", dm->numPolyData);
2972         BLI_dynstr_appendf(dynstr, "    'deformedOnly': %d,\n", dm->deformedOnly);
2973
2974         BLI_dynstr_appendf(dynstr, "    'vertexLayers': (\n");
2975         dm_debug_info_layers(dynstr, dm, dm->getVertDataArray);
2976         BLI_dynstr_appendf(dynstr, "    ),\n");
2977
2978         BLI_dynstr_appendf(dynstr, "    'loopLayers': (\n");
2979         dm_debug_info_layers(dynstr, dm, DM_get_loop_data_layer);
2980         BLI_dynstr_appendf(dynstr, "    ),\n");
2981
2982         BLI_dynstr_appendf(dynstr, "    'edgeLayers': (\n");
2983         dm_debug_info_layers(dynstr, dm, dm->getEdgeDataArray);
2984         BLI_dynstr_appendf(dynstr, "    ),\n");
2985
2986         BLI_dynstr_appendf(dynstr, "    'tessFaceLayers': (\n");
2987         dm_debug_info_layers(dynstr, dm, dm->getTessFaceDataArray);
2988         BLI_dynstr_appendf(dynstr, "    ),\n");
2989
2990         BLI_dynstr_appendf(dynstr, "    'polyLayers': (\n");
2991         dm_debug_info_layers(dynstr, dm, DM_get_poly_data_layer);
2992         BLI_dynstr_appendf(dynstr, "    ),\n");
2993
2994         BLI_dynstr_appendf(dynstr, "}\n");
2995
2996         ret = BLI_dynstr_get_cstring(dynstr);
2997         BLI_dynstr_free(dynstr);
2998         return ret;
2999 }
3000
3001 void DM_debug_print(DerivedMesh *dm)
3002 {
3003         char *str = DM_debug_info(dm);
3004         printf("%s", str);
3005         fflush(stdout);
3006         MEM_freeN(str);
3007 }
3008
3009 #endif /* NDEBUG */