Slight refactor of VBO code to deal with multiple textures.
[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
64 #ifdef WITH_GAMEENGINE
65 #include "BKE_navmesh_conversion.h"
66 static DerivedMesh *navmesh_dm_createNavMeshForVisualization(DerivedMesh *dm);
67 #endif
68
69 #include "BLO_sys_types.h" // for intptr_t support
70
71 #include "GL/glew.h"
72
73 #include "GPU_buffers.h"
74 #include "GPU_draw.h"
75 #include "GPU_extensions.h"
76 #include "GPU_material.h"
77
78 extern GLubyte stipple_quarttone[128]; /* glutil.c, bad level data */
79
80 ///////////////////////////////////
81 ///////////////////////////////////
82
83 static MVert *dm_getVertArray(DerivedMesh *dm)
84 {
85         MVert *mvert = CustomData_get_layer(&dm->vertData, CD_MVERT);
86
87         if (!mvert) {
88                 mvert = CustomData_add_layer(&dm->vertData, CD_MVERT, CD_CALLOC, NULL,
89                         dm->getNumVerts(dm));
90                 CustomData_set_layer_flag(&dm->vertData, CD_MVERT, CD_FLAG_TEMPORARY);
91                 dm->copyVertArray(dm, mvert);
92         }
93
94         return mvert;
95 }
96
97 static MEdge *dm_getEdgeArray(DerivedMesh *dm)
98 {
99         MEdge *medge = CustomData_get_layer(&dm->edgeData, CD_MEDGE);
100
101         if (!medge) {
102                 medge = CustomData_add_layer(&dm->edgeData, CD_MEDGE, CD_CALLOC, NULL,
103                         dm->getNumEdges(dm));
104                 CustomData_set_layer_flag(&dm->edgeData, CD_MEDGE, CD_FLAG_TEMPORARY);
105                 dm->copyEdgeArray(dm, medge);
106         }
107
108         return medge;
109 }
110
111 static MFace *dm_getFaceArray(DerivedMesh *dm)
112 {
113         MFace *mface = CustomData_get_layer(&dm->faceData, CD_MFACE);
114
115         if (!mface) {
116                 mface = CustomData_add_layer(&dm->faceData, CD_MFACE, CD_CALLOC, NULL,
117                         dm->getNumFaces(dm));
118                 CustomData_set_layer_flag(&dm->faceData, CD_MFACE, CD_FLAG_TEMPORARY);
119                 dm->copyFaceArray(dm, mface);
120         }
121
122         return mface;
123 }
124
125 static MVert *dm_dupVertArray(DerivedMesh *dm)
126 {
127         MVert *tmp = MEM_callocN(sizeof(*tmp) * dm->getNumVerts(dm),
128                                                          "dm_dupVertArray tmp");
129
130         if(tmp) dm->copyVertArray(dm, tmp);
131
132         return tmp;
133 }
134
135 static MEdge *dm_dupEdgeArray(DerivedMesh *dm)
136 {
137         MEdge *tmp = MEM_callocN(sizeof(*tmp) * dm->getNumEdges(dm),
138                                                          "dm_dupEdgeArray tmp");
139
140         if(tmp) dm->copyEdgeArray(dm, tmp);
141
142         return tmp;
143 }
144
145 static MFace *dm_dupFaceArray(DerivedMesh *dm)
146 {
147         MFace *tmp = MEM_callocN(sizeof(*tmp) * dm->getNumFaces(dm),
148                                                          "dm_dupFaceArray tmp");
149
150         if(tmp) dm->copyFaceArray(dm, tmp);
151
152         return tmp;
153 }
154
155 void DM_init_funcs(DerivedMesh *dm)
156 {
157         /* default function implementations */
158         dm->getVertArray = dm_getVertArray;
159         dm->getEdgeArray = dm_getEdgeArray;
160         dm->getFaceArray = dm_getFaceArray;
161         dm->dupVertArray = dm_dupVertArray;
162         dm->dupEdgeArray = dm_dupEdgeArray;
163         dm->dupFaceArray = dm_dupFaceArray;
164
165         dm->getVertData = DM_get_vert_data;
166         dm->getEdgeData = DM_get_edge_data;
167         dm->getFaceData = DM_get_face_data;
168         dm->getVertDataArray = DM_get_vert_data_layer;
169         dm->getEdgeDataArray = DM_get_edge_data_layer;
170         dm->getFaceDataArray = DM_get_face_data_layer;
171
172         bvhcache_init(&dm->bvhCache);
173 }
174
175 void DM_init(DerivedMesh *dm, DerivedMeshType type,
176                          int numVerts, int numEdges, int numFaces)
177 {
178         dm->type = type;
179         dm->numVertData = numVerts;
180         dm->numEdgeData = numEdges;
181         dm->numFaceData = numFaces;
182
183         DM_init_funcs(dm);
184         
185         dm->needsFree = 1;
186 }
187
188 void DM_from_template(DerivedMesh *dm, DerivedMesh *source, DerivedMeshType type,
189                                           int numVerts, int numEdges, int numFaces)
190 {
191         CustomData_copy(&source->vertData, &dm->vertData, CD_MASK_DERIVEDMESH,
192                                         CD_CALLOC, numVerts);
193         CustomData_copy(&source->edgeData, &dm->edgeData, CD_MASK_DERIVEDMESH,
194                                         CD_CALLOC, numEdges);
195         CustomData_copy(&source->faceData, &dm->faceData, CD_MASK_DERIVEDMESH,
196                                         CD_CALLOC, numFaces);
197
198         dm->type = type;
199         dm->numVertData = numVerts;
200         dm->numEdgeData = numEdges;
201         dm->numFaceData = numFaces;
202
203         DM_init_funcs(dm);
204
205         dm->needsFree = 1;
206 }
207
208 int DM_release(DerivedMesh *dm)
209 {
210         if (dm->needsFree) {
211                 bvhcache_free(&dm->bvhCache);
212                 GPU_drawobject_free( dm );
213                 CustomData_free(&dm->vertData, dm->numVertData);
214                 CustomData_free(&dm->edgeData, dm->numEdgeData);
215                 CustomData_free(&dm->faceData, dm->numFaceData);
216
217                 return 1;
218         }
219         else {
220                 CustomData_free_temporary(&dm->vertData, dm->numVertData);
221                 CustomData_free_temporary(&dm->edgeData, dm->numEdgeData);
222                 CustomData_free_temporary(&dm->faceData, dm->numFaceData);
223
224                 return 0;
225         }
226 }
227
228 void DM_to_mesh(DerivedMesh *dm, Mesh *me)
229 {
230         /* dm might depend on me, so we need to do everything with a local copy */
231         Mesh tmp = *me;
232         int totvert, totedge, totface;
233
234         memset(&tmp.vdata, 0, sizeof(tmp.vdata));
235         memset(&tmp.edata, 0, sizeof(tmp.edata));
236         memset(&tmp.fdata, 0, sizeof(tmp.fdata));
237
238         totvert = tmp.totvert = dm->getNumVerts(dm);
239         totedge = tmp.totedge = dm->getNumEdges(dm);
240         totface = tmp.totface = dm->getNumFaces(dm);
241
242         CustomData_copy(&dm->vertData, &tmp.vdata, CD_MASK_MESH, CD_DUPLICATE, totvert);
243         CustomData_copy(&dm->edgeData, &tmp.edata, CD_MASK_MESH, CD_DUPLICATE, totedge);
244         CustomData_copy(&dm->faceData, &tmp.fdata, CD_MASK_MESH, CD_DUPLICATE, totface);
245
246         /* not all DerivedMeshes store their verts/edges/faces in CustomData, so
247            we set them here in case they are missing */
248         if(!CustomData_has_layer(&tmp.vdata, CD_MVERT))
249                 CustomData_add_layer(&tmp.vdata, CD_MVERT, CD_ASSIGN, dm->dupVertArray(dm), totvert);
250         if(!CustomData_has_layer(&tmp.edata, CD_MEDGE))
251                 CustomData_add_layer(&tmp.edata, CD_MEDGE, CD_ASSIGN, dm->dupEdgeArray(dm), totedge);
252         if(!CustomData_has_layer(&tmp.fdata, CD_MFACE))
253                 CustomData_add_layer(&tmp.fdata, CD_MFACE, CD_ASSIGN, dm->dupFaceArray(dm), totface);
254
255         /* object had got displacement layer, should copy this layer to save sculpted data */
256         /* NOTE: maybe some other layers should be copied? nazgul */
257         if(CustomData_has_layer(&me->fdata, CD_MDISPS)) {
258                 if (totface == me->totface) {
259                         MDisps *mdisps = CustomData_get_layer(&me->fdata, CD_MDISPS);
260                         CustomData_add_layer(&tmp.fdata, CD_MDISPS, CD_DUPLICATE, mdisps, totface);
261                 }
262         }
263
264         mesh_update_customdata_pointers(&tmp);
265
266         CustomData_free(&me->vdata, me->totvert);
267         CustomData_free(&me->edata, me->totedge);
268         CustomData_free(&me->fdata, me->totface);
269
270         /* if the number of verts has changed, remove invalid data */
271         if(tmp.totvert != me->totvert) {
272                 if(tmp.key) tmp.key->id.us--;
273                 tmp.key = NULL;
274         }
275
276         *me = tmp;
277 }
278
279 void DM_to_meshkey(DerivedMesh *dm, Mesh *me, KeyBlock *kb)
280 {
281         int a, totvert = dm->getNumVerts(dm);
282         float *fp;
283         MVert *mvert;
284         
285         if(totvert==0 || me->totvert==0 || me->totvert!=totvert) return;
286         
287         if(kb->data) MEM_freeN(kb->data);
288         kb->data= MEM_callocN(me->key->elemsize*me->totvert, "kb->data");
289         kb->totelem= totvert;
290         
291         fp= kb->data;
292         mvert=dm->getVertDataArray(dm, CD_MVERT);
293         
294         for(a=0; a<kb->totelem; a++, fp+=3, mvert++) {
295                 copy_v3_v3(fp, mvert->co);
296         }
297 }
298
299 void DM_set_only_copy(DerivedMesh *dm, CustomDataMask mask)
300 {
301         CustomData_set_only_copy(&dm->vertData, mask);
302         CustomData_set_only_copy(&dm->edgeData, mask);
303         CustomData_set_only_copy(&dm->faceData, mask);
304 }
305
306 void DM_add_vert_layer(DerivedMesh *dm, int type, int alloctype, void *layer)
307 {
308         CustomData_add_layer(&dm->vertData, type, alloctype, layer, dm->numVertData);
309 }
310
311 void DM_add_edge_layer(DerivedMesh *dm, int type, int alloctype, void *layer)
312 {
313         CustomData_add_layer(&dm->edgeData, type, alloctype, layer, dm->numEdgeData);
314 }
315
316 void DM_add_face_layer(DerivedMesh *dm, int type, int alloctype, void *layer)
317 {
318         CustomData_add_layer(&dm->faceData, type, alloctype, layer, dm->numFaceData);
319 }
320
321 void *DM_get_vert_data(DerivedMesh *dm, int index, int type)
322 {
323         return CustomData_get(&dm->vertData, index, type);
324 }
325
326 void *DM_get_edge_data(DerivedMesh *dm, int index, int type)
327 {
328         return CustomData_get(&dm->edgeData, index, type);
329 }
330
331 void *DM_get_face_data(DerivedMesh *dm, int index, int type)
332 {
333         return CustomData_get(&dm->faceData, index, type);
334 }
335
336 void *DM_get_vert_data_layer(DerivedMesh *dm, int type)
337 {
338         if(type == CD_MVERT)
339                 return dm->getVertArray(dm);
340
341         return CustomData_get_layer(&dm->vertData, type);
342 }
343
344 void *DM_get_edge_data_layer(DerivedMesh *dm, int type)
345 {
346         if(type == CD_MEDGE)
347                 return dm->getEdgeArray(dm);
348
349         return CustomData_get_layer(&dm->edgeData, type);
350 }
351
352 void *DM_get_face_data_layer(DerivedMesh *dm, int type)
353 {
354         if(type == CD_MFACE)
355                 return dm->getFaceArray(dm);
356
357         return CustomData_get_layer(&dm->faceData, type);
358 }
359
360 void DM_set_vert_data(DerivedMesh *dm, int index, int type, void *data)
361 {
362         CustomData_set(&dm->vertData, index, type, data);
363 }
364
365 void DM_set_edge_data(DerivedMesh *dm, int index, int type, void *data)
366 {
367         CustomData_set(&dm->edgeData, index, type, data);
368 }
369
370 void DM_set_face_data(DerivedMesh *dm, int index, int type, void *data)
371 {
372         CustomData_set(&dm->faceData, index, type, data);
373 }
374
375 void DM_copy_vert_data(DerivedMesh *source, DerivedMesh *dest,
376                                            int source_index, int dest_index, int count)
377 {
378         CustomData_copy_data(&source->vertData, &dest->vertData,
379                                                  source_index, dest_index, count);
380 }
381
382 void DM_copy_edge_data(DerivedMesh *source, DerivedMesh *dest,
383                                            int source_index, int dest_index, int count)
384 {
385         CustomData_copy_data(&source->edgeData, &dest->edgeData,
386                                                  source_index, dest_index, count);
387 }
388
389 void DM_copy_face_data(DerivedMesh *source, DerivedMesh *dest,
390                                            int source_index, int dest_index, int count)
391 {
392         CustomData_copy_data(&source->faceData, &dest->faceData,
393                                                  source_index, dest_index, count);
394 }
395
396 void DM_free_vert_data(struct DerivedMesh *dm, int index, int count)
397 {
398         CustomData_free_elem(&dm->vertData, index, count);
399 }
400
401 void DM_free_edge_data(struct DerivedMesh *dm, int index, int count)
402 {
403         CustomData_free_elem(&dm->edgeData, index, count);
404 }
405
406 void DM_free_face_data(struct DerivedMesh *dm, int index, int count)
407 {
408         CustomData_free_elem(&dm->faceData, index, count);
409 }
410
411 void DM_interp_vert_data(DerivedMesh *source, DerivedMesh *dest,
412                                                  int *src_indices, float *weights,
413                                                  int count, int dest_index)
414 {
415         CustomData_interp(&source->vertData, &dest->vertData, src_indices,
416                                           weights, NULL, count, dest_index);
417 }
418
419 void DM_interp_edge_data(DerivedMesh *source, DerivedMesh *dest,
420                                                  int *src_indices,
421                                                  float *weights, EdgeVertWeight *vert_weights,
422                                                  int count, int dest_index)
423 {
424         CustomData_interp(&source->edgeData, &dest->edgeData, src_indices,
425                                           weights, (float*)vert_weights, count, dest_index);
426 }
427
428 void DM_interp_face_data(DerivedMesh *source, DerivedMesh *dest,
429                                                  int *src_indices,
430                                                  float *weights, FaceVertWeight *vert_weights,
431                                                  int count, int dest_index)
432 {
433         CustomData_interp(&source->faceData, &dest->faceData, src_indices,
434                                           weights, (float*)vert_weights, count, dest_index);
435 }
436
437 void DM_swap_face_data(DerivedMesh *dm, int index, const int *corner_indices)
438 {
439         CustomData_swap(&dm->faceData, index, corner_indices);
440 }
441
442 ///
443
444 DerivedMesh *mesh_create_derived(Mesh *me, Object *ob, float (*vertCos)[3])
445 {
446         DerivedMesh *dm = CDDM_from_mesh(me, ob);
447         
448         if(!dm)
449                 return NULL;
450         
451         if (vertCos)
452                 CDDM_apply_vert_coords(dm, vertCos);
453
454         CDDM_calc_normals(dm);
455
456         return dm;
457 }
458
459 ///
460
461 typedef struct {
462         DerivedMesh dm;
463
464         EditMesh *em;
465         float (*vertexCos)[3];
466         float (*vertexNos)[3];
467         float (*faceNos)[3];
468 } EditMeshDerivedMesh;
469
470 static void emDM_foreachMappedVert(DerivedMesh *dm, void (*func)(void *userData, int index, float *co, float *no_f, short *no_s), void *userData)
471 {
472         EditMeshDerivedMesh *emdm= (EditMeshDerivedMesh*) dm;
473         EditVert *eve;
474         int i;
475
476         for (i=0,eve= emdm->em->verts.first; eve; i++,eve=eve->next) {
477                 if (emdm->vertexCos) {
478                         func(userData, i, emdm->vertexCos[i], emdm->vertexNos[i], NULL);
479                 } else {
480                         func(userData, i, eve->co, eve->no, NULL);
481                 }
482         }
483 }
484 static void emDM_foreachMappedEdge(DerivedMesh *dm, void (*func)(void *userData, int index, float *v0co, float *v1co), void *userData)
485 {
486         EditMeshDerivedMesh *emdm= (EditMeshDerivedMesh*) dm;
487         EditEdge *eed;
488         int i;
489
490         if (emdm->vertexCos) {
491                 EditVert *eve;
492
493                 for (i=0,eve=emdm->em->verts.first; eve; eve= eve->next)
494                         eve->tmp.l = (intptr_t) i++;
495                 for(i=0,eed= emdm->em->edges.first; eed; i++,eed= eed->next)
496                         func(userData, i, emdm->vertexCos[(int) eed->v1->tmp.l], emdm->vertexCos[(int) eed->v2->tmp.l]);
497         } else {
498                 for(i=0,eed= emdm->em->edges.first; eed; i++,eed= eed->next)
499                         func(userData, i, eed->v1->co, eed->v2->co);
500         }
501 }
502 static void emDM_drawMappedEdges(DerivedMesh *dm, int (*setDrawOptions)(void *userData, int index), void *userData) 
503 {
504         EditMeshDerivedMesh *emdm= (EditMeshDerivedMesh*) dm;
505         EditEdge *eed;
506         int i;
507
508         if (emdm->vertexCos) {
509                 EditVert *eve;
510
511                 for (i=0,eve=emdm->em->verts.first; eve; eve= eve->next)
512                         eve->tmp.l = (intptr_t) i++;
513
514                 glBegin(GL_LINES);
515                 for(i=0,eed= emdm->em->edges.first; eed; i++,eed= eed->next) {
516                         if(!setDrawOptions || setDrawOptions(userData, i)) {
517                                 glVertex3fv(emdm->vertexCos[(int) eed->v1->tmp.l]);
518                                 glVertex3fv(emdm->vertexCos[(int) eed->v2->tmp.l]);
519                         }
520                 }
521                 glEnd();
522         } else {
523                 glBegin(GL_LINES);
524                 for(i=0,eed= emdm->em->edges.first; eed; i++,eed= eed->next) {
525                         if(!setDrawOptions || setDrawOptions(userData, i)) {
526                                 glVertex3fv(eed->v1->co);
527                                 glVertex3fv(eed->v2->co);
528                         }
529                 }
530                 glEnd();
531         }
532 }
533 static void emDM_drawEdges(DerivedMesh *dm, int UNUSED(drawLooseEdges), int UNUSED(drawAllEdges))
534 {
535         emDM_drawMappedEdges(dm, NULL, NULL);
536 }
537 static void emDM_drawMappedEdgesInterp(DerivedMesh *dm, int (*setDrawOptions)(void *userData, int index), void (*setDrawInterpOptions)(void *userData, int index, float t), void *userData) 
538 {
539         EditMeshDerivedMesh *emdm= (EditMeshDerivedMesh*) dm;
540         EditEdge *eed;
541         int i;
542
543         if (emdm->vertexCos) {
544                 EditVert *eve;
545
546                 for (i=0,eve=emdm->em->verts.first; eve; eve= eve->next)
547                         eve->tmp.l = (intptr_t) i++;
548
549                 glBegin(GL_LINES);
550                 for (i=0,eed= emdm->em->edges.first; eed; i++,eed= eed->next) {
551                         if(!setDrawOptions || setDrawOptions(userData, i)) {
552                                 setDrawInterpOptions(userData, i, 0.0);
553                                 glVertex3fv(emdm->vertexCos[(int) eed->v1->tmp.l]);
554                                 setDrawInterpOptions(userData, i, 1.0);
555                                 glVertex3fv(emdm->vertexCos[(int) eed->v2->tmp.l]);
556                         }
557                 }
558                 glEnd();
559         } else {
560                 glBegin(GL_LINES);
561                 for (i=0,eed= emdm->em->edges.first; eed; i++,eed= eed->next) {
562                         if(!setDrawOptions || setDrawOptions(userData, i)) {
563                                 setDrawInterpOptions(userData, i, 0.0);
564                                 glVertex3fv(eed->v1->co);
565                                 setDrawInterpOptions(userData, i, 1.0);
566                                 glVertex3fv(eed->v2->co);
567                         }
568                 }
569                 glEnd();
570         }
571 }
572
573 static void emDM_drawUVEdges(DerivedMesh *dm)
574 {
575         EditMeshDerivedMesh *emdm= (EditMeshDerivedMesh*) dm;
576         EditFace *efa;
577         MTFace *tf;
578
579         glBegin(GL_LINES);
580         for(efa= emdm->em->faces.first; efa; efa= efa->next) {
581                 tf = CustomData_em_get(&emdm->em->fdata, efa->data, CD_MTFACE);
582
583                 if(tf && !(efa->h)) {
584                         glVertex2fv(tf->uv[0]);
585                         glVertex2fv(tf->uv[1]);
586
587                         glVertex2fv(tf->uv[1]);
588                         glVertex2fv(tf->uv[2]);
589
590                         if (!efa->v4) {
591                                 glVertex2fv(tf->uv[2]);
592                                 glVertex2fv(tf->uv[0]);
593                         } else {
594                                 glVertex2fv(tf->uv[2]);
595                                 glVertex2fv(tf->uv[3]);
596                                 glVertex2fv(tf->uv[3]);
597                                 glVertex2fv(tf->uv[0]);
598                         }
599                 }
600         }
601         glEnd();
602 }
603
604 static void emDM__calcFaceCent(EditFace *efa, float cent[3], float (*vertexCos)[3])
605 {
606         if (vertexCos) {
607                 copy_v3_v3(cent, vertexCos[(int) efa->v1->tmp.l]);
608                 add_v3_v3(cent, vertexCos[(int) efa->v2->tmp.l]);
609                 add_v3_v3(cent, vertexCos[(int) efa->v3->tmp.l]);
610                 if (efa->v4) add_v3_v3(cent, vertexCos[(int) efa->v4->tmp.l]);
611         } else {
612                 copy_v3_v3(cent, efa->v1->co);
613                 add_v3_v3(cent, efa->v2->co);
614                 add_v3_v3(cent, efa->v3->co);
615                 if (efa->v4) add_v3_v3(cent, efa->v4->co);
616         }
617
618         if (efa->v4) {
619                 mul_v3_fl(cent, 0.25f);
620         } else {
621                 mul_v3_fl(cent, 0.33333333333f);
622         }
623 }
624 static void emDM_foreachMappedFaceCenter(DerivedMesh *dm, void (*func)(void *userData, int index, float *co, float *no), void *userData)
625 {
626         EditMeshDerivedMesh *emdm= (EditMeshDerivedMesh*) dm;
627         EditVert *eve;
628         EditFace *efa;
629         float cent[3];
630         int i;
631
632         if (emdm->vertexCos) {
633                 for (i=0,eve=emdm->em->verts.first; eve; eve= eve->next)
634                         eve->tmp.l = (intptr_t) i++;
635         }
636
637         for(i=0,efa= emdm->em->faces.first; efa; i++,efa= efa->next) {
638                 emDM__calcFaceCent(efa, cent, emdm->vertexCos);
639                 func(userData, i, cent, emdm->vertexCos?emdm->faceNos[i]:efa->n);
640         }
641 }
642
643 /* note, material function is ignored for now. */
644 static void emDM_drawMappedFaces(DerivedMesh *dm,
645                         int (*setDrawOptions)(void *userData, int index, int *drawSmooth_r),
646                         int (*setMaterial)(int, void *attribs),
647                         int (*compareDrawOptions)(void *userData, int cur_index, int next_index),
648                         void *userData, int UNUSED(useColors))
649 {
650         EditMeshDerivedMesh *emdm= (EditMeshDerivedMesh*) dm;
651         EditFace *efa;
652         int i, draw;
653         const int skip_normals= !glIsEnabled(GL_LIGHTING); /* could be passed as an arg */
654
655         /* GL_ZERO is used to detect if drawing has started or not */
656         GLenum poly_prev= GL_ZERO;
657         GLenum shade_prev= GL_ZERO;
658
659         (void)setMaterial; /* unused */
660
661         /* currently unused -- each original face is handled separately */
662         (void)compareDrawOptions;
663
664         if (emdm->vertexCos) {
665                 /* add direct access */
666                 float (*vertexCos)[3]= emdm->vertexCos;
667                 float (*vertexNos)[3]= emdm->vertexNos;
668                 float (*faceNos)[3]=   emdm->faceNos;
669                 EditVert *eve;
670
671                 for (i=0,eve=emdm->em->verts.first; eve; eve= eve->next)
672                         eve->tmp.l = (intptr_t) i++;
673
674                 for (i=0,efa= emdm->em->faces.first; efa; i++,efa= efa->next) {
675                         int drawSmooth = (efa->flag & ME_SMOOTH);
676                         draw = setDrawOptions==NULL ? 1 : setDrawOptions(userData, i, &drawSmooth);
677                         if(draw) {
678                                 const GLenum poly_type= efa->v4 ? GL_QUADS:GL_TRIANGLES;
679                                 if (draw==2) { /* enabled with stipple */
680
681                                         if(poly_prev != GL_ZERO) glEnd();
682                                         poly_prev= GL_ZERO; /* force glBegin */
683
684                                         glEnable(GL_POLYGON_STIPPLE);
685                                         glPolygonStipple(stipple_quarttone);
686                                 }
687                                 
688                                 if(skip_normals) {
689                                         if(poly_type != poly_prev) {
690                                                 if(poly_prev != GL_ZERO) glEnd();
691                                                 glBegin((poly_prev= poly_type));
692                                         }
693                                         glVertex3fv(vertexCos[(int) efa->v1->tmp.l]);
694                                         glVertex3fv(vertexCos[(int) efa->v2->tmp.l]);
695                                         glVertex3fv(vertexCos[(int) efa->v3->tmp.l]);
696                                         if(poly_type == GL_QUADS) glVertex3fv(vertexCos[(int) efa->v4->tmp.l]);
697                                 }
698                                 else {
699                                         const GLenum shade_type= drawSmooth ? GL_SMOOTH : GL_FLAT;
700                                         if (shade_type != shade_prev) {
701                                                 if(poly_prev != GL_ZERO) glEnd();
702                                                 glShadeModel((shade_prev= shade_type)); /* same as below but switch shading */
703                                                 glBegin((poly_prev= poly_type));
704                                         }
705                                         else if(poly_type != poly_prev) {
706                                                 if(poly_prev != GL_ZERO) glEnd();
707                                                 glBegin((poly_prev= poly_type));
708                                         }
709
710                                         if (!drawSmooth) {
711                                                 glNormal3fv(faceNos[i]);
712                                                 glVertex3fv(vertexCos[(int) efa->v1->tmp.l]);
713                                                 glVertex3fv(vertexCos[(int) efa->v2->tmp.l]);
714                                                 glVertex3fv(vertexCos[(int) efa->v3->tmp.l]);
715                                                 if(poly_type == GL_QUADS) glVertex3fv(vertexCos[(int) efa->v4->tmp.l]);
716                                         } else {
717                                                 glNormal3fv(vertexNos[(int) efa->v1->tmp.l]);
718                                                 glVertex3fv(vertexCos[(int) efa->v1->tmp.l]);
719                                                 glNormal3fv(vertexNos[(int) efa->v2->tmp.l]);
720                                                 glVertex3fv(vertexCos[(int) efa->v2->tmp.l]);
721                                                 glNormal3fv(vertexNos[(int) efa->v3->tmp.l]);
722                                                 glVertex3fv(vertexCos[(int) efa->v3->tmp.l]);
723                                                 if(poly_type == GL_QUADS) {
724                                                         glNormal3fv(vertexNos[(int) efa->v4->tmp.l]);
725                                                         glVertex3fv(vertexCos[(int) efa->v4->tmp.l]);
726                                                 }
727                                         }
728                                 }
729
730                                 
731                                 if (draw==2) {
732                                         glEnd();
733                                         poly_prev= GL_ZERO; /* force glBegin */
734
735                                         glDisable(GL_POLYGON_STIPPLE);
736                                 }
737                         }
738                 }
739         }
740         else {
741                 for (i=0,efa= emdm->em->faces.first; efa; i++,efa= efa->next) {
742                         int drawSmooth = (efa->flag & ME_SMOOTH);
743                         draw = setDrawOptions==NULL ? 1 : setDrawOptions(userData, i, &drawSmooth);
744                         if(draw) {
745                                 const GLenum poly_type= efa->v4 ? GL_QUADS:GL_TRIANGLES;
746                                 if (draw==2) { /* enabled with stipple */
747
748                                         if(poly_prev != GL_ZERO) glEnd();
749                                         poly_prev= GL_ZERO; /* force glBegin */
750
751                                         glEnable(GL_POLYGON_STIPPLE);
752                                         glPolygonStipple(stipple_quarttone);
753                                 }
754
755                                 if(skip_normals) {
756                                         if(poly_type != poly_prev) {
757                                                 if(poly_prev != GL_ZERO) glEnd();
758                                                 glBegin((poly_prev= poly_type));
759                                         }
760                                         glVertex3fv(efa->v1->co);
761                                         glVertex3fv(efa->v2->co);
762                                         glVertex3fv(efa->v3->co);
763                                         if(poly_type == GL_QUADS) glVertex3fv(efa->v4->co);
764                                 }
765                                 else {
766                                         const GLenum shade_type= drawSmooth ? GL_SMOOTH : GL_FLAT;
767                                         if (shade_type != shade_prev) {
768                                                 if(poly_prev != GL_ZERO) glEnd();
769                                                 glShadeModel((shade_prev= shade_type)); /* same as below but switch shading */
770                                                 glBegin((poly_prev= poly_type));
771                                         }
772                                         else if(poly_type != poly_prev) {
773                                                 if(poly_prev != GL_ZERO) glEnd();
774                                                 glBegin((poly_prev= poly_type));
775                                         }
776
777                                         if (!drawSmooth) {
778                                                 glNormal3fv(efa->n);
779                                                 glVertex3fv(efa->v1->co);
780                                                 glVertex3fv(efa->v2->co);
781                                                 glVertex3fv(efa->v3->co);
782                                                 if(poly_type == GL_QUADS) glVertex3fv(efa->v4->co);
783                                         } else {
784                                                 glNormal3fv(efa->v1->no);
785                                                 glVertex3fv(efa->v1->co);
786                                                 glNormal3fv(efa->v2->no);
787                                                 glVertex3fv(efa->v2->co);
788                                                 glNormal3fv(efa->v3->no);
789                                                 glVertex3fv(efa->v3->co);
790                                                 if(poly_type == GL_QUADS) {
791                                                         glNormal3fv(efa->v4->no);
792                                                         glVertex3fv(efa->v4->co);
793                                                 }
794                                         }
795                                 }
796
797                                 
798                                 if (draw==2) {
799                                         glEnd();
800                                         poly_prev= GL_ZERO;
801
802                                         glDisable(GL_POLYGON_STIPPLE);
803                                 }
804                         }
805                 }
806         }
807
808         /* if non zero we know a face was rendered */
809         if(poly_prev != GL_ZERO) glEnd();
810 }
811
812 static void emDM_drawFacesTex_common(DerivedMesh *dm,
813                            int (*drawParams)(MTFace *tface, int has_mcol, int matnr),
814                            int (*drawParamsMapped)(void *userData, int index),
815                            int (*compareDrawOptions)(void *userData, int cur_index, int next_index),
816                            void *userData)
817 {
818         EditMeshDerivedMesh *emdm= (EditMeshDerivedMesh*) dm;
819         EditMesh *em= emdm->em;
820         float (*vertexCos)[3]= emdm->vertexCos;
821         float (*vertexNos)[3]= emdm->vertexNos;
822         EditFace *efa;
823         int i;
824
825         (void) compareDrawOptions;
826
827         /* always use smooth shading even for flat faces, else vertex colors wont interpolate */
828         glShadeModel(GL_SMOOTH);
829         
830         if (vertexCos) {
831                 EditVert *eve;
832
833                 for (i=0,eve=em->verts.first; eve; eve= eve->next)
834                         eve->tmp.l = (intptr_t) i++;
835
836                 for (i=0,efa= em->faces.first; efa; i++,efa= efa->next) {
837                         MTFace *tf= CustomData_em_get(&em->fdata, efa->data, CD_MTFACE);
838                         MCol *mcol= CustomData_em_get(&em->fdata, efa->data, CD_MCOL);
839                         unsigned char *cp= NULL;
840                         int drawSmooth= (efa->flag & ME_SMOOTH);
841                         int flag;
842
843                         if(drawParams)
844                                 flag= drawParams(tf, (mcol != NULL), efa->mat_nr);
845                         else if(drawParamsMapped)
846                                 flag= drawParamsMapped(userData, i);
847                         else
848                                 flag= 1;
849
850                         if(flag != 0) { /* flag 0 == the face is hidden or invisible */
851                                 
852                                 /* we always want smooth here since otherwise vertex colors dont interpolate */
853                                 if (mcol) {
854                                         if (flag==1) {
855                                                 cp= (unsigned char*)mcol;
856                                         }
857                                 } else {
858                                         glShadeModel(drawSmooth?GL_SMOOTH:GL_FLAT);
859                                 } 
860                                 
861                                 glBegin(efa->v4?GL_QUADS:GL_TRIANGLES);
862                                 if (!drawSmooth) {
863                                         glNormal3fv(emdm->faceNos[i]);
864
865                                         if(tf) glTexCoord2fv(tf->uv[0]);
866                                         if(cp) glColor3ub(cp[3], cp[2], cp[1]);
867                                         glVertex3fv(vertexCos[(int) efa->v1->tmp.l]);
868
869                                         if(tf) glTexCoord2fv(tf->uv[1]);
870                                         if(cp) glColor3ub(cp[7], cp[6], cp[5]);
871                                         glVertex3fv(vertexCos[(int) efa->v2->tmp.l]);
872
873                                         if(tf) glTexCoord2fv(tf->uv[2]);
874                                         if(cp) glColor3ub(cp[11], cp[10], cp[9]);
875                                         glVertex3fv(vertexCos[(int) efa->v3->tmp.l]);
876
877                                         if(efa->v4) {
878                                                 if(tf) glTexCoord2fv(tf->uv[3]);
879                                                 if(cp) glColor3ub(cp[15], cp[14], cp[13]);
880                                                 glVertex3fv(vertexCos[(int) efa->v4->tmp.l]);
881                                         }
882                                 } else {
883                                         if(tf) glTexCoord2fv(tf->uv[0]);
884                                         if(cp) glColor3ub(cp[3], cp[2], cp[1]);
885                                         glNormal3fv(vertexNos[(int) efa->v1->tmp.l]);
886                                         glVertex3fv(vertexCos[(int) efa->v1->tmp.l]);
887
888                                         if(tf) glTexCoord2fv(tf->uv[1]);
889                                         if(cp) glColor3ub(cp[7], cp[6], cp[5]);
890                                         glNormal3fv(vertexNos[(int) efa->v2->tmp.l]);
891                                         glVertex3fv(vertexCos[(int) efa->v2->tmp.l]);
892
893                                         if(tf) glTexCoord2fv(tf->uv[2]);
894                                         if(cp) glColor3ub(cp[11], cp[10], cp[9]);
895                                         glNormal3fv(vertexNos[(int) efa->v3->tmp.l]);
896                                         glVertex3fv(vertexCos[(int) efa->v3->tmp.l]);
897
898                                         if(efa->v4) {
899                                                 if(tf) glTexCoord2fv(tf->uv[3]);
900                                                 if(cp) glColor3ub(cp[15], cp[14], cp[13]);
901                                                 glNormal3fv(vertexNos[(int) efa->v4->tmp.l]);
902                                                 glVertex3fv(vertexCos[(int) efa->v4->tmp.l]);
903                                         }
904                                 }
905                                 glEnd();
906                         }
907                 }
908         } else {
909                 for (i=0,efa= em->faces.first; efa; i++,efa= efa->next) {
910                         MTFace *tf= CustomData_em_get(&em->fdata, efa->data, CD_MTFACE);
911                         MCol *mcol= CustomData_em_get(&em->fdata, efa->data, CD_MCOL);
912                         unsigned char *cp= NULL;
913                         int drawSmooth= (efa->flag & ME_SMOOTH);
914                         int flag;
915
916                         if(drawParams)
917                                 flag= drawParams(tf, (mcol != NULL), efa->mat_nr);
918                         else if(drawParamsMapped)
919                                 flag= drawParamsMapped(userData, i);
920                         else
921                                 flag= 1;
922
923                         if(flag != 0) { /* flag 0 == the face is hidden or invisible */
924                                 /* we always want smooth here since otherwise vertex colors dont interpolate */
925                                 if (mcol) {
926                                         if (flag==1) {
927                                                 cp= (unsigned char*)mcol;
928                                         }
929                                 } else {
930                                         glShadeModel(drawSmooth?GL_SMOOTH:GL_FLAT);
931                                 } 
932
933                                 glBegin(efa->v4?GL_QUADS:GL_TRIANGLES);
934                                 if (!drawSmooth) {
935                                         glNormal3fv(efa->n);
936
937                                         if(tf) glTexCoord2fv(tf->uv[0]);
938                                         if(cp) glColor3ub(cp[3], cp[2], cp[1]);
939                                         glVertex3fv(efa->v1->co);
940
941                                         if(tf) glTexCoord2fv(tf->uv[1]);
942                                         if(cp) glColor3ub(cp[7], cp[6], cp[5]);
943                                         glVertex3fv(efa->v2->co);
944
945                                         if(tf) glTexCoord2fv(tf->uv[2]);
946                                         if(cp) glColor3ub(cp[11], cp[10], cp[9]);
947                                         glVertex3fv(efa->v3->co);
948
949                                         if(efa->v4) {
950                                                 if(tf) glTexCoord2fv(tf->uv[3]);
951                                                 if(cp) glColor3ub(cp[15], cp[14], cp[13]);
952                                                 glVertex3fv(efa->v4->co);
953                                         }
954                                 } else {
955                                         if(tf) glTexCoord2fv(tf->uv[0]);
956                                         if(cp) glColor3ub(cp[3], cp[2], cp[1]);
957                                         glNormal3fv(efa->v1->no);
958                                         glVertex3fv(efa->v1->co);
959
960                                         if(tf) glTexCoord2fv(tf->uv[1]);
961                                         if(cp) glColor3ub(cp[7], cp[6], cp[5]);
962                                         glNormal3fv(efa->v2->no);
963                                         glVertex3fv(efa->v2->co);
964
965                                         if(tf) glTexCoord2fv(tf->uv[2]);
966                                         if(cp) glColor3ub(cp[11], cp[10], cp[9]);
967                                         glNormal3fv(efa->v3->no);
968                                         glVertex3fv(efa->v3->co);
969
970                                         if(efa->v4) {
971                                                 if(tf) glTexCoord2fv(tf->uv[3]);
972                                                 if(cp) glColor3ub(cp[15], cp[14], cp[13]);
973                                                 glNormal3fv(efa->v4->no);
974                                                 glVertex3fv(efa->v4->co);
975                                         }
976                                 }
977                                 glEnd();
978                         }
979                 }
980         }
981 }
982
983 static void emDM_drawFacesTex(DerivedMesh *dm,
984                            int (*setDrawOptions)(MTFace *tface, int has_mcol, int matnr),
985                            int (*compareDrawOptions)(void *userData, int cur_index, int next_index),
986                            void *userData)
987 {
988         emDM_drawFacesTex_common(dm, setDrawOptions, NULL, compareDrawOptions, userData);
989 }
990
991 static void emDM_drawMappedFacesTex(DerivedMesh *dm,
992                            int (*setDrawOptions)(void *userData, int index),
993                            int (*compareDrawOptions)(void *userData, int cur_index, int next_index),
994                            void *userData)
995 {
996         emDM_drawFacesTex_common(dm, NULL, setDrawOptions, compareDrawOptions, userData);
997 }
998
999 static void emDM_drawMappedFacesGLSL(DerivedMesh *dm,
1000                            int (*setMaterial)(int, void *attribs),
1001                            int (*setDrawOptions)(void *userData, int index),
1002                            void *userData)
1003 {
1004         EditMeshDerivedMesh *emdm= (EditMeshDerivedMesh*) dm;
1005         EditMesh *em= emdm->em;
1006         float (*vertexCos)[3]= emdm->vertexCos;
1007         float (*vertexNos)[3]= emdm->vertexNos;
1008         EditVert *eve;
1009         EditFace *efa;
1010         DMVertexAttribs attribs= {{{0}}};
1011         GPUVertexAttribs gattribs;
1012         /* int tfoffset; */ /* UNUSED */
1013         int i, b, matnr, new_matnr, dodraw /* , layer */ /* UNUSED */;
1014
1015         dodraw = 0;
1016         matnr = -1;
1017
1018         /* layer = CustomData_get_layer_index(&em->fdata, CD_MTFACE); */ /* UNUSED */
1019         /* tfoffset = (layer == -1)? -1: em->fdata.layers[layer].offset; */ /* UNUSED */
1020
1021         /* always use smooth shading even for flat faces, else vertex colors wont interpolate */
1022         glShadeModel(GL_SMOOTH);
1023
1024         for (i=0,eve=em->verts.first; eve; eve= eve->next)
1025                 eve->tmp.l = (intptr_t) i++;
1026
1027 #define PASSATTRIB(efa, eve, vert) {                                                                                    \
1028         if(attribs.totorco) {                                                                                                           \
1029                 float *orco = attribs.orco.array[eve->tmp.l];                                                   \
1030                 glVertexAttrib3fvARB(attribs.orco.glIndex, orco);                                               \
1031         }                                                                                                                                                       \
1032         for(b = 0; b < attribs.tottface; b++) {                                                                         \
1033                 MTFace *_tf = (MTFace*)((char*)efa->data + attribs.tface[b].emOffset);  \
1034                 glVertexAttrib2fvARB(attribs.tface[b].glIndex, _tf->uv[vert]);                  \
1035         }                                                                                                                                                       \
1036         for(b = 0; b < attribs.totmcol; b++) {                                                                          \
1037                 MCol *cp = (MCol*)((char*)efa->data + attribs.mcol[b].emOffset);                \
1038                 GLubyte col[4];                                                                                                                 \
1039                 col[0]= cp->b; col[1]= cp->g; col[2]= cp->r; col[3]= cp->a;                             \
1040                 glVertexAttrib4ubvARB(attribs.mcol[b].glIndex, col);                                    \
1041         }                                                                                                                                                       \
1042         if(attribs.tottang) {                                                                                                           \
1043                 float *tang = attribs.tang.array[i*4 + vert];                                                   \
1044                 glVertexAttrib4fvARB(attribs.tang.glIndex, tang);                                               \
1045         }                                                                                                                                                       \
1046 }
1047
1048         for (i=0,efa= em->faces.first; efa; i++,efa= efa->next) {
1049                 int drawSmooth= (efa->flag & ME_SMOOTH);
1050
1051                 if(setDrawOptions && !setDrawOptions(userData, i))
1052                         continue;
1053
1054                 new_matnr = efa->mat_nr + 1;
1055                 if(new_matnr != matnr) {
1056                         dodraw = setMaterial(matnr = new_matnr, &gattribs);
1057                         if(dodraw)
1058                                 DM_vertex_attributes_from_gpu(dm, &gattribs, &attribs);
1059                 }
1060
1061                 if(dodraw) {
1062                         glBegin(efa->v4?GL_QUADS:GL_TRIANGLES);
1063                         if (!drawSmooth) {
1064                                 if(vertexCos) glNormal3fv(emdm->faceNos[i]);
1065                                 else glNormal3fv(efa->n);
1066
1067                                 PASSATTRIB(efa, efa->v1, 0);
1068                                 if(vertexCos) glVertex3fv(vertexCos[(int) efa->v1->tmp.l]);
1069                                 else glVertex3fv(efa->v1->co);
1070
1071                                 PASSATTRIB(efa, efa->v2, 1);
1072                                 if(vertexCos) glVertex3fv(vertexCos[(int) efa->v2->tmp.l]);
1073                                 else glVertex3fv(efa->v2->co);
1074
1075                                 PASSATTRIB(efa, efa->v3, 2);
1076                                 if(vertexCos) glVertex3fv(vertexCos[(int) efa->v3->tmp.l]);
1077                                 else glVertex3fv(efa->v3->co);
1078
1079                                 if(efa->v4) {
1080                                         PASSATTRIB(efa, efa->v4, 3);
1081                                         if(vertexCos) glVertex3fv(vertexCos[(int) efa->v4->tmp.l]);
1082                                         else glVertex3fv(efa->v4->co);
1083                                 }
1084                         } else {
1085                                 PASSATTRIB(efa, efa->v1, 0);
1086                                 if(vertexCos) {
1087                                         glNormal3fv(vertexNos[(int) efa->v1->tmp.l]);
1088                                         glVertex3fv(vertexCos[(int) efa->v1->tmp.l]);
1089                                 }
1090                                 else {
1091                                         glNormal3fv(efa->v1->no);
1092                                         glVertex3fv(efa->v1->co);
1093                                 }
1094
1095                                 PASSATTRIB(efa, efa->v2, 1);
1096                                 if(vertexCos) {
1097                                         glNormal3fv(vertexNos[(int) efa->v2->tmp.l]);
1098                                         glVertex3fv(vertexCos[(int) efa->v2->tmp.l]);
1099                                 }
1100                                 else {
1101                                         glNormal3fv(efa->v2->no);
1102                                         glVertex3fv(efa->v2->co);
1103                                 }
1104
1105                                 PASSATTRIB(efa, efa->v3, 2);
1106                                 if(vertexCos) {
1107                                         glNormal3fv(vertexNos[(int) efa->v3->tmp.l]);
1108                                         glVertex3fv(vertexCos[(int) efa->v3->tmp.l]);
1109                                 }
1110                                 else {
1111                                         glNormal3fv(efa->v3->no);
1112                                         glVertex3fv(efa->v3->co);
1113                                 }
1114
1115                                 if(efa->v4) {
1116                                         PASSATTRIB(efa, efa->v4, 3);
1117                                         if(vertexCos) {
1118                                                 glNormal3fv(vertexNos[(int) efa->v4->tmp.l]);
1119                                                 glVertex3fv(vertexCos[(int) efa->v4->tmp.l]);
1120                                         }
1121                                         else {
1122                                                 glNormal3fv(efa->v4->no);
1123                                                 glVertex3fv(efa->v4->co);
1124                                         }
1125                                 }
1126                         }
1127                         glEnd();
1128                 }
1129         }
1130 #undef PASSATTRIB
1131 }
1132
1133 static void emDM_drawFacesGLSL(DerivedMesh *dm,
1134                            int (*setMaterial)(int, void *attribs))
1135 {
1136         dm->drawMappedFacesGLSL(dm, setMaterial, NULL, NULL);
1137 }
1138
1139 static void emDM_drawMappedFacesMat(DerivedMesh *dm,
1140                            void (*setMaterial)(void *userData, int, void *attribs),
1141                            int (*setFace)(void *userData, int index), void *userData) 
1142 {
1143         EditMeshDerivedMesh *emdm= (EditMeshDerivedMesh*) dm;
1144         EditMesh *em= emdm->em;
1145         float (*vertexCos)[3]= emdm->vertexCos;
1146         float (*vertexNos)[3]= emdm->vertexNos;
1147         EditVert *eve;
1148         EditFace *efa;
1149         DMVertexAttribs attribs= {{{0}}};
1150         GPUVertexAttribs gattribs;
1151         int i, b, matnr, new_matnr;
1152
1153         matnr = -1;
1154
1155         /* always use smooth shading even for flat faces, else vertex colors wont interpolate */
1156         glShadeModel(GL_SMOOTH);
1157
1158         for (i=0,eve=em->verts.first; eve; eve= eve->next)
1159                 eve->tmp.l = (intptr_t) i++;
1160
1161 #define PASSATTRIB(efa, eve, vert) {                                                                                    \
1162         if(attribs.totorco) {                                                                                                           \
1163                 float *orco = attribs.orco.array[eve->tmp.l];                                                   \
1164                 if(attribs.orco.glTexco)                                                                                                \
1165                         glTexCoord3fv(orco);                                                                                            \
1166                 else                                                                                                                                    \
1167                         glVertexAttrib3fvARB(attribs.orco.glIndex, orco);                                       \
1168         }                                                                                                                                                       \
1169         for(b = 0; b < attribs.tottface; b++) {                                                                         \
1170                 MTFace *_tf = (MTFace*)((char*)efa->data + attribs.tface[b].emOffset);  \
1171                 if(attribs.tface[b].glTexco)                                                                                    \
1172                         glTexCoord2fv(_tf->uv[vert]);                                                                           \
1173                 else                                                                                                                                    \
1174                         glVertexAttrib2fvARB(attribs.tface[b].glIndex, _tf->uv[vert]);          \
1175         }                                                                                                                                                       \
1176         for(b = 0; b < attribs.totmcol; b++) {                                                                          \
1177                 MCol *cp = (MCol*)((char*)efa->data + attribs.mcol[b].emOffset);                \
1178                 GLubyte col[4];                                                                                                                 \
1179                 col[0]= cp->b; col[1]= cp->g; col[2]= cp->r; col[3]= cp->a;                             \
1180                 glVertexAttrib4ubvARB(attribs.mcol[b].glIndex, col);                                    \
1181         }                                                                                                                                                       \
1182         if(attribs.tottang) {                                                                                                           \
1183                 float *tang = attribs.tang.array[i*4 + vert];                                                   \
1184                 glVertexAttrib4fvARB(attribs.tang.glIndex, tang);                                               \
1185         }                                                                                                                                                       \
1186 }
1187
1188         for (i=0,efa= em->faces.first; efa; i++,efa= efa->next) {
1189                 int drawSmooth= (efa->flag & ME_SMOOTH);
1190
1191                 /* face hiding */
1192                 if(setFace && !setFace(userData, i))
1193                         continue;
1194
1195                 /* material */
1196                 new_matnr = efa->mat_nr + 1;
1197                 if(new_matnr != matnr) {
1198                         setMaterial(userData, matnr = new_matnr, &gattribs);
1199                         DM_vertex_attributes_from_gpu(dm, &gattribs, &attribs);
1200                 }
1201
1202                 /* face */
1203                 glBegin(efa->v4?GL_QUADS:GL_TRIANGLES);
1204                 if (!drawSmooth) {
1205                         if(vertexCos) glNormal3fv(emdm->faceNos[i]);
1206                         else glNormal3fv(efa->n);
1207
1208                         PASSATTRIB(efa, efa->v1, 0);
1209                         if(vertexCos) glVertex3fv(vertexCos[(int) efa->v1->tmp.l]);
1210                         else glVertex3fv(efa->v1->co);
1211
1212                         PASSATTRIB(efa, efa->v2, 1);
1213                         if(vertexCos) glVertex3fv(vertexCos[(int) efa->v2->tmp.l]);
1214                         else glVertex3fv(efa->v2->co);
1215
1216                         PASSATTRIB(efa, efa->v3, 2);
1217                         if(vertexCos) glVertex3fv(vertexCos[(int) efa->v3->tmp.l]);
1218                         else glVertex3fv(efa->v3->co);
1219
1220                         if(efa->v4) {
1221                                 PASSATTRIB(efa, efa->v4, 3);
1222                                 if(vertexCos) glVertex3fv(vertexCos[(int) efa->v4->tmp.l]);
1223                                 else glVertex3fv(efa->v4->co);
1224                         }
1225                 } else {
1226                         PASSATTRIB(efa, efa->v1, 0);
1227                         if(vertexCos) {
1228                                 glNormal3fv(vertexNos[(int) efa->v1->tmp.l]);
1229                                 glVertex3fv(vertexCos[(int) efa->v1->tmp.l]);
1230                         }
1231                         else {
1232                                 glNormal3fv(efa->v1->no);
1233                                 glVertex3fv(efa->v1->co);
1234                         }
1235
1236                         PASSATTRIB(efa, efa->v2, 1);
1237                         if(vertexCos) {
1238                                 glNormal3fv(vertexNos[(int) efa->v2->tmp.l]);
1239                                 glVertex3fv(vertexCos[(int) efa->v2->tmp.l]);
1240                         }
1241                         else {
1242                                 glNormal3fv(efa->v2->no);
1243                                 glVertex3fv(efa->v2->co);
1244                         }
1245
1246                         PASSATTRIB(efa, efa->v3, 2);
1247                         if(vertexCos) {
1248                                 glNormal3fv(vertexNos[(int) efa->v3->tmp.l]);
1249                                 glVertex3fv(vertexCos[(int) efa->v3->tmp.l]);
1250                         }
1251                         else {
1252                                 glNormal3fv(efa->v3->no);
1253                                 glVertex3fv(efa->v3->co);
1254                         }
1255
1256                         if(efa->v4) {
1257                                 PASSATTRIB(efa, efa->v4, 3);
1258                                 if(vertexCos) {
1259                                         glNormal3fv(vertexNos[(int) efa->v4->tmp.l]);
1260                                         glVertex3fv(vertexCos[(int) efa->v4->tmp.l]);
1261                                 }
1262                                 else {
1263                                         glNormal3fv(efa->v4->no);
1264                                         glVertex3fv(efa->v4->co);
1265                                 }
1266                         }
1267                 }
1268                 glEnd();
1269         }
1270 #undef PASSATTRIB
1271 }
1272
1273 static void emDM_getMinMax(DerivedMesh *dm, float min_r[3], float max_r[3])
1274 {
1275         EditMeshDerivedMesh *emdm= (EditMeshDerivedMesh*) dm;
1276         EditVert *eve;
1277         int i;
1278
1279         if (emdm->em->verts.first) {
1280                 for (i=0,eve= emdm->em->verts.first; eve; i++,eve= eve->next) {
1281                         if (emdm->vertexCos) {
1282                                 DO_MINMAX(emdm->vertexCos[i], min_r, max_r);
1283                         } else {
1284                                 DO_MINMAX(eve->co, min_r, max_r);
1285                         }
1286                 }
1287         } else {
1288                 min_r[0] = min_r[1] = min_r[2] = max_r[0] = max_r[1] = max_r[2] = 0.0;
1289         }
1290 }
1291 static int emDM_getNumVerts(DerivedMesh *dm)
1292 {
1293         EditMeshDerivedMesh *emdm= (EditMeshDerivedMesh*) dm;
1294
1295         return BLI_countlist(&emdm->em->verts);
1296 }
1297
1298 static int emDM_getNumEdges(DerivedMesh *dm)
1299 {
1300         EditMeshDerivedMesh *emdm= (EditMeshDerivedMesh*) dm;
1301
1302         return BLI_countlist(&emdm->em->edges);
1303 }
1304
1305 static int emDM_getNumFaces(DerivedMesh *dm)
1306 {
1307         EditMeshDerivedMesh *emdm= (EditMeshDerivedMesh*) dm;
1308
1309         return BLI_countlist(&emdm->em->faces);
1310 }
1311
1312 static void emDM_getVertCos(DerivedMesh *dm, float (*cos_r)[3])
1313 {
1314         EditMeshDerivedMesh *emdm= (EditMeshDerivedMesh*) dm;
1315         EditVert *eve;
1316         int i;
1317
1318         for (i=0,eve= emdm->em->verts.first; eve; i++,eve=eve->next) {
1319                 if (emdm->vertexCos) {
1320                         copy_v3_v3(cos_r[i], emdm->vertexCos[i]);
1321                 } else {
1322                         copy_v3_v3(cos_r[i], eve->co);
1323                 }
1324         }
1325 }
1326
1327 static void emDM_getVert(DerivedMesh *dm, int index, MVert *vert_r)
1328 {
1329         EditVert *ev = ((EditMeshDerivedMesh *)dm)->em->verts.first;
1330         int i;
1331
1332         for(i = 0; i < index; ++i) ev = ev->next;
1333
1334         copy_v3_v3(vert_r->co, ev->co);
1335
1336         normal_float_to_short_v3(vert_r->no, ev->no);
1337
1338         /* TODO what to do with vert_r->flag? */
1339         vert_r->bweight = (unsigned char) (ev->bweight*255.0f);
1340 }
1341
1342 static void emDM_getEdge(DerivedMesh *dm, int index, MEdge *edge_r)
1343 {
1344         EditMesh *em = ((EditMeshDerivedMesh *)dm)->em;
1345         EditEdge *ee = em->edges.first;
1346         EditVert *ev, *v1, *v2;
1347         int i;
1348
1349         for(i = 0; i < index; ++i) ee = ee->next;
1350
1351         edge_r->crease = (unsigned char) (ee->crease*255.0f);
1352         edge_r->bweight = (unsigned char) (ee->bweight*255.0f);
1353         /* TODO what to do with edge_r->flag? */
1354         edge_r->flag = ME_EDGEDRAW|ME_EDGERENDER;
1355         if (ee->seam) edge_r->flag |= ME_SEAM;
1356         if (ee->sharp) edge_r->flag |= ME_SHARP;
1357 #if 0
1358         /* this needs setup of f2 field */
1359         if (!ee->f2) edge_r->flag |= ME_LOOSEEDGE;
1360 #endif
1361
1362         /* goddamn, we have to search all verts to find indices */
1363         v1 = ee->v1;
1364         v2 = ee->v2;
1365         for(i = 0, ev = em->verts.first; v1 || v2; i++, ev = ev->next) {
1366                 if(ev == v1) {
1367                         edge_r->v1 = i;
1368                         v1 = NULL;
1369                 }
1370                 if(ev == v2) {
1371                         edge_r->v2 = i;
1372                         v2 = NULL;
1373                 }
1374         }
1375 }
1376
1377 static void emDM_getFace(DerivedMesh *dm, int index, MFace *face_r)
1378 {
1379         EditMesh *em = ((EditMeshDerivedMesh *)dm)->em;
1380         EditFace *ef = em->faces.first;
1381         EditVert *ev, *v1, *v2, *v3, *v4;
1382         int i;
1383
1384         for(i = 0; i < index; ++i) ef = ef->next;
1385
1386         face_r->mat_nr = ef->mat_nr;
1387         face_r->flag = ef->flag;
1388
1389         /* goddamn, we have to search all verts to find indices */
1390         v1 = ef->v1;
1391         v2 = ef->v2;
1392         v3 = ef->v3;
1393         v4 = ef->v4;
1394         if(!v4) face_r->v4 = 0;
1395
1396         for(i = 0, ev = em->verts.first; v1 || v2 || v3 || v4;
1397                 i++, ev = ev->next) {
1398                 if(ev == v1) {
1399                         face_r->v1 = i;
1400                         v1 = NULL;
1401                 }
1402                 if(ev == v2) {
1403                         face_r->v2 = i;
1404                         v2 = NULL;
1405                 }
1406                 if(ev == v3) {
1407                         face_r->v3 = i;
1408                         v3 = NULL;
1409                 }
1410                 if(ev == v4) {
1411                         face_r->v4 = i;
1412                         v4 = NULL;
1413                 }
1414         }
1415
1416         test_index_face(face_r, NULL, 0, ef->v4?4:3);
1417 }
1418
1419 static void emDM_copyVertArray(DerivedMesh *dm, MVert *vert_r)
1420 {
1421         EditMeshDerivedMesh *emdm= (EditMeshDerivedMesh*) dm;
1422         EditVert *ev = emdm->em->verts.first;
1423         int i;
1424
1425         for(i=0; ev; ev = ev->next, ++vert_r, ++i) {
1426                 if(emdm->vertexCos)
1427                         copy_v3_v3(vert_r->co, emdm->vertexCos[i]);
1428                 else
1429                         copy_v3_v3(vert_r->co, ev->co);
1430
1431                 normal_float_to_short_v3(vert_r->no, ev->no);
1432
1433                 /* TODO what to do with vert_r->flag? */
1434                 vert_r->flag = 0;
1435                 vert_r->bweight = (unsigned char) (ev->bweight*255.0f);
1436         }
1437 }
1438
1439 static void emDM_copyEdgeArray(DerivedMesh *dm, MEdge *edge_r)
1440 {
1441         EditMesh *em = ((EditMeshDerivedMesh *)dm)->em;
1442         EditEdge *ee = em->edges.first;
1443         EditVert *ev;
1444         int i;
1445
1446         /* store vertex indices in tmp union */
1447         for(ev = em->verts.first, i = 0; ev; ev = ev->next, ++i)
1448                 ev->tmp.l = (intptr_t) i;
1449
1450         for( ; ee; ee = ee->next, ++edge_r) {
1451                 edge_r->crease = (unsigned char) (ee->crease*255.0f);
1452                 edge_r->bweight = (unsigned char) (ee->bweight*255.0f);
1453                 /* TODO what to do with edge_r->flag? */
1454                 edge_r->flag = ME_EDGEDRAW|ME_EDGERENDER;
1455                 if (ee->seam) edge_r->flag |= ME_SEAM;
1456                 if (ee->sharp) edge_r->flag |= ME_SHARP;
1457 #if 0
1458                 /* this needs setup of f2 field */
1459                 if (!ee->f2) edge_r->flag |= ME_LOOSEEDGE;
1460 #endif
1461
1462                 edge_r->v1 = (int)ee->v1->tmp.l;
1463                 edge_r->v2 = (int)ee->v2->tmp.l;
1464         }
1465 }
1466
1467 static void emDM_copyFaceArray(DerivedMesh *dm, MFace *face_r)
1468 {
1469         EditMesh *em = ((EditMeshDerivedMesh *)dm)->em;
1470         EditFace *ef = em->faces.first;
1471         EditVert *ev;
1472         int i;
1473
1474         /* store vertexes indices in tmp union */
1475         for(ev = em->verts.first, i = 0; ev; ev = ev->next, ++i)
1476                 ev->tmp.l = (intptr_t) i;
1477
1478         for( ; ef; ef = ef->next, ++face_r) {
1479                 face_r->mat_nr = ef->mat_nr;
1480                 face_r->flag = ef->flag;
1481
1482                 face_r->v1 = (int)ef->v1->tmp.l;
1483                 face_r->v2 = (int)ef->v2->tmp.l;
1484                 face_r->v3 = (int)ef->v3->tmp.l;
1485                 if(ef->v4) face_r->v4 = (int)ef->v4->tmp.l;
1486                 else face_r->v4 = 0;
1487
1488                 test_index_face(face_r, NULL, 0, ef->v4?4:3);
1489         }
1490 }
1491
1492 static void *emDM_getFaceDataArray(DerivedMesh *dm, int type)
1493 {
1494         EditMeshDerivedMesh *emdm= (EditMeshDerivedMesh*) dm;
1495         EditMesh *em= emdm->em;
1496         EditFace *efa;
1497         char *data, *emdata;
1498         void *datalayer;
1499         int index, size;
1500
1501         datalayer = DM_get_face_data_layer(dm, type);
1502         if(datalayer)
1503                 return datalayer;
1504
1505         /* layers are store per face for editmesh, we convert to a temporary
1506          * data layer array in the derivedmesh when these are requested */
1507         if(type == CD_MTFACE || type == CD_MCOL) {
1508                 index = CustomData_get_layer_index(&em->fdata, type);
1509
1510                 if(index != -1) {
1511                         /* int offset = em->fdata.layers[index].offset; */ /* UNUSED */
1512                         size = CustomData_sizeof(type);
1513
1514                         DM_add_face_layer(dm, type, CD_CALLOC, NULL);
1515                         index = CustomData_get_layer_index(&dm->faceData, type);
1516                         dm->faceData.layers[index].flag |= CD_FLAG_TEMPORARY;
1517
1518                         data = datalayer = DM_get_face_data_layer(dm, type);
1519                         for(efa=em->faces.first; efa; efa=efa->next, data+=size) {
1520                                 emdata = CustomData_em_get(&em->fdata, efa->data, type);
1521                                 memcpy(data, emdata, size);
1522                         }
1523                 }
1524         }
1525
1526         return datalayer;
1527 }
1528
1529 static void emDM_release(DerivedMesh *dm)
1530 {
1531         EditMeshDerivedMesh *emdm= (EditMeshDerivedMesh*) dm;
1532
1533         if (DM_release(dm)) {
1534                 if (emdm->vertexCos) {
1535                         MEM_freeN(emdm->vertexCos);
1536                         MEM_freeN(emdm->vertexNos);
1537                         MEM_freeN(emdm->faceNos);
1538                 }
1539
1540                 MEM_freeN(emdm);
1541         }
1542 }
1543
1544 DerivedMesh *editmesh_get_derived(EditMesh *em, float (*vertexCos)[3])
1545 {
1546         EditMeshDerivedMesh *emdm = MEM_callocN(sizeof(*emdm), "emdm");
1547
1548         DM_init(&emdm->dm, DM_TYPE_EDITMESH, BLI_countlist(&em->verts),
1549                                          BLI_countlist(&em->edges), BLI_countlist(&em->faces));
1550
1551         emdm->dm.getMinMax = emDM_getMinMax;
1552
1553         emdm->dm.getNumVerts = emDM_getNumVerts;
1554         emdm->dm.getNumEdges = emDM_getNumEdges;
1555         emdm->dm.getNumFaces = emDM_getNumFaces;
1556
1557         emdm->dm.getVertCos = emDM_getVertCos;
1558
1559         emdm->dm.getVert = emDM_getVert;
1560         emdm->dm.getEdge = emDM_getEdge;
1561         emdm->dm.getFace = emDM_getFace;
1562         emdm->dm.copyVertArray = emDM_copyVertArray;
1563         emdm->dm.copyEdgeArray = emDM_copyEdgeArray;
1564         emdm->dm.copyFaceArray = emDM_copyFaceArray;
1565         emdm->dm.getFaceDataArray = emDM_getFaceDataArray;
1566
1567         emdm->dm.foreachMappedVert = emDM_foreachMappedVert;
1568         emdm->dm.foreachMappedEdge = emDM_foreachMappedEdge;
1569         emdm->dm.foreachMappedFaceCenter = emDM_foreachMappedFaceCenter;
1570
1571         emdm->dm.drawEdges = emDM_drawEdges;
1572         emdm->dm.drawMappedEdges = emDM_drawMappedEdges;
1573         emdm->dm.drawMappedEdgesInterp = emDM_drawMappedEdgesInterp;
1574         emdm->dm.drawMappedFaces = emDM_drawMappedFaces;
1575         emdm->dm.drawMappedFacesTex = emDM_drawMappedFacesTex;
1576         emdm->dm.drawMappedFacesGLSL = emDM_drawMappedFacesGLSL;
1577         emdm->dm.drawFacesTex = emDM_drawFacesTex;
1578         emdm->dm.drawFacesGLSL = emDM_drawFacesGLSL;
1579         emdm->dm.drawMappedFacesMat = emDM_drawMappedFacesMat;
1580         emdm->dm.drawUVEdges = emDM_drawUVEdges;
1581
1582         emdm->dm.release = emDM_release;
1583         
1584         emdm->em = em;
1585         emdm->vertexCos = vertexCos;
1586
1587         if(CustomData_has_layer(&em->vdata, CD_MDEFORMVERT)) {
1588                 EditVert *eve;
1589                 int i;
1590
1591                 DM_add_vert_layer(&emdm->dm, CD_MDEFORMVERT, CD_CALLOC, NULL);
1592
1593                 for(eve = em->verts.first, i = 0; eve; eve = eve->next, ++i)
1594                         DM_set_vert_data(&emdm->dm, i, CD_MDEFORMVERT,
1595                                                          CustomData_em_get(&em->vdata, eve->data, CD_MDEFORMVERT));
1596         }
1597
1598         if(vertexCos) {
1599                 EditVert *eve;
1600                 EditFace *efa;
1601                 int totface = BLI_countlist(&em->faces);
1602                 int i;
1603
1604                 for (i=0,eve=em->verts.first; eve; eve= eve->next)
1605                         eve->tmp.l = (intptr_t) i++;
1606
1607                 emdm->vertexNos = MEM_callocN(sizeof(*emdm->vertexNos)*i, "emdm_vno");
1608                 emdm->faceNos = MEM_mallocN(sizeof(*emdm->faceNos)*totface, "emdm_vno");
1609
1610                 for(i=0, efa= em->faces.first; efa; i++, efa=efa->next) {
1611                         float *v1 = vertexCos[(int) efa->v1->tmp.l];
1612                         float *v2 = vertexCos[(int) efa->v2->tmp.l];
1613                         float *v3 = vertexCos[(int) efa->v3->tmp.l];
1614                         float *no = emdm->faceNos[i];
1615                         
1616                         if(efa->v4) {
1617                                 float *v4 = vertexCos[(int) efa->v4->tmp.l];
1618
1619                                 normal_quad_v3( no,v1, v2, v3, v4);
1620                                 add_v3_v3(emdm->vertexNos[(int) efa->v4->tmp.l], no);
1621                         }
1622                         else {
1623                                 normal_tri_v3( no,v1, v2, v3);
1624                         }
1625
1626                         add_v3_v3(emdm->vertexNos[(int) efa->v1->tmp.l], no);
1627                         add_v3_v3(emdm->vertexNos[(int) efa->v2->tmp.l], no);
1628                         add_v3_v3(emdm->vertexNos[(int) efa->v3->tmp.l], no);
1629                 }
1630
1631                 for(i=0, eve= em->verts.first; eve; i++, eve=eve->next) {
1632                         float *no = emdm->vertexNos[i];
1633                         /* following Mesh convention; we use vertex coordinate itself
1634                          * for normal in this case */
1635                         if (normalize_v3(no) == 0.0f) {
1636                                 normalize_v3_v3(no, vertexCos[i]);
1637                         }
1638                 }
1639         }
1640
1641         return (DerivedMesh*) emdm;
1642 }
1643
1644 /***/
1645
1646 DerivedMesh *mesh_create_derived_for_modifier(Scene *scene, Object *ob, ModifierData *md)
1647 {
1648         Mesh *me = ob->data;
1649         ModifierTypeInfo *mti = modifierType_getInfo(md->type);
1650         DerivedMesh *dm;
1651
1652         md->scene= scene;
1653         
1654         if (!(md->mode&eModifierMode_Realtime)) return NULL;
1655         if (mti->isDisabled && mti->isDisabled(md, 0)) return NULL;
1656
1657         if (mti->type==eModifierTypeType_OnlyDeform) {
1658                 int numVerts;
1659                 float (*deformedVerts)[3] = mesh_getVertexCos(me, &numVerts);
1660
1661                 mti->deformVerts(md, ob, NULL, deformedVerts, numVerts, 0, 0);
1662                 dm = mesh_create_derived(me, ob, deformedVerts);
1663
1664                 MEM_freeN(deformedVerts);
1665         } else {
1666                 DerivedMesh *tdm = mesh_create_derived(me, ob, NULL);
1667                 dm = mti->applyModifier(md, ob, tdm, 0, 0);
1668
1669                 if(tdm != dm) tdm->release(tdm);
1670         }
1671
1672         return dm;
1673 }
1674
1675 static float *get_editmesh_orco_verts(EditMesh *em)
1676 {
1677         EditVert *eve;
1678         float *orco;
1679         int a, totvert;
1680
1681         /* these may not really be the orco's, but it's only for preview.
1682          * could be solver better once, but isn't simple */
1683
1684         totvert= 0;
1685         for(eve=em->verts.first; eve; eve=eve->next)
1686                 totvert++;
1687         
1688         orco = MEM_mallocN(sizeof(float)*3*totvert, "EditMesh Orco");
1689
1690         for(a=0, eve=em->verts.first; eve; eve=eve->next, a+=3) {
1691                 copy_v3_v3(orco+a, eve->co);
1692         }
1693         
1694         return orco;
1695 }
1696
1697 /* orco custom data layer */
1698
1699 static void *get_orco_coords_dm(Object *ob, EditMesh *em, int layer, int *free)
1700 {
1701         *free= 0;
1702
1703         if(layer == CD_ORCO) {
1704                 /* get original coordinates */
1705                 *free= 1;
1706
1707                 if(em)
1708                         return (float(*)[3])get_editmesh_orco_verts(em);
1709                 else
1710                         return (float(*)[3])get_mesh_orco_verts(ob);
1711         }
1712         else if(layer == CD_CLOTH_ORCO) {
1713                 /* apply shape key for cloth, this should really be solved
1714                    by a more flexible customdata system, but not simple */
1715                 if(!em) {
1716                         ClothModifierData *clmd = (ClothModifierData *)modifiers_findByType(ob, eModifierType_Cloth);
1717                         KeyBlock *kb= key_get_keyblock(ob_get_key(ob), clmd->sim_parms->shapekey_rest);
1718
1719                         if(kb->data)
1720                                 return kb->data;
1721                 }
1722
1723                 return NULL;
1724         }
1725
1726         return NULL;
1727 }
1728
1729 static DerivedMesh *create_orco_dm(Object *ob, Mesh *me, EditMesh *em, int layer)
1730 {
1731         DerivedMesh *dm;
1732         float (*orco)[3];
1733         int free;
1734
1735         if(em) dm= CDDM_from_editmesh(em, me);
1736         else dm= CDDM_from_mesh(me, ob);
1737
1738         orco= get_orco_coords_dm(ob, em, layer, &free);
1739
1740         if(orco) {
1741                 CDDM_apply_vert_coords(dm, orco);
1742                 if(free) MEM_freeN(orco);
1743         }
1744
1745         CDDM_calc_normals(dm);
1746
1747         return dm;
1748 }
1749
1750 static void add_orco_dm(Object *ob, EditMesh *em, DerivedMesh *dm, DerivedMesh *orcodm, int layer)
1751 {
1752         float (*orco)[3], (*layerorco)[3];
1753         int totvert, free;
1754
1755         totvert= dm->getNumVerts(dm);
1756
1757         if(orcodm) {
1758                 orco= MEM_callocN(sizeof(float)*3*totvert, "dm orco");
1759                 free= 1;
1760
1761                 if(orcodm->getNumVerts(orcodm) == totvert)
1762                         orcodm->getVertCos(orcodm, orco);
1763                 else
1764                         dm->getVertCos(dm, orco);
1765         }
1766         else
1767                 orco= get_orco_coords_dm(ob, em, layer, &free);
1768
1769         if(orco) {
1770                 if(layer == CD_ORCO)
1771                         transform_mesh_orco_verts(ob->data, orco, totvert, 0);
1772
1773                 if(!(layerorco = DM_get_vert_data_layer(dm, layer))) {
1774                         DM_add_vert_layer(dm, layer, CD_CALLOC, NULL);
1775                         layerorco = DM_get_vert_data_layer(dm, layer);
1776                 }
1777
1778                 memcpy(layerorco, orco, sizeof(float)*3*totvert);
1779                 if(free) MEM_freeN(orco);
1780         }
1781 }
1782
1783 /* weight paint colors */
1784
1785 /* Something of a hack, at the moment deal with weightpaint
1786  * by tucking into colors during modifier eval, only in
1787  * wpaint mode. Works ok but need to make sure recalc
1788  * happens on enter/exit wpaint.
1789  */
1790
1791 void weight_to_rgb(float r_rgb[3], const float weight)
1792 {
1793         const float blend= ((weight/2.0f)+0.5f);
1794
1795         if (weight<=0.25f){     // blue->cyan
1796                 r_rgb[0]= 0.0f;
1797                 r_rgb[1]= blend*weight*4.0f;
1798                 r_rgb[2]= blend;
1799         }
1800         else if (weight<=0.50f){        // cyan->green
1801                 r_rgb[0]= 0.0f;
1802                 r_rgb[1]= blend;
1803                 r_rgb[2]= blend*(1.0f-((weight-0.25f)*4.0f));
1804         }
1805         else if (weight <= 0.75f){      // green->yellow
1806                 r_rgb[0]= blend * ((weight-0.50f)*4.0f);
1807                 r_rgb[1]= blend;
1808                 r_rgb[2]= 0.0f;
1809         }
1810         else if (weight <= 1.0f){ // yellow->red
1811                 r_rgb[0]= blend;
1812                 r_rgb[1]= blend * (1.0f-((weight-0.75f)*4.0f));
1813                 r_rgb[2]= 0.0f;
1814         }
1815 }
1816
1817 /* draw_flag's for calc_weightpaint_vert_color */
1818 enum {
1819         CALC_WP_MULTIPAINT= (1<<0),
1820         CALC_WP_AUTO_NORMALIZE= (1<<1),
1821 };
1822
1823 static void calc_weightpaint_vert_color(Object *ob, ColorBand *coba, int vert, unsigned char *col, char *dg_flags, int selected, int UNUSED(unselected), const int draw_flag)
1824 {
1825         Mesh *me = ob->data;
1826         float colf[4], input = 0.0f;
1827         int i;
1828
1829         
1830         int make_black= FALSE;
1831
1832         if (me->dvert) {
1833                 if ((selected > 1) && (draw_flag & CALC_WP_MULTIPAINT)) {
1834                         
1835                         int was_a_nonzero= FALSE;
1836                         for (i=0; i<me->dvert[vert].totweight; i++) {
1837                                 /* in multipaint, get the average if auto normalize is inactive
1838                                  * get the sum if it is active */
1839                                 if(dg_flags[me->dvert[vert].dw[i].def_nr]) {
1840                                         if(me->dvert[vert].dw[i].weight) {
1841                                                 input+= me->dvert[vert].dw[i].weight;
1842                                                 was_a_nonzero= TRUE;
1843                                         }
1844                                 }
1845                         }
1846
1847                         /* make it black if the selected groups have no weight on a vertex */
1848                         if(was_a_nonzero == FALSE) {
1849                                 make_black = TRUE;
1850                         }
1851                         else if ((draw_flag & CALC_WP_AUTO_NORMALIZE) == FALSE) {
1852                                 input /= selected; /* get the average */
1853                         }
1854                 }
1855                 else {
1856                         /* default, non tricky behavior */
1857                         for (i=0; i<me->dvert[vert].totweight; i++) {
1858                                 if (me->dvert[vert].dw[i].def_nr==ob->actdef-1) {
1859                                         input+=me->dvert[vert].dw[i].weight;
1860                                 }
1861                         }
1862                 }
1863         }
1864         
1865         if (make_black) {
1866                 col[3] = 0;
1867                 col[2] = 0;
1868                 col[1] = 0;
1869                 col[0] = 255;
1870                 return;
1871         }
1872
1873         CLAMP(input, 0.0f, 1.0f);       
1874
1875         if(coba)
1876                 do_colorband(coba, input, colf);
1877         else
1878                 weight_to_rgb(colf, input);
1879         
1880         col[3] = (unsigned char)(colf[0] * 255.0f);
1881         col[2] = (unsigned char)(colf[1] * 255.0f);
1882         col[1] = (unsigned char)(colf[2] * 255.0f);
1883         col[0] = 255;
1884 }
1885
1886 static ColorBand *stored_cb= NULL;
1887
1888 void vDM_ColorBand_store(ColorBand *coba)
1889 {
1890         stored_cb= coba;
1891 }
1892
1893 static void add_weight_mcol_dm(Object *ob, DerivedMesh *dm, int const draw_flag)
1894 {
1895         Mesh *me = ob->data;
1896         MFace *mf = me->mface;
1897         ColorBand *coba= stored_cb;     /* warning, not a local var */
1898         unsigned char *wtcol;
1899         int i;
1900         
1901         int defbase_len = BLI_countlist(&ob->defbase);
1902         char *defbase_sel = MEM_mallocN(defbase_len * sizeof(char), __func__);
1903         int selected = get_selected_defgroups(ob, defbase_sel, defbase_len);
1904         int unselected = defbase_len - selected;
1905
1906         wtcol = MEM_callocN (sizeof (unsigned char) * me->totface*4*4, "weightmap");
1907         
1908         memset(wtcol, 0x55, sizeof (unsigned char) * me->totface*4*4);
1909         for (i=0; i<me->totface; i++, mf++) {
1910                 calc_weightpaint_vert_color(ob, coba, mf->v1, &wtcol[(i*4 + 0)*4], defbase_sel, selected, unselected, draw_flag);
1911                 calc_weightpaint_vert_color(ob, coba, mf->v2, &wtcol[(i*4 + 1)*4], defbase_sel, selected, unselected, draw_flag);
1912                 calc_weightpaint_vert_color(ob, coba, mf->v3, &wtcol[(i*4 + 2)*4], defbase_sel, selected, unselected, draw_flag);
1913                 if (mf->v4)
1914                         calc_weightpaint_vert_color(ob, coba, mf->v4, &wtcol[(i*4 + 3)*4], defbase_sel, selected, unselected, draw_flag);
1915         }
1916         
1917         MEM_freeN(defbase_sel);
1918
1919         CustomData_add_layer(&dm->faceData, CD_WEIGHT_MCOL, CD_ASSIGN, wtcol, dm->numFaceData);
1920 }
1921
1922 /* new value for useDeform -1  (hack for the gameengine):
1923  * - apply only the modifier stack of the object, skipping the virtual modifiers,
1924  * - don't apply the key
1925  * - apply deform modifiers and input vertexco
1926  */
1927 static void mesh_calc_modifiers(Scene *scene, Object *ob, float (*inputVertexCos)[3],
1928                                                                 DerivedMesh **deform_r, DerivedMesh **final_r,
1929                                                                 int useRenderParams, int useDeform,
1930                                                                 int needMapping, CustomDataMask dataMask, int index, int useCache)
1931 {
1932         Mesh *me = ob->data;
1933         ModifierData *firstmd, *md;
1934         LinkNode *datamasks, *curr;
1935         CustomDataMask mask, nextmask, append_mask = 0;
1936         float (*deformedVerts)[3] = NULL;
1937         DerivedMesh *dm, *orcodm, *clothorcodm, *finaldm;
1938         int numVerts = me->totvert;
1939         int required_mode;
1940         int isPrevDeform= FALSE;
1941         int skipVirtualArmature = (useDeform < 0);
1942         MultiresModifierData *mmd= get_multires_modifier(scene, ob, 0);
1943         int has_multires = mmd != NULL, multires_applied = 0;
1944         int sculpt_mode = ob->mode & OB_MODE_SCULPT && ob->sculpt;
1945
1946         int draw_flag= ((scene->toolsettings->multipaint ? CALC_WP_MULTIPAINT : 0) |
1947                         (scene->toolsettings->auto_normalize ? CALC_WP_AUTO_NORMALIZE : 0));
1948
1949         if(mmd && !mmd->sculptlvl)
1950                 has_multires = 0;
1951
1952         if(!skipVirtualArmature) {
1953                 firstmd = modifiers_getVirtualModifierList(ob);
1954         }
1955         else {
1956                 /* game engine exception */
1957                 firstmd = ob->modifiers.first;
1958                 if(firstmd && firstmd->type == eModifierType_Armature)
1959                         firstmd = firstmd->next;
1960         }
1961
1962         md = firstmd;
1963
1964         modifiers_clearErrors(ob);
1965
1966         if(useRenderParams) required_mode = eModifierMode_Render;
1967         else required_mode = eModifierMode_Realtime;
1968
1969         datamasks = modifiers_calcDataMasks(scene, ob, md, dataMask, required_mode);
1970         curr = datamasks;
1971
1972         if(deform_r) *deform_r = NULL;
1973         *final_r = NULL;
1974
1975         if(useDeform) {
1976                 if(inputVertexCos)
1977                         deformedVerts = inputVertexCos;
1978                 
1979                 /* Apply all leading deforming modifiers */
1980                 for(;md; md = md->next, curr = curr->next) {
1981                         ModifierTypeInfo *mti = modifierType_getInfo(md->type);
1982
1983                         md->scene= scene;
1984                         
1985                         if(!modifier_isEnabled(scene, md, required_mode)) continue;
1986                         if(useDeform < 0 && mti->dependsOnTime && mti->dependsOnTime(md)) continue;
1987
1988                         if(mti->type == eModifierTypeType_OnlyDeform) {
1989                                 if(!deformedVerts)
1990                                         deformedVerts = mesh_getVertexCos(me, &numVerts);
1991
1992                                 mti->deformVerts(md, ob, NULL, deformedVerts, numVerts, useRenderParams, useDeform);
1993                         } else {
1994                                 break;
1995                         }
1996                         
1997                         /* grab modifiers until index i */
1998                         if((index >= 0) && (modifiers_indexInObject(ob, md) >= index))
1999                                 break;
2000                 }
2001
2002                 /* Result of all leading deforming modifiers is cached for
2003                  * places that wish to use the original mesh but with deformed
2004                  * coordinates (vpaint, etc.)
2005                  */
2006                 if (deform_r) {
2007                         *deform_r = CDDM_from_mesh(me, ob);
2008
2009                         if(deformedVerts) {
2010                                 CDDM_apply_vert_coords(*deform_r, deformedVerts);
2011                                 CDDM_calc_normals(*deform_r);
2012                         }
2013                 }
2014         } else {
2015                 /* default behaviour for meshes */
2016                 if(inputVertexCos)
2017                         deformedVerts = inputVertexCos;
2018                 else
2019                         deformedVerts = mesh_getVertexCos(me, &numVerts);
2020         }
2021
2022
2023         /* Now apply all remaining modifiers. If useDeform is off then skip
2024          * OnlyDeform ones. 
2025          */
2026         dm = NULL;
2027         orcodm = NULL;
2028         clothorcodm = NULL;
2029
2030         for(;md; md = md->next, curr = curr->next) {
2031                 ModifierTypeInfo *mti = modifierType_getInfo(md->type);
2032
2033                 md->scene= scene;
2034
2035                 if(!modifier_isEnabled(scene, md, required_mode)) continue;
2036                 if(mti->type == eModifierTypeType_OnlyDeform && !useDeform) continue;
2037                 if((mti->flags & eModifierTypeFlag_RequiresOriginalData) && dm) {
2038                         modifier_setError(md, "Modifier requires original data, bad stack position.");
2039                         continue;
2040                 }
2041                 if(sculpt_mode && (!has_multires || multires_applied)) {
2042                         int unsupported= 0;
2043
2044                         if(scene->toolsettings->sculpt->flags & SCULPT_ONLY_DEFORM)
2045                                 unsupported|= mti->type != eModifierTypeType_OnlyDeform;
2046
2047                         unsupported|= md->type == eModifierType_Multires && ((MultiresModifierData*)md)->sculptlvl==0;
2048                         unsupported|= multires_applied;
2049
2050                         if(unsupported) {
2051                                 modifier_setError(md, "Not supported in sculpt mode.");
2052                                 continue;
2053                         }
2054                 }
2055                 if(needMapping && !modifier_supportsMapping(md)) continue;
2056                 if(useDeform < 0 && mti->dependsOnTime && mti->dependsOnTime(md)) continue;
2057
2058                 /* add an orco layer if needed by this modifier */
2059                 if(mti->requiredDataMask)
2060                         mask = mti->requiredDataMask(ob, md);
2061                 else
2062                         mask = 0;
2063
2064                 if(dm && (mask & CD_MASK_ORCO))
2065                         add_orco_dm(ob, NULL, dm, orcodm, CD_ORCO);
2066
2067                 /* How to apply modifier depends on (a) what we already have as
2068                  * a result of previous modifiers (could be a DerivedMesh or just
2069                  * deformed vertices) and (b) what type the modifier is.
2070                  */
2071
2072                 if(mti->type == eModifierTypeType_OnlyDeform) {
2073                         /* No existing verts to deform, need to build them. */
2074                         if(!deformedVerts) {
2075                                 if(dm) {
2076                                         /* Deforming a derived mesh, read the vertex locations
2077                                          * out of the mesh and deform them. Once done with this
2078                                          * run of deformers verts will be written back.
2079                                          */
2080                                         numVerts = dm->getNumVerts(dm);
2081                                         deformedVerts =
2082                                                 MEM_mallocN(sizeof(*deformedVerts) * numVerts, "dfmv");
2083                                         dm->getVertCos(dm, deformedVerts);
2084                                 } else {
2085                                         deformedVerts = mesh_getVertexCos(me, &numVerts);
2086                                 }
2087                         }
2088
2089                         /* if this is not the last modifier in the stack then recalculate the normals
2090                          * to avoid giving bogus normals to the next modifier see: [#23673] */
2091                         if(isPrevDeform &&  mti->dependsOnNormals && mti->dependsOnNormals(md)) {
2092                                 /* XXX, this covers bug #23673, but we may need normal calc for other types */
2093                                 if(dm && dm->type == DM_TYPE_CDDM) {
2094                                         CDDM_apply_vert_coords(dm, deformedVerts);
2095                                         CDDM_calc_normals(dm);
2096                                 }
2097                         }
2098
2099                         mti->deformVerts(md, ob, dm, deformedVerts, numVerts, useRenderParams, useDeform);
2100                 } else {
2101                         DerivedMesh *ndm;
2102
2103                         /* determine which data layers are needed by following modifiers */
2104                         if(curr->next)
2105                                 nextmask= (CustomDataMask)GET_INT_FROM_POINTER(curr->next->link);
2106                         else
2107                                 nextmask= dataMask;
2108
2109                         /* apply vertex coordinates or build a DerivedMesh as necessary */
2110                         if(dm) {
2111                                 if(deformedVerts) {
2112                                         DerivedMesh *tdm = CDDM_copy(dm);
2113                                         dm->release(dm);
2114                                         dm = tdm;
2115
2116                                         CDDM_apply_vert_coords(dm, deformedVerts);
2117                                         CDDM_calc_normals(dm);
2118                                 }
2119                         } else {
2120                                 dm = CDDM_from_mesh(me, ob);
2121
2122                                 if(deformedVerts) {
2123                                         CDDM_apply_vert_coords(dm, deformedVerts);
2124                                         CDDM_calc_normals(dm);
2125                                 }
2126
2127                                 if((dataMask & CD_MASK_WEIGHT_MCOL) && (ob->mode & OB_MODE_WEIGHT_PAINT))
2128                                         add_weight_mcol_dm(ob, dm, draw_flag); 
2129
2130                                 /* Constructive modifiers need to have an origindex
2131                                  * otherwise they wont have anywhere to copy the data from.
2132                                  *
2133                                  * Also create ORIGINDEX data if any of the following modifiers
2134                                  * requests it, this way Mirror, Solidify etc will keep ORIGINDEX
2135                                  * data by using generic DM_copy_vert_data() functions.
2136                                  */
2137                                 if(needMapping || (nextmask & CD_MASK_ORIGINDEX)) {
2138                                         /* calc */
2139                                         DM_add_vert_layer(dm, CD_ORIGINDEX, CD_CALLOC, NULL);
2140                                         DM_add_edge_layer(dm, CD_ORIGINDEX, CD_CALLOC, NULL);
2141                                         DM_add_face_layer(dm, CD_ORIGINDEX, CD_CALLOC, NULL);
2142
2143                                         range_vn_i(DM_get_vert_data_layer(dm, CD_ORIGINDEX), dm->numVertData, 0);
2144                                         range_vn_i(DM_get_edge_data_layer(dm, CD_ORIGINDEX), dm->numEdgeData, 0);
2145                                         range_vn_i(DM_get_face_data_layer(dm, CD_ORIGINDEX), dm->numFaceData, 0);
2146                                 }
2147                         }
2148
2149                         
2150                         /* set the DerivedMesh to only copy needed data */
2151                         mask= (CustomDataMask)GET_INT_FROM_POINTER(curr->link);
2152                         /* needMapping check here fixes bug [#28112], otherwise its
2153                          * possible that it wont be copied */
2154                         mask |= append_mask;
2155                         DM_set_only_copy(dm, mask | (needMapping ? CD_MASK_ORIGINDEX : 0));
2156                         
2157                         /* add cloth rest shape key if need */
2158                         if(mask & CD_MASK_CLOTH_ORCO)
2159                                 add_orco_dm(ob, NULL, dm, clothorcodm, CD_CLOTH_ORCO);
2160
2161                         /* add an origspace layer if needed */
2162                         if(((CustomDataMask)GET_INT_FROM_POINTER(curr->link)) & CD_MASK_ORIGSPACE)
2163                                 if(!CustomData_has_layer(&dm->faceData, CD_ORIGSPACE))
2164                                         DM_add_face_layer(dm, CD_ORIGSPACE, CD_DEFAULT, NULL);
2165
2166                         ndm = mti->applyModifier(md, ob, dm, useRenderParams, useCache);
2167
2168                         if(ndm) {
2169                                 /* if the modifier returned a new dm, release the old one */
2170                                 if(dm && dm != ndm) dm->release(dm);
2171
2172                                 dm = ndm;
2173
2174                                 if(deformedVerts) {
2175                                         if(deformedVerts != inputVertexCos)
2176                                                 MEM_freeN(deformedVerts);
2177
2178                                         deformedVerts = NULL;
2179                                 }
2180                         } 
2181
2182                         /* create an orco derivedmesh in parallel */
2183                         if(nextmask & CD_MASK_ORCO) {
2184                                 if(!orcodm)
2185                                         orcodm= create_orco_dm(ob, me, NULL, CD_ORCO);
2186
2187                                 nextmask &= ~CD_MASK_ORCO;
2188                                 DM_set_only_copy(orcodm, nextmask | CD_MASK_ORIGINDEX);
2189                                 ndm = mti->applyModifier(md, ob, orcodm, useRenderParams, 0);
2190
2191                                 if(ndm) {
2192                                         /* if the modifier returned a new dm, release the old one */
2193                                         if(orcodm && orcodm != ndm) orcodm->release(orcodm);
2194                                         orcodm = ndm;
2195                                 }
2196                         }
2197
2198                         /* create cloth orco derivedmesh in parallel */
2199                         if(nextmask & CD_MASK_CLOTH_ORCO) {
2200                                 if(!clothorcodm)
2201                                         clothorcodm= create_orco_dm(ob, me, NULL, CD_CLOTH_ORCO);
2202
2203                                 nextmask &= ~CD_MASK_CLOTH_ORCO;
2204                                 DM_set_only_copy(clothorcodm, nextmask | CD_MASK_ORIGINDEX);
2205                                 ndm = mti->applyModifier(md, ob, clothorcodm, useRenderParams, 0);
2206
2207                                 if(ndm) {
2208                                         /* if the modifier returned a new dm, release the old one */
2209                                         if(clothorcodm && clothorcodm != ndm) clothorcodm->release(clothorcodm);
2210                                         clothorcodm = ndm;
2211                                 }
2212                         }
2213
2214                         /* in case of dynamic paint, make sure preview mask remains for following modifiers */
2215                         if (md->type == eModifierType_DynamicPaint)
2216                                 append_mask |= CD_MASK_WEIGHT_MCOL;
2217                 }
2218
2219                 isPrevDeform= (mti->type == eModifierTypeType_OnlyDeform);
2220
2221                 /* grab modifiers until index i */
2222                 if((index >= 0) && (modifiers_indexInObject(ob, md) >= index))
2223                         break;
2224
2225                 if(sculpt_mode && md->type == eModifierType_Multires)
2226                         multires_applied = 1;
2227         }
2228
2229         for(md=firstmd; md; md=md->next)
2230                 modifier_freeTemporaryData(md);
2231
2232         /* Yay, we are done. If we have a DerivedMesh and deformed vertices
2233          * need to apply these back onto the DerivedMesh. If we have no
2234          * DerivedMesh then we need to build one.
2235          */
2236         if(dm && deformedVerts) {
2237                 finaldm = CDDM_copy(dm);
2238
2239                 dm->release(dm);
2240
2241                 CDDM_apply_vert_coords(finaldm, deformedVerts);
2242                 CDDM_calc_normals(finaldm);
2243
2244                 if((dataMask & CD_MASK_WEIGHT_MCOL) && (ob->mode & OB_MODE_WEIGHT_PAINT))
2245                         add_weight_mcol_dm(ob, finaldm, draw_flag);
2246         } else if(dm) {
2247                 finaldm = dm;
2248         } else {
2249                 finaldm = CDDM_from_mesh(me, ob);
2250
2251                 if(deformedVerts) {
2252                         CDDM_apply_vert_coords(finaldm, deformedVerts);
2253                         CDDM_calc_normals(finaldm);
2254                 }
2255
2256                 if((dataMask & CD_MASK_WEIGHT_MCOL) && (ob->mode & OB_MODE_WEIGHT_PAINT))
2257                         add_weight_mcol_dm(ob, finaldm, draw_flag);
2258         }
2259
2260         /* add an orco layer if needed */
2261         if(dataMask & CD_MASK_ORCO) {
2262                 add_orco_dm(ob, NULL, finaldm, orcodm, CD_ORCO);
2263
2264                 if(deform_r && *deform_r)
2265                         add_orco_dm(ob, NULL, *deform_r, NULL, CD_ORCO);
2266         }
2267
2268 #ifdef WITH_GAMEENGINE
2269         /* NavMesh - this is a hack but saves having a NavMesh modifier */
2270         if ((ob->gameflag & OB_NAVMESH) && (finaldm->type == DM_TYPE_CDDM)) {
2271                 DerivedMesh *tdm;
2272                 tdm= navmesh_dm_createNavMeshForVisualization(finaldm);
2273                 if (finaldm != tdm) {
2274                         finaldm->release(finaldm);
2275                         finaldm= tdm;
2276                 }
2277         }
2278 #endif /* WITH_GAMEENGINE */
2279
2280         *final_r = finaldm;
2281
2282         if(orcodm)
2283                 orcodm->release(orcodm);
2284         if(clothorcodm)
2285                 clothorcodm->release(clothorcodm);
2286
2287         if(deformedVerts && deformedVerts != inputVertexCos)
2288                 MEM_freeN(deformedVerts);
2289
2290         BLI_linklist_free(datamasks, NULL);
2291 }
2292
2293 float (*editmesh_get_vertex_cos(EditMesh *em, int *numVerts_r))[3]
2294 {
2295         int i, numVerts = *numVerts_r = BLI_countlist(&em->verts);
2296         float (*cos)[3];
2297         EditVert *eve;
2298
2299         cos = MEM_mallocN(sizeof(*cos)*numVerts, "vertexcos");
2300         for (i=0,eve=em->verts.first; i<numVerts; i++,eve=eve->next) {
2301                 copy_v3_v3(cos[i], eve->co);
2302         }
2303
2304         return cos;
2305 }
2306
2307 int editmesh_modifier_is_enabled(Scene *scene, ModifierData *md, DerivedMesh *dm)
2308 {
2309         ModifierTypeInfo *mti = modifierType_getInfo(md->type);
2310         int required_mode = eModifierMode_Realtime | eModifierMode_Editmode;
2311
2312         if(!modifier_isEnabled(scene, md, required_mode)) return 0;
2313         if((mti->flags & eModifierTypeFlag_RequiresOriginalData) && dm) {
2314                 modifier_setError(md, "Modifier requires original data, bad stack position.");
2315                 return 0;
2316         }
2317         
2318         return 1;
2319 }
2320
2321 static void editmesh_calc_modifiers(Scene *scene, Object *ob, EditMesh *em, DerivedMesh **cage_r,
2322                                                                         DerivedMesh **final_r,
2323                                                                         CustomDataMask dataMask)
2324 {
2325         ModifierData *md;
2326         float (*deformedVerts)[3] = NULL;
2327         CustomDataMask mask;
2328         DerivedMesh *dm, *orcodm = NULL;
2329         int i, numVerts = 0, cageIndex = modifiers_getCageIndex(scene, ob, NULL, 1);
2330         LinkNode *datamasks, *curr;
2331         int required_mode = eModifierMode_Realtime | eModifierMode_Editmode;
2332
2333         modifiers_clearErrors(ob);
2334
2335         if(cage_r && cageIndex == -1) {
2336                 *cage_r = editmesh_get_derived(em, NULL);
2337         }
2338
2339         dm = NULL;
2340         md = modifiers_getVirtualModifierList(ob);
2341
2342         datamasks = modifiers_calcDataMasks(scene, ob, md, dataMask, required_mode);
2343
2344         curr = datamasks;
2345         for(i = 0; md; i++, md = md->next, curr = curr->next) {
2346                 ModifierTypeInfo *mti = modifierType_getInfo(md->type);
2347
2348                 md->scene= scene;
2349                 
2350                 if(!editmesh_modifier_is_enabled(scene, md, dm))
2351                         continue;
2352
2353                 /* add an orco layer if needed by this modifier */
2354                 if(dm && mti->requiredDataMask) {
2355                         mask = mti->requiredDataMask(ob, md);
2356                         if(mask & CD_MASK_ORCO)
2357                                 add_orco_dm(ob, em, dm, orcodm, CD_ORCO);
2358                 }
2359
2360                 /* How to apply modifier depends on (a) what we already have as
2361                  * a result of previous modifiers (could be a DerivedMesh or just
2362                  * deformed vertices) and (b) what type the modifier is.
2363                  */
2364
2365                 if(mti->type == eModifierTypeType_OnlyDeform) {
2366                         /* No existing verts to deform, need to build them. */
2367                         if(!deformedVerts) {
2368                                 if(dm) {
2369                                         /* Deforming a derived mesh, read the vertex locations
2370                                          * out of the mesh and deform them. Once done with this
2371                                          * run of deformers verts will be written back.
2372                                          */
2373                                         numVerts = dm->getNumVerts(dm);
2374                                         deformedVerts =
2375                                                 MEM_mallocN(sizeof(*deformedVerts) * numVerts, "dfmv");
2376                                         dm->getVertCos(dm, deformedVerts);
2377                                 } else {
2378                                         deformedVerts = editmesh_get_vertex_cos(em, &numVerts);
2379                                 }
2380                         }
2381
2382                         if (mti->deformVertsEM)
2383                                 mti->deformVertsEM(md, ob, em, dm, deformedVerts, numVerts);
2384                         else mti->deformVerts(md, ob, dm, deformedVerts, numVerts, 0, 0);
2385                 } else {
2386                         DerivedMesh *ndm;
2387
2388                         /* apply vertex coordinates or build a DerivedMesh as necessary */
2389                         if(dm) {
2390                                 if(deformedVerts) {
2391                                         DerivedMesh *tdm = CDDM_copy(dm);
2392                                         if(!(cage_r && dm == *cage_r)) dm->release(dm);
2393                                         dm = tdm;
2394
2395                                         CDDM_apply_vert_coords(dm, deformedVerts);
2396                                         CDDM_calc_normals(dm);
2397                                 } else if(cage_r && dm == *cage_r) {
2398                                         /* dm may be changed by this modifier, so we need to copy it
2399                                          */
2400                                         dm = CDDM_copy(dm);
2401                                 }
2402
2403                         } else {
2404                                 dm = CDDM_from_editmesh(em, ob->data);
2405
2406                                 if(deformedVerts) {
2407                                         CDDM_apply_vert_coords(dm, deformedVerts);
2408                                         CDDM_calc_normals(dm);
2409                                 }
2410                         }
2411
2412                         /* create an orco derivedmesh in parallel */
2413                         mask= (CustomDataMask)GET_INT_FROM_POINTER(curr->link);
2414                         if(mask & CD_MASK_ORCO) {
2415                                 if(!orcodm)
2416                                         orcodm= create_orco_dm(ob, ob->data, em, CD_ORCO);
2417
2418                                 mask &= ~CD_MASK_ORCO;
2419                                 DM_set_only_copy(orcodm, mask | CD_MASK_ORIGINDEX);
2420
2421                                 if (mti->applyModifierEM)
2422                                         ndm = mti->applyModifierEM(md, ob, em, orcodm);
2423                                 else
2424                                         ndm = mti->applyModifier(md, ob, orcodm, 0, 0);
2425
2426                                 if(ndm) {
2427                                         /* if the modifier returned a new dm, release the old one */
2428                                         if(orcodm && orcodm != ndm) orcodm->release(orcodm);
2429                                         orcodm = ndm;
2430                                 }
2431                         }
2432
2433                         /* set the DerivedMesh to only copy needed data */
2434                         mask= (CustomDataMask)GET_INT_FROM_POINTER(curr->link); /* CD_MASK_ORCO may have been cleared above */
2435
2436                         DM_set_only_copy(dm, mask | CD_MASK_ORIGINDEX);
2437
2438                         if(mask & CD_MASK_ORIGSPACE)
2439                                 if(!CustomData_has_layer(&dm->faceData, CD_ORIGSPACE))
2440                                         DM_add_face_layer(dm, CD_ORIGSPACE, CD_DEFAULT, NULL);
2441                         
2442                         if (mti->applyModifierEM)
2443                                 ndm = mti->applyModifierEM(md, ob, em, dm);
2444                         else
2445                                 ndm = mti->applyModifier(md, ob, dm, 0, 0);
2446
2447                         if (ndm) {
2448                                 if(dm && dm != ndm)
2449                                         dm->release(dm);
2450
2451                                 dm = ndm;
2452
2453                                 if (deformedVerts) {
2454                                         MEM_freeN(deformedVerts);
2455                                         deformedVerts = NULL;
2456                                 }
2457                         }
2458                 }
2459
2460                 if(cage_r && i == cageIndex) {
2461                         if(dm && deformedVerts) {
2462                                 *cage_r = CDDM_copy(dm);
2463                                 CDDM_apply_vert_coords(*cage_r, deformedVerts);
2464                         } else if(dm) {
2465                                 *cage_r = dm;
2466                         } else {
2467                                 *cage_r =
2468                                         editmesh_get_derived(em,
2469                                                 deformedVerts ? MEM_dupallocN(deformedVerts) : NULL);
2470                         }
2471                 }
2472         }
2473
2474         BLI_linklist_free(datamasks, NULL);
2475
2476         /* Yay, we are done. If we have a DerivedMesh and deformed vertices need
2477          * to apply these back onto the DerivedMesh. If we have no DerivedMesh
2478          * then we need to build one.
2479          */
2480         if(dm && deformedVerts) {
2481                 *final_r = CDDM_copy(dm);
2482
2483                 if(!(cage_r && dm == *cage_r)) dm->release(dm);
2484
2485                 CDDM_apply_vert_coords(*final_r, deformedVerts);
2486                 CDDM_calc_normals(*final_r);
2487         } else if (dm) {
2488                 *final_r = dm;
2489         } else if (!deformedVerts && cage_r && *cage_r) {
2490                 *final_r = *cage_r;
2491         } else {
2492                 *final_r = editmesh_get_derived(em, deformedVerts);
2493                 deformedVerts = NULL;
2494         }
2495
2496         /* add an orco layer if needed */
2497         if(dataMask & CD_MASK_ORCO)
2498                 add_orco_dm(ob, em, *final_r, orcodm, CD_ORCO);
2499
2500         if(orcodm)
2501                 orcodm->release(orcodm);
2502
2503         if(deformedVerts)
2504                 MEM_freeN(deformedVerts);
2505 }
2506
2507 static void clear_mesh_caches(Object *ob)
2508 {
2509         Mesh *me= ob->data;
2510
2511                 /* also serves as signal to remake texspace */
2512         if (ob->bb) {
2513                 MEM_freeN(ob->bb);
2514                 ob->bb = NULL;
2515         }
2516         if (me->bb) {
2517                 MEM_freeN(me->bb);
2518                 me->bb = NULL;
2519         }
2520
2521         freedisplist(&ob->disp);
2522
2523         if (ob->derivedFinal) {
2524                 ob->derivedFinal->needsFree = 1;
2525                 ob->derivedFinal->release(ob->derivedFinal);
2526                 ob->derivedFinal= NULL;
2527         }
2528         if (ob->derivedDeform) {
2529                 ob->derivedDeform->needsFree = 1;
2530                 ob->derivedDeform->release(ob->derivedDeform);
2531                 ob->derivedDeform= NULL;
2532         }
2533
2534         if(ob->sculpt) {
2535                 object_sculpt_modifiers_changed(ob);
2536         }
2537 }
2538
2539 static void mesh_build_data(Scene *scene, Object *ob, CustomDataMask dataMask)
2540 {
2541         Object *obact = scene->basact?scene->basact->object:NULL;
2542         int editing = paint_facesel_test(ob) || paint_vertsel_test(ob);/* paint_vertsel_test */
2543         /* weight paint and face select need original indices because of selection buffer drawing */
2544         int needMapping = (ob==obact) && (editing || (ob->mode & (OB_MODE_WEIGHT_PAINT|OB_MODE_VERTEX_PAINT)));
2545
2546         clear_mesh_caches(ob);
2547
2548         mesh_calc_modifiers(scene, ob, NULL, &ob->derivedDeform,
2549                                                 &ob->derivedFinal, 0, 1,
2550                                                 needMapping, dataMask, -1, 1);
2551
2552         DM_set_object_boundbox (ob, ob->derivedFinal);
2553
2554         ob->derivedFinal->needsFree = 0;
2555         ob->derivedDeform->needsFree = 0;
2556         ob->lastDataMask = dataMask;
2557 }
2558
2559 static void editmesh_build_data(Scene *scene, Object *obedit, EditMesh *em, CustomDataMask dataMask)
2560 {
2561         clear_mesh_caches(obedit);
2562
2563         if (em->derivedFinal) {
2564                 if (em->derivedFinal!=em->derivedCage) {
2565                         em->derivedFinal->needsFree = 1;
2566                         em->derivedFinal->release(em->derivedFinal);
2567                 }
2568                 em->derivedFinal = NULL;
2569         }
2570         if (em->derivedCage) {
2571                 em->derivedCage->needsFree = 1;
2572                 em->derivedCage->release(em->derivedCage);
2573                 em->derivedCage = NULL;
2574         }
2575
2576         editmesh_calc_modifiers(scene, obedit, em, &em->derivedCage, &em->derivedFinal, dataMask);
2577         DM_set_object_boundbox (obedit, em->derivedFinal);
2578
2579         em->lastDataMask = dataMask;
2580         em->derivedFinal->needsFree = 0;
2581         em->derivedCage->needsFree = 0;
2582 }
2583
2584 void makeDerivedMesh(Scene *scene, Object *ob, EditMesh *em, CustomDataMask dataMask)
2585 {
2586         if (em) {
2587                 editmesh_build_data(scene, ob, em, dataMask);
2588         } else {
2589                 mesh_build_data(scene, ob, dataMask);
2590         }
2591 }
2592
2593 /***/
2594
2595 DerivedMesh *mesh_get_derived_final(Scene *scene, Object *ob, CustomDataMask dataMask)
2596 {
2597         /* if there's no derived mesh or the last data mask used doesn't include
2598          * the data we need, rebuild the derived mesh
2599          */
2600         if(!ob->derivedFinal || (dataMask & ob->lastDataMask) != dataMask)
2601                 mesh_build_data(scene, ob, dataMask);
2602
2603         return ob->derivedFinal;
2604 }
2605
2606 DerivedMesh *mesh_get_derived_deform(Scene *scene, Object *ob, CustomDataMask dataMask)
2607 {
2608         /* if there's no derived mesh or the last data mask used doesn't include
2609          * the data we need, rebuild the derived mesh
2610          */
2611         if(!ob->derivedDeform || (dataMask & ob->lastDataMask) != dataMask)
2612                 mesh_build_data(scene, ob, dataMask);
2613
2614         return ob->derivedDeform;
2615 }
2616
2617 DerivedMesh *mesh_create_derived_render(Scene *scene, Object *ob, CustomDataMask dataMask)
2618 {
2619         DerivedMesh *final;
2620         
2621         mesh_calc_modifiers(scene, ob, NULL, NULL, &final, 1, 1, 0, dataMask, -1, 0);
2622
2623         return final;
2624 }
2625
2626 DerivedMesh *mesh_create_derived_index_render(Scene *scene, Object *ob, CustomDataMask dataMask, int index)
2627 {
2628         DerivedMesh *final;
2629         
2630         mesh_calc_modifiers(scene, ob, NULL, NULL, &final, 1, 1, 0, dataMask, index, 0);
2631
2632         return final;
2633 }
2634
2635 DerivedMesh *mesh_create_derived_view(Scene *scene, Object *ob, CustomDataMask dataMask)
2636 {
2637         DerivedMesh *final;
2638
2639         mesh_calc_modifiers(scene, ob, NULL, NULL, &final, 0, 1, 0, dataMask, -1, 0);
2640
2641         return final;
2642 }
2643
2644 DerivedMesh *mesh_create_derived_no_deform(Scene *scene, Object *ob, float (*vertCos)[3],
2645                                                                                    CustomDataMask dataMask)
2646 {
2647         DerivedMesh *final;
2648         
2649         mesh_calc_modifiers(scene, ob, vertCos, NULL, &final, 0, 0, 0, dataMask, -1, 0);
2650
2651         return final;
2652 }
2653
2654 DerivedMesh *mesh_create_derived_no_virtual(Scene *scene, Object *ob, float (*vertCos)[3],
2655                                                                                         CustomDataMask dataMask)
2656 {
2657         DerivedMesh *final;
2658         
2659         mesh_calc_modifiers(scene, ob, vertCos, NULL, &final, 0, -1, 0, dataMask, -1, 0);
2660
2661         return final;
2662 }
2663
2664 DerivedMesh *mesh_create_derived_physics(Scene *scene, Object *ob, float (*vertCos)[3],
2665                                                                                         CustomDataMask dataMask)
2666 {
2667         DerivedMesh *final;
2668         
2669         mesh_calc_modifiers(scene, ob, vertCos, NULL, &final, 0, -1, 1, dataMask, -1, 0);
2670
2671         return final;
2672 }
2673
2674 DerivedMesh *mesh_create_derived_no_deform_render(Scene *scene, Object *ob,
2675                                                                                                   float (*vertCos)[3],
2676                                                                                                   CustomDataMask dataMask)
2677 {
2678         DerivedMesh *final;
2679
2680         mesh_calc_modifiers(scene, ob, vertCos, NULL, &final, 1, 0, 0, dataMask, -1, 0);
2681
2682         return final;
2683 }
2684
2685 /***/
2686
2687 DerivedMesh *editmesh_get_derived_cage_and_final(Scene *scene, Object *obedit, EditMesh *em, DerivedMesh **final_r,
2688                                                                                                  CustomDataMask dataMask)
2689 {
2690         /* if there's no derived mesh or the last data mask used doesn't include
2691          * the data we need, rebuild the derived mesh
2692          */
2693         if(!em->derivedCage ||
2694            (em->lastDataMask & dataMask) != dataMask)
2695                 editmesh_build_data(scene, obedit, em, dataMask);
2696
2697         *final_r = em->derivedFinal;
2698         return em->derivedCage;
2699 }
2700
2701 DerivedMesh *editmesh_get_derived_cage(Scene *scene, Object *obedit, EditMesh *em, CustomDataMask dataMask)
2702 {
2703         /* if there's no derived mesh or the last data mask used doesn't include
2704          * the data we need, rebuild the derived mesh
2705          */
2706         if(!em->derivedCage ||
2707            (em->lastDataMask & dataMask) != dataMask)
2708                 editmesh_build_data(scene, obedit, em, dataMask);
2709
2710         return em->derivedCage;
2711 }
2712
2713 DerivedMesh *editmesh_get_derived_base(Object *UNUSED(obedit), EditMesh *em)
2714 {
2715         return editmesh_get_derived(em, NULL);
2716 }
2717
2718
2719 /* ********* For those who don't grasp derived stuff! (ton) :) *************** */
2720
2721 static void make_vertexcosnos__mapFunc(void *userData, int index, float *co, float *no_f, short *no_s)
2722 {
2723         float *vec = userData;
2724         
2725         vec+= 6*index;
2726
2727         /* check if we've been here before (normal should not be 0) */
2728         if(vec[3] || vec[4] || vec[5]) return;
2729
2730         copy_v3_v3(vec, co);
2731         vec+= 3;
2732         if(no_f) {
2733                 copy_v3_v3(vec, no_f);
2734         }
2735         else {
2736                 normal_short_to_float_v3(vec, no_s);
2737         }
2738 }
2739
2740 /* always returns original amount me->totvert of vertices and normals, but fully deformed and subsurfered */
2741 /* this is needed for all code using vertexgroups (no subsurf support) */
2742 /* it stores the normals as floats, but they can still be scaled as shorts (32767 = unit) */
2743 /* in use now by vertex/weight paint and particle generating */
2744
2745 float *mesh_get_mapped_verts_nors(Scene *scene, Object *ob)
2746 {
2747         Mesh *me= ob->data;
2748         DerivedMesh *dm;
2749         float *vertexcosnos;
2750         
2751         /* lets prevent crashing... */
2752         if(ob->type!=OB_MESH || me->totvert==0)
2753                 return NULL;
2754         
2755         dm= mesh_get_derived_final(scene, ob, CD_MASK_BAREMESH);
2756         vertexcosnos= MEM_callocN(6*sizeof(float)*me->totvert, "vertexcosnos map");
2757         
2758         if(dm->foreachMappedVert) {
2759                 dm->foreachMappedVert(dm, make_vertexcosnos__mapFunc, vertexcosnos);
2760         }
2761         else {
2762                 float *fp= vertexcosnos;
2763                 int a;
2764                 
2765                 for(a=0; a< me->totvert; a++, fp+=6) {
2766                         dm->getVertCo(dm, a, fp);
2767                         dm->getVertNo(dm, a, fp+3);
2768                 }
2769         }
2770         
2771         dm->release(dm);
2772         return vertexcosnos;
2773 }
2774
2775 /* ******************* GLSL ******************** */
2776
2777 typedef struct
2778 {
2779         float * precomputedFaceNormals;
2780         MTFace * mtface;        // texture coordinates
2781         MFace * mface;          // indices
2782         MVert * mvert;          // vertices & normals
2783         float (*orco)[3];
2784         float (*tangent)[4];    // destination
2785         int numFaces;
2786
2787 } SGLSLMeshToTangent;
2788
2789 // interface
2790 #include "mikktspace.h"
2791
2792 static int GetNumFaces(const SMikkTSpaceContext * pContext)
2793 {
2794         SGLSLMeshToTangent * pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
2795         return pMesh->numFaces;
2796 }
2797
2798 static int GetNumVertsOfFace(const SMikkTSpaceContext * pContext, const int face_num)
2799 {
2800         SGLSLMeshToTangent * pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
2801         return pMesh->mface[face_num].v4!=0 ? 4 : 3;
2802 }
2803
2804 static void GetPosition(const SMikkTSpaceContext * pContext, float fPos[], const int face_num, const int vert_index)
2805 {
2806         //assert(vert_index>=0 && vert_index<4);
2807         SGLSLMeshToTangent * pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
2808         const float *co= pMesh->mvert[(&pMesh->mface[face_num].v1)[vert_index]].co;
2809         copy_v3_v3(fPos, co);
2810 }
2811
2812 static void GetTextureCoordinate(const SMikkTSpaceContext * pContext, float fUV[], const int face_num, const int vert_index)
2813 {
2814         //assert(vert_index>=0 && vert_index<4);
2815         SGLSLMeshToTangent * pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
2816
2817         if(pMesh->mtface!=NULL) {
2818                 float * uv = pMesh->mtface[face_num].uv[vert_index];
2819                 fUV[0]=uv[0]; fUV[1]=uv[1];
2820         }
2821         else {
2822                 const float *orco= pMesh->orco[(&pMesh->mface[face_num].v1)[vert_index]];
2823                 map_to_sphere( &fUV[0], &fUV[1], orco[0], orco[1], orco[2]);
2824         }
2825 }
2826
2827 static void GetNormal(const SMikkTSpaceContext * pContext, float fNorm[], const int face_num, const int vert_index)
2828 {
2829         //assert(vert_index>=0 && vert_index<4);
2830         SGLSLMeshToTangent * pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
2831
2832         const int smoothnormal = (pMesh->mface[face_num].flag & ME_SMOOTH);
2833         if(!smoothnormal) {     // flat
2834                 if(pMesh->precomputedFaceNormals) {
2835                         copy_v3_v3(fNorm, &pMesh->precomputedFaceNormals[3*face_num]);
2836                 }
2837                 else {
2838                         MFace *mf= &pMesh->mface[face_num];
2839                         float *p0= pMesh->mvert[mf->v1].co;
2840                         float *p1= pMesh->mvert[mf->v2].co;
2841                         float *p2= pMesh->mvert[mf->v3].co;
2842
2843                         if(mf->v4) {
2844                                 float *p3 = pMesh->mvert[mf->v4].co;
2845                                 normal_quad_v3(fNorm, p0, p1, p2, p3);
2846                         }
2847                         else {
2848                                 normal_tri_v3(fNorm, p0, p1, p2);
2849                         }
2850                 }
2851         }
2852         else {
2853                 const short *no= pMesh->mvert[(&pMesh->mface[face_num].v1)[vert_index]].no;
2854                 normal_short_to_float_v3(fNorm, no);
2855         }
2856 }
2857 static void SetTSpace(const SMikkTSpaceContext * pContext, const float fvTangent[], const float fSign, const int face_num, const int iVert)
2858 {
2859         //assert(vert_index>=0 && vert_index<4);
2860         SGLSLMeshToTangent * pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
2861         float * pRes = pMesh->tangent[4*face_num+iVert];
2862         copy_v3_v3(pRes, fvTangent);
2863         pRes[3]=fSign;
2864 }
2865
2866
2867 void DM_add_tangent_layer(DerivedMesh *dm)
2868 {
2869         /* mesh vars */
2870         MTFace *mtface, *tf;
2871         MFace *mface, *mf;
2872         MVert *mvert, *v1, *v2, *v3, *v4;
2873         MemArena *arena= NULL;
2874         VertexTangent **vtangents= NULL;
2875         float (*orco)[3]= NULL, (*tangent)[4];
2876         float *uv1, *uv2, *uv3, *uv4, *vtang;
2877         float fno[3], tang[3], uv[4][2];
2878         int i, j, len, mf_vi[4], totvert, totface, iCalcNewMethod;
2879         float *nors;
2880
2881         if(CustomData_get_layer_index(&dm->faceData, CD_TANGENT) != -1)
2882                 return;
2883
2884         nors = dm->getFaceDataArray(dm, CD_NORMAL);
2885
2886         /* check we have all the needed layers */
2887         totvert= dm->getNumVerts(dm);
2888         totface= dm->getNumFaces(dm);
2889
2890         mvert= dm->getVertArray(dm);
2891         mface= dm->getFaceArray(dm);
2892         mtface= dm->getFaceDataArray(dm, CD_MTFACE);
2893
2894         if(!mtface) {
2895                 orco= dm->getVertDataArray(dm, CD_ORCO);
2896                 if(!orco)
2897                         return;
2898         }
2899         
2900         /* create tangent layer */
2901         DM_add_face_layer(dm, CD_TANGENT, CD_CALLOC, NULL);
2902         tangent= DM_get_face_data_layer(dm, CD_TANGENT);
2903         
2904         /* allocate some space */
2905         arena= BLI_memarena_new(BLI_MEMARENA_STD_BUFSIZE, "tangent layer arena");
2906         BLI_memarena_use_calloc(arena);
2907         vtangents= MEM_callocN(sizeof(VertexTangent*)*totvert, "VertexTangent");
2908
2909         // new computation method
2910         iCalcNewMethod = 1;
2911         if(iCalcNewMethod != 0) {
2912                 SGLSLMeshToTangent mesh2tangent= {0};
2913                 SMikkTSpaceContext sContext= {0};
2914                 SMikkTSpaceInterface sInterface= {0};
2915
2916                 mesh2tangent.precomputedFaceNormals = nors;
2917                 mesh2tangent.mtface = mtface;
2918                 mesh2tangent.mface = mface;
2919                 mesh2tangent.mvert = mvert;
2920                 mesh2tangent.orco = orco;
2921                 mesh2tangent.tangent = tangent;
2922                 mesh2tangent.numFaces = totface;
2923
2924                 sContext.m_pUserData = &mesh2tangent;
2925                 sContext.m_pInterface = &sInterface;
2926                 sInterface.m_getNumFaces = GetNumFaces;
2927                 sInterface.m_getNumVerticesOfFace = GetNumVertsOfFace;
2928                 sInterface.m_getPosition = GetPosition;
2929                 sInterface.m_getTexCoord = GetTextureCoordinate;
2930                 sInterface.m_getNormal = GetNormal;
2931                 sInterface.m_setTSpaceBasic = SetTSpace;
2932
2933                 // 0 if failed
2934                 iCalcNewMethod = genTangSpaceDefault(&sContext);
2935         }
2936
2937         if(!iCalcNewMethod) {
2938                 /* sum tangents at connected vertices */
2939                 for(i=0, tf=mtface, mf=mface; i < totface; mf++, tf++, i++) {
2940                         v1= &mvert[mf->v1];
2941                         v2= &mvert[mf->v2];
2942                         v3= &mvert[mf->v3];
2943
2944                         if (mf->v4) {
2945                                 v4= &mvert[mf->v4];
2946                                 normal_quad_v3( fno,v4->co, v3->co, v2->co, v1->co);
2947                         }
2948                         else {
2949                                 v4= NULL;
2950                                 normal_tri_v3( fno,v3->co, v2->co, v1->co);
2951                         }
2952                 
2953                         if(mtface) {
2954                                 uv1= tf->uv[0];
2955                                 uv2= tf->uv[1];
2956                                 uv3= tf->uv[2];
2957                                 uv4= tf->uv[3];
2958                         }
2959                         else {
2960                                 uv1= uv[0]; uv2= uv[1]; uv3= uv[2]; uv4= uv[3];
2961                                 map_to_sphere( &uv[0][0], &uv[0][1],orco[mf->v1][0], orco[mf->v1][1], orco[mf->v1][2]);
2962                                 map_to_sphere( &uv[1][0], &uv[1][1],orco[mf->v2][0], orco[mf->v2][1], orco[mf->v2][2]);
2963                                 map_to_sphere( &uv[2][0], &uv[2][1],orco[mf->v3][0], orco[mf->v3][1], orco[mf->v3][2]);
2964                                 if(v4)
2965                                         map_to_sphere( &uv[3][0], &uv[3][1],orco[mf->v4][0], orco[mf->v4][1], orco[mf->v4][2]);
2966                         }
2967                 
2968                         tangent_from_uv(uv1, uv2, uv3, v1->co, v2->co, v3->co, fno, tang);
2969                         sum_or_add_vertex_tangent(arena, &vtangents[mf->v1], tang, uv1);
2970                         sum_or_add_vertex_tangent(arena, &vtangents[mf->v2], tang, uv2);
2971                         sum_or_add_vertex_tangent(arena, &vtangents[mf->v3], tang, uv3);
2972                 
2973               &n