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