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