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