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