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