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