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