Merged changes in the trunk up to revision 41225.
[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_getMinMax(DerivedMesh *dm, float min_r[3], float max_r[3])
1129 {
1130         EditMeshDerivedMesh *emdm= (EditMeshDerivedMesh*) dm;
1131         EditVert *eve;
1132         int i;
1133
1134         if (emdm->em->verts.first) {
1135                 for (i=0,eve= emdm->em->verts.first; eve; i++,eve= eve->next) {
1136                         if (emdm->vertexCos) {
1137                                 DO_MINMAX(emdm->vertexCos[i], min_r, max_r);
1138                         } else {
1139                                 DO_MINMAX(eve->co, min_r, max_r);
1140                         }
1141                 }
1142         } else {
1143                 min_r[0] = min_r[1] = min_r[2] = max_r[0] = max_r[1] = max_r[2] = 0.0;
1144         }
1145 }
1146 static int emDM_getNumVerts(DerivedMesh *dm)
1147 {
1148         EditMeshDerivedMesh *emdm= (EditMeshDerivedMesh*) dm;
1149
1150         return BLI_countlist(&emdm->em->verts);
1151 }
1152
1153 static int emDM_getNumEdges(DerivedMesh *dm)
1154 {
1155         EditMeshDerivedMesh *emdm= (EditMeshDerivedMesh*) dm;
1156
1157         return BLI_countlist(&emdm->em->edges);
1158 }
1159
1160 static int emDM_getNumFaces(DerivedMesh *dm)
1161 {
1162         EditMeshDerivedMesh *emdm= (EditMeshDerivedMesh*) dm;
1163
1164         return BLI_countlist(&emdm->em->faces);
1165 }
1166
1167 static void emDM_getVertCos(DerivedMesh *dm, float (*cos_r)[3])
1168 {
1169         EditMeshDerivedMesh *emdm= (EditMeshDerivedMesh*) dm;
1170         EditVert *eve;
1171         int i;
1172
1173         for (i=0,eve= emdm->em->verts.first; eve; i++,eve=eve->next) {
1174                 if (emdm->vertexCos) {
1175                         copy_v3_v3(cos_r[i], emdm->vertexCos[i]);
1176                 } else {
1177                         copy_v3_v3(cos_r[i], eve->co);
1178                 }
1179         }
1180 }
1181
1182 static void emDM_getVert(DerivedMesh *dm, int index, MVert *vert_r)
1183 {
1184         EditVert *ev = ((EditMeshDerivedMesh *)dm)->em->verts.first;
1185         int i;
1186
1187         for(i = 0; i < index; ++i) ev = ev->next;
1188
1189         VECCOPY(vert_r->co, ev->co);
1190
1191         normal_float_to_short_v3(vert_r->no, ev->no);
1192
1193         /* TODO what to do with vert_r->flag? */
1194         vert_r->bweight = (unsigned char) (ev->bweight*255.0f);
1195 }
1196
1197 static void emDM_getEdge(DerivedMesh *dm, int index, MEdge *edge_r)
1198 {
1199         EditMesh *em = ((EditMeshDerivedMesh *)dm)->em;
1200         EditEdge *ee = em->edges.first;
1201         EditVert *ev, *v1, *v2;
1202         int i;
1203
1204         for(i = 0; i < index; ++i) ee = ee->next;
1205
1206         edge_r->crease = (unsigned char) (ee->crease*255.0f);
1207         edge_r->bweight = (unsigned char) (ee->bweight*255.0f);
1208         /* TODO what to do with edge_r->flag? */
1209         edge_r->flag = ME_EDGEDRAW|ME_EDGERENDER;
1210         if (ee->seam) edge_r->flag |= ME_SEAM;
1211         if (ee->sharp) edge_r->flag |= ME_SHARP;
1212         if (ee->freestyle) edge_r->flag |= ME_FREESTYLE_EDGE;
1213 #if 0
1214         /* this needs setup of f2 field */
1215         if (!ee->f2) edge_r->flag |= ME_LOOSEEDGE;
1216 #endif
1217
1218         /* goddamn, we have to search all verts to find indices */
1219         v1 = ee->v1;
1220         v2 = ee->v2;
1221         for(i = 0, ev = em->verts.first; v1 || v2; i++, ev = ev->next) {
1222                 if(ev == v1) {
1223                         edge_r->v1 = i;
1224                         v1 = NULL;
1225                 }
1226                 if(ev == v2) {
1227                         edge_r->v2 = i;
1228                         v2 = NULL;
1229                 }
1230         }
1231 }
1232
1233 static void emDM_getFace(DerivedMesh *dm, int index, MFace *face_r)
1234 {
1235         EditMesh *em = ((EditMeshDerivedMesh *)dm)->em;
1236         EditFace *ef = em->faces.first;
1237         EditVert *ev, *v1, *v2, *v3, *v4;
1238         int i;
1239
1240         for(i = 0; i < index; ++i) ef = ef->next;
1241
1242         face_r->mat_nr = ef->mat_nr;
1243         face_r->flag = ef->flag;
1244
1245         /* goddamn, we have to search all verts to find indices */
1246         v1 = ef->v1;
1247         v2 = ef->v2;
1248         v3 = ef->v3;
1249         v4 = ef->v4;
1250         if(!v4) face_r->v4 = 0;
1251
1252         for(i = 0, ev = em->verts.first; v1 || v2 || v3 || v4;
1253                 i++, ev = ev->next) {
1254                 if(ev == v1) {
1255                         face_r->v1 = i;
1256                         v1 = NULL;
1257                 }
1258                 if(ev == v2) {
1259                         face_r->v2 = i;
1260                         v2 = NULL;
1261                 }
1262                 if(ev == v3) {
1263                         face_r->v3 = i;
1264                         v3 = NULL;
1265                 }
1266                 if(ev == v4) {
1267                         face_r->v4 = i;
1268                         v4 = NULL;
1269                 }
1270         }
1271
1272         test_index_face(face_r, NULL, 0, ef->v4?4:3);
1273 }
1274
1275 static void emDM_copyVertArray(DerivedMesh *dm, MVert *vert_r)
1276 {
1277         EditMeshDerivedMesh *emdm= (EditMeshDerivedMesh*) dm;
1278         EditVert *ev = emdm->em->verts.first;
1279         int i;
1280
1281         for(i=0; ev; ev = ev->next, ++vert_r, ++i) {
1282                 if(emdm->vertexCos)
1283                         copy_v3_v3(vert_r->co, emdm->vertexCos[i]);
1284                 else
1285                         copy_v3_v3(vert_r->co, ev->co);
1286
1287                 normal_float_to_short_v3(vert_r->no, ev->no);
1288
1289                 /* TODO what to do with vert_r->flag? */
1290                 vert_r->flag = 0;
1291                 vert_r->bweight = (unsigned char) (ev->bweight*255.0f);
1292         }
1293 }
1294
1295 static void emDM_copyEdgeArray(DerivedMesh *dm, MEdge *edge_r)
1296 {
1297         EditMesh *em = ((EditMeshDerivedMesh *)dm)->em;
1298         EditEdge *ee = em->edges.first;
1299         EditVert *ev;
1300         int i;
1301
1302         /* store vertex indices in tmp union */
1303         for(ev = em->verts.first, i = 0; ev; ev = ev->next, ++i)
1304                 ev->tmp.l = (intptr_t) i;
1305
1306         for( ; ee; ee = ee->next, ++edge_r) {
1307                 edge_r->crease = (unsigned char) (ee->crease*255.0f);
1308                 edge_r->bweight = (unsigned char) (ee->bweight*255.0f);
1309                 /* TODO what to do with edge_r->flag? */
1310                 edge_r->flag = ME_EDGEDRAW|ME_EDGERENDER;
1311                 if (ee->seam) edge_r->flag |= ME_SEAM;
1312                 if (ee->sharp) edge_r->flag |= ME_SHARP;
1313                 if (ee->freestyle) edge_r->flag |= ME_FREESTYLE_EDGE;
1314 #if 0
1315                 /* this needs setup of f2 field */
1316                 if (!ee->f2) edge_r->flag |= ME_LOOSEEDGE;
1317 #endif
1318
1319                 edge_r->v1 = (int)ee->v1->tmp.l;
1320                 edge_r->v2 = (int)ee->v2->tmp.l;
1321         }
1322 }
1323
1324 static void emDM_copyFaceArray(DerivedMesh *dm, MFace *face_r)
1325 {
1326         EditMesh *em = ((EditMeshDerivedMesh *)dm)->em;
1327         EditFace *ef = em->faces.first;
1328         EditVert *ev;
1329         int i;
1330
1331         /* store vertexes indices in tmp union */
1332         for(ev = em->verts.first, i = 0; ev; ev = ev->next, ++i)
1333                 ev->tmp.l = (intptr_t) i;
1334
1335         for( ; ef; ef = ef->next, ++face_r) {
1336                 face_r->mat_nr = ef->mat_nr;
1337                 face_r->flag = ef->flag;
1338
1339                 face_r->v1 = (int)ef->v1->tmp.l;
1340                 face_r->v2 = (int)ef->v2->tmp.l;
1341                 face_r->v3 = (int)ef->v3->tmp.l;
1342                 if(ef->v4) face_r->v4 = (int)ef->v4->tmp.l;
1343                 else face_r->v4 = 0;
1344
1345                 test_index_face(face_r, NULL, 0, ef->v4?4:3);
1346         }
1347 }
1348
1349 static void *emDM_getFaceDataArray(DerivedMesh *dm, int type)
1350 {
1351         EditMeshDerivedMesh *emdm= (EditMeshDerivedMesh*) dm;
1352         EditMesh *em= emdm->em;
1353         EditFace *efa;
1354         char *data, *emdata;
1355         void *datalayer;
1356         int index, size;
1357
1358         datalayer = DM_get_face_data_layer(dm, type);
1359         if(datalayer)
1360                 return datalayer;
1361
1362         /* layers are store per face for editmesh, we convert to a temporary
1363          * data layer array in the derivedmesh when these are requested */
1364         if(type == CD_MTFACE || type == CD_MCOL) {
1365                 index = CustomData_get_layer_index(&em->fdata, type);
1366
1367                 if(index != -1) {
1368                         /* int offset = em->fdata.layers[index].offset; */ /* UNUSED */
1369                         size = CustomData_sizeof(type);
1370
1371                         DM_add_face_layer(dm, type, CD_CALLOC, NULL);
1372                         index = CustomData_get_layer_index(&dm->faceData, type);
1373                         dm->faceData.layers[index].flag |= CD_FLAG_TEMPORARY;
1374
1375                         data = datalayer = DM_get_face_data_layer(dm, type);
1376                         for(efa=em->faces.first; efa; efa=efa->next, data+=size) {
1377                                 emdata = CustomData_em_get(&em->fdata, efa->data, type);
1378                                 memcpy(data, emdata, size);
1379                         }
1380                 }
1381         }
1382
1383         return datalayer;
1384 }
1385
1386 static void emDM_release(DerivedMesh *dm)
1387 {
1388         EditMeshDerivedMesh *emdm= (EditMeshDerivedMesh*) dm;
1389
1390         if (DM_release(dm)) {
1391                 if (emdm->vertexCos) {
1392                         MEM_freeN(emdm->vertexCos);
1393                         MEM_freeN(emdm->vertexNos);
1394                         MEM_freeN(emdm->faceNos);
1395                 }
1396
1397                 MEM_freeN(emdm);
1398         }
1399 }
1400
1401 DerivedMesh *editmesh_get_derived(EditMesh *em, float (*vertexCos)[3])
1402 {
1403         EditMeshDerivedMesh *emdm = MEM_callocN(sizeof(*emdm), "emdm");
1404
1405         DM_init(&emdm->dm, DM_TYPE_EDITMESH, BLI_countlist(&em->verts),
1406                                          BLI_countlist(&em->edges), BLI_countlist(&em->faces));
1407
1408         emdm->dm.getMinMax = emDM_getMinMax;
1409
1410         emdm->dm.getNumVerts = emDM_getNumVerts;
1411         emdm->dm.getNumEdges = emDM_getNumEdges;
1412         emdm->dm.getNumFaces = emDM_getNumFaces;
1413
1414         emdm->dm.getVertCos = emDM_getVertCos;
1415
1416         emdm->dm.getVert = emDM_getVert;
1417         emdm->dm.getEdge = emDM_getEdge;
1418         emdm->dm.getFace = emDM_getFace;
1419         emdm->dm.copyVertArray = emDM_copyVertArray;
1420         emdm->dm.copyEdgeArray = emDM_copyEdgeArray;
1421         emdm->dm.copyFaceArray = emDM_copyFaceArray;
1422         emdm->dm.getFaceDataArray = emDM_getFaceDataArray;
1423
1424         emdm->dm.foreachMappedVert = emDM_foreachMappedVert;
1425         emdm->dm.foreachMappedEdge = emDM_foreachMappedEdge;
1426         emdm->dm.foreachMappedFaceCenter = emDM_foreachMappedFaceCenter;
1427
1428         emdm->dm.drawEdges = emDM_drawEdges;
1429         emdm->dm.drawMappedEdges = emDM_drawMappedEdges;
1430         emdm->dm.drawMappedEdgesInterp = emDM_drawMappedEdgesInterp;
1431         emdm->dm.drawMappedFaces = emDM_drawMappedFaces;
1432         emdm->dm.drawMappedFacesTex = emDM_drawMappedFacesTex;
1433         emdm->dm.drawMappedFacesGLSL = emDM_drawMappedFacesGLSL;
1434         emdm->dm.drawFacesTex = emDM_drawFacesTex;
1435         emdm->dm.drawFacesGLSL = emDM_drawFacesGLSL;
1436         emdm->dm.drawUVEdges = emDM_drawUVEdges;
1437
1438         emdm->dm.release = emDM_release;
1439         
1440         emdm->em = em;
1441         emdm->vertexCos = vertexCos;
1442
1443         if(CustomData_has_layer(&em->vdata, CD_MDEFORMVERT)) {
1444                 EditVert *eve;
1445                 int i;
1446
1447                 DM_add_vert_layer(&emdm->dm, CD_MDEFORMVERT, CD_CALLOC, NULL);
1448
1449                 for(eve = em->verts.first, i = 0; eve; eve = eve->next, ++i)
1450                         DM_set_vert_data(&emdm->dm, i, CD_MDEFORMVERT,
1451                                                          CustomData_em_get(&em->vdata, eve->data, CD_MDEFORMVERT));
1452         }
1453
1454         if(vertexCos) {
1455                 EditVert *eve;
1456                 EditFace *efa;
1457                 int totface = BLI_countlist(&em->faces);
1458                 int i;
1459
1460                 for (i=0,eve=em->verts.first; eve; eve= eve->next)
1461                         eve->tmp.l = (intptr_t) i++;
1462
1463                 emdm->vertexNos = MEM_callocN(sizeof(*emdm->vertexNos)*i, "emdm_vno");
1464                 emdm->faceNos = MEM_mallocN(sizeof(*emdm->faceNos)*totface, "emdm_vno");
1465
1466                 for(i=0, efa= em->faces.first; efa; i++, efa=efa->next) {
1467                         float *v1 = vertexCos[(int) efa->v1->tmp.l];
1468                         float *v2 = vertexCos[(int) efa->v2->tmp.l];
1469                         float *v3 = vertexCos[(int) efa->v3->tmp.l];
1470                         float *no = emdm->faceNos[i];
1471                         
1472                         if(efa->v4) {
1473                                 float *v4 = vertexCos[(int) efa->v4->tmp.l];
1474
1475                                 normal_quad_v3( no,v1, v2, v3, v4);
1476                                 add_v3_v3(emdm->vertexNos[(int) efa->v4->tmp.l], no);
1477                         }
1478                         else {
1479                                 normal_tri_v3( no,v1, v2, v3);
1480                         }
1481
1482                         add_v3_v3(emdm->vertexNos[(int) efa->v1->tmp.l], no);
1483                         add_v3_v3(emdm->vertexNos[(int) efa->v2->tmp.l], no);
1484                         add_v3_v3(emdm->vertexNos[(int) efa->v3->tmp.l], no);
1485                 }
1486
1487                 for(i=0, eve= em->verts.first; eve; i++, eve=eve->next) {
1488                         float *no = emdm->vertexNos[i];
1489                         /* following Mesh convention; we use vertex coordinate itself
1490                          * for normal in this case */
1491                         if (normalize_v3(no) == 0.0f) {
1492                                 normalize_v3_v3(no, vertexCos[i]);
1493                         }
1494                 }
1495         }
1496
1497         return (DerivedMesh*) emdm;
1498 }
1499
1500 /***/
1501
1502 DerivedMesh *mesh_create_derived_for_modifier(Scene *scene, Object *ob, ModifierData *md)
1503 {
1504         Mesh *me = ob->data;
1505         ModifierTypeInfo *mti = modifierType_getInfo(md->type);
1506         DerivedMesh *dm;
1507
1508         md->scene= scene;
1509         
1510         if (!(md->mode&eModifierMode_Realtime)) return NULL;
1511         if (mti->isDisabled && mti->isDisabled(md, 0)) return NULL;
1512
1513         if (mti->type==eModifierTypeType_OnlyDeform) {
1514                 int numVerts;
1515                 float (*deformedVerts)[3] = mesh_getVertexCos(me, &numVerts);
1516
1517                 mti->deformVerts(md, ob, NULL, deformedVerts, numVerts, 0, 0);
1518                 dm = mesh_create_derived(me, ob, deformedVerts);
1519
1520                 MEM_freeN(deformedVerts);
1521         } else {
1522                 DerivedMesh *tdm = mesh_create_derived(me, ob, NULL);
1523                 dm = mti->applyModifier(md, ob, tdm, 0, 0);
1524
1525                 if(tdm != dm) tdm->release(tdm);
1526         }
1527
1528         return dm;
1529 }
1530
1531 static float *get_editmesh_orco_verts(EditMesh *em)
1532 {
1533         EditVert *eve;
1534         float *orco;
1535         int a, totvert;
1536
1537         /* these may not really be the orco's, but it's only for preview.
1538          * could be solver better once, but isn't simple */
1539
1540         totvert= 0;
1541         for(eve=em->verts.first; eve; eve=eve->next)
1542                 totvert++;
1543         
1544         orco = MEM_mallocN(sizeof(float)*3*totvert, "EditMesh Orco");
1545
1546         for(a=0, eve=em->verts.first; eve; eve=eve->next, a+=3)
1547                 VECCOPY(orco+a, eve->co);
1548         
1549         return orco;
1550 }
1551
1552 /* orco custom data layer */
1553
1554 static void *get_orco_coords_dm(Object *ob, EditMesh *em, int layer, int *free)
1555 {
1556         *free= 0;
1557
1558         if(layer == CD_ORCO) {
1559                 /* get original coordinates */
1560                 *free= 1;
1561
1562                 if(em)
1563                         return (float(*)[3])get_editmesh_orco_verts(em);
1564                 else
1565                         return (float(*)[3])get_mesh_orco_verts(ob);
1566         }
1567         else if(layer == CD_CLOTH_ORCO) {
1568                 /* apply shape key for cloth, this should really be solved
1569                    by a more flexible customdata system, but not simple */
1570                 if(!em) {
1571                         ClothModifierData *clmd = (ClothModifierData *)modifiers_findByType(ob, eModifierType_Cloth);
1572                         KeyBlock *kb= key_get_keyblock(ob_get_key(ob), clmd->sim_parms->shapekey_rest);
1573
1574                         if(kb->data)
1575                                 return kb->data;
1576                 }
1577
1578                 return NULL;
1579         }
1580
1581         return NULL;
1582 }
1583
1584 static DerivedMesh *create_orco_dm(Object *ob, Mesh *me, EditMesh *em, int layer)
1585 {
1586         DerivedMesh *dm;
1587         float (*orco)[3];
1588         int free;
1589
1590         if(em) dm= CDDM_from_editmesh(em, me);
1591         else dm= CDDM_from_mesh(me, ob);
1592
1593         orco= get_orco_coords_dm(ob, em, layer, &free);
1594
1595         if(orco) {
1596                 CDDM_apply_vert_coords(dm, orco);
1597                 if(free) MEM_freeN(orco);
1598         }
1599
1600         CDDM_calc_normals(dm);
1601
1602         return dm;
1603 }
1604
1605 static void add_orco_dm(Object *ob, EditMesh *em, DerivedMesh *dm, DerivedMesh *orcodm, int layer)
1606 {
1607         float (*orco)[3], (*layerorco)[3];
1608         int totvert, free;
1609
1610         totvert= dm->getNumVerts(dm);
1611
1612         if(orcodm) {
1613                 orco= MEM_callocN(sizeof(float)*3*totvert, "dm orco");
1614                 free= 1;
1615
1616                 if(orcodm->getNumVerts(orcodm) == totvert)
1617                         orcodm->getVertCos(orcodm, orco);
1618                 else
1619                         dm->getVertCos(dm, orco);
1620         }
1621         else
1622                 orco= get_orco_coords_dm(ob, em, layer, &free);
1623
1624         if(orco) {
1625                 if(layer == CD_ORCO)
1626                         transform_mesh_orco_verts(ob->data, orco, totvert, 0);
1627
1628                 if(!(layerorco = DM_get_vert_data_layer(dm, layer))) {
1629                         DM_add_vert_layer(dm, layer, CD_CALLOC, NULL);
1630                         layerorco = DM_get_vert_data_layer(dm, layer);
1631                 }
1632
1633                 memcpy(layerorco, orco, sizeof(float)*3*totvert);
1634                 if(free) MEM_freeN(orco);
1635         }
1636 }
1637
1638 /* weight paint colors */
1639
1640 /* Something of a hack, at the moment deal with weightpaint
1641  * by tucking into colors during modifier eval, only in
1642  * wpaint mode. Works ok but need to make sure recalc
1643  * happens on enter/exit wpaint.
1644  */
1645
1646 void weight_to_rgb(float input, float *fr, float *fg, float *fb)
1647 {
1648         float blend;
1649         
1650         blend= ((input/2.0f)+0.5f);
1651         
1652         if (input<=0.25f){      // blue->cyan
1653                 *fr= 0.0f;
1654                 *fg= blend*input*4.0f;
1655                 *fb= blend;
1656         }
1657         else if (input<=0.50f){ // cyan->green
1658                 *fr= 0.0f;
1659                 *fg= blend;
1660                 *fb= blend*(1.0f-((input-0.25f)*4.0f)); 
1661         }
1662         else if (input <= 0.75f){       // green->yellow
1663                 *fr= blend * ((input-0.50f)*4.0f);
1664                 *fg= blend;
1665                 *fb= 0.0f;
1666         }
1667         else if (input <= 1.0f){ // yellow->red
1668                 *fr= blend;
1669                 *fg= blend * (1.0f-((input-0.75f)*4.0f)); 
1670                 *fb= 0.0f;
1671         }
1672 }
1673
1674 /* draw_flag's for calc_weightpaint_vert_color */
1675 enum {
1676         CALC_WP_MULTIPAINT= (1<<0),
1677         CALC_WP_AUTO_NORMALIZE= (1<<1),
1678 };
1679
1680 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)
1681 {
1682         Mesh *me = ob->data;
1683         float colf[4], input = 0.0f;
1684         int i;
1685
1686         
1687         int make_black= FALSE;
1688
1689         if (me->dvert) {
1690                 if ((selected > 1) && (draw_flag & CALC_WP_MULTIPAINT)) {
1691                         
1692                         int was_a_nonzero= FALSE;
1693                         for (i=0; i<me->dvert[vert].totweight; i++) {
1694                                 /* in multipaint, get the average if auto normalize is inactive
1695                                  * get the sum if it is active */
1696                                 if(dg_flags[me->dvert[vert].dw[i].def_nr]) {
1697                                         if(me->dvert[vert].dw[i].weight) {
1698                                                 input+= me->dvert[vert].dw[i].weight;
1699                                                 was_a_nonzero= TRUE;
1700                                         }
1701                                 }
1702                         }
1703
1704                         /* make it black if the selected groups have no weight on a vertex */
1705                         if(was_a_nonzero == FALSE) {
1706                                 make_black = TRUE;
1707                         }
1708                         else if ((draw_flag & CALC_WP_AUTO_NORMALIZE) == FALSE) {
1709                                 input /= selected; /* get the average */
1710                         }
1711                 }
1712                 else {
1713                         /* default, non tricky behavior */
1714                         for (i=0; i<me->dvert[vert].totweight; i++) {
1715                                 if (me->dvert[vert].dw[i].def_nr==ob->actdef-1) {
1716                                         input+=me->dvert[vert].dw[i].weight;
1717                                 }
1718                         }
1719                 }
1720         }
1721         
1722         if (make_black) {
1723                 col[3] = 0;
1724                 col[2] = 0;
1725                 col[1] = 0;
1726                 col[0] = 255;
1727                 return;
1728         }
1729
1730         CLAMP(input, 0.0f, 1.0f);       
1731
1732         if(coba)
1733                 do_colorband(coba, input, colf);
1734         else
1735                 weight_to_rgb(input, colf, colf+1, colf+2);
1736         
1737         col[3] = (unsigned char)(colf[0] * 255.0f);
1738         col[2] = (unsigned char)(colf[1] * 255.0f);
1739         col[1] = (unsigned char)(colf[2] * 255.0f);
1740         col[0] = 255;
1741 }
1742
1743 static ColorBand *stored_cb= NULL;
1744
1745 void vDM_ColorBand_store(ColorBand *coba)
1746 {
1747         stored_cb= coba;
1748 }
1749
1750 static void add_weight_mcol_dm(Object *ob, DerivedMesh *dm, int const draw_flag)
1751 {
1752         Mesh *me = ob->data;
1753         MFace *mf = me->mface;
1754         ColorBand *coba= stored_cb;     /* warning, not a local var */
1755         unsigned char *wtcol;
1756         int i;
1757         
1758         int defbase_len = BLI_countlist(&ob->defbase);
1759         char *defbase_sel = MEM_mallocN(defbase_len * sizeof(char), __func__);
1760         int selected = get_selected_defgroups(ob, defbase_sel, defbase_len);
1761         int unselected = defbase_len - selected;
1762
1763         wtcol = MEM_callocN (sizeof (unsigned char) * me->totface*4*4, "weightmap");
1764         
1765         memset(wtcol, 0x55, sizeof (unsigned char) * me->totface*4*4);
1766         for (i=0; i<me->totface; i++, mf++) {
1767                 calc_weightpaint_vert_color(ob, coba, mf->v1, &wtcol[(i*4 + 0)*4], defbase_sel, selected, unselected, draw_flag);
1768                 calc_weightpaint_vert_color(ob, coba, mf->v2, &wtcol[(i*4 + 1)*4], defbase_sel, selected, unselected, draw_flag);
1769                 calc_weightpaint_vert_color(ob, coba, mf->v3, &wtcol[(i*4 + 2)*4], defbase_sel, selected, unselected, draw_flag);
1770                 if (mf->v4)
1771                         calc_weightpaint_vert_color(ob, coba, mf->v4, &wtcol[(i*4 + 3)*4], defbase_sel, selected, unselected, draw_flag);
1772         }
1773         
1774         MEM_freeN(defbase_sel);
1775
1776         CustomData_add_layer(&dm->faceData, CD_WEIGHT_MCOL, CD_ASSIGN, wtcol, dm->numFaceData);
1777 }
1778
1779 /* new value for useDeform -1  (hack for the gameengine):
1780  * - apply only the modifier stack of the object, skipping the virtual modifiers,
1781  * - don't apply the key
1782  * - apply deform modifiers and input vertexco
1783  */
1784 static void mesh_calc_modifiers(Scene *scene, Object *ob, float (*inputVertexCos)[3],
1785                                                                 DerivedMesh **deform_r, DerivedMesh **final_r,
1786                                                                 int useRenderParams, int useDeform,
1787                                                                 int needMapping, CustomDataMask dataMask, int index, int useCache)
1788 {
1789         Mesh *me = ob->data;
1790         ModifierData *firstmd, *md;
1791         LinkNode *datamasks, *curr;
1792         CustomDataMask mask, nextmask;
1793         float (*deformedVerts)[3] = NULL;
1794         DerivedMesh *dm, *orcodm, *clothorcodm, *finaldm;
1795         int numVerts = me->totvert;
1796         int required_mode;
1797         int isPrevDeform= FALSE;
1798         int skipVirtualArmature = (useDeform < 0);
1799         MultiresModifierData *mmd= get_multires_modifier(scene, ob, 0);
1800         int has_multires = mmd != NULL, multires_applied = 0;
1801         int sculpt_mode = ob->mode & OB_MODE_SCULPT && ob->sculpt;
1802
1803         int draw_flag= ((scene->toolsettings->multipaint ? CALC_WP_MULTIPAINT : 0) |
1804                         (scene->toolsettings->auto_normalize ? CALC_WP_AUTO_NORMALIZE : 0));
1805
1806         if(mmd && !mmd->sculptlvl)
1807                 has_multires = 0;
1808
1809         if(!skipVirtualArmature) {
1810                 firstmd = modifiers_getVirtualModifierList(ob);
1811         }
1812         else {
1813                 /* game engine exception */
1814                 firstmd = ob->modifiers.first;
1815                 if(firstmd && firstmd->type == eModifierType_Armature)
1816                         firstmd = firstmd->next;
1817         }
1818
1819         md = firstmd;
1820
1821         modifiers_clearErrors(ob);
1822
1823         if(useRenderParams) required_mode = eModifierMode_Render;
1824         else required_mode = eModifierMode_Realtime;
1825
1826         datamasks = modifiers_calcDataMasks(scene, ob, md, dataMask, required_mode);
1827         curr = datamasks;
1828
1829         if(deform_r) *deform_r = NULL;
1830         *final_r = NULL;
1831
1832         if(useDeform) {
1833                 if(inputVertexCos)
1834                         deformedVerts = inputVertexCos;
1835                 
1836                 /* Apply all leading deforming modifiers */
1837                 for(;md; md = md->next, curr = curr->next) {
1838                         ModifierTypeInfo *mti = modifierType_getInfo(md->type);
1839
1840                         md->scene= scene;
1841                         
1842                         if(!modifier_isEnabled(scene, md, required_mode)) continue;
1843                         if(useDeform < 0 && mti->dependsOnTime && mti->dependsOnTime(md)) continue;
1844
1845                         if(mti->type == eModifierTypeType_OnlyDeform) {
1846                                 if(!deformedVerts)
1847                                         deformedVerts = mesh_getVertexCos(me, &numVerts);
1848
1849                                 mti->deformVerts(md, ob, NULL, deformedVerts, numVerts, useRenderParams, useDeform);
1850                         } else {
1851                                 break;
1852                         }
1853                         
1854                         /* grab modifiers until index i */
1855                         if((index >= 0) && (modifiers_indexInObject(ob, md) >= index))
1856                                 break;
1857                 }
1858
1859                 /* Result of all leading deforming modifiers is cached for
1860                  * places that wish to use the original mesh but with deformed
1861                  * coordinates (vpaint, etc.)
1862                  */
1863                 if (deform_r) {
1864                         *deform_r = CDDM_from_mesh(me, ob);
1865
1866                         if(deformedVerts) {
1867                                 CDDM_apply_vert_coords(*deform_r, deformedVerts);
1868                                 CDDM_calc_normals(*deform_r);
1869                         }
1870                 }
1871         } else {
1872                 /* default behaviour for meshes */
1873                 if(inputVertexCos)
1874                         deformedVerts = inputVertexCos;
1875                 else
1876                         deformedVerts = mesh_getVertexCos(me, &numVerts);
1877         }
1878
1879
1880         /* Now apply all remaining modifiers. If useDeform is off then skip
1881          * OnlyDeform ones. 
1882          */
1883         dm = NULL;
1884         orcodm = NULL;
1885         clothorcodm = NULL;
1886
1887         for(;md; md = md->next, curr = curr->next) {
1888                 ModifierTypeInfo *mti = modifierType_getInfo(md->type);
1889
1890                 md->scene= scene;
1891
1892                 if(!modifier_isEnabled(scene, md, required_mode)) continue;
1893                 if(mti->type == eModifierTypeType_OnlyDeform && !useDeform) continue;
1894                 if((mti->flags & eModifierTypeFlag_RequiresOriginalData) && dm) {
1895                         modifier_setError(md, "Modifier requires original data, bad stack position.");
1896                         continue;
1897                 }
1898                 if(sculpt_mode && (!has_multires || multires_applied)) {
1899                         int unsupported= 0;
1900
1901                         if(scene->toolsettings->sculpt->flags & SCULPT_ONLY_DEFORM)
1902                                 unsupported|= mti->type != eModifierTypeType_OnlyDeform;
1903
1904                         unsupported|= md->type == eModifierType_Multires && ((MultiresModifierData*)md)->sculptlvl==0;
1905                         unsupported|= multires_applied;
1906
1907                         if(unsupported) {
1908                                 modifier_setError(md, "Not supported in sculpt mode.");
1909                                 continue;
1910                         }
1911                 }
1912                 if(needMapping && !modifier_supportsMapping(md)) continue;
1913                 if(useDeform < 0 && mti->dependsOnTime && mti->dependsOnTime(md)) continue;
1914
1915                 /* add an orco layer if needed by this modifier */
1916                 if(mti->requiredDataMask)
1917                         mask = mti->requiredDataMask(ob, md);
1918                 else
1919                         mask = 0;
1920
1921                 if(dm && (mask & CD_MASK_ORCO))
1922                         add_orco_dm(ob, NULL, dm, orcodm, CD_ORCO);
1923
1924                 /* How to apply modifier depends on (a) what we already have as
1925                  * a result of previous modifiers (could be a DerivedMesh or just
1926                  * deformed vertices) and (b) what type the modifier is.
1927                  */
1928
1929                 if(mti->type == eModifierTypeType_OnlyDeform) {
1930                         /* No existing verts to deform, need to build them. */
1931                         if(!deformedVerts) {
1932                                 if(dm) {
1933                                         /* Deforming a derived mesh, read the vertex locations
1934                                          * out of the mesh and deform them. Once done with this
1935                                          * run of deformers verts will be written back.
1936                                          */
1937                                         numVerts = dm->getNumVerts(dm);
1938                                         deformedVerts =
1939                                                 MEM_mallocN(sizeof(*deformedVerts) * numVerts, "dfmv");
1940                                         dm->getVertCos(dm, deformedVerts);
1941                                 } else {
1942                                         deformedVerts = mesh_getVertexCos(me, &numVerts);
1943                                 }
1944                         }
1945
1946                         /* if this is not the last modifier in the stack then recalculate the normals
1947                          * to avoid giving bogus normals to the next modifier see: [#23673] */
1948                         if(isPrevDeform &&  mti->dependsOnNormals && mti->dependsOnNormals(md)) {
1949                                 /* XXX, this covers bug #23673, but we may need normal calc for other types */
1950                                 if(dm && dm->type == DM_TYPE_CDDM) {
1951                                         CDDM_apply_vert_coords(dm, deformedVerts);
1952                                         CDDM_calc_normals(dm);
1953                                 }
1954                         }
1955
1956                         mti->deformVerts(md, ob, dm, deformedVerts, numVerts, useRenderParams, useDeform);
1957                 } else {
1958                         DerivedMesh *ndm;
1959
1960                         /* determine which data layers are needed by following modifiers */
1961                         if(curr->next)
1962                                 nextmask= (CustomDataMask)GET_INT_FROM_POINTER(curr->next->link);
1963                         else
1964                                 nextmask= dataMask;
1965
1966                         /* apply vertex coordinates or build a DerivedMesh as necessary */
1967                         if(dm) {
1968                                 if(deformedVerts) {
1969                                         DerivedMesh *tdm = CDDM_copy(dm);
1970                                         dm->release(dm);
1971                                         dm = tdm;
1972
1973                                         CDDM_apply_vert_coords(dm, deformedVerts);
1974                                         CDDM_calc_normals(dm);
1975                                 }
1976                         } else {
1977                                 dm = CDDM_from_mesh(me, ob);
1978
1979                                 if(deformedVerts) {
1980                                         CDDM_apply_vert_coords(dm, deformedVerts);
1981                                         CDDM_calc_normals(dm);
1982                                 }
1983
1984                                 if((dataMask & CD_MASK_WEIGHT_MCOL) && (ob->mode & OB_MODE_WEIGHT_PAINT))
1985                                         add_weight_mcol_dm(ob, dm, draw_flag); 
1986
1987                                 /* Constructive modifiers need to have an origindex
1988                                  * otherwise they wont have anywhere to copy the data from.
1989                                  *
1990                                  * Also create ORIGINDEX data if any of the following modifiers
1991                                  * requests it, this way Mirror, Solidify etc will keep ORIGINDEX
1992                                  * data by using generic DM_copy_vert_data() functions.
1993                                  */
1994                                 if(needMapping || (nextmask & CD_MASK_ORIGINDEX)) {
1995                                         /* calc */
1996                                         DM_add_vert_layer(dm, CD_ORIGINDEX, CD_CALLOC, NULL);
1997                                         DM_add_edge_layer(dm, CD_ORIGINDEX, CD_CALLOC, NULL);
1998                                         DM_add_face_layer(dm, CD_ORIGINDEX, CD_CALLOC, NULL);
1999
2000                                         range_vni(DM_get_vert_data_layer(dm, CD_ORIGINDEX), dm->numVertData, 0);
2001                                         range_vni(DM_get_edge_data_layer(dm, CD_ORIGINDEX), dm->numEdgeData, 0);
2002                                         range_vni(DM_get_face_data_layer(dm, CD_ORIGINDEX), dm->numFaceData, 0);
2003                                 }
2004                         }
2005
2006                         
2007                         /* set the DerivedMesh to only copy needed data */
2008                         mask= (CustomDataMask)GET_INT_FROM_POINTER(curr->link);
2009                         /* needMapping check here fixes bug [#28112], otherwise its
2010                          * possible that it wont be copied */
2011                         DM_set_only_copy(dm, mask | (needMapping ? CD_MASK_ORIGINDEX : 0));
2012                         
2013                         /* add cloth rest shape key if need */
2014                         if(mask & CD_MASK_CLOTH_ORCO)
2015                                 add_orco_dm(ob, NULL, dm, clothorcodm, CD_CLOTH_ORCO);
2016
2017                         /* add an origspace layer if needed */
2018                         if(((CustomDataMask)GET_INT_FROM_POINTER(curr->link)) & CD_MASK_ORIGSPACE)
2019                                 if(!CustomData_has_layer(&dm->faceData, CD_ORIGSPACE))
2020                                         DM_add_face_layer(dm, CD_ORIGSPACE, CD_DEFAULT, NULL);
2021
2022                         ndm = mti->applyModifier(md, ob, dm, useRenderParams, useCache);
2023
2024                         if(ndm) {
2025                                 /* if the modifier returned a new dm, release the old one */
2026                                 if(dm && dm != ndm) dm->release(dm);
2027
2028                                 dm = ndm;
2029
2030                                 if(deformedVerts) {
2031                                         if(deformedVerts != inputVertexCos)
2032                                                 MEM_freeN(deformedVerts);
2033
2034                                         deformedVerts = NULL;
2035                                 }
2036                         } 
2037
2038                         /* create an orco derivedmesh in parallel */
2039                         if(nextmask & CD_MASK_ORCO) {
2040                                 if(!orcodm)
2041                                         orcodm= create_orco_dm(ob, me, NULL, CD_ORCO);
2042
2043                                 nextmask &= ~CD_MASK_ORCO;
2044                                 DM_set_only_copy(orcodm, nextmask | CD_MASK_ORIGINDEX);
2045                                 ndm = mti->applyModifier(md, ob, orcodm, useRenderParams, 0);
2046
2047                                 if(ndm) {
2048                                         /* if the modifier returned a new dm, release the old one */
2049                                         if(orcodm && orcodm != ndm) orcodm->release(orcodm);
2050                                         orcodm = ndm;
2051                                 }
2052                         }
2053
2054                         /* create cloth orco derivedmesh in parallel */
2055                         if(nextmask & CD_MASK_CLOTH_ORCO) {
2056                                 if(!clothorcodm)
2057                                         clothorcodm= create_orco_dm(ob, me, NULL, CD_CLOTH_ORCO);
2058
2059                                 nextmask &= ~CD_MASK_CLOTH_ORCO;
2060                                 DM_set_only_copy(clothorcodm, nextmask | CD_MASK_ORIGINDEX);
2061                                 ndm = mti->applyModifier(md, ob, clothorcodm, useRenderParams, 0);
2062
2063                                 if(ndm) {
2064                                         /* if the modifier returned a new dm, release the old one */
2065                                         if(clothorcodm && clothorcodm != ndm) clothorcodm->release(clothorcodm);
2066                                         clothorcodm = ndm;
2067                                 }
2068                         }
2069                 }
2070
2071                 isPrevDeform= (mti->type == eModifierTypeType_OnlyDeform);
2072
2073                 /* grab modifiers until index i */
2074                 if((index >= 0) && (modifiers_indexInObject(ob, md) >= index))
2075                         break;
2076
2077                 if(sculpt_mode && md->type == eModifierType_Multires)
2078                         multires_applied = 1;
2079         }
2080
2081         for(md=firstmd; md; md=md->next)
2082                 modifier_freeTemporaryData(md);
2083
2084         /* Yay, we are done. If we have a DerivedMesh and deformed vertices
2085          * need to apply these back onto the DerivedMesh. If we have no
2086          * DerivedMesh then we need to build one.
2087          */
2088         if(dm && deformedVerts) {
2089                 finaldm = CDDM_copy(dm);
2090
2091                 dm->release(dm);
2092
2093                 CDDM_apply_vert_coords(finaldm, deformedVerts);
2094                 CDDM_calc_normals(finaldm);
2095
2096                 if((dataMask & CD_MASK_WEIGHT_MCOL) && (ob->mode & OB_MODE_WEIGHT_PAINT))
2097                         add_weight_mcol_dm(ob, finaldm, draw_flag);
2098         } else if(dm) {
2099                 finaldm = dm;
2100         } else {
2101                 finaldm = CDDM_from_mesh(me, ob);
2102
2103                 if(deformedVerts) {
2104                         CDDM_apply_vert_coords(finaldm, deformedVerts);
2105                         CDDM_calc_normals(finaldm);
2106                 }
2107
2108                 if((dataMask & CD_MASK_WEIGHT_MCOL) && (ob->mode & OB_MODE_WEIGHT_PAINT))
2109                         add_weight_mcol_dm(ob, finaldm, draw_flag);
2110         }
2111
2112         /* add an orco layer if needed */
2113         if(dataMask & CD_MASK_ORCO) {
2114                 add_orco_dm(ob, NULL, finaldm, orcodm, CD_ORCO);
2115
2116                 if(deform_r && *deform_r)
2117                         add_orco_dm(ob, NULL, *deform_r, NULL, CD_ORCO);
2118         }
2119
2120 #ifdef WITH_GAMEENGINE
2121         /* NavMesh - this is a hack but saves having a NavMesh modifier */
2122         if ((ob->gameflag & OB_NAVMESH) && (finaldm->type == DM_TYPE_CDDM)) {
2123                 DerivedMesh *tdm;
2124                 tdm= navmesh_dm_createNavMeshForVisualization(finaldm);
2125                 if (finaldm != tdm) {
2126                         finaldm->release(finaldm);
2127                         finaldm= tdm;
2128                 }
2129         }
2130 #endif /* WITH_GAMEENGINE */
2131
2132         *final_r = finaldm;
2133
2134         if(orcodm)
2135                 orcodm->release(orcodm);
2136         if(clothorcodm)
2137                 clothorcodm->release(clothorcodm);
2138
2139         if(deformedVerts && deformedVerts != inputVertexCos)
2140                 MEM_freeN(deformedVerts);
2141
2142         BLI_linklist_free(datamasks, NULL);
2143 }
2144
2145 float (*editmesh_get_vertex_cos(EditMesh *em, int *numVerts_r))[3]
2146 {
2147         int i, numVerts = *numVerts_r = BLI_countlist(&em->verts);
2148         float (*cos)[3];
2149         EditVert *eve;
2150
2151         cos = MEM_mallocN(sizeof(*cos)*numVerts, "vertexcos");
2152         for (i=0,eve=em->verts.first; i<numVerts; i++,eve=eve->next) {
2153                 VECCOPY(cos[i], eve->co);
2154         }
2155
2156         return cos;
2157 }
2158
2159 int editmesh_modifier_is_enabled(Scene *scene, ModifierData *md, DerivedMesh *dm)
2160 {
2161         ModifierTypeInfo *mti = modifierType_getInfo(md->type);
2162         int required_mode = eModifierMode_Realtime | eModifierMode_Editmode;
2163
2164         if(!modifier_isEnabled(scene, md, required_mode)) return 0;
2165         if((mti->flags & eModifierTypeFlag_RequiresOriginalData) && dm) {
2166                 modifier_setError(md, "Modifier requires original data, bad stack position.");
2167                 return 0;
2168         }
2169         
2170         return 1;
2171 }
2172
2173 static void editmesh_calc_modifiers(Scene *scene, Object *ob, EditMesh *em, DerivedMesh **cage_r,
2174                                                                         DerivedMesh **final_r,
2175                                                                         CustomDataMask dataMask)
2176 {
2177         ModifierData *md;
2178         float (*deformedVerts)[3] = NULL;
2179         CustomDataMask mask;
2180         DerivedMesh *dm, *orcodm = NULL;
2181         int i, numVerts = 0, cageIndex = modifiers_getCageIndex(scene, ob, NULL, 1);
2182         LinkNode *datamasks, *curr;
2183         int required_mode = eModifierMode_Realtime | eModifierMode_Editmode;
2184
2185         modifiers_clearErrors(ob);
2186
2187         if(cage_r && cageIndex == -1) {
2188                 *cage_r = editmesh_get_derived(em, NULL);
2189         }
2190
2191         dm = NULL;
2192         md = modifiers_getVirtualModifierList(ob);
2193
2194         datamasks = modifiers_calcDataMasks(scene, ob, md, dataMask, required_mode);
2195
2196         curr = datamasks;
2197         for(i = 0; md; i++, md = md->next, curr = curr->next) {
2198                 ModifierTypeInfo *mti = modifierType_getInfo(md->type);
2199
2200                 md->scene= scene;
2201                 
2202                 if(!editmesh_modifier_is_enabled(scene, md, dm))
2203                         continue;
2204
2205                 /* add an orco layer if needed by this modifier */
2206                 if(dm && mti->requiredDataMask) {
2207                         mask = mti->requiredDataMask(ob, md);
2208                         if(mask & CD_MASK_ORCO)
2209                                 add_orco_dm(ob, em, dm, orcodm, CD_ORCO);
2210                 }
2211
2212                 /* How to apply modifier depends on (a) what we already have as
2213                  * a result of previous modifiers (could be a DerivedMesh or just
2214                  * deformed vertices) and (b) what type the modifier is.
2215                  */
2216
2217                 if(mti->type == eModifierTypeType_OnlyDeform) {
2218                         /* No existing verts to deform, need to build them. */
2219                         if(!deformedVerts) {
2220                                 if(dm) {
2221                                         /* Deforming a derived mesh, read the vertex locations
2222                                          * out of the mesh and deform them. Once done with this
2223                                          * run of deformers verts will be written back.
2224                                          */
2225                                         numVerts = dm->getNumVerts(dm);
2226                                         deformedVerts =
2227                                                 MEM_mallocN(sizeof(*deformedVerts) * numVerts, "dfmv");
2228                                         dm->getVertCos(dm, deformedVerts);
2229                                 } else {
2230                                         deformedVerts = editmesh_get_vertex_cos(em, &numVerts);
2231                                 }
2232                         }
2233
2234                         if (mti->deformVertsEM)
2235                                 mti->deformVertsEM(md, ob, em, dm, deformedVerts, numVerts);
2236                         else mti->deformVerts(md, ob, dm, deformedVerts, numVerts, 0, 0);
2237                 } else {
2238                         DerivedMesh *ndm;
2239
2240                         /* apply vertex coordinates or build a DerivedMesh as necessary */
2241                         if(dm) {
2242                                 if(deformedVerts) {
2243                                         DerivedMesh *tdm = CDDM_copy(dm);
2244                                         if(!(cage_r && dm == *cage_r)) dm->release(dm);
2245                                         dm = tdm;
2246
2247                                         CDDM_apply_vert_coords(dm, deformedVerts);
2248                                         CDDM_calc_normals(dm);
2249                                 } else if(cage_r && dm == *cage_r) {
2250                                         /* dm may be changed by this modifier, so we need to copy it
2251                                          */
2252                                         dm = CDDM_copy(dm);
2253                                 }
2254
2255                         } else {
2256                                 dm = CDDM_from_editmesh(em, ob->data);
2257
2258                                 if(deformedVerts) {
2259                                         CDDM_apply_vert_coords(dm, deformedVerts);
2260                                         CDDM_calc_normals(dm);
2261                                 }
2262                         }
2263
2264                         /* create an orco derivedmesh in parallel */
2265                         mask= (CustomDataMask)GET_INT_FROM_POINTER(curr->link);
2266                         if(mask & CD_MASK_ORCO) {
2267                                 if(!orcodm)
2268                                         orcodm= create_orco_dm(ob, ob->data, em, CD_ORCO);
2269
2270                                 mask &= ~CD_MASK_ORCO;
2271                                 DM_set_only_copy(orcodm, mask | CD_MASK_ORIGINDEX);
2272
2273                                 if (mti->applyModifierEM)
2274                                         ndm = mti->applyModifierEM(md, ob, em, orcodm);
2275                                 else
2276                                         ndm = mti->applyModifier(md, ob, orcodm, 0, 0);
2277
2278                                 if(ndm) {
2279                                         /* if the modifier returned a new dm, release the old one */
2280                                         if(orcodm && orcodm != ndm) orcodm->release(orcodm);
2281                                         orcodm = ndm;
2282                                 }
2283                         }
2284
2285                         /* set the DerivedMesh to only copy needed data */
2286                         mask= (CustomDataMask)GET_INT_FROM_POINTER(curr->link); /* CD_MASK_ORCO may have been cleared above */
2287
2288                         DM_set_only_copy(dm, mask | CD_MASK_ORIGINDEX);
2289
2290                         if(mask & CD_MASK_ORIGSPACE)
2291                                 if(!CustomData_has_layer(&dm->faceData, CD_ORIGSPACE))
2292                                         DM_add_face_layer(dm, CD_ORIGSPACE, CD_DEFAULT, NULL);
2293                         
2294                         if (mti->applyModifierEM)
2295                                 ndm = mti->applyModifierEM(md, ob, em, dm);
2296                         else
2297                                 ndm = mti->applyModifier(md, ob, dm, 0, 0);
2298
2299                         if (ndm) {
2300                                 if(dm && dm != ndm)
2301                                         dm->release(dm);
2302
2303                                 dm = ndm;
2304
2305                                 if (deformedVerts) {
2306                                         MEM_freeN(deformedVerts);
2307                                         deformedVerts = NULL;
2308                                 }
2309                         }
2310                 }
2311
2312                 if(cage_r && i == cageIndex) {
2313                         if(dm && deformedVerts) {
2314                                 *cage_r = CDDM_copy(dm);
2315                                 CDDM_apply_vert_coords(*cage_r, deformedVerts);
2316                         } else if(dm) {
2317                                 *cage_r = dm;
2318                         } else {
2319                                 *cage_r =
2320                                         editmesh_get_derived(em,
2321                                                 deformedVerts ? MEM_dupallocN(deformedVerts) : NULL);
2322                         }
2323                 }
2324         }
2325
2326         BLI_linklist_free(datamasks, NULL);
2327
2328         /* Yay, we are done. If we have a DerivedMesh and deformed vertices need
2329          * to apply these back onto the DerivedMesh. If we have no DerivedMesh
2330          * then we need to build one.
2331          */
2332         if(dm && deformedVerts) {
2333                 *final_r = CDDM_copy(dm);
2334
2335                 if(!(cage_r && dm == *cage_r)) dm->release(dm);
2336
2337                 CDDM_apply_vert_coords(*final_r, deformedVerts);
2338                 CDDM_calc_normals(*final_r);
2339         } else if (dm) {
2340                 *final_r = dm;
2341         } else if (!deformedVerts && cage_r && *cage_r) {
2342                 *final_r = *cage_r;
2343         } else {
2344                 *final_r = editmesh_get_derived(em, deformedVerts);
2345                 deformedVerts = NULL;
2346         }
2347
2348         /* add an orco layer if needed */
2349         if(dataMask & CD_MASK_ORCO)
2350                 add_orco_dm(ob, em, *final_r, orcodm, CD_ORCO);
2351
2352         if(orcodm)
2353                 orcodm->release(orcodm);
2354
2355         if(deformedVerts)
2356                 MEM_freeN(deformedVerts);
2357 }
2358
2359 static void clear_mesh_caches(Object *ob)
2360 {
2361         Mesh *me= ob->data;
2362
2363                 /* also serves as signal to remake texspace */
2364         if (ob->bb) {
2365                 MEM_freeN(ob->bb);
2366                 ob->bb = NULL;
2367         }
2368         if (me->bb) {
2369                 MEM_freeN(me->bb);
2370                 me->bb = NULL;
2371         }
2372
2373         freedisplist(&ob->disp);
2374
2375         if (ob->derivedFinal) {
2376                 ob->derivedFinal->needsFree = 1;
2377                 ob->derivedFinal->release(ob->derivedFinal);
2378                 ob->derivedFinal= NULL;
2379         }
2380         if (ob->derivedDeform) {
2381                 ob->derivedDeform->needsFree = 1;
2382                 ob->derivedDeform->release(ob->derivedDeform);
2383                 ob->derivedDeform= NULL;
2384         }
2385
2386         if(ob->sculpt) {
2387                 object_sculpt_modifiers_changed(ob);
2388         }
2389 }
2390
2391 static void mesh_build_data(Scene *scene, Object *ob, CustomDataMask dataMask)
2392 {
2393         Object *obact = scene->basact?scene->basact->object:NULL;
2394         int editing = paint_facesel_test(ob) || paint_vertsel_test(ob);/* paint_vertsel_test */
2395         /* weight paint and face select need original indices because of selection buffer drawing */
2396         int needMapping = (ob==obact) && (editing || (ob->mode & (OB_MODE_WEIGHT_PAINT|OB_MODE_VERTEX_PAINT)));
2397
2398         clear_mesh_caches(ob);
2399
2400         mesh_calc_modifiers(scene, ob, NULL, &ob->derivedDeform,
2401                                                 &ob->derivedFinal, 0, 1,
2402                                                 needMapping, dataMask, -1, 1);
2403
2404         DM_set_object_boundbox (ob, ob->derivedFinal);
2405
2406         ob->derivedFinal->needsFree = 0;
2407         ob->derivedDeform->needsFree = 0;
2408         ob->lastDataMask = dataMask;
2409 }
2410
2411 static void editmesh_build_data(Scene *scene, Object *obedit, EditMesh *em, CustomDataMask dataMask)
2412 {
2413         clear_mesh_caches(obedit);
2414
2415         if (em->derivedFinal) {
2416                 if (em->derivedFinal!=em->derivedCage) {
2417                         em->derivedFinal->needsFree = 1;
2418                         em->derivedFinal->release(em->derivedFinal);
2419                 }
2420                 em->derivedFinal = NULL;
2421         }
2422         if (em->derivedCage) {
2423                 em->derivedCage->needsFree = 1;
2424                 em->derivedCage->release(em->derivedCage);
2425                 em->derivedCage = NULL;
2426         }
2427
2428         editmesh_calc_modifiers(scene, obedit, em, &em->derivedCage, &em->derivedFinal, dataMask);
2429         DM_set_object_boundbox (obedit, em->derivedFinal);
2430
2431         em->lastDataMask = dataMask;
2432         em->derivedFinal->needsFree = 0;
2433         em->derivedCage->needsFree = 0;
2434 }
2435
2436 void makeDerivedMesh(Scene *scene, Object *ob, EditMesh *em, CustomDataMask dataMask)
2437 {
2438         if (em) {
2439                 editmesh_build_data(scene, ob, em, dataMask);
2440         } else {
2441                 mesh_build_data(scene, ob, dataMask);
2442         }
2443 }
2444
2445 /***/
2446
2447 DerivedMesh *mesh_get_derived_final(Scene *scene, Object *ob, CustomDataMask dataMask)
2448 {
2449         /* if there's no derived mesh or the last data mask used doesn't include
2450          * the data we need, rebuild the derived mesh
2451          */
2452         if(!ob->derivedFinal || (dataMask & ob->lastDataMask) != dataMask)
2453                 mesh_build_data(scene, ob, dataMask);
2454
2455         return ob->derivedFinal;
2456 }
2457
2458 DerivedMesh *mesh_get_derived_deform(Scene *scene, Object *ob, CustomDataMask dataMask)
2459 {
2460         /* if there's no derived mesh or the last data mask used doesn't include
2461          * the data we need, rebuild the derived mesh
2462          */
2463         if(!ob->derivedDeform || (dataMask & ob->lastDataMask) != dataMask)
2464                 mesh_build_data(scene, ob, dataMask);
2465
2466         return ob->derivedDeform;
2467 }
2468
2469 DerivedMesh *mesh_create_derived_render(Scene *scene, Object *ob, CustomDataMask dataMask)
2470 {
2471         DerivedMesh *final;
2472         
2473         mesh_calc_modifiers(scene, ob, NULL, NULL, &final, 1, 1, 0, dataMask, -1, 0);
2474
2475         return final;
2476 }
2477
2478 DerivedMesh *mesh_create_derived_index_render(Scene *scene, Object *ob, CustomDataMask dataMask, int index)
2479 {
2480         DerivedMesh *final;
2481         
2482         mesh_calc_modifiers(scene, ob, NULL, NULL, &final, 1, 1, 0, dataMask, index, 0);
2483
2484         return final;
2485 }
2486
2487 DerivedMesh *mesh_create_derived_view(Scene *scene, Object *ob, CustomDataMask dataMask)
2488 {
2489         DerivedMesh *final;
2490
2491         mesh_calc_modifiers(scene, ob, NULL, NULL, &final, 0, 1, 0, dataMask, -1, 0);
2492
2493         return final;
2494 }
2495
2496 DerivedMesh *mesh_create_derived_no_deform(Scene *scene, Object *ob, float (*vertCos)[3],
2497                                                                                    CustomDataMask dataMask)
2498 {
2499         DerivedMesh *final;
2500         
2501         mesh_calc_modifiers(scene, ob, vertCos, NULL, &final, 0, 0, 0, dataMask, -1, 0);
2502
2503         return final;
2504 }
2505
2506 DerivedMesh *mesh_create_derived_no_virtual(Scene *scene, Object *ob, float (*vertCos)[3],
2507                                                                                         CustomDataMask dataMask)
2508 {
2509         DerivedMesh *final;
2510         
2511         mesh_calc_modifiers(scene, ob, vertCos, NULL, &final, 0, -1, 0, dataMask, -1, 0);
2512
2513         return final;
2514 }
2515
2516 DerivedMesh *mesh_create_derived_physics(Scene *scene, Object *ob, float (*vertCos)[3],
2517                                                                                         CustomDataMask dataMask)
2518 {
2519         DerivedMesh *final;
2520         
2521         mesh_calc_modifiers(scene, ob, vertCos, NULL, &final, 0, -1, 1, dataMask, -1, 0);
2522
2523         return final;
2524 }
2525
2526 DerivedMesh *mesh_create_derived_no_deform_render(Scene *scene, Object *ob,
2527                                                                                                   float (*vertCos)[3],
2528                                                                                                   CustomDataMask dataMask)
2529 {
2530         DerivedMesh *final;
2531
2532         mesh_calc_modifiers(scene, ob, vertCos, NULL, &final, 1, 0, 0, dataMask, -1, 0);
2533
2534         return final;
2535 }
2536
2537 /***/
2538
2539 DerivedMesh *editmesh_get_derived_cage_and_final(Scene *scene, Object *obedit, EditMesh *em, DerivedMesh **final_r,
2540                                                                                                  CustomDataMask dataMask)
2541 {
2542         /* if there's no derived mesh or the last data mask used doesn't include
2543          * the data we need, rebuild the derived mesh
2544          */
2545         if(!em->derivedCage ||
2546            (em->lastDataMask & dataMask) != dataMask)
2547                 editmesh_build_data(scene, obedit, em, dataMask);
2548
2549         *final_r = em->derivedFinal;
2550         return em->derivedCage;
2551 }
2552
2553 DerivedMesh *editmesh_get_derived_cage(Scene *scene, Object *obedit, EditMesh *em, CustomDataMask dataMask)
2554 {
2555         /* if there's no derived mesh or the last data mask used doesn't include
2556          * the data we need, rebuild the derived mesh
2557          */
2558         if(!em->derivedCage ||
2559            (em->lastDataMask & dataMask) != dataMask)
2560                 editmesh_build_data(scene, obedit, em, dataMask);
2561
2562         return em->derivedCage;
2563 }
2564
2565 DerivedMesh *editmesh_get_derived_base(Object *UNUSED(obedit), EditMesh *em)
2566 {
2567         return editmesh_get_derived(em, NULL);
2568 }
2569
2570
2571 /* ********* For those who don't grasp derived stuff! (ton) :) *************** */
2572
2573 static void make_vertexcosnos__mapFunc(void *userData, int index, float *co, float *no_f, short *no_s)
2574 {
2575         float *vec = userData;
2576         
2577         vec+= 6*index;
2578
2579         /* check if we've been here before (normal should not be 0) */
2580         if(vec[3] || vec[4] || vec[5]) return;
2581
2582         copy_v3_v3(vec, co);
2583         vec+= 3;
2584         if(no_f) {
2585                 copy_v3_v3(vec, no_f);
2586         }
2587         else {
2588                 normal_short_to_float_v3(vec, no_s);
2589         }
2590 }
2591
2592 /* always returns original amount me->totvert of vertices and normals, but fully deformed and subsurfered */
2593 /* this is needed for all code using vertexgroups (no subsurf support) */
2594 /* it stores the normals as floats, but they can still be scaled as shorts (32767 = unit) */
2595 /* in use now by vertex/weight paint and particle generating */
2596
2597 float *mesh_get_mapped_verts_nors(Scene *scene, Object *ob)
2598 {
2599         Mesh *me= ob->data;
2600         DerivedMesh *dm;
2601         float *vertexcosnos;
2602         
2603         /* lets prevent crashing... */
2604         if(ob->type!=OB_MESH || me->totvert==0)
2605                 return NULL;
2606         
2607         dm= mesh_get_derived_final(scene, ob, CD_MASK_BAREMESH);
2608         vertexcosnos= MEM_callocN(6*sizeof(float)*me->totvert, "vertexcosnos map");
2609         
2610         if(dm->foreachMappedVert) {
2611                 dm->foreachMappedVert(dm, make_vertexcosnos__mapFunc, vertexcosnos);
2612         }
2613         else {
2614                 float *fp= vertexcosnos;
2615                 int a;
2616                 
2617                 for(a=0; a< me->totvert; a++, fp+=6) {
2618                         dm->getVertCo(dm, a, fp);
2619                         dm->getVertNo(dm, a, fp+3);
2620                 }
2621         }
2622         
2623         dm->release(dm);
2624         return vertexcosnos;
2625 }
2626
2627 /* ******************* GLSL ******************** */
2628
2629 typedef struct
2630 {
2631         float * precomputedFaceNormals;
2632         MTFace * mtface;        // texture coordinates
2633         MFace * mface;          // indices
2634         MVert * mvert;          // vertices & normals
2635         float (*orco)[3];
2636         float (*tangent)[4];    // destination
2637         int numFaces;
2638
2639 } SGLSLMeshToTangent;
2640
2641 // interface
2642 #include "mikktspace.h"
2643
2644 static int GetNumFaces(const SMikkTSpaceContext * pContext)
2645 {
2646         SGLSLMeshToTangent * pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
2647         return pMesh->numFaces;
2648 }
2649
2650 static int GetNumVertsOfFace(const SMikkTSpaceContext * pContext, const int face_num)
2651 {
2652         SGLSLMeshToTangent * pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
2653         return pMesh->mface[face_num].v4!=0 ? 4 : 3;
2654 }
2655
2656 static void GetPosition(const SMikkTSpaceContext * pContext, float fPos[], const int face_num, const int vert_index)
2657 {
2658         //assert(vert_index>=0 && vert_index<4);
2659         SGLSLMeshToTangent * pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
2660         const float *co= pMesh->mvert[(&pMesh->mface[face_num].v1)[vert_index]].co;
2661         VECCOPY(fPos, co);
2662 }
2663
2664 static void GetTextureCoordinate(const SMikkTSpaceContext * pContext, float fUV[], const int face_num, const int vert_index)
2665 {
2666         //assert(vert_index>=0 && vert_index<4);
2667         SGLSLMeshToTangent * pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
2668
2669         if(pMesh->mtface!=NULL) {
2670                 float * uv = pMesh->mtface[face_num].uv[vert_index];
2671                 fUV[0]=uv[0]; fUV[1]=uv[1];
2672         }
2673         else {
2674                 const float *orco= pMesh->orco[(&pMesh->mface[face_num].v1)[vert_index]];
2675                 map_to_sphere( &fUV[0], &fUV[1], orco[0], orco[1], orco[2]);
2676         }
2677 }
2678
2679 static void GetNormal(const SMikkTSpaceContext * pContext, float fNorm[], const int face_num, const int vert_index)
2680 {
2681         //assert(vert_index>=0 && vert_index<4);
2682         SGLSLMeshToTangent * pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
2683
2684         const int smoothnormal = (pMesh->mface[face_num].flag & ME_SMOOTH);
2685         if(!smoothnormal) {     // flat
2686                 if(pMesh->precomputedFaceNormals) {
2687                         VECCOPY(fNorm, &pMesh->precomputedFaceNormals[3*face_num]);
2688                 }
2689                 else {
2690                         MFace *mf= &pMesh->mface[face_num];
2691                         float *p0= pMesh->mvert[mf->v1].co;
2692                         float *p1= pMesh->mvert[mf->v2].co;
2693                         float *p2= pMesh->mvert[mf->v3].co;
2694
2695                         if(mf->v4) {
2696                                 float *p3 = pMesh->mvert[mf->v4].co;
2697                                 normal_quad_v3(fNorm, p0, p1, p2, p3);
2698                         }
2699                         else {
2700                                 normal_tri_v3(fNorm, p0, p1, p2);
2701                         }
2702                 }
2703         }
2704         else {
2705                 const short *no= pMesh->mvert[(&pMesh->mface[face_num].v1)[vert_index]].no;
2706                 normal_short_to_float_v3(fNorm, no);
2707         }
2708 }
2709 static void SetTSpace(const SMikkTSpaceContext * pContext, const float fvTangent[], const float fSign, const int face_num, const int iVert)
2710 {
2711         //assert(vert_index>=0 && vert_index<4);
2712         SGLSLMeshToTangent * pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
2713         float * pRes = pMesh->tangent[4*face_num+iVert];
2714         VECCOPY(pRes, fvTangent);
2715         pRes[3]=fSign;
2716 }
2717
2718
2719 void DM_add_tangent_layer(DerivedMesh *dm)
2720 {
2721         /* mesh vars */
2722         MTFace *mtface, *tf;
2723         MFace *mface, *mf;
2724         MVert *mvert, *v1, *v2, *v3, *v4;
2725         MemArena *arena= NULL;
2726         VertexTangent **vtangents= NULL;
2727         float (*orco)[3]= NULL, (*tangent)[4];
2728         float *uv1, *uv2, *uv3, *uv4, *vtang;
2729         float fno[3], tang[3], uv[4][2];
2730         int i, j, len, mf_vi[4], totvert, totface, iCalcNewMethod;
2731         float *nors;
2732
2733         if(CustomData_get_layer_index(&dm->faceData, CD_TANGENT) != -1)
2734                 return;
2735
2736         nors = dm->getFaceDataArray(dm, CD_NORMAL);
2737
2738         /* check we have all the needed layers */
2739         totvert= dm->getNumVerts(dm);
2740         totface= dm->getNumFaces(dm);
2741
2742         mvert= dm->getVertArray(dm);
2743         mface= dm->getFaceArray(dm);
2744         mtface= dm->getFaceDataArray(dm, CD_MTFACE);
2745
2746         if(!mtface) {
2747                 orco= dm->getVertDataArray(dm, CD_ORCO);
2748                 if(!orco)
2749                         return;
2750         }
2751         
2752         /* create tangent layer */
2753         DM_add_face_layer(dm, CD_TANGENT, CD_CALLOC, NULL);
2754         tangent= DM_get_face_data_layer(dm, CD_TANGENT);
2755         
2756         /* allocate some space */
2757         arena= BLI_memarena_new(BLI_MEMARENA_STD_BUFSIZE, "tangent layer arena");
2758         BLI_memarena_use_calloc(arena);
2759         vtangents= MEM_callocN(sizeof(VertexTangent*)*totvert, "VertexTangent");
2760
2761         // new computation method
2762         iCalcNewMethod = 1;
2763         if(iCalcNewMethod != 0) {
2764                 SGLSLMeshToTangent mesh2tangent= {0};
2765                 SMikkTSpaceContext sContext= {0};
2766                 SMikkTSpaceInterface sInterface= {0};
2767
2768                 mesh2tangent.precomputedFaceNormals = nors;
2769                 mesh2tangent.mtface = mtface;
2770                 mesh2tangent.mface = mface;
2771                 mesh2tangent.mvert = mvert;
2772                 mesh2tangent.orco = orco;
2773                 mesh2tangent.tangent = tangent;
2774                 mesh2tangent.numFaces = totface;
2775
2776                 sContext.m_pUserData = &mesh2tangent;
2777                 sContext.m_pInterface = &sInterface;
2778                 sInterface.m_getNumFaces = GetNumFaces;
2779                 sInterface.m_getNumVerticesOfFace = GetNumVertsOfFace;
2780                 sInterface.m_getPosition = GetPosition;
2781                 sInterface.m_getTexCoord = GetTextureCoordinate;
2782                 sInterface.m_getNormal = GetNormal;
2783                 sInterface.m_setTSpaceBasic = SetTSpace;
2784
2785                 // 0 if failed
2786                 iCalcNewMethod = genTangSpaceDefault(&sContext);
2787         }
2788
2789         if(!iCalcNewMethod) {
2790                 /* sum tangents at connected vertices */
2791                 for(i=0, tf=mtface, mf=mface; i < totface; mf++, tf++, i++) {
2792                         v1= &mvert[mf->v1];
2793                         v2= &mvert[mf->v2];
2794                         v3= &mvert[mf->v3];
2795
2796                         if (mf->v4) {
2797                                 v4= &mvert[mf->v4];
2798                                 normal_quad_v3( fno,v4->co, v3->co, v2->co, v1->co);
2799                         }
2800                         else {
2801                                 v4= NULL;
2802                                 normal_tri_v3( fno,v3->co, v2->co, v1->co);
2803                         }
2804                 
2805                         if(mtface) {
2806                                 uv1= tf->uv[0];
2807                                 uv2= tf->uv[1];
2808                                 uv3= tf->uv[2];
2809                                 uv4= tf->uv[3];
2810                         }
2811                         else {
2812                                 uv1= uv[0]; uv2= uv[1]; uv3= uv[2]; uv4= uv[3];
2813                                 map_to_sphere( &uv[0][0], &uv[0][1],orco[mf->v1][0], orco[mf->v1][1], orco[mf->v1][2]);
2814                                 map_to_sphere( &uv[1][0], &uv[1][1],orco[mf->v2][0], orco[mf->v2][1], orco[mf->v2][2]);
2815                                 map_to_sphere( &uv[2][0], &uv[2][1],orco[mf->v3][0], orco[mf->v3][1], orco[mf->v3][2]);
2816                                 if(v4)
2817                                         map_to_sphere( &uv[3][0], &uv[3][1],orco[mf->v4][0], orco[mf->v4][1], orco[mf->v4][2]);
2818                         }
2819                 
2820                         tangent_from_uv(uv1, uv2, uv3, v1->co, v2->co, v3->co, fno, tang);
2821                         sum_or_add_vertex_tangent(arena, &vtangents[mf->v1], tang, uv1);
2822                         sum_or_add_vertex_tangent(arena, &vtangents[mf->v2], tang, uv2);
2823                         sum_or_add_vertex_tangent(arena, &vtangents[mf->v3], tang, uv3);
2824                 
2825                         if(mf->v4) {
2826                                 v4= &mvert[mf->v4];
2827                         
2828                                 tangent_from_uv(uv1, uv3, uv4, v1->co, v3->co, v4->co, fno, tang);
2829                                 sum_or_add_vertex_tangent(arena, &vtangents[mf->v1], tang, uv1);
2830                                 sum_or_add_vertex_tangent(arena, &vtangents[mf->v3], tang, uv3);
2831                                 sum_or_add_vertex_tangent(arena, &vtangents[mf->v4], tang, uv4);
2832                         }
2833                 }
2834         
2835                 /* write tangent to layer */
2836                 for(i=0, tf=mtface, mf=mface; i < totface; mf++, tf++, i++, tangent+=4) {
2837                         len= (mf->v4)? 4 : 3; 
2838
2839                         if(mtface == NULL) {
2840                                 map_to_sphere( &uv[0][0], &uv[0][1],orco[mf->v1][0], orco[mf->v1][1], orco[mf->v1][2]);
2841                                 map_to_sphere( &uv[1][0], &uv[1][1],orco[mf->v2][0], orco[mf->v2][1], orco[mf->v2][2]);
2842                                 map_to_sphere( &uv[2][0], &uv[2][1],orco[mf->v3][0], orco[mf->v3][1], orco[mf->v3][2]);
2843                                 if(len==4)
2844                                         map_to_sphere( &uv[3][0], &uv[3][1],orco[mf->v4][0], orco[mf->v4][1], orco[mf->v4][2]);
2845                         }
2846                 
2847                         mf_vi[0]= mf->v1;
2848                         mf_vi[1]= mf->v2;
2849                         mf_vi[2]= mf->v3;
2850                         mf_vi[3]= mf->v4;
2851                 
2852                         for(j=0; j<len; j++) {
2853                                 vtang= find_vertex_tangent(vtangents[mf_vi[j]], mtface ? tf->uv[j] : uv[j]);
2854                                 normalize_v3_v3(tangent[j], vtang);
2855                                 ((float *) tangent[j])[3]=1.0f;
2856                         }
2857                 }
2858         }
2859         
2860         BLI_memarena_free(arena);
2861         MEM_freeN(vtangents);
2862 }
2863
2864 void DM_vertex_attributes_from_gpu(DerivedMesh *dm, GPUVertexAttribs *gattribs, DMVertexAttribs *attribs)
2865 {
2866         CustomData *vdata, *fdata, *tfdata = NULL;
2867         int a, b, layer;
2868
2869         /* From the layers requested by the GLSL shader, figure out which ones are
2870          * actually available for this derivedmesh, and retrieve the pointers */
2871
2872         memset(attribs, 0, sizeof(DMVertexAttribs));
2873
2874         vdata = &dm->vertData;
2875         fdata = &dm->faceData;
2876
2877         /* ugly hack, editmesh derivedmesh doesn't copy face data, this way we
2878          * can use offsets instead */
2879         if(dm->release == emDM_release)
2880                 tfdata = &((EditMeshDerivedMesh*)dm)->em->fdata;
2881         else
2882                 tfdata = fdata;
2883
2884         /* add a tangent layer if necessary */
2885         for(b = 0; b < gattribs->totlayer; b++)
2886                 if(gattribs->layer[b].type == CD_TANGENT)
2887                         if(CustomData_get_layer_index(fdata, CD_TANGENT) == -1)
2888                                 DM_add_tangent_layer(dm);
2889
2890         for(b = 0; b < gattribs->totlayer; b++) {
2891                 if(gattribs->layer[b].type == CD_MTFACE) {
2892                         /* uv coordinates */
2893                         if(gattribs->layer[b].name[0])
2894                                 layer = CustomData_get_named_layer_index(tfdata, CD_MTFACE,
2895                                         gattribs->layer[b].name);
2896                         else
2897                                 layer = CustomData_get_active_layer_index(tfdata, CD_MTFACE);
2898
2899                         if(layer != -1) {
2900                                 a = attribs->tottface++;
2901
2902                                 attribs->tface[a].array = tfdata->layers[layer].data;
2903                                 attribs->tface[a].emOffset = tfdata->layers[layer].offset;
2904                                 attribs->tface[a].glIndex = gattribs->layer[b].glindex;
2905                                 attribs->tface[a].glTexco = gattribs->layer[b].gltexco;
2906                         }
2907                 }
2908                 else if(gattribs->layer[b].type == CD_MCOL) {
2909                         /* vertex colors */
2910                         if(gattribs->layer[b].name[0])
2911                                 layer = CustomData_get_named_layer_index(tfdata, CD_MCOL,
2912                                         gattribs->layer[b].name);
2913                         else
2914                                 layer = CustomData_get_active_layer_index(tfdata, CD_MCOL);
2915
2916                         if(layer != -1) {
2917                                 a = attribs->totmcol++;
2918
2919                                 attribs->mcol[a].array = tfdata->layers[layer].data;
2920                                 attribs->mcol[a].emOffset = tfdata->layers[layer].offset;
2921                                 attribs->mcol[a].glIndex = gattribs->layer[b].glindex;
2922                         }
2923                 }
2924                 else if(gattribs->layer[b].type == CD_TANGENT) {
2925                         /* tangents */
2926                         layer = CustomData_get_layer_index(fdata, CD_TANGENT);
2927
2928                         if(layer != -1) {
2929                                 attribs->tottang = 1;
2930
2931                                 attribs->tang.array = fdata->layers[layer].data;
2932                                 attribs->tang.emOffset = fdata->layers[layer].offset;
2933                                 attribs->tang.glIndex = gattribs->layer[b].glindex;
2934                         }
2935                 }
2936                 else if(gattribs->layer[b].type == CD_ORCO) {
2937                         /* original coordinates */
2938                         layer = Custom