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