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