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