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