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