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