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