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