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