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