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