calculate weight paint colors once per vertex rather then on every face corner (was...
[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 */
721 static unsigned char *calc_weightpaint_vert_array(Object *ob, int const draw_flag, ColorBand *coba)
722 {
723         Mesh *me = ob->data;
724         unsigned char *wtcol_v = MEM_callocN (sizeof(unsigned char) * me->totvert * 4, "weightmap_v");
725
726         if (me->dvert) {
727                 unsigned char *wc = wtcol_v;
728                 MDeformVert *dv= me->dvert;
729                 unsigned int i;
730
731                 /* varisbles for multipaint */
732                 const int defbase_tot = BLI_countlist(&ob->defbase);
733                 const int defbase_act = ob->actdef-1;
734                 char *dg_flags = MEM_mallocN(defbase_tot * sizeof(char), __func__);
735                 const int selected = get_selected_defgroups(ob, dg_flags, defbase_tot);
736                 /* const int unselected = defbase_tot - selected; */ /* UNUSED */
737
738                 for (i = me->totvert; i != 0; i--, wc += 4, dv++) {
739                         calc_weightpaint_vert_color(wc, dv, coba, defbase_tot, defbase_act, dg_flags, selected, draw_flag);
740                 }
741
742                 MEM_freeN(dg_flags);
743         }
744         else {
745                 int col_i;
746                 weightpaint_color((unsigned char *)&col_i, coba, 0.0f);
747                 fill_vn_i((int *)wtcol_v, me->totvert, col_i);
748         }
749
750         return wtcol_v;
751 }
752
753 #include "PIL_time.h"
754
755 static void add_weight_mcol_dm(Object *ob, DerivedMesh *dm, int const draw_flag)
756 {
757         ColorBand *coba= stored_cb;     /* warning, not a local var */
758
759         Mesh *me = ob->data;
760         unsigned char *wtcol_v = calc_weightpaint_vert_array(ob, draw_flag, coba);
761         unsigned char *wtcol_f = MEM_mallocN (sizeof(unsigned char) * me->totface*4*4, "weightmap_f");
762
763         MFace *mf = me->mface;
764         int i;
765
766         for (i=0; i<me->totface; i++, mf++) {
767                 unsigned int fidx= mf->v4 ? 3:2;
768                 do {
769                         copy_v4_v4_char((char *)&wtcol_f[(4 * i + fidx) * 4],
770                                         (char *)&wtcol_v[4 * (*(&mf->v1 + fidx))]);
771                 } while (fidx--);
772         }
773
774         MEM_freeN(wtcol_v);
775
776         CustomData_add_layer(&dm->faceData, CD_WEIGHT_MCOL, CD_ASSIGN, wtcol_f, dm->numFaceData);
777 }
778
779 /* new value for useDeform -1  (hack for the gameengine):
780  * - apply only the modifier stack of the object, skipping the virtual modifiers,
781  * - don't apply the key
782  * - apply deform modifiers and input vertexco
783  */
784 static void mesh_calc_modifiers(Scene *scene, Object *ob, float (*inputVertexCos)[3],
785                                                                 DerivedMesh **deform_r, DerivedMesh **final_r,
786                                                                 int useRenderParams, int useDeform,
787                                                                 int needMapping, CustomDataMask dataMask, int index, int useCache)
788 {
789         Mesh *me = ob->data;
790         ModifierData *firstmd, *md;
791         LinkNode *datamasks, *curr;
792         CustomDataMask mask, nextmask, append_mask = 0;
793         float (*deformedVerts)[3] = NULL;
794         DerivedMesh *dm, *orcodm, *clothorcodm, *finaldm;
795         int numVerts = me->totvert;
796         int required_mode;
797         int isPrevDeform= FALSE;
798         int skipVirtualArmature = (useDeform < 0);
799         MultiresModifierData *mmd= get_multires_modifier(scene, ob, 0);
800         int has_multires = mmd != NULL, multires_applied = 0;
801         int sculpt_mode = ob->mode & OB_MODE_SCULPT && ob->sculpt;
802
803         int draw_flag= ((scene->toolsettings->multipaint ? CALC_WP_MULTIPAINT : 0) |
804                         (scene->toolsettings->auto_normalize ? CALC_WP_AUTO_NORMALIZE : 0));
805
806         if(mmd && !mmd->sculptlvl)
807                 has_multires = 0;
808
809         if(!skipVirtualArmature) {
810                 firstmd = modifiers_getVirtualModifierList(ob);
811         }
812         else {
813                 /* game engine exception */
814                 firstmd = ob->modifiers.first;
815                 if(firstmd && firstmd->type == eModifierType_Armature)
816                         firstmd = firstmd->next;
817         }
818
819         md = firstmd;
820
821         modifiers_clearErrors(ob);
822
823         if(useRenderParams) required_mode = eModifierMode_Render;
824         else required_mode = eModifierMode_Realtime;
825
826         datamasks = modifiers_calcDataMasks(scene, ob, md, dataMask, required_mode);
827         curr = datamasks;
828
829         if(deform_r) *deform_r = NULL;
830         *final_r = NULL;
831
832         if(useDeform) {
833                 if(inputVertexCos)
834                         deformedVerts = inputVertexCos;
835                 
836                 /* Apply all leading deforming modifiers */
837                 for(;md; md = md->next, curr = curr->next) {
838                         ModifierTypeInfo *mti = modifierType_getInfo(md->type);
839
840                         md->scene= scene;
841                         
842                         if(!modifier_isEnabled(scene, md, required_mode)) continue;
843                         if(useDeform < 0 && mti->dependsOnTime && mti->dependsOnTime(md)) continue;
844
845                         if(mti->type == eModifierTypeType_OnlyDeform) {
846                                 if(!deformedVerts)
847                                         deformedVerts = mesh_getVertexCos(me, &numVerts);
848
849                                 mti->deformVerts(md, ob, NULL, deformedVerts, numVerts, useRenderParams, useDeform);
850                         } else {
851                                 break;
852                         }
853                         
854                         /* grab modifiers until index i */
855                         if((index >= 0) && (modifiers_indexInObject(ob, md) >= index))
856                                 break;
857                 }
858
859                 /* Result of all leading deforming modifiers is cached for
860                  * places that wish to use the original mesh but with deformed
861                  * coordinates (vpaint, etc.)
862                  */
863                 if (deform_r) {
864                         *deform_r = CDDM_from_mesh(me, ob);
865
866                         if(deformedVerts) {
867                                 CDDM_apply_vert_coords(*deform_r, deformedVerts);
868                                 CDDM_calc_normals(*deform_r);
869                         }
870                 }
871         } else {
872                 /* default behaviour for meshes */
873                 if(inputVertexCos)
874                         deformedVerts = inputVertexCos;
875                 else
876                         deformedVerts = mesh_getVertexCos(me, &numVerts);
877         }
878
879
880         /* Now apply all remaining modifiers. If useDeform is off then skip
881          * OnlyDeform ones. 
882          */
883         dm = NULL;
884         orcodm = NULL;
885         clothorcodm = NULL;
886
887         for(;md; md = md->next, curr = curr->next) {
888                 ModifierTypeInfo *mti = modifierType_getInfo(md->type);
889
890                 md->scene= scene;
891
892                 if(!modifier_isEnabled(scene, md, required_mode)) continue;
893                 if(mti->type == eModifierTypeType_OnlyDeform && !useDeform) continue;
894                 if((mti->flags & eModifierTypeFlag_RequiresOriginalData) && dm) {
895                         modifier_setError(md, "Modifier requires original data, bad stack position.");
896                         continue;
897                 }
898                 if(sculpt_mode && (!has_multires || multires_applied)) {
899                         int unsupported= 0;
900
901                         if(scene->toolsettings->sculpt->flags & SCULPT_ONLY_DEFORM)
902                                 unsupported|= mti->type != eModifierTypeType_OnlyDeform;
903
904                         unsupported|= md->type == eModifierType_Multires && ((MultiresModifierData*)md)->sculptlvl==0;
905                         unsupported|= multires_applied;
906
907                         if(unsupported) {
908                                 modifier_setError(md, "Not supported in sculpt mode.");
909                                 continue;
910                         }
911                 }
912                 if(needMapping && !modifier_supportsMapping(md)) continue;
913                 if(useDeform < 0 && mti->dependsOnTime && mti->dependsOnTime(md)) continue;
914
915                 /* add an orco layer if needed by this modifier */
916                 if(mti->requiredDataMask)
917                         mask = mti->requiredDataMask(ob, md);
918                 else
919                         mask = 0;
920
921                 if(dm && (mask & CD_MASK_ORCO))
922                         add_orco_dm(ob, NULL, dm, orcodm, CD_ORCO);
923
924                 /* How to apply modifier depends on (a) what we already have as
925                  * a result of previous modifiers (could be a DerivedMesh or just
926                  * deformed vertices) and (b) what type the modifier is.
927                  */
928
929                 if(mti->type == eModifierTypeType_OnlyDeform) {
930                         /* No existing verts to deform, need to build them. */
931                         if(!deformedVerts) {
932                                 if(dm) {
933                                         /* Deforming a derived mesh, read the vertex locations
934                                          * out of the mesh and deform them. Once done with this
935                                          * run of deformers verts will be written back.
936                                          */
937                                         numVerts = dm->getNumVerts(dm);
938                                         deformedVerts =
939                                                 MEM_mallocN(sizeof(*deformedVerts) * numVerts, "dfmv");
940                                         dm->getVertCos(dm, deformedVerts);
941                                 } else {
942                                         deformedVerts = mesh_getVertexCos(me, &numVerts);
943                                 }
944                         }
945
946                         /* if this is not the last modifier in the stack then recalculate the normals
947                          * to avoid giving bogus normals to the next modifier see: [#23673] */
948                         if(isPrevDeform &&  mti->dependsOnNormals && mti->dependsOnNormals(md)) {
949                                 /* XXX, this covers bug #23673, but we may need normal calc for other types */
950                                 if(dm && dm->type == DM_TYPE_CDDM) {
951                                         CDDM_apply_vert_coords(dm, deformedVerts);
952                                         CDDM_calc_normals(dm);
953                                 }
954                         }
955
956                         mti->deformVerts(md, ob, dm, deformedVerts, numVerts, useRenderParams, useDeform);
957                 } else {
958                         DerivedMesh *ndm;
959
960                         /* determine which data layers are needed by following modifiers */
961                         if(curr->next)
962                                 nextmask= (CustomDataMask)GET_INT_FROM_POINTER(curr->next->link);
963                         else
964                                 nextmask= dataMask;
965
966                         /* apply vertex coordinates or build a DerivedMesh as necessary */
967                         if(dm) {
968                                 if(deformedVerts) {
969                                         DerivedMesh *tdm = CDDM_copy(dm);
970                                         dm->release(dm);
971                                         dm = tdm;
972
973                                         CDDM_apply_vert_coords(dm, deformedVerts);
974                                         CDDM_calc_normals(dm);
975                                 }
976                         } else {
977                                 dm = CDDM_from_mesh(me, ob);
978
979                                 if(deformedVerts) {
980                                         CDDM_apply_vert_coords(dm, deformedVerts);
981                                         CDDM_calc_normals(dm);
982                                 }
983
984                                 if((dataMask & CD_MASK_WEIGHT_MCOL) && (ob->mode & OB_MODE_WEIGHT_PAINT))
985                                         add_weight_mcol_dm(ob, dm, draw_flag); 
986
987                                 /* Constructive modifiers need to have an origindex
988                                  * otherwise they wont have anywhere to copy the data from.
989                                  *
990                                  * Also create ORIGINDEX data if any of the following modifiers
991                                  * requests it, this way Mirror, Solidify etc will keep ORIGINDEX
992                                  * data by using generic DM_copy_vert_data() functions.
993                                  */
994                                 if(needMapping || (nextmask & CD_MASK_ORIGINDEX)) {
995                                         /* calc */
996                                         DM_add_vert_layer(dm, CD_ORIGINDEX, CD_CALLOC, NULL);
997                                         DM_add_edge_layer(dm, CD_ORIGINDEX, CD_CALLOC, NULL);
998                                         DM_add_face_layer(dm, CD_ORIGINDEX, CD_CALLOC, NULL);
999
1000                                         range_vn_i(DM_get_vert_data_layer(dm, CD_ORIGINDEX), dm->numVertData, 0);
1001                                         range_vn_i(DM_get_edge_data_layer(dm, CD_ORIGINDEX), dm->numEdgeData, 0);
1002                                         range_vn_i(DM_get_face_data_layer(dm, CD_ORIGINDEX), dm->numFaceData, 0);
1003                                 }
1004                         }
1005
1006                         
1007                         /* set the DerivedMesh to only copy needed data */
1008                         mask= (CustomDataMask)GET_INT_FROM_POINTER(curr->link);
1009                         /* needMapping check here fixes bug [#28112], otherwise its
1010                          * possible that it wont be copied */
1011                         mask |= append_mask;
1012                         DM_set_only_copy(dm, mask | (needMapping ? CD_MASK_ORIGINDEX : 0));
1013                         
1014                         /* add cloth rest shape key if need */
1015                         if(mask & CD_MASK_CLOTH_ORCO)
1016                                 add_orco_dm(ob, NULL, dm, clothorcodm, CD_CLOTH_ORCO);
1017
1018                         /* add an origspace layer if needed */
1019                         if(((CustomDataMask)GET_INT_FROM_POINTER(curr->link)) & CD_MASK_ORIGSPACE)
1020                                 if(!CustomData_has_layer(&dm->faceData, CD_ORIGSPACE))
1021                                         DM_add_face_layer(dm, CD_ORIGSPACE, CD_DEFAULT, NULL);
1022
1023                         ndm = mti->applyModifier(md, ob, dm, useRenderParams, useCache);
1024
1025                         if(ndm) {
1026                                 /* if the modifier returned a new dm, release the old one */
1027                                 if(dm && dm != ndm) dm->release(dm);
1028
1029                                 dm = ndm;
1030
1031                                 if(deformedVerts) {
1032                                         if(deformedVerts != inputVertexCos)
1033                                                 MEM_freeN(deformedVerts);
1034
1035                                         deformedVerts = NULL;
1036                                 }
1037                         } 
1038
1039                         /* create an orco derivedmesh in parallel */
1040                         if(nextmask & CD_MASK_ORCO) {
1041                                 if(!orcodm)
1042                                         orcodm= create_orco_dm(ob, me, NULL, CD_ORCO);
1043
1044                                 nextmask &= ~CD_MASK_ORCO;
1045                                 DM_set_only_copy(orcodm, nextmask | CD_MASK_ORIGINDEX);
1046                                 ndm = mti->applyModifier(md, ob, orcodm, useRenderParams, 0);
1047
1048                                 if(ndm) {
1049                                         /* if the modifier returned a new dm, release the old one */
1050                                         if(orcodm && orcodm != ndm) orcodm->release(orcodm);
1051                                         orcodm = ndm;
1052                                 }
1053                         }
1054
1055                         /* create cloth orco derivedmesh in parallel */
1056                         if(nextmask & CD_MASK_CLOTH_ORCO) {
1057                                 if(!clothorcodm)
1058                                         clothorcodm= create_orco_dm(ob, me, NULL, CD_CLOTH_ORCO);
1059
1060                                 nextmask &= ~CD_MASK_CLOTH_ORCO;
1061                                 DM_set_only_copy(clothorcodm, nextmask | CD_MASK_ORIGINDEX);
1062                                 ndm = mti->applyModifier(md, ob, clothorcodm, useRenderParams, 0);
1063
1064                                 if(ndm) {
1065                                         /* if the modifier returned a new dm, release the old one */
1066                                         if(clothorcodm && clothorcodm != ndm) clothorcodm->release(clothorcodm);
1067                                         clothorcodm = ndm;
1068                                 }
1069                         }
1070
1071                         /* in case of dynamic paint, make sure preview mask remains for following modifiers */
1072                         if (md->type == eModifierType_DynamicPaint)
1073                                 append_mask |= CD_MASK_WEIGHT_MCOL;
1074                 }
1075
1076                 isPrevDeform= (mti->type == eModifierTypeType_OnlyDeform);
1077
1078                 /* grab modifiers until index i */
1079                 if((index >= 0) && (modifiers_indexInObject(ob, md) >= index))
1080                         break;
1081
1082                 if(sculpt_mode && md->type == eModifierType_Multires)
1083                         multires_applied = 1;
1084         }
1085
1086         for(md=firstmd; md; md=md->next)
1087                 modifier_freeTemporaryData(md);
1088
1089         /* Yay, we are done. If we have a DerivedMesh and deformed vertices
1090          * need to apply these back onto the DerivedMesh. If we have no
1091          * DerivedMesh then we need to build one.
1092          */
1093         if(dm && deformedVerts) {
1094                 finaldm = CDDM_copy(dm);
1095
1096                 dm->release(dm);
1097
1098                 CDDM_apply_vert_coords(finaldm, deformedVerts);
1099                 CDDM_calc_normals(finaldm);
1100
1101                 if((dataMask & CD_MASK_WEIGHT_MCOL) && (ob->mode & OB_MODE_WEIGHT_PAINT))
1102                         add_weight_mcol_dm(ob, finaldm, draw_flag);
1103         } else if(dm) {
1104                 finaldm = dm;
1105         } else {
1106                 finaldm = CDDM_from_mesh(me, ob);
1107
1108                 if(deformedVerts) {
1109                         CDDM_apply_vert_coords(finaldm, deformedVerts);
1110                         CDDM_calc_normals(finaldm);
1111                 }
1112
1113                 if((dataMask & CD_MASK_WEIGHT_MCOL) && (ob->mode & OB_MODE_WEIGHT_PAINT))
1114                         add_weight_mcol_dm(ob, finaldm, draw_flag);
1115         }
1116
1117         /* add an orco layer if needed */
1118         if(dataMask & CD_MASK_ORCO) {
1119                 add_orco_dm(ob, NULL, finaldm, orcodm, CD_ORCO);
1120
1121                 if(deform_r && *deform_r)
1122                         add_orco_dm(ob, NULL, *deform_r, NULL, CD_ORCO);
1123         }
1124
1125 #ifdef WITH_GAMEENGINE
1126         /* NavMesh - this is a hack but saves having a NavMesh modifier */
1127         if ((ob->gameflag & OB_NAVMESH) && (finaldm->type == DM_TYPE_CDDM)) {
1128                 DerivedMesh *tdm;
1129                 tdm= navmesh_dm_createNavMeshForVisualization(finaldm);
1130                 if (finaldm != tdm) {
1131                         finaldm->release(finaldm);
1132                         finaldm= tdm;
1133                 }
1134         }
1135 #endif /* WITH_GAMEENGINE */
1136
1137         *final_r = finaldm;
1138
1139         if(orcodm)
1140                 orcodm->release(orcodm);
1141         if(clothorcodm)
1142                 clothorcodm->release(clothorcodm);
1143
1144         if(deformedVerts && deformedVerts != inputVertexCos)
1145                 MEM_freeN(deformedVerts);
1146
1147         BLI_linklist_free(datamasks, NULL);
1148 }
1149
1150 float (*editmesh_get_vertex_cos(EditMesh *em, int *numVerts_r))[3]
1151 {
1152         int i, numVerts = *numVerts_r = BLI_countlist(&em->verts);
1153         float (*cos)[3];
1154         EditVert *eve;
1155
1156         cos = MEM_mallocN(sizeof(*cos)*numVerts, "vertexcos");
1157         for (i=0,eve=em->verts.first; i<numVerts; i++,eve=eve->next) {
1158                 copy_v3_v3(cos[i], eve->co);
1159         }
1160
1161         return cos;
1162 }
1163
1164 int editmesh_modifier_is_enabled(Scene *scene, ModifierData *md, DerivedMesh *dm)
1165 {
1166         ModifierTypeInfo *mti = modifierType_getInfo(md->type);
1167         int required_mode = eModifierMode_Realtime | eModifierMode_Editmode;
1168
1169         if(!modifier_isEnabled(scene, md, required_mode)) return 0;
1170         if((mti->flags & eModifierTypeFlag_RequiresOriginalData) && dm) {
1171                 modifier_setError(md, "Modifier requires original data, bad stack position.");
1172                 return 0;
1173         }
1174         
1175         return 1;
1176 }
1177
1178 static void editmesh_calc_modifiers(Scene *scene, Object *ob, EditMesh *em, DerivedMesh **cage_r,
1179                                                                         DerivedMesh **final_r,
1180                                                                         CustomDataMask dataMask)
1181 {
1182         ModifierData *md;
1183         float (*deformedVerts)[3] = NULL;
1184         CustomDataMask mask;
1185         DerivedMesh *dm, *orcodm = NULL;
1186         int i, numVerts = 0, cageIndex = modifiers_getCageIndex(scene, ob, NULL, 1);
1187         LinkNode *datamasks, *curr;
1188         int required_mode = eModifierMode_Realtime | eModifierMode_Editmode;
1189
1190         modifiers_clearErrors(ob);
1191
1192         if(cage_r && cageIndex == -1) {
1193                 *cage_r = editmesh_get_derived(em, NULL);
1194         }
1195
1196         dm = NULL;
1197         md = modifiers_getVirtualModifierList(ob);
1198
1199         datamasks = modifiers_calcDataMasks(scene, ob, md, dataMask, required_mode);
1200
1201         curr = datamasks;
1202         for(i = 0; md; i++, md = md->next, curr = curr->next) {
1203                 ModifierTypeInfo *mti = modifierType_getInfo(md->type);
1204
1205                 md->scene= scene;
1206                 
1207                 if(!editmesh_modifier_is_enabled(scene, md, dm))
1208                         continue;
1209
1210                 /* add an orco layer if needed by this modifier */
1211                 if(dm && mti->requiredDataMask) {
1212                         mask = mti->requiredDataMask(ob, md);
1213                         if(mask & CD_MASK_ORCO)
1214                                 add_orco_dm(ob, em, dm, orcodm, CD_ORCO);
1215                 }
1216
1217                 /* How to apply modifier depends on (a) what we already have as
1218                  * a result of previous modifiers (could be a DerivedMesh or just
1219                  * deformed vertices) and (b) what type the modifier is.
1220                  */
1221
1222                 if(mti->type == eModifierTypeType_OnlyDeform) {
1223                         /* No existing verts to deform, need to build them. */
1224                         if(!deformedVerts) {
1225                                 if(dm) {
1226                                         /* Deforming a derived mesh, read the vertex locations
1227                                          * out of the mesh and deform them. Once done with this
1228                                          * run of deformers verts will be written back.
1229                                          */
1230                                         numVerts = dm->getNumVerts(dm);
1231                                         deformedVerts =
1232                                                 MEM_mallocN(sizeof(*deformedVerts) * numVerts, "dfmv");
1233                                         dm->getVertCos(dm, deformedVerts);
1234                                 } else {
1235                                         deformedVerts = editmesh_get_vertex_cos(em, &numVerts);
1236                                 }
1237                         }
1238
1239                         if (mti->deformVertsEM)
1240                                 mti->deformVertsEM(md, ob, em, dm, deformedVerts, numVerts);
1241                         else mti->deformVerts(md, ob, dm, deformedVerts, numVerts, 0, 0);
1242                 } else {
1243                         DerivedMesh *ndm;
1244
1245                         /* apply vertex coordinates or build a DerivedMesh as necessary */
1246                         if(dm) {
1247                                 if(deformedVerts) {
1248                                         DerivedMesh *tdm = CDDM_copy(dm);
1249                                         if(!(cage_r && dm == *cage_r)) dm->release(dm);
1250                                         dm = tdm;
1251
1252                                         CDDM_apply_vert_coords(dm, deformedVerts);
1253                                         CDDM_calc_normals(dm);
1254                                 } else if(cage_r && dm == *cage_r) {
1255                                         /* dm may be changed by this modifier, so we need to copy it
1256                                          */
1257                                         dm = CDDM_copy(dm);
1258                                 }
1259
1260                         } else {
1261                                 dm = CDDM_from_editmesh(em, ob->data);
1262
1263                                 if(deformedVerts) {
1264                                         CDDM_apply_vert_coords(dm, deformedVerts);
1265                                         CDDM_calc_normals(dm);
1266                                 }
1267                         }
1268
1269                         /* create an orco derivedmesh in parallel */
1270                         mask= (CustomDataMask)GET_INT_FROM_POINTER(curr->link);
1271                         if(mask & CD_MASK_ORCO) {
1272                                 if(!orcodm)
1273                                         orcodm= create_orco_dm(ob, ob->data, em, CD_ORCO);
1274
1275                                 mask &= ~CD_MASK_ORCO;
1276                                 DM_set_only_copy(orcodm, mask | CD_MASK_ORIGINDEX);
1277
1278                                 if (mti->applyModifierEM)
1279                                         ndm = mti->applyModifierEM(md, ob, em, orcodm);
1280                                 else
1281                                         ndm = mti->applyModifier(md, ob, orcodm, 0, 0);
1282
1283                                 if(ndm) {
1284                                         /* if the modifier returned a new dm, release the old one */
1285                                         if(orcodm && orcodm != ndm) orcodm->release(orcodm);
1286                                         orcodm = ndm;
1287                                 }
1288                         }
1289
1290                         /* set the DerivedMesh to only copy needed data */
1291                         mask= (CustomDataMask)GET_INT_FROM_POINTER(curr->link); /* CD_MASK_ORCO may have been cleared above */
1292
1293                         DM_set_only_copy(dm, mask | CD_MASK_ORIGINDEX);
1294
1295                         if(mask & CD_MASK_ORIGSPACE)
1296                                 if(!CustomData_has_layer(&dm->faceData, CD_ORIGSPACE))
1297                                         DM_add_face_layer(dm, CD_ORIGSPACE, CD_DEFAULT, NULL);
1298                         
1299                         if (mti->applyModifierEM)
1300                                 ndm = mti->applyModifierEM(md, ob, em, dm);
1301                         else
1302                                 ndm = mti->applyModifier(md, ob, dm, 0, 0);
1303
1304                         if (ndm) {
1305                                 if(dm && dm != ndm)
1306                                         dm->release(dm);
1307
1308                                 dm = ndm;
1309
1310                                 if (deformedVerts) {
1311                                         MEM_freeN(deformedVerts);
1312                                         deformedVerts = NULL;
1313                                 }
1314                         }
1315                 }
1316
1317                 if(cage_r && i == cageIndex) {
1318                         if(dm && deformedVerts) {
1319                                 *cage_r = CDDM_copy(dm);
1320                                 CDDM_apply_vert_coords(*cage_r, deformedVerts);
1321                         } else if(dm) {
1322                                 *cage_r = dm;
1323                         } else {
1324                                 *cage_r =
1325                                         editmesh_get_derived(em,
1326                                                 deformedVerts ? MEM_dupallocN(deformedVerts) : NULL);
1327                         }
1328                 }
1329         }
1330
1331         BLI_linklist_free(datamasks, NULL);
1332
1333         /* Yay, we are done. If we have a DerivedMesh and deformed vertices need
1334          * to apply these back onto the DerivedMesh. If we have no DerivedMesh
1335          * then we need to build one.
1336          */
1337         if(dm && deformedVerts) {
1338                 *final_r = CDDM_copy(dm);
1339
1340                 if(!(cage_r && dm == *cage_r)) dm->release(dm);
1341
1342                 CDDM_apply_vert_coords(*final_r, deformedVerts);
1343                 CDDM_calc_normals(*final_r);
1344         } else if (dm) {
1345                 *final_r = dm;
1346         } else if (!deformedVerts && cage_r && *cage_r) {
1347                 *final_r = *cage_r;
1348         } else {
1349                 *final_r = editmesh_get_derived(em, deformedVerts);
1350                 deformedVerts = NULL;
1351         }
1352
1353         /* add an orco layer if needed */
1354         if(dataMask & CD_MASK_ORCO)
1355                 add_orco_dm(ob, em, *final_r, orcodm, CD_ORCO);
1356
1357         if(orcodm)
1358                 orcodm->release(orcodm);
1359
1360         if(deformedVerts)
1361                 MEM_freeN(deformedVerts);
1362 }
1363
1364 static void clear_mesh_caches(Object *ob)
1365 {
1366         Mesh *me= ob->data;
1367
1368                 /* also serves as signal to remake texspace */
1369         if (ob->bb) {
1370                 MEM_freeN(ob->bb);
1371                 ob->bb = NULL;
1372         }
1373         if (me->bb) {
1374                 MEM_freeN(me->bb);
1375                 me->bb = NULL;
1376         }
1377
1378         freedisplist(&ob->disp);
1379
1380         if (ob->derivedFinal) {
1381                 ob->derivedFinal->needsFree = 1;
1382                 ob->derivedFinal->release(ob->derivedFinal);
1383                 ob->derivedFinal= NULL;
1384         }
1385         if (ob->derivedDeform) {
1386                 ob->derivedDeform->needsFree = 1;
1387                 ob->derivedDeform->release(ob->derivedDeform);
1388                 ob->derivedDeform= NULL;
1389         }
1390
1391         if(ob->sculpt) {
1392                 object_sculpt_modifiers_changed(ob);
1393         }
1394 }
1395
1396 static void mesh_build_data(Scene *scene, Object *ob, CustomDataMask dataMask)
1397 {
1398         Object *obact = scene->basact?scene->basact->object:NULL;
1399         int editing = paint_facesel_test(ob) || paint_vertsel_test(ob);/* paint_vertsel_test */
1400         /* weight paint and face select need original indices because of selection buffer drawing */
1401         int needMapping = (ob==obact) && (editing || (ob->mode & (OB_MODE_WEIGHT_PAINT|OB_MODE_VERTEX_PAINT)));
1402
1403         clear_mesh_caches(ob);
1404
1405         mesh_calc_modifiers(scene, ob, NULL, &ob->derivedDeform,
1406                                                 &ob->derivedFinal, 0, 1,
1407                                                 needMapping, dataMask, -1, 1);
1408
1409         DM_set_object_boundbox (ob, ob->derivedFinal);
1410
1411         ob->derivedFinal->needsFree = 0;
1412         ob->derivedDeform->needsFree = 0;
1413         ob->lastDataMask = dataMask;
1414 }
1415
1416 static void editmesh_build_data(Scene *scene, Object *obedit, EditMesh *em, CustomDataMask dataMask)
1417 {
1418         clear_mesh_caches(obedit);
1419
1420         if (em->derivedFinal) {
1421                 if (em->derivedFinal!=em->derivedCage) {
1422                         em->derivedFinal->needsFree = 1;
1423                         em->derivedFinal->release(em->derivedFinal);
1424                 }
1425                 em->derivedFinal = NULL;
1426         }
1427         if (em->derivedCage) {
1428                 em->derivedCage->needsFree = 1;
1429                 em->derivedCage->release(em->derivedCage);
1430                 em->derivedCage = NULL;
1431         }
1432
1433         editmesh_calc_modifiers(scene, obedit, em, &em->derivedCage, &em->derivedFinal, dataMask);
1434         DM_set_object_boundbox (obedit, em->derivedFinal);
1435
1436         em->lastDataMask = dataMask;
1437         em->derivedFinal->needsFree = 0;
1438         em->derivedCage->needsFree = 0;
1439 }
1440
1441 void makeDerivedMesh(Scene *scene, Object *ob, EditMesh *em, CustomDataMask dataMask)
1442 {
1443         if (em) {
1444                 editmesh_build_data(scene, ob, em, dataMask);
1445         } else {
1446                 mesh_build_data(scene, ob, dataMask);
1447         }
1448 }
1449
1450 /***/
1451
1452 DerivedMesh *mesh_get_derived_final(Scene *scene, Object *ob, CustomDataMask dataMask)
1453 {
1454         /* if there's no derived mesh or the last data mask used doesn't include
1455          * the data we need, rebuild the derived mesh
1456          */
1457         if(!ob->derivedFinal || (dataMask & ob->lastDataMask) != dataMask)
1458                 mesh_build_data(scene, ob, dataMask);
1459
1460         return ob->derivedFinal;
1461 }
1462
1463 DerivedMesh *mesh_get_derived_deform(Scene *scene, Object *ob, CustomDataMask dataMask)
1464 {
1465         /* if there's no derived mesh or the last data mask used doesn't include
1466          * the data we need, rebuild the derived mesh
1467          */
1468         if(!ob->derivedDeform || (dataMask & ob->lastDataMask) != dataMask)
1469                 mesh_build_data(scene, ob, dataMask);
1470
1471         return ob->derivedDeform;
1472 }
1473
1474 DerivedMesh *mesh_create_derived_render(Scene *scene, Object *ob, CustomDataMask dataMask)
1475 {
1476         DerivedMesh *final;
1477         
1478         mesh_calc_modifiers(scene, ob, NULL, NULL, &final, 1, 1, 0, dataMask, -1, 0);
1479
1480         return final;
1481 }
1482
1483 DerivedMesh *mesh_create_derived_index_render(Scene *scene, Object *ob, CustomDataMask dataMask, int index)
1484 {
1485         DerivedMesh *final;
1486         
1487         mesh_calc_modifiers(scene, ob, NULL, NULL, &final, 1, 1, 0, dataMask, index, 0);
1488
1489         return final;
1490 }
1491
1492 DerivedMesh *mesh_create_derived_view(Scene *scene, Object *ob, CustomDataMask dataMask)
1493 {
1494         DerivedMesh *final;
1495
1496         mesh_calc_modifiers(scene, ob, NULL, NULL, &final, 0, 1, 0, dataMask, -1, 0);
1497
1498         return final;
1499 }
1500
1501 DerivedMesh *mesh_create_derived_no_deform(Scene *scene, Object *ob, float (*vertCos)[3],
1502                                                                                    CustomDataMask dataMask)
1503 {
1504         DerivedMesh *final;
1505         
1506         mesh_calc_modifiers(scene, ob, vertCos, NULL, &final, 0, 0, 0, dataMask, -1, 0);
1507
1508         return final;
1509 }
1510
1511 DerivedMesh *mesh_create_derived_no_virtual(Scene *scene, Object *ob, float (*vertCos)[3],
1512                                                                                         CustomDataMask dataMask)
1513 {
1514         DerivedMesh *final;
1515         
1516         mesh_calc_modifiers(scene, ob, vertCos, NULL, &final, 0, -1, 0, dataMask, -1, 0);
1517
1518         return final;
1519 }
1520
1521 DerivedMesh *mesh_create_derived_physics(Scene *scene, Object *ob, float (*vertCos)[3],
1522                                                                                         CustomDataMask dataMask)
1523 {
1524         DerivedMesh *final;
1525         
1526         mesh_calc_modifiers(scene, ob, vertCos, NULL, &final, 0, -1, 1, dataMask, -1, 0);
1527
1528         return final;
1529 }
1530
1531 DerivedMesh *mesh_create_derived_no_deform_render(Scene *scene, Object *ob,
1532                                                                                                   float (*vertCos)[3],
1533                                                                                                   CustomDataMask dataMask)
1534 {
1535         DerivedMesh *final;
1536
1537         mesh_calc_modifiers(scene, ob, vertCos, NULL, &final, 1, 0, 0, dataMask, -1, 0);
1538
1539         return final;
1540 }
1541
1542 /***/
1543
1544 DerivedMesh *editmesh_get_derived_cage_and_final(Scene *scene, Object *obedit, EditMesh *em, DerivedMesh **final_r,
1545                                                                                                  CustomDataMask dataMask)
1546 {
1547         /* if there's no derived mesh or the last data mask used doesn't include
1548          * the data we need, rebuild the derived mesh
1549          */
1550         if(!em->derivedCage ||
1551            (em->lastDataMask & dataMask) != dataMask)
1552                 editmesh_build_data(scene, obedit, em, dataMask);
1553
1554         *final_r = em->derivedFinal;
1555         return em->derivedCage;
1556 }
1557
1558 DerivedMesh *editmesh_get_derived_cage(Scene *scene, Object *obedit, EditMesh *em, CustomDataMask dataMask)
1559 {
1560         /* if there's no derived mesh or the last data mask used doesn't include
1561          * the data we need, rebuild the derived mesh
1562          */
1563         if(!em->derivedCage ||
1564            (em->lastDataMask & dataMask) != dataMask)
1565                 editmesh_build_data(scene, obedit, em, dataMask);
1566
1567         return em->derivedCage;
1568 }
1569
1570 DerivedMesh *editmesh_get_derived_base(Object *UNUSED(obedit), EditMesh *em)
1571 {
1572         return editmesh_get_derived(em, NULL);
1573 }
1574
1575
1576 /* ********* For those who don't grasp derived stuff! (ton) :) *************** */
1577
1578 static void make_vertexcosnos__mapFunc(void *userData, int index, float *co, float *no_f, short *no_s)
1579 {
1580         float *vec = userData;
1581         
1582         vec+= 6*index;
1583
1584         /* check if we've been here before (normal should not be 0) */
1585         if(vec[3] || vec[4] || vec[5]) return;
1586
1587         copy_v3_v3(vec, co);
1588         vec+= 3;
1589         if(no_f) {
1590                 copy_v3_v3(vec, no_f);
1591         }
1592         else {
1593                 normal_short_to_float_v3(vec, no_s);
1594         }
1595 }
1596
1597 /* always returns original amount me->totvert of vertices and normals, but fully deformed and subsurfered */
1598 /* this is needed for all code using vertexgroups (no subsurf support) */
1599 /* it stores the normals as floats, but they can still be scaled as shorts (32767 = unit) */
1600 /* in use now by vertex/weight paint and particle generating */
1601
1602 float *mesh_get_mapped_verts_nors(Scene *scene, Object *ob)
1603 {
1604         Mesh *me= ob->data;
1605         DerivedMesh *dm;
1606         float *vertexcosnos;
1607         
1608         /* lets prevent crashing... */
1609         if(ob->type!=OB_MESH || me->totvert==0)
1610                 return NULL;
1611         
1612         dm= mesh_get_derived_final(scene, ob, CD_MASK_BAREMESH);
1613         vertexcosnos= MEM_callocN(6*sizeof(float)*me->totvert, "vertexcosnos map");
1614         
1615         if(dm->foreachMappedVert) {
1616                 dm->foreachMappedVert(dm, make_vertexcosnos__mapFunc, vertexcosnos);
1617         }
1618         else {
1619                 float *fp= vertexcosnos;
1620                 int a;
1621                 
1622                 for(a=0; a< me->totvert; a++, fp+=6) {
1623                         dm->getVertCo(dm, a, fp);
1624                         dm->getVertNo(dm, a, fp+3);
1625                 }
1626         }
1627         
1628         dm->release(dm);
1629         return vertexcosnos;
1630 }
1631
1632 /* ******************* GLSL ******************** */
1633
1634 typedef struct
1635 {
1636         float * precomputedFaceNormals;
1637         MTFace * mtface;        // texture coordinates
1638         MFace * mface;          // indices
1639         MVert * mvert;          // vertices & normals
1640         float (*orco)[3];
1641         float (*tangent)[4];    // destination
1642         int numFaces;
1643
1644 } SGLSLMeshToTangent;
1645
1646 // interface
1647 #include "mikktspace.h"
1648
1649 static int GetNumFaces(const SMikkTSpaceContext * pContext)
1650 {
1651         SGLSLMeshToTangent * pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
1652         return pMesh->numFaces;
1653 }
1654
1655 static int GetNumVertsOfFace(const SMikkTSpaceContext * pContext, const int face_num)
1656 {
1657         SGLSLMeshToTangent * pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
1658         return pMesh->mface[face_num].v4!=0 ? 4 : 3;
1659 }
1660
1661 static void GetPosition(const SMikkTSpaceContext * pContext, float fPos[], const int face_num, const int vert_index)
1662 {
1663         //assert(vert_index>=0 && vert_index<4);
1664         SGLSLMeshToTangent * pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
1665         const float *co= pMesh->mvert[(&pMesh->mface[face_num].v1)[vert_index]].co;
1666         copy_v3_v3(fPos, co);
1667 }
1668
1669 static void GetTextureCoordinate(const SMikkTSpaceContext * pContext, float fUV[], const int face_num, const int vert_index)
1670 {
1671         //assert(vert_index>=0 && vert_index<4);
1672         SGLSLMeshToTangent * pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
1673
1674         if(pMesh->mtface!=NULL) {
1675                 float * uv = pMesh->mtface[face_num].uv[vert_index];
1676                 fUV[0]=uv[0]; fUV[1]=uv[1];
1677         }
1678         else {
1679                 const float *orco= pMesh->orco[(&pMesh->mface[face_num].v1)[vert_index]];
1680                 map_to_sphere( &fUV[0], &fUV[1], orco[0], orco[1], orco[2]);
1681         }
1682 }
1683
1684 static void GetNormal(const SMikkTSpaceContext * pContext, float fNorm[], const int face_num, const int vert_index)
1685 {
1686         //assert(vert_index>=0 && vert_index<4);
1687         SGLSLMeshToTangent * pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
1688
1689         const int smoothnormal = (pMesh->mface[face_num].flag & ME_SMOOTH);
1690         if(!smoothnormal) {     // flat
1691                 if(pMesh->precomputedFaceNormals) {
1692                         copy_v3_v3(fNorm, &pMesh->precomputedFaceNormals[3*face_num]);
1693                 }
1694                 else {
1695                         MFace *mf= &pMesh->mface[face_num];
1696                         float *p0= pMesh->mvert[mf->v1].co;
1697                         float *p1= pMesh->mvert[mf->v2].co;
1698                         float *p2= pMesh->mvert[mf->v3].co;
1699
1700                         if(mf->v4) {
1701                                 float *p3 = pMesh->mvert[mf->v4].co;
1702                                 normal_quad_v3(fNorm, p0, p1, p2, p3);
1703                         }
1704                         else {
1705                                 normal_tri_v3(fNorm, p0, p1, p2);
1706                         }
1707                 }
1708         }
1709         else {
1710                 const short *no= pMesh->mvert[(&pMesh->mface[face_num].v1)[vert_index]].no;
1711                 normal_short_to_float_v3(fNorm, no);
1712         }
1713 }
1714 static void SetTSpace(const SMikkTSpaceContext * pContext, const float fvTangent[], const float fSign, const int face_num, const int iVert)
1715 {
1716         //assert(vert_index>=0 && vert_index<4);
1717         SGLSLMeshToTangent * pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
1718         float * pRes = pMesh->tangent[4*face_num+iVert];
1719         copy_v3_v3(pRes, fvTangent);
1720         pRes[3]=fSign;
1721 }
1722
1723
1724 void DM_add_tangent_layer(DerivedMesh *dm)
1725 {
1726         /* mesh vars */
1727         MTFace *mtface, *tf;
1728         MFace *mface, *mf;
1729         MVert *mvert, *v1, *v2, *v3, *v4;
1730         MemArena *arena= NULL;
1731         VertexTangent **vtangents= NULL;
1732         float (*orco)[3]= NULL, (*tangent)[4];
1733         float *uv1, *uv2, *uv3, *uv4, *vtang;
1734         float fno[3], tang[3], uv[4][2];
1735         int i, j, len, mf_vi[4], totvert, totface, iCalcNewMethod;
1736         float *nors;
1737
1738         if(CustomData_get_layer_index(&dm->faceData, CD_TANGENT) != -1)
1739                 return;
1740
1741         nors = dm->getFaceDataArray(dm, CD_NORMAL);
1742
1743         /* check we have all the needed layers */
1744         totvert= dm->getNumVerts(dm);
1745         totface= dm->getNumFaces(dm);
1746
1747         mvert= dm->getVertArray(dm);
1748         mface= dm->getFaceArray(dm);
1749         mtface= dm->getFaceDataArray(dm, CD_MTFACE);
1750
1751         if(!mtface) {
1752                 orco= dm->getVertDataArray(dm, CD_ORCO);
1753                 if(!orco)
1754                         return;
1755         }
1756         
1757         /* create tangent layer */
1758         DM_add_face_layer(dm, CD_TANGENT, CD_CALLOC, NULL);
1759         tangent= DM_get_face_data_layer(dm, CD_TANGENT);
1760         
1761         /* allocate some space */
1762         arena= BLI_memarena_new(BLI_MEMARENA_STD_BUFSIZE, "tangent layer arena");
1763         BLI_memarena_use_calloc(arena);
1764         vtangents= MEM_callocN(sizeof(VertexTangent*)*totvert, "VertexTangent");
1765
1766         // new computation method
1767         iCalcNewMethod = 1;
1768         if(iCalcNewMethod != 0) {
1769                 SGLSLMeshToTangent mesh2tangent= {0};
1770                 SMikkTSpaceContext sContext= {0};
1771                 SMikkTSpaceInterface sInterface= {0};
1772
1773                 mesh2tangent.precomputedFaceNormals = nors;
1774                 mesh2tangent.mtface = mtface;
1775                 mesh2tangent.mface = mface;
1776                 mesh2tangent.mvert = mvert;
1777                 mesh2tangent.orco = orco;
1778                 mesh2tangent.tangent = tangent;
1779                 mesh2tangent.numFaces = totface;
1780
1781                 sContext.m_pUserData = &mesh2tangent;
1782                 sContext.m_pInterface = &sInterface;
1783                 sInterface.m_getNumFaces = GetNumFaces;
1784                 sInterface.m_getNumVerticesOfFace = GetNumVertsOfFace;
1785                 sInterface.m_getPosition = GetPosition;
1786                 sInterface.m_getTexCoord = GetTextureCoordinate;
1787                 sInterface.m_getNormal = GetNormal;
1788                 sInterface.m_setTSpaceBasic = SetTSpace;
1789
1790                 // 0 if failed
1791                 iCalcNewMethod = genTangSpaceDefault(&sContext);
1792         }
1793
1794         if(!iCalcNewMethod) {
1795                 /* sum tangents at connected vertices */
1796                 for(i=0, tf=mtface, mf=mface; i < totface; mf++, tf++, i++) {
1797                         v1= &mvert[mf->v1];
1798                         v2= &mvert[mf->v2];
1799                         v3= &mvert[mf->v3];
1800
1801                         if (mf->v4) {
1802                                 v4= &mvert[mf->v4];
1803                                 normal_quad_v3( fno,v4->co, v3->co, v2->co, v1->co);
1804                         }
1805                         else {
1806                                 v4= NULL;
1807                                 normal_tri_v3( fno,v3->co, v2->co, v1->co);
1808                         }
1809                 
1810                         if(mtface) {
1811                                 uv1= tf->uv[0];
1812                                 uv2= tf->uv[1];
1813                                 uv3= tf->uv[2];
1814                                 uv4= tf->uv[3];
1815                         }
1816                         else {
1817                                 uv1= uv[0]; uv2= uv[1]; uv3= uv[2]; uv4= uv[3];
1818                                 map_to_sphere( &uv[0][0], &uv[0][1],orco[mf->v1][0], orco[mf->v1][1], orco[mf->v1][2]);
1819                                 map_to_sphere( &uv[1][0], &uv[1][1],orco[mf->v2][0], orco[mf->v2][1], orco[mf->v2][2]);
1820                                 map_to_sphere( &uv[2][0], &uv[2][1],orco[mf->v3][0], orco[mf->v3][1], orco[mf->v3][2]);
1821                                 if(v4)
1822                                         map_to_sphere( &uv[3][0], &uv[3][1],orco[mf->v4][0], orco[mf->v4][1], orco[mf->v4][2]);
1823                         }
1824                 
1825                         tangent_from_uv(uv1, uv2, uv3, v1->co, v2->co, v3->co, fno, tang);
1826                         sum_or_add_vertex_tangent(arena, &vtangents[mf->v1], tang, uv1);
1827                         sum_or_add_vertex_tangent(arena, &vtangents[mf->v2], tang, uv2);
1828                         sum_or_add_vertex_tangent(arena, &vtangents[mf->v3], tang, uv3);
1829                 
1830                         if(mf->v4) {
1831                                 v4= &mvert[mf->v4];
1832                         
1833                                 tangent_from_uv(uv1, uv3, uv4, v1->co, v3->co, v4->co, fno, tang);
1834                                 sum_or_add_vertex_tangent(arena, &vtangents[mf->v1], tang, uv1);
1835                                 sum_or_add_vertex_tangent(arena, &vtangents[mf->v3], tang, uv3);
1836                                 sum_or_add_vertex_tangent(arena, &vtangents[mf->v4], tang, uv4);
1837                         }
1838                 }
1839         
1840                 /* write tangent to layer */
1841                 for(i=0, tf=mtface, mf=mface; i < totface; mf++, tf++, i++, tangent+=4) {
1842                         len= (mf->v4)? 4 : 3; 
1843
1844                         if(mtface == NULL) {
1845                                 map_to_sphere( &uv[0][0], &uv[0][1],orco[mf->v1][0], orco[mf->v1][1], orco[mf->v1][2]);
1846                                 map_to_sphere( &uv[1][0], &uv[1][1],orco[mf->v2][0], orco[mf->v2][1], orco[mf->v2][2]);
1847                                 map_to_sphere( &uv[2][0], &uv[2][1],orco[mf->v3][0], orco[mf->v3][1], orco[mf->v3][2]);
1848                                 if(len==4)
1849                                         map_to_sphere( &uv[3][0], &uv[3][1],orco[mf->v4][0], orco[mf->v4][1], orco[mf->v4][2]);
1850                         }
1851                 
1852                         mf_vi[0]= mf->v1;
1853                         mf_vi[1]= mf->v2;
1854                         mf_vi[2]= mf->v3;
1855                         mf_vi[3]= mf->v4;
1856                 
1857                         for(j=0; j<len; j++) {
1858                                 vtang= find_vertex_tangent(vtangents[mf_vi[j]], mtface ? tf->uv[j] : uv[j]);
1859                                 normalize_v3_v3(tangent[j], vtang);
1860                                 ((float *) tangent[j])[3]=1.0f;
1861                         }
1862                 }
1863         }
1864         
1865         BLI_memarena_free(arena);
1866         MEM_freeN(vtangents);
1867 }
1868
1869 void DM_calc_auto_bump_scale(DerivedMesh *dm)
1870 {
1871         /* int totvert= dm->getNumVerts(dm); */ /* UNUSED */
1872         int totface= dm->getNumFaces(dm);
1873
1874         MVert * mvert = dm->getVertArray(dm);
1875         MFace * mface = dm->getFaceArray(dm);
1876         MTFace * mtface = dm->getFaceDataArray(dm, CD_MTFACE);
1877
1878         if(mtface)
1879         {
1880                 double dsum = 0.0;
1881                 int nr_accumulated = 0;
1882                 int f;
1883
1884                 for ( f=0; f<totface; f++ )
1885                 {
1886                         {
1887                                 float * verts[4], * tex_coords[4];
1888                                 const int nr_verts = mface[f].v4!=0 ? 4 : 3;
1889                                 int i, is_degenerate;
1890
1891                                 verts[0]=mvert[mface[f].v1].co; verts[1]=mvert[mface[f].v2].co; verts[2]=mvert[mface[f].v3].co;
1892                                 tex_coords[0]=mtface[f].uv[0]; tex_coords[1]=mtface[f].uv[1]; tex_coords[2]=mtface[f].uv[2];
1893                                 if(nr_verts==4)
1894                                 {
1895                                         verts[3]=mvert[mface[f].v4].co;
1896                                         tex_coords[3]=mtface[f].uv[3];
1897                                 }
1898
1899                                 // discard degenerate faces
1900                                 is_degenerate = 0;
1901                                 if(     equals_v3v3(verts[0], verts[1]) || equals_v3v3(verts[0], verts[2]) || equals_v3v3(verts[1], verts[2]) ||
1902                                         equals_v2v2(tex_coords[0], tex_coords[1]) || equals_v2v2(tex_coords[0], tex_coords[2]) || equals_v2v2(tex_coords[1], tex_coords[2]) )
1903                                 {
1904                                         is_degenerate = 1;
1905                                 }
1906
1907                                 // verify last vertex as well if this is a quad
1908                                 if ( is_degenerate==0 && nr_verts==4 )
1909                                 {
1910                                         if(     equals_v3v3(verts[3], verts[0]) || equals_v3v3(verts[3], verts[1]) || equals_v3v3(verts[3], verts[2]) ||
1911                                                 equals_v2v2(tex_coords[3], tex_coords[0]) || equals_v2v2(tex_coords[3], tex_coords[1]) || equals_v2v2(tex_coords[3], tex_coords[2]) )
1912                                         {
1913                                                 is_degenerate = 1;
1914                                         }
1915
1916                                         // verify the winding is consistent
1917                                         if ( is_degenerate==0 )
1918                                         {
1919                                                 float prev_edge[2];
1920                                                 int is_signed = 0;
1921                                                 sub_v2_v2v2(prev_edge, tex_coords[0], tex_coords[3]);
1922
1923                                                 i = 0;
1924                                                 while ( is_degenerate==0 && i<4 )
1925                                                 {
1926                                                         float cur_edge[2], signed_area;
1927                                                         sub_v2_v2v2(cur_edge, tex_coords[(i+1)&0x3], tex_coords[i]);
1928                                                         signed_area = prev_edge[0]*cur_edge[1] - prev_edge[1]*cur_edge[0];
1929                                                         if ( i==0 ) is_signed = signed_area<0.0f ? 1 : 0;
1930                                                         else if((is_signed!=0)!=(signed_area<0.0f)) is_degenerate=1;
1931
1932                                                         if ( is_degenerate==0 )
1933                                                         {
1934                                                                 copy_v2_v2(prev_edge, cur_edge);
1935                                                                 ++i;
1936                                                         }
1937                                                 }
1938                                         }
1939                                 }
1940
1941                                 // proceed if not a degenerate face
1942                                 if ( is_degenerate==0 )
1943                                 {
1944                                         int nr_tris_to_pile=0;
1945                                         // quads split at shortest diagonal
1946                                         int offs = 0;           // initial triangulation is 0,1,2 and 0, 2, 3
1947                                         if ( nr_verts==4 )
1948                                         {
1949                                                 float pos_len_diag0, pos_len_diag1;
1950                                                 float vtmp[3];
1951                                                 sub_v3_v3v3(vtmp, verts[2], verts[0]);
1952                                                 pos_len_diag0 = dot_v3v3(vtmp, vtmp);
1953                                                 sub_v3_v3v3(vtmp, verts[3], verts[1]);
1954                                                 pos_len_diag1 = dot_v3v3(vtmp, vtmp);
1955
1956                                                 if(pos_len_diag1<pos_len_diag0)
1957                                                         offs=1;         // alter split
1958                                                 else if(pos_len_diag0==pos_len_diag1)           // do UV check instead
1959                                                 {
1960                                                         float tex_len_diag0, tex_len_diag1;
1961
1962                                                         sub_v2_v2v2(vtmp, tex_coords[2], tex_coords[0]);
1963                                                         tex_len_diag0 = dot_v2v2(vtmp, vtmp);
1964                                                         sub_v2_v2v2(vtmp, tex_coords[3], tex_coords[1]);
1965                                                         tex_len_diag1 = dot_v2v2(vtmp, vtmp);
1966
1967                                                         if(tex_len_diag1<tex_len_diag0)
1968                                                         {
1969                                                                 offs=1;         // alter split
1970                                                         }
1971                                                 }
1972                                         }
1973                                         nr_tris_to_pile = nr_verts-2 ;
1974                                         if ( nr_tris_to_pile==1 || nr_tris_to_pile==2 )
1975                                         {
1976                                                 const int indices[] = {offs+0, offs+1, offs+2, offs+0, offs+2, (offs+3)&0x3 };
1977                                                 int t;
1978                                                 for ( t=0; t<nr_tris_to_pile; t++ )
1979                                                 {
1980                                                         float f2x_area_uv;
1981                                                         float * p0 = verts[indices[t*3+0]];
1982                                                         float * p1 = verts[indices[t*3+1]];
1983                                                         float * p2 = verts[indices[t*3+2]];
1984
1985                                                         float edge_t0[2], edge_t1[2];
1986                                                         sub_v2_v2v2(edge_t0, tex_coords[indices[t*3+1]], tex_coords[indices[t*3+0]]);
1987                                                         sub_v2_v2v2(edge_t1, tex_coords[indices[t*3+2]], tex_coords[indices[t*3+0]]);
1988
1989                                                         f2x_area_uv = fabsf(edge_t0[0]*edge_t1[1] - edge_t0[1]*edge_t1[0]);
1990                                                         if ( f2x_area_uv>FLT_EPSILON )
1991                                                         {
1992                                                                 float norm[3], v0[3], v1[3], f2x_surf_area, fsurf_ratio;
1993                                                                 sub_v3_v3v3(v0, p1, p0);
1994                                                                 sub_v3_v3v3(v1, p2, p0);
1995                                                                 cross_v3_v3v3(norm, v0, v1);
1996
1997                                                                 f2x_surf_area = len_v3(norm);
1998                                                                 fsurf_ratio = f2x_surf_area/f2x_area_uv;        // tri area divided by texture area
1999
2000                                                                 ++nr_accumulated;
2001                                                                 dsum += (double)(fsurf_ratio);
2002                                                         }
2003                                                 }
2004                                         }
2005                                 }
2006                         }
2007                 }
2008
2009                 // finalize
2010                 {
2011                         const float avg_area_ratio = (nr_accumulated>0) ? ((float)(dsum / nr_accumulated)) : 1.0f;
2012                         const float use_as_render_bump_scale = sqrtf(avg_area_ratio);           // use width of average surface ratio as your bump scale
2013                         dm->auto_bump_scale = use_as_render_bump_scale;
2014                 }
2015         }
2016         else
2017         {
2018                 dm->auto_bump_scale = 1.0f;
2019         }
2020 }
2021
2022 void DM_vertex_attributes_from_gpu(DerivedMesh *dm, GPUVertexAttribs *gattribs, DMVertexAttribs *attribs)
2023 {
2024         CustomData *vdata, *fdata, *tfdata = NULL;
2025         int a, b, layer;
2026
2027         /* From the layers requested by the GLSL shader, figure out which ones are
2028          * actually available for this derivedmesh, and retrieve the pointers */
2029
2030         memset(attribs, 0, sizeof(DMVertexAttribs));
2031
2032         vdata = &dm->vertData;
2033         fdata = &dm->faceData;
2034
2035         /* ugly hack, editmesh derivedmesh doesn't copy face data, this way we
2036          * can use offsets instead */
2037         if(dm->type == DM_TYPE_EDITMESH)
2038                 tfdata = &((EditMeshDerivedMesh*)dm)->em->fdata;
2039         else
2040                 tfdata = fdata;
2041
2042         /* calc auto bump scale if necessary */
2043         if(dm->auto_bump_scale<=0.0f)
2044                 DM_calc_auto_bump_scale(dm);
2045
2046         /* add a tangent layer if necessary */
2047         for(b = 0; b < gattribs->totlayer; b++)
2048                 if(gattribs->layer[b].type == CD_TANGENT)
2049                         if(CustomData_get_layer_index(fdata, CD_TANGENT) == -1)
2050                                 DM_add_tangent_layer(dm);
2051
2052         for(b = 0; b < gattribs->totlayer; b++) {
2053                 if(gattribs->layer[b].type == CD_MTFACE) {
2054                         /* uv coordinates */
2055                         if(gattribs->layer[b].name[0])
2056                                 layer = CustomData_get_named_layer_index(tfdata, CD_MTFACE,
2057                                         gattribs->layer[b].name);
2058                         else
2059                                 layer = CustomData_get_active_layer_index(tfdata, CD_MTFACE);
2060
2061                         if(layer != -1) {
2062                                 a = attribs->tottface++;
2063
2064                                 attribs->tface[a].array = tfdata->layers[layer].data;
2065                                 attribs->tface[a].emOffset = tfdata->layers[layer].offset;
2066                                 attribs->tface[a].glIndex = gattribs->layer[b].glindex;
2067                                 attribs->tface[a].glTexco = gattribs->layer[b].gltexco;
2068                         }
2069                 }
2070                 else if(gattribs->layer[b].type == CD_MCOL) {
2071                         /* vertex colors */
2072                         if(gattribs->layer[b].name[0])
2073                                 layer = CustomData_get_named_layer_index(tfdata, CD_MCOL,
2074                                         gattribs->layer[b].name);
2075                         else
2076                                 layer = CustomData_get_active_layer_index(tfdata, CD_MCOL);
2077
2078                         if(layer != -1) {
2079                                 a = attribs->totmcol++;
2080
2081                                 attribs->mcol[a].array = tfdata->layers[layer].data;
2082                                 attribs->mcol[a].emOffset = tfdata->layers[layer].offset;
2083                                 attribs->mcol[a].glIndex = gattribs->layer[b].glindex;
2084                         }
2085                 }
2086                 else if(gattribs->layer[b].type == CD_TANGENT) {
2087                         /* tangents */
2088                         layer = CustomData_get_layer_index(fdata, CD_TANGENT);
2089
2090                         if(layer != -1) {
2091                                 attribs->tottang = 1;
2092
2093                                 attribs->tang.array = fdata->layers[layer].data;
2094                                 attribs->tang.emOffset = fdata->layers[layer].offset;
2095                                 attribs->tang.glIndex = gattribs->layer[b].glindex;
2096                         }
2097                 }
2098                 else if(gattribs->layer[b].type == CD_ORCO) {
2099                         /* original coordinates */
2100                         layer = CustomData_get_layer_index(vdata, CD_ORCO);
2101
2102                         if(layer != -1) {
2103                                 attribs->totorco = 1;
2104
2105                                 attribs->orco.array = vdata->layers[layer].data;
2106                                 attribs->orco.emOffset = vdata->layers[layer].offset;
2107                                 attribs->orco.glIndex = gattribs->layer[b].glindex;
2108                                 attribs->orco.glTexco = gattribs->layer[b].gltexco;
2109                         }
2110                 }
2111         }
2112 }
2113
2114 /* Set object's bounding box based on DerivedMesh min/max data */
2115 void DM_set_object_boundbox(Object *ob, DerivedMesh *dm)
2116 {
2117         float min[3], max[3];
2118
2119         INIT_MINMAX(min, max);
2120
2121         dm->getMinMax(dm, min, max);
2122
2123         if(!ob->bb)
2124                 ob->bb= MEM_callocN(sizeof(BoundBox), "DM-BoundBox");
2125
2126         boundbox_set_from_min_max(ob->bb, min, max);
2127 }
2128
2129 /* --- NAVMESH (begin) --- */
2130 #ifdef WITH_GAMEENGINE
2131
2132 BM_INLINE int navmesh_bit(int a, int b)
2133 {
2134         return (a & (1 << b)) >> b;
2135 }
2136
2137 BM_INLINE void navmesh_intToCol(int i, float col[3])
2138 {
2139         int     r = navmesh_bit(i, 0) + navmesh_bit(i, 3) * 2 + 1;
2140         int     g = navmesh_bit(i, 1) + navmesh_bit(i, 4) * 2 + 1;
2141         int     b = navmesh_bit(i, 2) + navmesh_bit(i, 5) * 2 + 1;
2142         col[0] = 1 - r*63.0f/255.0f;
2143         col[1] = 1 - g*63.0f/255.0f;
2144         col[2] = 1 - b*63.0f/255.0f;
2145 }
2146
2147 static void navmesh_drawColored(DerivedMesh *dm)
2148 {
2149         int a, glmode;
2150         MVert *mvert = (MVert *)CustomData_get_layer(&dm->vertData, CD_MVERT);
2151         MFace *mface = (MFace *)CustomData_get_layer(&dm->faceData, CD_MFACE);
2152         int *polygonIdx = (int *)CustomData_get_layer(&dm->faceData, CD_RECAST);
2153         float col[3];
2154
2155         if (!polygonIdx)
2156                 return;
2157
2158         /*
2159         //UI_ThemeColor(TH_WIRE);
2160         glDisable(GL_LIGHTING);
2161         glLineWidth(2.0);
2162         dm->drawEdges(dm, 0, 1);
2163         glLineWidth(1.0);
2164         glEnable(GL_LIGHTING);*/
2165
2166         glDisable(GL_LIGHTING);
2167         /*  if(GPU_buffer_legacy(dm) ) */ { /* TODO - VBO draw code, not high priority - campbell */
2168                 DEBUG_VBO( "Using legacy code. drawNavMeshColored\n" );
2169                 //glShadeModel(GL_SMOOTH);
2170                 glBegin(glmode = GL_QUADS);
2171                 for(a = 0; a < dm->numFaceData; a++, mface++) {
2172                         int new_glmode = mface->v4?GL_QUADS:GL_TRIANGLES;
2173                         int pi = polygonIdx[a];
2174                         if (pi <= 0) {
2175                                 zero_v3(col);
2176                         }
2177                         else {
2178                                 navmesh_intToCol(pi, col);
2179                         }
2180
2181                         if(new_glmode != glmode) {
2182                                 glEnd();
2183                                 glBegin(glmode = new_glmode);
2184                         }
2185                         glColor3fv(col);
2186                         glVertex3fv(mvert[mface->v1].co);
2187                         glVertex3fv(mvert[mface->v2].co);
2188                         glVertex3fv(mvert[mface->v3].co);
2189                         if(mface->v4) {
2190                                 glVertex3fv(mvert[mface->v4].co);
2191                         }
2192                 }
2193                 glEnd();
2194         }
2195         glEnable(GL_LIGHTING);
2196 }
2197
2198 static void navmesh_DM_drawFacesTex(DerivedMesh *dm,
2199                         int (*setDrawOptions)(MTFace *tface, int has_mcol, int matnr),
2200                         int (*compareDrawOptions)(void *userData, int cur_index, int next_index),
2201                         void *userData)
2202 {
2203         (void) setDrawOptions;
2204         (void) compareDrawOptions;
2205         (void) userData;
2206
2207         navmesh_drawColored(dm);
2208 }
2209
2210 static void navmesh_DM_drawFacesSolid(DerivedMesh *dm,
2211                                       float (*partial_redraw_planes)[4],
2212                                       int UNUSED(fast), int (*setMaterial)(int, void *attribs))
2213 {
2214         (void) partial_redraw_planes;
2215         (void) setMaterial;
2216
2217         //drawFacesSolid_original(dm, partial_redraw_planes, fast, setMaterial);
2218         navmesh_drawColored(dm);
2219 }
2220
2221 static DerivedMesh *navmesh_dm_createNavMeshForVisualization(DerivedMesh *dm)
2222 {
2223         DerivedMesh *result;
2224         int maxFaces = dm->getNumFaces(dm);
2225         int *recastData;
2226         int vertsPerPoly=0, nverts=0, ndtris=0, npolys=0;
2227         float* verts=NULL;
2228         unsigned short *dtris=NULL, *dmeshes=NULL, *polys=NULL;
2229         int *dtrisToPolysMap=NULL, *dtrisToTrisMap=NULL, *trisToFacesMap=NULL;
2230         int res;
2231
2232         result = CDDM_copy(dm);
2233         if (!CustomData_has_layer(&result->faceData, CD_RECAST)) {
2234                 int *sourceRecastData = (int*)CustomData_get_layer(&dm->faceData, CD_RECAST);
2235                 if (sourceRecastData) {
2236                         CustomData_add_layer_named(&result->faceData, CD_RECAST, CD_DUPLICATE,
2237                                                    sourceRecastData, maxFaces, "recastData");
2238                 }
2239         }
2240         recastData = (int*)CustomData_get_layer(&result->faceData, CD_RECAST);
2241
2242         /* note: This is not good design! - really should not be doing this */
2243         result->drawFacesTex =  navmesh_DM_drawFacesTex;
2244         result->drawFacesSolid = navmesh_DM_drawFacesSolid;
2245
2246
2247         /* process mesh */
2248         res  = buildNavMeshDataByDerivedMesh(dm, &vertsPerPoly, &nverts, &verts, &ndtris, &dtris,
2249                                              &npolys, &dmeshes, &polys, &dtrisToPolysMap, &dtrisToTrisMap,
2250                                              &trisToFacesMap);
2251         if (res) {
2252                 size_t polyIdx;
2253
2254                 /* invalidate concave polygon */
2255                 for (polyIdx=0; polyIdx<(size_t)npolys; polyIdx++) {
2256                         unsigned short* poly = &polys[polyIdx*2*vertsPerPoly];
2257                         if (!polyIsConvex(poly, vertsPerPoly, verts)) {
2258                                 /* set negative polygon idx to all faces */
2259                                 unsigned short *dmesh = &dmeshes[4*polyIdx];
2260                                 unsigned short tbase = dmesh[2];
2261                                 unsigned short tnum = dmesh[3];
2262                                 unsigned short ti;
2263
2264                                 for (ti=0; ti<tnum; ti++) {
2265                                         unsigned short triidx = dtrisToTrisMap[tbase+ti];
2266                                         unsigned short faceidx = trisToFacesMap[triidx];
2267                                         if (recastData[faceidx] > 0) {
2268                                                 recastData[faceidx] = -recastData[faceidx];
2269                                         }
2270                                 }
2271                         }
2272                 }
2273         }
2274         else {
2275                 printf("Error during creation polygon infos\n");
2276         }
2277
2278         /* clean up */
2279         if (verts!=NULL)
2280                 MEM_freeN(verts);
2281         if (dtris!=NULL)
2282                 MEM_freeN(dtris);
2283         if (dmeshes!=NULL)
2284                 MEM_freeN(dmeshes);
2285         if (polys!=NULL)
2286                 MEM_freeN(polys);
2287         if (dtrisToPolysMap!=NULL)
2288                 MEM_freeN(dtrisToPolysMap);
2289         if (dtrisToTrisMap!=NULL)
2290                 MEM_freeN(dtrisToTrisMap);
2291         if (trisToFacesMap!=NULL)
2292                 MEM_freeN(trisToFacesMap);
2293
2294         return result;
2295 }
2296
2297 #endif /* WITH_GAMEENGINE */
2298
2299 /* --- NAVMESH (end) --- */