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