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