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