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