Friday merge of bf-blender into orange branch.
[blender.git] / source / blender / src / editmesh_mods.c
1 /**
2  * $Id: 
3  *
4  * ***** BEGIN GPL/BL DUAL 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. The Blender
10  * Foundation also sells licenses for use in proprietary software under
11  * the Blender License.  See http://www.blender.org/BL/ for information
12  * about this.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program; if not, write to the Free Software Foundation,
21  * Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
22  *
23  * The Original Code is Copyright (C) 2004 by NaN Holding BV.
24  * All rights reserved.
25  *
26  * The Original Code is: all of this file.
27  *
28  * Contributor(s): none yet.
29  *
30  * ***** END GPL/BL DUAL LICENSE BLOCK *****
31  */
32
33 /*
34
35 editmesh_mods.c, UI level access, no geometry changes 
36
37 */
38
39 #include <stdlib.h>
40 #include <string.h>
41 #include <math.h>
42
43 #ifdef HAVE_CONFIG_H
44 #include <config.h>
45 #endif
46
47 #include "MEM_guardedalloc.h"
48
49 #include "MTC_matrixops.h"
50
51 #include "DNA_mesh_types.h"
52 #include "DNA_material_types.h"
53 #include "DNA_meshdata_types.h"
54 #include "DNA_modifier_types.h"
55 #include "DNA_object_types.h"
56 #include "DNA_texture_types.h"
57 #include "DNA_scene_types.h"
58 #include "DNA_screen_types.h"
59 #include "DNA_view3d_types.h"
60
61 #include "BLI_blenlib.h"
62 #include "BLI_arithb.h"
63 #include "BLI_editVert.h"
64 #include "BLI_rand.h"
65
66 #include "BKE_displist.h"
67 #include "BKE_depsgraph.h"
68 #include "BKE_DerivedMesh.h"
69 #include "BKE_global.h"
70 #include "BKE_mesh.h"
71 #include "BKE_material.h"
72 #include "BKE_texture.h"
73 #include "BKE_utildefines.h"
74
75 #include "BIF_editmesh.h"
76 #include "BIF_resources.h"
77 #include "BIF_gl.h"
78 #include "BIF_glutil.h"
79 #include "BIF_graphics.h"
80 #include "BIF_interface.h"
81 #include "BIF_meshtools.h"
82 #include "BIF_mywindow.h"
83 #include "BIF_resources.h"
84 #include "BIF_screen.h"
85 #include "BIF_space.h"
86 #include "BIF_toolbox.h"
87
88 #include "BDR_drawobject.h"
89 #include "BDR_editobject.h"
90
91 #include "BSE_drawview.h"
92 #include "BSE_edit.h"
93 #include "BSE_view.h"
94
95 #include "IMB_imbuf.h"
96
97 #include "mydevice.h"
98 #include "blendef.h"
99 #include "render.h"  // externtex
100
101 #include "editmesh.h"
102
103
104 /* ****************************** MIRROR **************** */
105
106 void EM_select_mirrored(void)
107 {
108         if(G.scene->selectmode & SCE_SELECT_VERTEX) {
109                 EditMesh *em = G.editMesh;
110                 EditVert *eve, *v1;
111                 
112                 for(eve= em->verts.first; eve; eve= eve->next) {
113                         if(eve->f & SELECT) {
114                                 v1= editmesh_get_x_mirror_vert(G.obedit, eve->co);
115                                 if(v1) {
116                                         eve->f &= ~SELECT;
117                                         v1->f |= SELECT;
118                                 }
119                         }
120                 }
121         }
122 }
123
124 /* ****************************** SELECTION ROUTINES **************** */
125
126 unsigned int em_solidoffs=0, em_wireoffs=0, em_vertoffs=0;      // set in drawobject.c ... for colorindices
127
128 static void check_backbuf(void)
129 {
130         if(G.vd->flag & V3D_NEEDBACKBUFDRAW) {
131                 backdrawview3d(0);
132         }
133 }
134
135 /* samples a single pixel (copied from vpaint) */
136 static unsigned int sample_backbuf(int x, int y)
137 {
138         unsigned int col;
139         
140         if(x>=curarea->winx || y>=curarea->winy) return 0;
141         x+= curarea->winrct.xmin;
142         y+= curarea->winrct.ymin;
143         
144         check_backbuf(); // actually not needed for apple
145
146 #ifdef __APPLE__
147         glReadBuffer(GL_AUX0);
148 #endif
149         glReadPixels(x,  y, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE,  &col);
150         glReadBuffer(GL_BACK);  
151         
152         if(G.order==B_ENDIAN) SWITCH_INT(col);
153         
154         return framebuffer_to_index(col);
155 }
156
157 /* reads full rect, converts indices */
158 static unsigned int *read_backbuf(short xmin, short ymin, short xmax, short ymax)
159 {
160         unsigned int *dr, *buf;
161         int a;
162         short xminc, yminc, xmaxc, ymaxc;
163         
164         /* clip */
165         if(xmin<0) xminc= 0; else xminc= xmin;
166         if(xmax>=curarea->winx) xmaxc= curarea->winx-1; else xmaxc= xmax;
167         if(xminc > xmaxc) return NULL;
168
169         if(ymin<0) yminc= 0; else yminc= ymin;
170         if(ymax>=curarea->winy) ymaxc= curarea->winy-1; else ymaxc= ymax;
171         if(yminc > ymaxc) return NULL;
172         
173         buf= MEM_mallocN( (xmaxc-xminc+1)*(ymaxc-yminc+1)*sizeof(int), "sample rect");
174
175         check_backbuf(); // actually not needed for apple
176         
177 #ifdef __APPLE__
178         glReadBuffer(GL_AUX0);
179 #endif
180         glReadPixels(curarea->winrct.xmin+xminc, curarea->winrct.ymin+yminc, (xmaxc-xminc+1), (ymaxc-yminc+1), GL_RGBA, GL_UNSIGNED_BYTE, buf);
181         glReadBuffer(GL_BACK);  
182
183         if(G.order==B_ENDIAN) IMB_convert_rgba_to_abgr((xmaxc-xminc+1)*(ymaxc-yminc+1), buf);
184
185         a= (xmaxc-xminc+1)*(ymaxc-yminc+1);
186         dr= buf;
187         while(a--) {
188                 if(*dr) *dr= framebuffer_to_index(*dr);
189                 dr++;
190         }
191         
192         /* put clipped result back, if needed */
193         if(xminc==xmin && xmaxc==xmax && yminc==ymin && ymaxc==ymax) return buf;
194         else {
195                 unsigned int *buf1= MEM_callocN( (xmax-xmin+1)*(ymax-ymin+1)*sizeof(int), "sample rect2");
196                 unsigned int *rd;
197                 short xs, ys;
198
199                 rd= buf;
200                 dr= buf1;
201                 
202                 for(ys= ymin; ys<=ymax; ys++) {
203                         for(xs= xmin; xs<=xmax; xs++, dr++) {
204                                 if( xs>=xminc && xs<=xmaxc && ys>=yminc && ys<=ymaxc) {
205                                         *dr= *rd;
206                                         rd++;
207                                 }
208                         }
209                 }
210                 MEM_freeN(buf);
211                 return buf1;
212         }
213         
214         return buf;
215 }
216
217
218 /* smart function to sample a rect spiralling outside, nice for backbuf selection */
219 static unsigned int sample_backbuf_rect(short mval[2], int size, unsigned int min, unsigned int max, short *dist)
220 {
221         unsigned int *buf, *bufmin, *bufmax;
222         int minx, miny;
223         int a, b, rc, nr, amount, dirvec[4][2];
224         short distance=0;
225         unsigned int index = 0;
226         
227         amount= (size-1)/2;
228
229         minx = mval[0]-(amount+1);
230         miny = mval[1]-(amount+1);
231         buf = read_backbuf(minx, miny, minx+size-1, miny+size-1);
232         if (!buf)
233                 return 0;
234
235         rc= 0;
236         
237         dirvec[0][0]= 1; dirvec[0][1]= 0;
238         dirvec[1][0]= 0; dirvec[1][1]= -size;
239         dirvec[2][0]= -1; dirvec[2][1]= 0;
240         dirvec[3][0]= 0; dirvec[3][1]= size;
241         
242         bufmin= buf;
243         bufmax= buf+ size*size;
244         buf+= amount*size+ amount;
245         
246         for(nr=1; nr<=size; nr++) {
247                 
248                 for(a=0; a<2; a++) {
249                         for(b=0; b<nr; b++, distance++) {
250                                 if (*buf && *buf>=min && *buf<max) {
251                                         *dist= (short) sqrt( (float)distance ); // XXX, this distance is wrong - zr
252                                         index = *buf - min+1; // messy yah, but indices start at 1
253                                         goto exit;
254                                 }
255                                 
256                                 buf+= (dirvec[rc][0]+dirvec[rc][1]);
257                                 
258                                 if(buf<bufmin || buf>=bufmax) {
259                                         goto exit;
260                                 }
261                         }
262                         rc++;
263                         rc &= 3;
264                 }
265         }
266
267 exit:
268         MEM_freeN(bufmin);
269         return index;
270 }
271
272 /* facilities for border select and circle select */
273 static char *selbuf= NULL;
274
275 /* opengl doesn't support concave... */
276 static void draw_triangulated(short mcords[][2], short tot)
277 {
278         ListBase lb={NULL, NULL};
279         DispList *dl;
280         float *fp;
281         int a;
282         
283         /* make displist */
284         dl= MEM_callocN(sizeof(DispList), "poly disp");
285         dl->type= DL_POLY;
286         dl->parts= 1;
287         dl->nr= tot;
288         dl->verts= fp=  MEM_callocN(tot*3*sizeof(float), "poly verts");
289         BLI_addtail(&lb, dl);
290         
291         for(a=0; a<tot; a++, fp+=3) {
292                 fp[0]= (float)mcords[a][0];
293                 fp[1]= (float)mcords[a][1];
294         }
295         
296         /* do the fill */
297         filldisplist(&lb, &lb);
298
299         /* do the draw */
300         dl= lb.first;   // filldisplist adds in head of list
301         if(dl->type==DL_INDEX3) {
302                 int *index;
303                 
304                 a= dl->parts;
305                 fp= dl->verts;
306                 index= dl->index;
307                 glBegin(GL_TRIANGLES);
308                 while(a--) {
309                         glVertex3fv(fp+3*index[0]);
310                         glVertex3fv(fp+3*index[1]);
311                         glVertex3fv(fp+3*index[2]);
312                         index+= 3;
313                 }
314                 glEnd();
315         }
316         
317         freedisplist(&lb);
318 }
319
320
321 /* reads rect, and builds selection array for quick lookup */
322 /* returns if all is OK */
323 int EM_init_backbuf_border(short xmin, short ymin, short xmax, short ymax)
324 {
325         unsigned int *buf, *dr;
326         int a;
327         
328         if(G.obedit==NULL || G.vd->drawtype<OB_SOLID || (G.vd->flag & V3D_ZBUF_SELECT)==0) return 0;
329         if(em_vertoffs==0) return 0;
330         
331         dr= buf= read_backbuf(xmin, ymin, xmax, ymax);
332         if(buf==NULL) return 0;
333         
334         /* build selection lookup */
335         selbuf= MEM_callocN(em_vertoffs+1, "selbuf");
336         
337         a= (xmax-xmin+1)*(ymax-ymin+1);
338         while(a--) {
339                 if(*dr>0 && *dr<=em_vertoffs) 
340                         selbuf[*dr]= 1;
341                 dr++;
342         }
343         MEM_freeN(buf);
344         return 1;
345 }
346
347 int EM_check_backbuf(unsigned int index)
348 {
349         if(selbuf==NULL) return 1;
350         if(index>0 && index<=em_vertoffs)
351                 return selbuf[index];
352         return 0;
353 }
354
355 void EM_free_backbuf(void)
356 {
357         if(selbuf) MEM_freeN(selbuf);
358         selbuf= NULL;
359 }
360
361 /* mcords is a polygon mask
362    - grab backbuffer,
363    - draw with black in backbuffer, 
364    - grab again and compare
365    returns 'OK' 
366 */
367 int EM_mask_init_backbuf_border(short mcords[][2], short tot, short xmin, short ymin, short xmax, short ymax)
368 {
369         unsigned int *buf, *bufmask, *dr, *drm;
370         int a;
371         
372         /* method in use for face selecting too */
373         if(G.obedit==NULL) {
374                 if(G.f & G_FACESELECT);
375                 else return 0;
376         }
377         else if(G.vd->drawtype<OB_SOLID || (G.vd->flag & V3D_ZBUF_SELECT)==0) return 0;
378
379         if(em_vertoffs==0) return 0;
380         
381         dr= buf= read_backbuf(xmin, ymin, xmax, ymax);
382         if(buf==NULL) return 0;
383
384         /* draw the mask */
385 #ifdef __APPLE__
386         glDrawBuffer(GL_AUX0);
387 #endif
388         glDisable(GL_DEPTH_TEST);
389         
390         persp(PERSP_WIN);
391         glColor3ub(0, 0, 0);
392         
393         /* yah, opengl doesn't do concave... tsk! */
394         draw_triangulated(mcords, tot); 
395         
396         glBegin(GL_LINE_LOOP);  // for zero sized masks, lines
397         for(a=0; a<tot; a++) glVertex2s(mcords[a][0], mcords[a][1]);
398         glEnd();
399         
400         persp(PERSP_VIEW);
401         glFinish();     // to be sure readpixels sees mask
402         
403         glDrawBuffer(GL_BACK);
404         
405         /* grab mask */
406         drm= bufmask= read_backbuf(xmin, ymin, xmax, ymax);
407         if(bufmask==NULL) return 0; // only when mem alloc fails, go crash somewhere else!
408         
409         /* build selection lookup */
410         selbuf= MEM_callocN(em_vertoffs+1, "selbuf");
411         
412         a= (xmax-xmin+1)*(ymax-ymin+1);
413         while(a--) {
414                 if(*dr>0 && *dr<=em_vertoffs && *drm==0) selbuf[*dr]= 1;
415                 dr++; drm++;
416         }
417         MEM_freeN(buf);
418         MEM_freeN(bufmask);
419         return 1;
420         
421 }
422
423 /* circle shaped sample area */
424 int EM_init_backbuf_circle(short xs, short ys, short rads)
425 {
426         unsigned int *buf, *dr;
427         short xmin, ymin, xmax, ymax, xc, yc;
428         int radsq;
429         
430         /* method in use for face selecting too */
431         if(G.obedit==NULL) {
432                 if(G.f & G_FACESELECT);
433                 else return 0;
434         }
435         else if(G.vd->drawtype<OB_SOLID || (G.vd->flag & V3D_ZBUF_SELECT)==0) return 0;
436         if(em_vertoffs==0) return 0;
437         
438         xmin= xs-rads; xmax= xs+rads;
439         ymin= ys-rads; ymax= ys+rads;
440         dr= buf= read_backbuf(xmin, ymin, xmax, ymax);
441         if(buf==NULL) return 0;
442         
443         /* build selection lookup */
444         selbuf= MEM_callocN(em_vertoffs+1, "selbuf");
445         radsq= rads*rads;
446         for(yc= -rads; yc<=rads; yc++) {
447                 for(xc= -rads; xc<=rads; xc++, dr++) {
448                         if(xc*xc + yc*yc < radsq) {
449                                 if(*dr>0 && *dr<=em_vertoffs) selbuf[*dr]= 1;
450                         }
451                 }
452         }
453
454         MEM_freeN(buf);
455         return 1;
456         
457 }
458
459 static void findnearestvert__doClosest(void *userData, EditVert *eve, int x, int y, int index)
460 {
461         struct { short mval[2], pass, select, dist; int lastIndex, closestIndex; EditVert *closest; } *data = userData;
462
463         if (data->pass==0) {
464                 if (index<=data->lastIndex)
465                         return;
466         } else {
467                 if (index>data->lastIndex)
468                         return;
469         }
470
471         if (data->dist>3) {
472                 short temp = abs(data->mval[0] - x) + abs(data->mval[1]- y);
473                 if ((eve->f&1)==data->select) temp += 5;
474
475                 if (temp<data->dist) {
476                         data->dist = temp;
477                         data->closest = eve;
478                         data->closestIndex = index;
479                 }
480         }
481 }
482 static EditVert *findnearestvert(short *dist, short sel)
483 {
484         short mval[2];
485
486         getmouseco_areawin(mval);
487                 
488         if(G.vd->drawtype>OB_WIRE && (G.vd->flag & V3D_ZBUF_SELECT)) {
489                 short distance;
490                 unsigned int index = sample_backbuf_rect(mval, 50, em_wireoffs, 0xFFFFFF, &distance);
491                 EditVert *eve = BLI_findlink(&G.editMesh->verts, index-1);
492
493                 if (eve && distance < *dist) {
494                         *dist = distance;
495                         return eve;
496                 } else {
497                         return NULL;
498                 }
499         }
500         else {
501                 struct { short mval[2], pass, select, dist; int lastIndex, closestIndex; EditVert *closest; } data;
502                 static int lastSelectedIndex=0;
503                 static EditVert *lastSelected=NULL;
504
505                 if (lastSelected && BLI_findlink(&G.editMesh->verts, lastSelectedIndex)!=lastSelected) {
506                         lastSelectedIndex = 0;
507                         lastSelected = NULL;
508                 }
509
510                 data.lastIndex = lastSelectedIndex;
511                 data.mval[0] = mval[0];
512                 data.mval[1] = mval[1];
513                 data.select = sel;
514                 data.dist = *dist;
515                 data.closest = NULL;
516                 data.closestIndex = 0;
517
518                 data.pass = 0;
519                 mesh_foreachScreenVert(findnearestvert__doClosest, &data, 1);
520
521                 if (data.dist>3) {
522                         data.pass = 1;
523                         mesh_foreachScreenVert(findnearestvert__doClosest, &data, 1);
524                 }
525
526                 *dist = data.dist;
527                 lastSelected = data.closest;
528                 lastSelectedIndex = data.closestIndex;
529
530                 return data.closest;
531         }
532 }
533
534 /* returns labda for closest distance v1 to line-piece v2-v3 */
535 static float labda_PdistVL2Dfl( float *v1, float *v2, float *v3) 
536 {
537         float rc[2], len;
538         
539         rc[0]= v3[0]-v2[0];
540         rc[1]= v3[1]-v2[1];
541         len= rc[0]*rc[0]+ rc[1]*rc[1];
542         if(len==0.0f)
543                 return 0.0f;
544         
545         return ( rc[0]*(v1[0]-v2[0]) + rc[1]*(v1[1]-v2[1]) )/len;
546 }
547
548 /* note; uses G.vd, so needs active 3d window */
549 static void findnearestedge__doClosest(void *userData, EditEdge *eed, int x0, int y0, int x1, int y1, int index)
550 {
551         struct { float mval[2]; short dist; EditEdge *closest; } *data = userData;
552         float v1[2], v2[2];
553         short distance;
554                 
555         v1[0] = x0;
556         v1[1] = y0;
557         v2[0] = x1;
558         v2[1] = y1;
559                 
560         distance= PdistVL2Dfl(data->mval, v1, v2);
561                 
562         if(eed->f & SELECT) distance+=5;
563         if(distance < data->dist) {
564                 if(G.vd->flag & V3D_CLIPPING) {
565                         float labda= labda_PdistVL2Dfl(data->mval, v1, v2);
566                         float vec[3];
567
568                         vec[0]= eed->v1->co[0] + labda*(eed->v2->co[0] - eed->v1->co[0]);
569                         vec[1]= eed->v1->co[1] + labda*(eed->v2->co[1] - eed->v1->co[1]);
570                         vec[2]= eed->v1->co[2] + labda*(eed->v2->co[2] - eed->v1->co[2]);
571                         Mat4MulVecfl(G.obedit->obmat, vec);
572
573                         if(view3d_test_clipping(G.vd, vec)==0) {
574                                 data->dist = distance;
575                                 data->closest = eed;
576                         }
577                 }
578                 else {
579                         data->dist = distance;
580                         data->closest = eed;
581                 }
582         }
583 }
584 EditEdge *findnearestedge(short *dist)
585 {
586         short mval[2];
587                 
588         getmouseco_areawin(mval);
589
590         if(G.vd->drawtype>OB_WIRE && (G.vd->flag & V3D_ZBUF_SELECT)) {
591                 short distance;
592                 unsigned int index = sample_backbuf_rect(mval, 50, em_solidoffs, em_wireoffs, &distance);
593                 EditEdge *eed = BLI_findlink(&G.editMesh->edges, index-1);
594
595                 if (eed && distance<*dist) {
596                         *dist = distance;
597                         return eed;
598                 } else {
599                         return NULL;
600                 }
601         }
602         else {
603                 struct { float mval[2]; short dist; EditEdge *closest; } data;
604
605                 data.mval[0] = mval[0];
606                 data.mval[1] = mval[1];
607                 data.dist = *dist;
608                 data.closest = NULL;
609
610                 mesh_foreachScreenEdge(findnearestedge__doClosest, &data, 2);
611
612                 *dist = data.dist;
613                 return data.closest;
614         }
615 }
616
617 static void findnearestface__getDistance(void *userData, EditFace *efa, int x, int y, int index)
618 {
619         struct { short mval[2], dist; EditFace *toFace; } *data = userData;
620
621         if (efa==data->toFace) {
622                 short temp = abs(data->mval[0]-x) + abs(data->mval[1]-y);
623
624                 if (temp<data->dist)
625                         data->dist = temp;
626         }
627 }
628 static void findnearestface__doClosest(void *userData, EditFace *efa, int x, int y, int index)
629 {
630         struct { short mval[2], pass, dist; int lastIndex, closestIndex; EditFace *closest; } *data = userData;
631
632         if (data->pass==0) {
633                 if (index<=data->lastIndex)
634                         return;
635         } else {
636                 if (index>data->lastIndex)
637                         return;
638         }
639
640         if (data->dist>3) {
641                 short temp = abs(data->mval[0]-x) + abs(data->mval[1]-y);
642
643                 if (temp<data->dist) {
644                         data->dist = temp;
645                         data->closest = efa;
646                         data->closestIndex = index;
647                 }
648         }
649 }
650 static EditFace *findnearestface(short *dist)
651 {
652         short mval[2];
653
654         getmouseco_areawin(mval);
655
656         if(G.vd->drawtype>OB_WIRE && (G.vd->flag & V3D_ZBUF_SELECT)) {
657                 unsigned int index = sample_backbuf(mval[0], mval[1]);
658                 EditFace *efa = BLI_findlink(&G.editMesh->faces, index-1);
659
660                 if (efa) {
661                         struct { short mval[2], dist; EditFace *toFace; } data;
662
663                         data.mval[0] = mval[0];
664                         data.mval[1] = mval[1];
665                         data.dist = 0x7FFF;             // largest short
666                         data.toFace = efa;
667
668                         mesh_foreachScreenFace(findnearestface__getDistance, &data);
669
670                         if(G.scene->selectmode == SCE_SELECT_FACE || data.dist<*dist) { // only faces, no dist check
671                                 *dist= data.dist;
672                                 return efa;
673                         }
674                 }
675                 
676                 return NULL;
677         }
678         else {
679                 struct { short mval[2], pass, dist; int lastIndex, closestIndex; EditFace *closest; } data;
680                 static int lastSelectedIndex=0;
681                 static EditFace *lastSelected=NULL;
682
683                 if (lastSelected && BLI_findlink(&G.editMesh->faces, lastSelectedIndex)!=lastSelected) {
684                         lastSelectedIndex = 0;
685                         lastSelected = NULL;
686                 }
687
688                 data.lastIndex = lastSelectedIndex;
689                 data.mval[0] = mval[0];
690                 data.mval[1] = mval[1];
691                 data.dist = *dist;
692                 data.closest = NULL;
693                 data.closestIndex = 0;
694
695                 data.pass = 0;
696                 mesh_foreachScreenFace(findnearestface__doClosest, &data);
697
698                 if (data.dist>3) {
699                         data.pass = 1;
700                         mesh_foreachScreenFace(findnearestface__doClosest, &data);
701                 }
702
703                 *dist = data.dist;
704                 lastSelected = data.closest;
705                 lastSelectedIndex = data.closestIndex;
706
707                 return data.closest;
708         }
709 }
710
711 /* for interactivity, frontbuffer draw in current window */
712 static void draw_dm_mapped_vert__mapFunc(void *theVert, int index, float *co, float *no_f, short *no_s)
713 {
714         if (EM_get_vert_for_index(index)==theVert) {
715                 bglVertex3fv(co);
716         }
717 }
718 static void draw_dm_mapped_vert(DerivedMesh *dm, EditVert *eve)
719 {
720         EM_init_index_arrays(1, 0, 0);
721         bglBegin(GL_POINTS);
722         dm->foreachMappedVert(dm, draw_dm_mapped_vert__mapFunc, eve);
723         bglEnd();
724         EM_free_index_arrays();
725 }
726
727 static int draw_dm_mapped_edge__setDrawOptions(void *theEdge, int index)
728 {
729         return EM_get_edge_for_index(index)==theEdge;
730 }
731 static void draw_dm_mapped_edge(DerivedMesh *dm, EditEdge *eed)
732 {
733         EM_init_index_arrays(0, 1, 0);
734         dm->drawMappedEdges(dm, draw_dm_mapped_edge__setDrawOptions, eed);
735         EM_free_index_arrays();
736 }
737
738 static void draw_dm_mapped_face_center__mapFunc(void *theFace, int index, float *cent, float *no)
739 {
740         if (EM_get_face_for_index(index)==theFace) {
741                 bglVertex3fv(cent);
742         }
743 }
744 static void draw_dm_mapped_face_center(DerivedMesh *dm, EditFace *efa)
745 {
746         EM_init_index_arrays(0, 0, 1);
747         bglBegin(GL_POINTS);
748         dm->foreachMappedFaceCenter(dm, draw_dm_mapped_face_center__mapFunc, efa);
749         bglEnd();
750         EM_free_index_arrays();
751 }
752
753 static void unified_select_draw(EditVert *eve, EditEdge *eed, EditFace *efa)
754 {
755         int dmNeedsFree;
756         DerivedMesh *dm = editmesh_get_derived_cage(&dmNeedsFree);
757
758         glDrawBuffer(GL_FRONT);
759
760         persp(PERSP_VIEW);
761         
762         if(G.vd->flag & V3D_CLIPPING)
763                 view3d_set_clipping(G.vd);
764         
765         glPushMatrix();
766         mymultmatrix(G.obedit->obmat);
767         
768         /* face selected */
769         if(efa) {
770                 if(G.scene->selectmode & SCE_SELECT_VERTEX) {
771                         glPointSize(BIF_GetThemeValuef(TH_VERTEX_SIZE));
772                         
773                         if(efa->f & SELECT) BIF_ThemeColor(TH_VERTEX_SELECT);
774                         else BIF_ThemeColor(TH_VERTEX);
775                         
776                         bglBegin(GL_POINTS);
777                         bglVertex3fv(efa->v1->co);
778                         bglVertex3fv(efa->v2->co);
779                         bglVertex3fv(efa->v3->co);
780                         if(efa->v4) bglVertex3fv(efa->v4->co);
781                         bglEnd();
782                 }
783
784                 if(G.scene->selectmode & (SCE_SELECT_EDGE|SCE_SELECT_FACE)) {
785                         if(efa->fgonf==0) {
786                                 BIF_ThemeColor((efa->f & SELECT)?TH_EDGE_SELECT:TH_WIRE);
787         
788                                 draw_dm_mapped_edge(dm, efa->e1);
789                                 draw_dm_mapped_edge(dm, efa->e2);
790                                 draw_dm_mapped_edge(dm, efa->e3);
791                                 if (efa->e4) {
792                                         draw_dm_mapped_edge(dm, efa->e4);
793                                 }
794                         }
795                 }
796                 
797                 if(G.scene->selectmode & SCE_SELECT_FACE) {
798                         if(efa->fgonf==0) {
799                                 glPointSize(BIF_GetThemeValuef(TH_FACEDOT_SIZE));
800                                 BIF_ThemeColor((efa->f & SELECT)?TH_FACE_DOT:TH_WIRE);
801
802                                 draw_dm_mapped_face_center(dm, efa);
803                         }
804                 }
805         }
806         /* edge selected */
807         if(eed) {
808                 if(G.scene->selectmode & (SCE_SELECT_EDGE|SCE_SELECT_FACE)) {
809                         BIF_ThemeColor((eed->f & SELECT)?TH_EDGE_SELECT:TH_WIRE);
810
811                         draw_dm_mapped_edge(dm, eed);
812                 }
813                 if(G.scene->selectmode & SCE_SELECT_VERTEX) {
814                         glPointSize(BIF_GetThemeValuef(TH_VERTEX_SIZE));
815                         
816                         BIF_ThemeColor((eed->f & SELECT)?TH_VERTEX_SELECT:TH_VERTEX);
817                         
818                         draw_dm_mapped_vert(dm, eed->v1);
819                         draw_dm_mapped_vert(dm, eed->v2);
820                 }
821         }
822         if(eve) {
823                 if(G.scene->selectmode & SCE_SELECT_VERTEX) {
824                         glPointSize(BIF_GetThemeValuef(TH_VERTEX_SIZE));
825                         
826                         BIF_ThemeColor((eve->f & SELECT)?TH_VERTEX_SELECT:TH_VERTEX);
827                         
828                         draw_dm_mapped_vert(dm, eve);
829                 }
830         }
831
832         glPointSize(1.0);
833         glPopMatrix();
834
835         glFlush();
836         glDrawBuffer(GL_BACK);
837
838         if(G.vd->flag & V3D_CLIPPING)
839                 view3d_clr_clipping();
840         
841         /* signal that frontbuf differs from back */
842         curarea->win_swap= WIN_FRONT_OK;
843
844         if (dmNeedsFree) {
845                 dm->release(dm);
846         }
847 }
848
849
850 /* best distance based on screen coords. 
851    use g.scene->selectmode to define how to use 
852    selected vertices and edges get disadvantage
853    return 1 if found one
854 */
855 static int unified_findnearest(EditVert **eve, EditEdge **eed, EditFace **efa) 
856 {
857         short dist= 75;
858         
859         *eve= NULL;
860         *eed= NULL;
861         *efa= NULL;
862         
863         if(G.scene->selectmode & SCE_SELECT_VERTEX)
864                 *eve= findnearestvert(&dist, SELECT);
865         if(G.scene->selectmode & SCE_SELECT_FACE)
866                 *efa= findnearestface(&dist);
867
868         dist-= 20;      // since edges select lines, we give dots advantage of 20 pix
869         if(G.scene->selectmode & SCE_SELECT_EDGE)
870                 *eed= findnearestedge(&dist);
871
872         /* return only one of 3 pointers, for frontbuffer redraws */
873         if(*eed) {
874                 *efa= NULL; *eve= NULL;
875         }
876         else if(*efa) {
877                 *eve= NULL;
878         }
879         
880         return (*eve || *eed || *efa);
881 }
882
883 /* ****************  LOOP SELECTS *************** */
884
885 /* selects quads in loop direction of indicated edge */
886 /* only flush over edges with valence <= 2 */
887 void faceloop_select(EditEdge *startedge, int select)
888 {
889         EditMesh *em = G.editMesh;
890         EditEdge *eed;
891         EditFace *efa;
892         int looking= 1;
893         
894         /* in eed->f1 we put the valence (amount of faces in edge) */
895         /* in eed->f2 we put tagged flag as correct loop */
896         /* in efa->f1 we put tagged flag as correct to select */
897
898         for(eed= em->edges.first; eed; eed= eed->next) {
899                 eed->f1= 0;
900                 eed->f2= 0;
901         }
902         for(efa= em->faces.first; efa; efa= efa->next) {
903                 efa->f1= 0;
904                 if(efa->h==0) {
905                         efa->e1->f1++;
906                         efa->e2->f1++;
907                         efa->e3->f1++;
908                         if(efa->e4) efa->e4->f1++;
909                 }
910         }
911         
912         // tag startedge OK
913         startedge->f2= 1;
914         
915         while(looking) {
916                 looking= 0;
917                 
918                 for(efa= em->faces.first; efa; efa= efa->next) {
919                         if(efa->e4 && efa->f1==0) {     // not done quad
920                                 if(efa->e1->f1<=2 && efa->e2->f1<=2 && efa->e3->f1<=2 && efa->e4->f1<=2) { // valence ok
921
922                                         // if edge tagged, select opposing edge and mark face ok
923                                         if(efa->e1->f2) {
924                                                 efa->e3->f2= 1;
925                                                 efa->f1= 1;
926                                                 looking= 1;
927                                         }
928                                         else if(efa->e2->f2) {
929                                                 efa->e4->f2= 1;
930                                                 efa->f1= 1;
931                                                 looking= 1;
932                                         }
933                                         if(efa->e3->f2) {
934                                                 efa->e1->f2= 1;
935                                                 efa->f1= 1;
936                                                 looking= 1;
937                                         }
938                                         if(efa->e4->f2) {
939                                                 efa->e2->f2= 1;
940                                                 efa->f1= 1;
941                                                 looking= 1;
942                                         }
943                                 }
944                         }
945                 }
946         }
947         
948         /* (de)select the faces */
949         if(select!=2) {
950                 for(efa= em->faces.first; efa; efa= efa->next) {
951                         if(efa->f1) EM_select_face(efa, select);
952                 }
953         }
954 }
955
956
957 /* helper for edgeloop_select, checks for eed->f2 tag in faces */
958 static int edge_not_in_tagged_face(EditEdge *eed)
959 {
960         EditMesh *em = G.editMesh;
961         EditFace *efa;
962         
963         for(efa= em->faces.first; efa; efa= efa->next) {
964                 if(efa->h==0) {
965                         if(efa->e1==eed || efa->e2==eed || efa->e3==eed || efa->e4==eed) {      // edge is in face
966                                 if(efa->e1->f2 || efa->e2->f2 || efa->e3->f2 || (efa->e4 && efa->e4->f2)) {     // face is tagged
967                                         return 0;
968                                 }
969                         }
970                 }
971         }
972         return 1;
973 }
974
975 /* selects or deselects edges that:
976 - if edges has 2 faces:
977         - has vertices with valence of 4
978         - not shares face with previous edge
979 - if edge has 1 face:
980         - has vertices with valence 4
981         - not shares face with previous edge
982         - but also only 1 face
983 - if edge no face:
984         - has vertices with valence 2
985 */
986 static void edgeloop_select(EditEdge *starteed, int select)
987 {
988         EditMesh *em = G.editMesh;
989         EditVert *eve;
990         EditEdge *eed;
991         EditFace *efa;
992         int looking= 1;
993         
994         /* in f1 we put the valence (amount of edges in a vertex, or faces in edge) */
995         /* in eed->f2 and efa->f1 we put tagged flag as correct loop */
996         for(eve= em->verts.first; eve; eve= eve->next) {
997                 eve->f1= 0;
998                 eve->f2= 0;
999         }
1000         for(eed= em->edges.first; eed; eed= eed->next) {
1001                 eed->f1= 0;
1002                 eed->f2= 0;
1003                 if((eed->h & 1)==0) {   // fgon edges add to valence too
1004                         eed->v1->f1++; eed->v2->f1++;
1005                 }
1006         }
1007         for(efa= em->faces.first; efa; efa= efa->next) {
1008                 efa->f1= 0;
1009                 if(efa->h==0) {
1010                         efa->e1->f1++;
1011                         efa->e2->f1++;
1012                         efa->e3->f1++;
1013                         if(efa->e4) efa->e4->f1++;
1014                 }
1015         }
1016         
1017         /* looped edges & vertices get tagged f2 */
1018         starteed->f2= 1;
1019         if(starteed->v1->f1<5) starteed->v1->f2= 1;
1020         if(starteed->v2->f1<5) starteed->v2->f2= 1;
1021         /* sorry, first edge isnt even ok */
1022         if(starteed->v1->f2==0 && starteed->v2->f2==0) looking= 0;
1023         
1024         while(looking) {
1025                 looking= 0;
1026                 
1027                 /* find correct valence edges which are not tagged yet, but connect to tagged one */
1028                 for(eed= em->edges.first; eed; eed= eed->next) {
1029                         if(eed->h==0 && eed->f2==0) { // edge not hidden, not tagged
1030                                 if( (eed->v1->f1<5 && eed->v1->f2) || (eed->v2->f1<5 && eed->v2->f2)) { // valence of vertex OK, and is tagged
1031                                         /* new edge is not allowed to be in face with tagged edge */
1032                                         if(edge_not_in_tagged_face(eed)) {
1033                                                 if(eed->f1==starteed->f1) {     // same amount of faces
1034                                                         looking= 1;
1035                                                         eed->f2= 1;
1036                                                         if(eed->v2->f1<5) eed->v2->f2= 1;
1037                                                         if(eed->v1->f1<5) eed->v1->f2= 1;
1038                                                 }
1039                                         }
1040                                 }
1041                         }
1042                 }
1043         }
1044         /* and we do the select */
1045         for(eed= em->edges.first; eed; eed= eed->next) {
1046                 if(eed->f2) EM_select_edge(eed, select);
1047         }
1048 }
1049
1050 /* 
1051    Almostly exactly the same code as faceloop select
1052 */
1053 static void edgering_select(EditEdge *startedge, int select){
1054         EditMesh *em = G.editMesh;
1055         EditEdge *eed;
1056         EditFace *efa;
1057         int looking= 1;
1058         
1059         /* in eed->f1 we put the valence (amount of faces in edge) */
1060         /* in eed->f2 we put tagged flag as correct loop */
1061         /* in efa->f1 we put tagged flag as correct to select */
1062
1063         for(eed= em->edges.first; eed; eed= eed->next) {
1064                 eed->f1= 0;
1065                 eed->f2= 0;
1066         }
1067         for(efa= em->faces.first; efa; efa= efa->next) {
1068                 efa->f1= 0;
1069                 if(efa->h==0) {
1070                         efa->e1->f1++;
1071                         efa->e2->f1++;
1072                         efa->e3->f1++;
1073                         if(efa->e4) efa->e4->f1++;
1074                 }
1075         }
1076         
1077         // tag startedge OK
1078         startedge->f2= 1;
1079         
1080         while(looking) {
1081                 looking= 0;
1082                 
1083                 for(efa= em->faces.first; efa; efa= efa->next) {
1084                         if(efa->e4 && efa->f1==0) {     // not done quad
1085                                 if(efa->e1->f1<=2 && efa->e2->f1<=2 && efa->e3->f1<=2 && efa->e4->f1<=2) { // valence ok
1086
1087                                         // if edge tagged, select opposing edge and mark face ok
1088                                         if(efa->e1->f2) {
1089                                                 efa->e3->f2= 1;
1090                                                 efa->f1= 1;
1091                                                 looking= 1;
1092                                         }
1093                                         else if(efa->e2->f2) {
1094                                                 efa->e4->f2= 1;
1095                                                 efa->f1= 1;
1096                                                 looking= 1;
1097                                         }
1098                                         if(efa->e3->f2) {
1099                                                 efa->e1->f2= 1;
1100                                                 efa->f1= 1;
1101                                                 looking= 1;
1102                                         }
1103                                         if(efa->e4->f2) {
1104                                                 efa->e2->f2= 1;
1105                                                 efa->f1= 1;
1106                                                 looking= 1;
1107                                         }
1108                                 }
1109                         }
1110                 }
1111         }
1112         
1113         /* (de)select the edges */
1114         for(eed= em->edges.first; eed; eed= eed->next) {
1115                 if(eed->f2) EM_select_edge(eed, select);
1116         }
1117 }
1118 /* ***************** MAIN MOUSE SELECTION ************** */
1119
1120 // just to have the functions nice together
1121 static void mouse_mesh_loop(void)
1122 {
1123         EditEdge *eed;
1124         short dist= 50;
1125         
1126         eed= findnearestedge(&dist);
1127         if(eed) {
1128                 
1129                 if((G.qual & LR_SHIFTKEY)==0) EM_clear_flag_all(SELECT);
1130                 
1131                 if((eed->f & SELECT)==0) EM_select_edge(eed, 1);
1132                 else if(G.qual & LR_SHIFTKEY) EM_select_edge(eed, 0);
1133
1134                 if(G.scene->selectmode & SCE_SELECT_FACE) {
1135                         faceloop_select(eed, eed->f & SELECT);
1136                 }
1137                 else if(G.scene->selectmode & SCE_SELECT_EDGE) {
1138             if(G.qual == (LR_CTRLKEY | LR_ALTKEY) || G.qual == (LR_CTRLKEY | LR_ALTKEY |LR_SHIFTKEY))
1139                         edgering_select(eed, eed->f & SELECT);
1140             else if(G.qual & LR_ALTKEY)
1141                         edgeloop_select(eed, eed->f & SELECT);
1142                 }
1143         else if(G.scene->selectmode & SCE_SELECT_VERTEX) {
1144             if(G.qual == (LR_CTRLKEY | LR_ALTKEY) || G.qual == (LR_CTRLKEY | LR_ALTKEY |LR_SHIFTKEY))
1145                         edgering_select(eed, eed->f & SELECT);
1146             else if(G.qual & LR_ALTKEY)
1147                         edgeloop_select(eed, eed->f & SELECT);
1148                 }
1149
1150                 /* frontbuffer draw of last selected only */
1151                 unified_select_draw(NULL, eed, NULL);
1152                 
1153                 EM_selectmode_flush();
1154                 countall();
1155                 
1156                 allqueue(REDRAWVIEW3D, 0);
1157         }
1158 }
1159
1160
1161 /* here actual select happens */
1162 void mouse_mesh(void)
1163 {
1164         EditVert *eve;
1165         EditEdge *eed;
1166         EditFace *efa;
1167         
1168         if(G.qual & LR_ALTKEY) mouse_mesh_loop();
1169         else if(unified_findnearest(&eve, &eed, &efa)) {
1170                 
1171                 if((G.qual & LR_SHIFTKEY)==0) EM_clear_flag_all(SELECT);
1172                 
1173                 if(efa) {
1174                         
1175                         if( (efa->f & SELECT)==0 ) {
1176                                 EM_select_face_fgon(efa, 1);
1177                         }
1178                         else if(G.qual & LR_SHIFTKEY) {
1179                                 EM_select_face_fgon(efa, 0);
1180                         }
1181                 }
1182                 else if(eed) {
1183                         if((eed->f & SELECT)==0) {
1184                                 EM_select_edge(eed, 1);
1185                         }
1186                         else if(G.qual & LR_SHIFTKEY) {
1187                                 EM_select_edge(eed, 0);
1188                         }
1189                 }
1190                 else if(eve) {
1191                         if((eve->f & SELECT)==0) eve->f |= SELECT;
1192                         else if(G.qual & LR_SHIFTKEY) eve->f &= ~SELECT;
1193                 }
1194                 
1195                 /* frontbuffer draw of last selected only */
1196                 unified_select_draw(eve, eed, efa);
1197         
1198                 EM_selectmode_flush();
1199                 countall();
1200
1201                 allqueue(REDRAWVIEW3D, 0);
1202         }
1203
1204         rightmouse_transform();
1205 }
1206
1207
1208 static void selectconnectedAll(void)
1209 {
1210         EditMesh *em = G.editMesh;
1211         EditVert *v1,*v2;
1212         EditEdge *eed;
1213         short done=1, toggle=0;
1214
1215         if(em->edges.first==0) return;
1216         
1217         while(done==1) {
1218                 done= 0;
1219                 
1220                 toggle++;
1221                 if(toggle & 1) eed= em->edges.first;
1222                 else eed= em->edges.last;
1223                 
1224                 while(eed) {
1225                         v1= eed->v1;
1226                         v2= eed->v2;
1227                         if(eed->h==0) {
1228                                 if(v1->f & SELECT) {
1229                                         if( (v2->f & SELECT)==0 ) {
1230                                                 v2->f |= SELECT;
1231                                                 done= 1;
1232                                         }
1233                                 }
1234                                 else if(v2->f & SELECT) {
1235                                         if( (v1->f & SELECT)==0 ) {
1236                                                 v1->f |= SELECT;
1237                                                 done= 1;
1238                                         }
1239                                 }
1240                         }
1241                         if(toggle & 1) eed= eed->next;
1242                         else eed= eed->prev;
1243                 }
1244         }
1245
1246         /* now use vertex select flag to select rest */
1247         EM_select_flush();
1248         
1249         countall();
1250
1251         allqueue(REDRAWVIEW3D, 0);
1252         BIF_undo_push("Select Connected (All)");
1253 }
1254
1255 void selectconnected_mesh(int qual)
1256 {
1257         EditMesh *em = G.editMesh;
1258         EditVert *eve, *v1, *v2;
1259         EditEdge *eed;
1260         EditFace *efa;
1261         short done=1, sel, toggle=0;
1262
1263         if(em->edges.first==0) return;
1264
1265         if(qual & LR_CTRLKEY) {
1266                 selectconnectedAll();
1267                 return;
1268         }
1269
1270         
1271         if( unified_findnearest(&eve, &eed, &efa)==0 ) {
1272                 error("Nothing indicated ");
1273                 return;
1274         }
1275         
1276         sel= 1;
1277         if(qual & LR_SHIFTKEY) sel=0;
1278
1279         /* clear test flags */
1280         for(v1= em->verts.first; v1; v1= v1->next) v1->f1= 0;
1281         
1282         /* start vertex/face/edge */
1283         if(eve) eve->f1= 1;
1284         else if(eed) eed->v1->f1= eed->v2->f1= 1;
1285         else efa->v1->f1= efa->v2->f1= efa->v3->f1= 1;
1286         
1287         /* set flag f1 if affected */
1288         while(done==1) {
1289                 done= 0;
1290                 toggle++;
1291                 
1292                 if(toggle & 1) eed= em->edges.first;
1293                 else eed= em->edges.last;
1294                 
1295                 while(eed) {
1296                         v1= eed->v1;
1297                         v2= eed->v2;
1298                         
1299                         if(eed->h==0) {
1300                                 if(v1->f1 && v2->f1==0) {
1301                                         v2->f1= 1;
1302                                         done= 1;
1303                                 }
1304                                 else if(v1->f1==0 && v2->f1) {
1305                                         v1->f1= 1;
1306                                         done= 1;
1307                                 }
1308                         }
1309                         
1310                         if(toggle & 1) eed= eed->next;
1311                         else eed= eed->prev;
1312                 }
1313         }
1314         
1315         /* now use vertex f1 flag to select/deselect */
1316         for(eed= em->edges.first; eed; eed= eed->next) {
1317                 if(eed->v1->f1 && eed->v2->f1) 
1318                         EM_select_edge(eed, sel);
1319         }
1320         for(efa= em->faces.first; efa; efa= efa->next) {
1321                 if(efa->v1->f1 && efa->v2->f1 && efa->v3->f1 && (efa->v4==NULL || efa->v4->f1)) 
1322                         EM_select_face(efa, sel);
1323         }
1324         /* no flush needed, connected geometry is done */
1325         
1326         countall();
1327         
1328         allqueue(REDRAWVIEW3D, 0);
1329         BIF_undo_push("Select Linked");
1330         
1331 }
1332
1333 /* swap is 0 or 1, if 1 it hides not selected */
1334 void hide_mesh(int swap)
1335 {
1336         EditMesh *em = G.editMesh;
1337         EditVert *eve;
1338         EditEdge *eed;
1339         EditFace *efa;
1340         int a;
1341         
1342         if(G.obedit==0) return;
1343
1344         /* hide happens on least dominant select mode, and flushes up, not down! (helps preventing errors in subsurf) */
1345         /*  - vertex hidden, always means edge is hidden too
1346                 - edge hidden, always means face is hidden too
1347                 - face hidden, only set face hide
1348                 - then only flush back down what's absolute hidden
1349         */
1350         if(G.scene->selectmode & SCE_SELECT_VERTEX) {
1351                 for(eve= em->verts.first; eve; eve= eve->next) {
1352                         if((eve->f & SELECT)!=swap) {
1353                                 eve->f &= ~SELECT;
1354                                 eve->h= 1;
1355                         }
1356                 }
1357         
1358                 for(eed= em->edges.first; eed; eed= eed->next) {
1359                         if(eed->v1->h || eed->v2->h) {
1360                                 eed->h |= 1;
1361                                 eed->f &= ~SELECT;
1362                         }
1363                 }
1364         
1365                 for(efa= em->faces.first; efa; efa= efa->next) {
1366                         if(efa->e1->h || efa->e2->h || efa->e3->h || (efa->e4 && efa->e4->h)) {
1367                                 efa->h= 1;
1368                                 efa->f &= ~SELECT;
1369                         }
1370                 }
1371         }
1372         else if(G.scene->selectmode & SCE_SELECT_EDGE) {
1373
1374                 for(eed= em->edges.first; eed; eed= eed->next) {
1375                         if((eed->f & SELECT)!=swap) {
1376                                 eed->h |= 1;
1377                                 EM_select_edge(eed, 0);
1378                         }
1379                 }
1380
1381                 for(efa= em->faces.first; efa; efa= efa->next) {
1382                         if(efa->e1->h || efa->e2->h || efa->e3->h || (efa->e4 && efa->e4->h)) {
1383                                 efa->h= 1;
1384                                 efa->f &= ~SELECT;
1385                         }
1386                 }
1387         }
1388         else {
1389
1390                 for(efa= em->faces.first; efa; efa= efa->next) {
1391                         if((efa->f & SELECT)!=swap) {
1392                                 efa->h= 1;
1393                                 EM_select_face(efa, 0);
1394                         }
1395                 }
1396         }
1397         
1398         /* flush down, only whats 100% hidden */
1399         for(eve= em->verts.first; eve; eve= eve->next) eve->f1= 0;
1400         for(eed= em->edges.first; eed; eed= eed->next) eed->f1= 0;
1401         
1402         if(G.scene->selectmode & SCE_SELECT_FACE) {
1403                 for(efa= em->faces.first; efa; efa= efa->next) {
1404                         if(efa->h) a= 1; else a= 2;
1405                         efa->e1->f1 |= a;
1406                         efa->e2->f1 |= a;
1407                         efa->e3->f1 |= a;
1408                         if(efa->e4) efa->e4->f1 |= a;
1409                 }
1410         }
1411         
1412         if(G.scene->selectmode >= SCE_SELECT_EDGE) {
1413                 for(eed= em->edges.first; eed; eed= eed->next) {
1414                         if(eed->f1==1) eed->h |= 1;
1415                         if(eed->h & 1) a= 1; else a= 2;
1416                         eed->v1->f1 |= a;
1417                         eed->v2->f1 |= a;
1418                 }
1419         }
1420
1421         if(G.scene->selectmode >= SCE_SELECT_VERTEX) {
1422                 for(eve= em->verts.first; eve; eve= eve->next) {
1423                         if(eve->f1==1) eve->h= 1;
1424                 }
1425         }
1426                 
1427         allqueue(REDRAWVIEW3D, 0);
1428         DAG_object_flush_update(G.scene, G.obedit, OB_RECALC_DATA);     
1429         BIF_undo_push("Hide");
1430 }
1431
1432
1433 void reveal_mesh(void)
1434 {
1435         EditMesh *em = G.editMesh;
1436         EditVert *eve;
1437         EditEdge *eed;
1438         EditFace *efa;
1439         
1440         if(G.obedit==0) return;
1441
1442         for(eve= em->verts.first; eve; eve= eve->next) {
1443                 if(eve->h) {
1444                         eve->h= 0;
1445                         eve->f |= SELECT;
1446                 }
1447         }
1448         for(eed= em->edges.first; eed; eed= eed->next) {
1449                 if(eed->h & 1) {
1450                         eed->h &= ~1;
1451                         if(G.scene->selectmode & SCE_SELECT_VERTEX); 
1452                         else EM_select_edge(eed, 1);
1453                 }
1454         }
1455         for(efa= em->faces.first; efa; efa= efa->next) {
1456                 if(efa->h) {
1457                         efa->h= 0;
1458                         if(G.scene->selectmode & (SCE_SELECT_EDGE|SCE_SELECT_VERTEX)); 
1459                         else EM_select_face(efa, 1);
1460                 }
1461         }
1462
1463         EM_fgon_flags();        // redo flags and indices for fgons
1464         EM_selectmode_flush();
1465         
1466         allqueue(REDRAWVIEW3D, 0);
1467         DAG_object_flush_update(G.scene, G.obedit, OB_RECALC_DATA);     
1468         BIF_undo_push("Reveal");
1469 }
1470
1471 void select_faces_by_numverts(int numverts)
1472 {
1473         EditMesh *em = G.editMesh;
1474         EditFace *efa;
1475
1476         /* Selects isolated verts, and edges that do not have 2 neighboring
1477          * faces
1478          */
1479         
1480         if(G.scene->selectmode!=SCE_SELECT_FACE) {
1481                 error("Only works in face selection mode");
1482                 return;
1483         }
1484
1485         efa= em->faces.first;
1486         while(efa) {
1487                 if (efa->e4) {
1488                         EM_select_face(efa, (numverts==4) );
1489                 }
1490                 else if (efa->e3) {
1491                         EM_select_face(efa, (numverts==3) );
1492                 }
1493                 else 
1494                         EM_select_face(efa, (numverts!=3) && (numverts!=4) );
1495                 efa= efa->next;
1496         }
1497
1498         countall();
1499         addqueue(curarea->win,  REDRAW, 0);
1500
1501         if (numverts==3)
1502                 BIF_undo_push("Select Triangles");
1503         else if (numverts==4)
1504                 BIF_undo_push("Select Quads");
1505         else
1506                 BIF_undo_push("Select non-Triangles/Quads");
1507 }
1508
1509 void select_non_manifold(void)
1510 {
1511         EditMesh *em = G.editMesh;
1512         EditVert *eve;
1513         EditEdge *eed;
1514         EditFace *efa;
1515
1516         /* Selects isolated verts, and edges that do not have 2 neighboring
1517          * faces
1518          */
1519         
1520         if(G.scene->selectmode==SCE_SELECT_FACE) {
1521                 error("Doesn't work in face selection mode");
1522                 return;
1523         }
1524
1525         eve= em->verts.first;
1526         while(eve) {
1527                 /* this will count how many edges are connected
1528                  * to this vert */
1529                 eve->f1= 0;
1530                 eve= eve->next;
1531         }
1532
1533         eed= em->edges.first;
1534         while(eed) {
1535                 /* this will count how many faces are connected to
1536                  * this edge */
1537                 eed->f1= 0;
1538                 /* increase edge count for verts */
1539                 ++eed->v1->f1;
1540                 ++eed->v2->f1;
1541                 eed= eed->next;
1542         }
1543
1544         efa= em->faces.first;
1545         while(efa) {
1546                 /* increase face count for edges */
1547                 ++efa->e1->f1;
1548                 ++efa->e2->f1;
1549                 ++efa->e3->f1;
1550                 if (efa->e4)
1551                         ++efa->e4->f1;                  
1552                 efa= efa->next;
1553         }
1554
1555         /* select verts that are attached to an edge that does not
1556          * have 2 neighboring faces */
1557         eed= em->edges.first;
1558         while(eed) {
1559                 if (eed->h==0 && eed->f1 != 2) {
1560                         EM_select_edge(eed, 1);
1561                 }
1562                 eed= eed->next;
1563         }
1564
1565         /* select isolated verts */
1566         eve= em->verts.first;
1567         while(eve) {
1568                 if (eve->f1 == 0) {
1569                         if (!eve->h) eve->f |= SELECT;
1570                 }
1571                 eve= eve->next;
1572         }
1573
1574         countall();
1575         addqueue(curarea->win,  REDRAW, 0);
1576         BIF_undo_push("Select Non Manifold");
1577 }
1578
1579 void selectswap_mesh(void) /* UI level */
1580 {
1581         EditMesh *em = G.editMesh;
1582         EditVert *eve;
1583         EditEdge *eed;
1584         EditFace *efa;
1585         
1586         if(G.scene->selectmode & SCE_SELECT_VERTEX) {
1587
1588                 for(eve= em->verts.first; eve; eve= eve->next) {
1589                         if(eve->h==0) {
1590                                 if(eve->f & SELECT) eve->f &= ~SELECT;
1591                                 else eve->f|= SELECT;
1592                         }
1593                 }
1594         }
1595         else if(G.scene->selectmode & SCE_SELECT_EDGE) {
1596                 for(eed= em->edges.first; eed; eed= eed->next) {
1597                         if(eed->h==0) {
1598                                 EM_select_edge(eed, !(eed->f & SELECT));
1599                         }
1600                 }
1601         }
1602         else {
1603                 for(efa= em->faces.first; efa; efa= efa->next) {
1604                         if(efa->h==0) {
1605                                 EM_select_face(efa, !(efa->f & SELECT));
1606                         }
1607                 }
1608         }
1609
1610         EM_selectmode_flush();
1611         
1612         countall();
1613         allqueue(REDRAWVIEW3D, 0);
1614
1615         BIF_undo_push("Select Swap");
1616         
1617 }
1618
1619 void deselectall_mesh(void)      /* this toggles!!!, UI level */
1620 {
1621         
1622         if(G.obedit->lay & G.vd->lay) {
1623
1624                 if( EM_nvertices_selected() ) {
1625                         EM_clear_flag_all(SELECT);
1626                         BIF_undo_push("Deselect All");
1627                 }
1628                 else  {
1629                         EM_set_flag_all(SELECT);
1630                         BIF_undo_push("Select All");
1631                 }
1632                 
1633                 countall();
1634                 allqueue(REDRAWVIEW3D, 0);
1635         }
1636 }
1637
1638 void select_more(void)
1639 {
1640         EditMesh *em = G.editMesh;
1641         EditVert *eve;
1642         EditEdge *eed;
1643         EditFace *efa;
1644         
1645         for(eve= em->verts.first; eve; eve= eve->next) {
1646                 if(eve->f & SELECT) eve->f1= 1;
1647                 else eve->f1 = 0;
1648         }
1649         
1650         /* set f1 flags in vertices to select 'more' */
1651         for(eed= em->edges.first; eed; eed= eed->next) {
1652                 if(eed->h==0) {
1653                         if (eed->v1->f & SELECT)
1654                                 eed->v2->f1 = 1;
1655                         if (eed->v2->f & SELECT)
1656                                 eed->v1->f1 = 1;
1657                 }
1658         }
1659
1660         /* new selected edges, but not in facemode */
1661         if(G.scene->selectmode <= SCE_SELECT_EDGE) {
1662                 
1663                 for(eed= em->edges.first; eed; eed= eed->next) {
1664                         if(eed->h==0) {
1665                                 if(eed->v1->f1 && eed->v2->f1) EM_select_edge(eed, 1);
1666                         }
1667                 }
1668         }
1669         /* new selected faces */
1670         for(efa= em->faces.first; efa; efa= efa->next) {
1671                 if(efa->h==0) {
1672                         if(efa->v1->f1 && efa->v2->f1 && efa->v3->f1 && (efa->v4==NULL || efa->v4->f1)) 
1673                                 EM_select_face(efa, 1);
1674                 }
1675         }
1676
1677         countall();
1678         addqueue(curarea->win,  REDRAW, 0);
1679         BIF_undo_push("Select More");
1680 }
1681
1682 void select_less(void)
1683 {
1684         EditMesh *em = G.editMesh;
1685         EditEdge *eed;
1686         EditFace *efa;
1687
1688         if(G.scene->selectmode <= SCE_SELECT_EDGE) {
1689                 /* eed->f1 == 1:  edge with a selected and deselected vert */ 
1690
1691                 for(eed= em->edges.first; eed; eed= eed->next) {
1692                         eed->f1= 0;
1693                         if(eed->h==0) {
1694                                 
1695                                 if ( !(eed->v1->f & SELECT) && (eed->v2->f & SELECT) ) 
1696                                         eed->f1= 1;
1697                                 if ( (eed->v1->f & SELECT) && !(eed->v2->f & SELECT) ) 
1698                                         eed->f1= 1;
1699                         }
1700                 }
1701                 
1702                 /* deselect edges with flag set */
1703                 for(eed= em->edges.first; eed; eed= eed->next) {
1704                         if (eed->h==0 && eed->f1 == 1) {
1705                                 EM_select_edge(eed, 0);
1706                         }
1707                 }
1708                 EM_deselect_flush();
1709                 
1710         }
1711         else {
1712                 /* deselect faces with 1 or more deselect edges */
1713                 /* eed->f1 == mixed selection edge */
1714                 for(eed= em->edges.first; eed; eed= eed->next) eed->f1= 0;
1715
1716                 for(efa= em->faces.first; efa; efa= efa->next) {
1717                         if(efa->h==0) {
1718                                 if(efa->f & SELECT) {
1719                                         efa->e1->f1 |= 1;
1720                                         efa->e2->f1 |= 1;
1721                                         efa->e3->f1 |= 1;
1722                                         if(efa->e4) efa->e4->f1 |= 1;
1723                                 }
1724                                 else {
1725                                         efa->e1->f1 |= 2;
1726                                         efa->e2->f1 |= 2;
1727                                         efa->e3->f1 |= 2;
1728                                         if(efa->e4) efa->e4->f1 |= 2;
1729                                 }
1730                         }
1731                 }
1732                 for(efa= em->faces.first; efa; efa= efa->next) {
1733                         if(efa->h==0) {
1734                                 if(efa->e1->f1==3 || efa->e2->f1==3 || efa->e3->f1==3 || (efa->e4 && efa->e4->f1==3)) { 
1735                                         EM_select_face(efa, 0);
1736                                 }
1737                         }
1738                 }
1739                 EM_selectmode_flush();
1740                 
1741         }
1742         
1743         countall();
1744         allqueue(REDRAWVIEW3D, 0);
1745 }
1746
1747
1748 void selectrandom_mesh(void) /* randomly selects a user-set % of vertices/edges/faces */
1749 {
1750         EditMesh *em = G.editMesh;
1751         EditVert *eve;
1752         EditEdge *eed;
1753         EditFace *efa;
1754         short randfac = 50;
1755
1756         if(G.obedit==NULL || (G.obedit->lay & G.vd->lay)==0) return;
1757
1758         /* Get the percentage of vertices to randomly select as 'randfac' */
1759         if(button(&randfac,0, 100,"Percentage:")==0) return;
1760
1761         BLI_srand( BLI_rand() ); /* random seed */
1762         
1763         if(G.scene->selectmode & SCE_SELECT_VERTEX) {
1764                 for(eve= em->verts.first; eve; eve= eve->next) {
1765                         if(eve->h==0) {
1766                                 if ( (BLI_frand() * 100) < randfac) 
1767                                         eve->f |= SELECT;
1768                         }
1769                 }
1770         }
1771         else if(G.scene->selectmode & SCE_SELECT_EDGE) {
1772                 for(eed= em->edges.first; eed; eed= eed->next) {
1773                         if(eed->h==0) {
1774                                 if ( (BLI_frand() * 100) < randfac) 
1775                                         EM_select_edge(eed, 1);
1776                         }
1777                 }
1778         }
1779         else {
1780                 for(efa= em->faces.first; efa; efa= efa->next) {
1781                         if(efa->h==0) {
1782                                 if ( (BLI_frand() * 100) < randfac) 
1783                                         EM_select_face(efa, 1);
1784                         }
1785                 }
1786         }
1787         
1788         EM_selectmode_flush();
1789
1790         countall();
1791         allqueue(REDRAWVIEW3D, 0);
1792 }
1793
1794 void editmesh_select_by_material(int index) 
1795 {
1796         EditMesh *em = G.editMesh;
1797         EditFace *efa;
1798         
1799         for (efa=em->faces.first; efa; efa= efa->next) {
1800                 if (efa->mat_nr==index) {
1801                         EM_select_face(efa, 1);
1802                 }
1803         }
1804
1805         EM_selectmode_flush();
1806 }
1807
1808 void editmesh_deselect_by_material(int index) 
1809 {
1810         EditMesh *em = G.editMesh;
1811         EditFace *efa;
1812         
1813         for (efa=em->faces.first; efa; efa= efa->next) {
1814                 if (efa->mat_nr==index) {
1815                         EM_select_face(efa, 0);
1816                 }
1817         }
1818
1819         EM_selectmode_flush();
1820 }
1821
1822 void EM_selectmode_menu(void)
1823 {
1824         int val;
1825         
1826         if(G.scene->selectmode & SCE_SELECT_VERTEX) pupmenu_set_active(1);
1827         else if(G.scene->selectmode & SCE_SELECT_EDGE) pupmenu_set_active(2);
1828         else pupmenu_set_active(3);
1829         
1830         val= pupmenu("Select Mode%t|Vertices|Edges|Faces");
1831         if(val>0) {
1832                 if(val==1) G.scene->selectmode= SCE_SELECT_VERTEX;
1833                 else if(val==2) G.scene->selectmode= SCE_SELECT_EDGE;
1834                 else G.scene->selectmode= SCE_SELECT_FACE;
1835         
1836                 EM_selectmode_set(); // when mode changes
1837                 allqueue(REDRAWVIEW3D, 1);
1838         }
1839 }
1840
1841 /* ************************* SEAMS AND EDGES **************** */
1842
1843 void editmesh_mark_seam(int clear)
1844 {
1845         EditMesh *em= G.editMesh;
1846         EditEdge *eed;
1847
1848         /* auto-enable seams drawing */
1849         if(clear==0) {
1850                 if(!(G.f & G_DRAWSEAMS)) {
1851                         G.f |= G_DRAWSEAMS;
1852                         allqueue(REDRAWBUTSEDIT, 0);
1853                 }
1854         }
1855
1856         if(clear) {
1857                 eed= em->edges.first;
1858                 while(eed) {
1859                         if((eed->h==0) && (eed->f & SELECT)) {
1860                                 eed->seam = 0;
1861                         }
1862                         eed= eed->next;
1863                 }
1864                 BIF_undo_push("Mark Seam");
1865         }
1866         else {
1867                 eed= em->edges.first;
1868                 while(eed) {
1869                         if((eed->h==0) && (eed->f & SELECT)) {
1870                                 eed->seam = 1;
1871                         }
1872                         eed= eed->next;
1873                 }
1874                 BIF_undo_push("Clear Seam");
1875         }
1876
1877         allqueue(REDRAWVIEW3D, 0);
1878 }
1879
1880 void Edge_Menu() {
1881         short ret;
1882
1883         ret= pupmenu("Edge Specials%t|Mark Seam %x1|Clear Seam %x2|Rotate Edge CW%x3|Rotate Edge CCW%x4|Loopcut%x6|Edge Slide%x5");
1884
1885         switch(ret)
1886         {
1887         case 1:
1888                 editmesh_mark_seam(0);
1889                 break;
1890         case 2:
1891                 editmesh_mark_seam(1);
1892                 break;
1893         case 3:
1894                 edge_rotate_selected(2);
1895                 break;
1896         case 4:
1897                 edge_rotate_selected(1);
1898                 break;
1899         case 5:
1900                 EdgeSlide(0,0.0);
1901                 BIF_undo_push("EdgeSlide");
1902                 break;
1903         case 6:
1904                 CutEdgeloop(1);
1905                 BIF_undo_push("Loopcut New");
1906                 break;
1907         }
1908 }
1909
1910
1911 /* **************** NORMALS ************** */
1912
1913 void righthandfaces(int select) /* makes faces righthand turning */
1914 {
1915         EditMesh *em = G.editMesh;
1916         EditEdge *eed, *ed1, *ed2, *ed3, *ed4;
1917         EditFace *efa, *startvl;
1918         float maxx, nor[3], cent[3];
1919         int totsel, found, foundone, direct, turn, tria_nr;
1920
1921    /* based at a select-connected to witness loose objects */
1922
1923         /* count per edge the amount of faces */
1924
1925         /* find the ultimate left, front, upper face (not manhattan dist!!) */
1926         /* also evaluate both triangle cases in quad, since these can be non-flat */
1927
1928         /* put normal to the outside, and set the first direction flags in edges */
1929
1930         /* then check the object, and set directions / direction-flags: but only for edges with 1 or 2 faces */
1931         /* this is in fact the 'select connected' */
1932         
1933         /* in case (selected) faces were not done: start over with 'find the ultimate ...' */
1934
1935         waitcursor(1);
1936         
1937         eed= em->edges.first;
1938         while(eed) {
1939                 eed->f2= 0;             // edge direction
1940                 eed->f1= 0;             // counter
1941                 eed= eed->next;
1942         }
1943
1944         /* count faces and edges */
1945         totsel= 0;
1946         efa= em->faces.first;
1947         while(efa) {
1948                 if(select==0 || (efa->f & SELECT) ) {
1949                         efa->f1= 1;
1950                         totsel++;
1951                         efa->e1->f1++;
1952                         efa->e2->f1++;
1953                         efa->e3->f1++;
1954                         if(efa->v4) efa->e4->f1++;
1955                 }
1956                 else efa->f1= 0;
1957
1958                 efa= efa->next;
1959         }
1960
1961         while(totsel>0) {
1962                 /* from the outside to the inside */
1963
1964                 efa= em->faces.first;
1965                 startvl= NULL;
1966                 maxx= -1.0e10;
1967                 tria_nr= 0;
1968
1969                 while(efa) {
1970                         if(efa->f1) {
1971                                 CalcCent3f(cent, efa->v1->co, efa->v2->co, efa->v3->co);
1972                                 cent[0]= cent[0]*cent[0] + cent[1]*cent[1] + cent[2]*cent[2];
1973                                 
1974                                 if(cent[0]>maxx) {
1975                                         maxx= cent[0];
1976                                         startvl= efa;
1977                                         tria_nr= 0;
1978                                 }
1979                                 if(efa->v4) {
1980                                         CalcCent3f(cent, efa->v1->co, efa->v3->co, efa->v4->co);
1981                                         cent[0]= cent[0]*cent[0] + cent[1]*cent[1] + cent[2]*cent[2];
1982                                         
1983                                         if(cent[0]>maxx) {
1984                                                 maxx= cent[0];
1985                                                 startvl= efa;
1986                                                 tria_nr= 1;
1987                                         }
1988                                 }
1989                         }
1990                         efa= efa->next;
1991                 }
1992                 
1993                 /* set first face correct: calc normal */
1994                 
1995                 if(tria_nr==1) {
1996                         CalcNormFloat(startvl->v1->co, startvl->v3->co, startvl->v4->co, nor);
1997                         CalcCent3f(cent, startvl->v1->co, startvl->v3->co, startvl->v4->co);
1998                 } else {
1999                         CalcNormFloat(startvl->v1->co, startvl->v2->co, startvl->v3->co, nor);
2000                         CalcCent3f(cent, startvl->v1->co, startvl->v2->co, startvl->v3->co);
2001                 }
2002                 /* first normal is oriented this way or the other */
2003                 if(select) {
2004                         if(select==2) {
2005                                 if(cent[0]*nor[0]+cent[1]*nor[1]+cent[2]*nor[2] > 0.0) flipface(startvl);
2006                         }
2007                         else {
2008                                 if(cent[0]*nor[0]+cent[1]*nor[1]+cent[2]*nor[2] < 0.0) flipface(startvl);
2009                         }
2010                 }
2011                 else if(cent[0]*nor[0]+cent[1]*nor[1]+cent[2]*nor[2] < 0.0) flipface(startvl);
2012
2013
2014                 eed= startvl->e1;
2015                 if(eed->v1==startvl->v1) eed->f2= 1; 
2016                 else eed->f2= 2;
2017                 
2018                 eed= startvl->e2;
2019                 if(eed->v1==startvl->v2) eed->f2= 1; 
2020                 else eed->f2= 2;
2021                 
2022                 eed= startvl->e3;
2023                 if(eed->v1==startvl->v3) eed->f2= 1; 
2024                 else eed->f2= 2;
2025                 
2026                 eed= startvl->e4;
2027                 if(eed) {
2028                         if(eed->v1==startvl->v4) eed->f2= 1; 
2029                         else eed->f2= 2;
2030                 }
2031                 
2032                 startvl->f1= 0;
2033                 totsel--;
2034
2035                 /* test normals */
2036                 found= 1;
2037                 direct= 1;
2038                 while(found) {
2039                         found= 0;
2040                         if(direct) efa= em->faces.first;
2041                         else efa= em->faces.last;
2042                         while(efa) {
2043                                 if(efa->f1) {
2044                                         turn= 0;
2045                                         foundone= 0;
2046
2047                                         ed1= efa->e1;
2048                                         ed2= efa->e2;
2049                                         ed3= efa->e3;
2050                                         ed4= efa->e4;
2051
2052                                         if(ed1->f2) {
2053                                                 if(ed1->v1==efa->v1 && ed1->f2==1) turn= 1;
2054                                                 if(ed1->v2==efa->v1 && ed1->f2==2) turn= 1;
2055                                                 foundone= 1;
2056                                         }
2057                                         else if(ed2->f2) {
2058                                                 if(ed2->v1==efa->v2 && ed2->f2==1) turn= 1;
2059                                                 if(ed2->v2==efa->v2 && ed2->f2==2) turn= 1;
2060                                                 foundone= 1;
2061                                         }
2062                                         else if(ed3->f2) {
2063                                                 if(ed3->v1==efa->v3 && ed3->f2==1) turn= 1;
2064                                                 if(ed3->v2==efa->v3 && ed3->f2==2) turn= 1;
2065                                                 foundone= 1;
2066                                         }
2067                                         else if(ed4 && ed4->f2) {
2068                                                 if(ed4->v1==efa->v4 && ed4->f2==1) turn= 1;
2069                                                 if(ed4->v2==efa->v4 && ed4->f2==2) turn= 1;
2070                                                 foundone= 1;
2071                                         }
2072
2073                                         if(foundone) {
2074                                                 found= 1;
2075                                                 totsel--;
2076                                                 efa->f1= 0;
2077
2078                                                 if(turn) {
2079                                                         if(ed1->v1==efa->v1) ed1->f2= 2; 
2080                                                         else ed1->f2= 1;
2081                                                         if(ed2->v1==efa->v2) ed2->f2= 2; 
2082                                                         else ed2->f2= 1;
2083                                                         if(ed3->v1==efa->v3) ed3->f2= 2; 
2084                                                         else ed3->f2= 1;
2085                                                         if(ed4) {
2086                                                                 if(ed4->v1==efa->v4) ed4->f2= 2; 
2087                                                                 else ed4->f2= 1;
2088                                                         }
2089
2090                                                         flipface(efa);
2091
2092                                                 }
2093                                                 else {
2094                                                         if(ed1->v1== efa->v1) ed1->f2= 1; 
2095                                                         else ed1->f2= 2;
2096                                                         if(ed2->v1==efa->v2) ed2->f2= 1; 
2097                                                         else ed2->f2= 2;
2098                                                         if(ed3->v1==efa->v3) ed3->f2= 1; 
2099                                                         else ed3->f2= 2;
2100                                                         if(ed4) {
2101                                                                 if(ed4->v1==efa->v4) ed4->f2= 1; 
2102                                                                 else ed4->f2= 2;
2103                                                         }
2104                                                 }
2105                                         }
2106                                 }
2107                                 if(direct) efa= efa->next;
2108                                 else efa= efa->prev;
2109                         }
2110                         direct= 1-direct;
2111                 }
2112         }
2113
2114         recalc_editnormals();
2115         
2116         DAG_object_flush_update(G.scene, G.obedit, OB_RECALC_DATA);
2117         
2118         waitcursor(0);
2119 }
2120
2121
2122 /* ********** ALIGN WITH VIEW **************** */
2123
2124
2125 static void editmesh_calc_selvert_center(float cent_r[3])
2126 {
2127         EditMesh *em = G.editMesh;
2128         EditVert *eve;
2129         int nsel= 0;
2130
2131         cent_r[0]= cent_r[1]= cent_r[0]= 0.0;
2132
2133         for (eve= em->verts.first; eve; eve= eve->next) {
2134                 if (eve->f & SELECT) {
2135                         cent_r[0]+= eve->co[0];
2136                         cent_r[1]+= eve->co[1];
2137                         cent_r[2]+= eve->co[2];
2138                         nsel++;
2139                 }
2140         }
2141
2142         if (nsel) {
2143                 cent_r[0]/= nsel;
2144                 cent_r[1]/= nsel;
2145                 cent_r[2]/= nsel;
2146         }
2147 }
2148
2149 static int tface_is_selected(TFace *tf)
2150 {
2151         return (!(tf->flag & TF_HIDE) && (tf->flag & TF_SELECT));
2152 }
2153
2154 static int faceselect_nfaces_selected(Mesh *me)
2155 {
2156         int i, count= 0;
2157
2158         for (i=0; i<me->totface; i++)
2159                 if (tface_is_selected(&me->tface[i]))
2160                         count++;
2161
2162         return count;
2163 }
2164
2165         /* XXX, code for both these functions should be abstract,
2166          * then unified, then written for other things (like objects,
2167          * which would use same as vertices method), then added
2168          * to interface! Hoera! - zr
2169          */
2170 void faceselect_align_view_to_selected(View3D *v3d, Mesh *me, int axis)
2171 {
2172         if (!faceselect_nfaces_selected(me)) {
2173                 error("No faces selected.");
2174         } else {
2175                 float norm[3];
2176                 int i;
2177
2178                 norm[0]= norm[1]= norm[2]= 0.0;
2179                 for (i=0; i<me->totface; i++) {
2180                         MFace *mf= ((MFace*) me->mface) + i;
2181                         TFace *tf= ((TFace*) me->tface) + i;
2182         
2183                         if (tface_is_selected(tf)) {
2184                                 float *v1, *v2, *v3, fno[3];
2185
2186                                 v1= me->mvert[mf->v1].co;
2187                                 v2= me->mvert[mf->v2].co;
2188                                 v3= me->mvert[mf->v3].co;
2189                                 if (mf->v4) {
2190                                         float *v4= me->mvert[mf->v4].co;
2191                                         CalcNormFloat4(v1, v2, v3, v4, fno);
2192                                 } else {
2193                                         CalcNormFloat(v1, v2, v3, fno);
2194                                 }
2195
2196                                 norm[0]+= fno[0];
2197                                 norm[1]+= fno[1];
2198                                 norm[2]+= fno[2];
2199                         }
2200                 }
2201
2202                 view3d_align_axis_to_vector(v3d, axis, norm);
2203         }
2204 }
2205
2206 void editmesh_align_view_to_selected(View3D *v3d, int axis)
2207 {
2208         EditMesh *em = G.editMesh;
2209         int nselverts= EM_nvertices_selected();
2210
2211         if (nselverts<3) {
2212                 if (nselverts==0) {
2213                         error("No faces or vertices selected.");
2214                 } else {
2215                         error("At least one face or three vertices must be selected.");
2216                 }
2217         } else if (EM_nfaces_selected()) {
2218                 float norm[3];
2219                 EditFace *efa;
2220
2221                 norm[0]= norm[1]= norm[2]= 0.0;
2222                 for (efa= em->faces.first; efa; efa= efa->next) {
2223                         if (faceselectedAND(efa, SELECT)) {
2224                                 float fno[3];
2225                                 if (efa->v4) CalcNormFloat4(efa->v1->co, efa->v2->co, efa->v3->co, efa->v4->co, fno);
2226                                 else CalcNormFloat(efa->v1->co, efa->v2->co, efa->v3->co, fno);
2227                                                 /* XXX, fixme, should be flipped intp a 
2228                                                  * consistent direction. -zr
2229                                                  */
2230                                 norm[0]+= fno[0];
2231                                 norm[1]+= fno[1];
2232                                 norm[2]+= fno[2];
2233                         }
2234                 }
2235
2236                 Mat4Mul3Vecfl(G.obedit->obmat, norm);
2237                 view3d_align_axis_to_vector(v3d, axis, norm);
2238         } else {
2239                 float cent[3], norm[3];
2240                 EditVert *eve, *leve= NULL;
2241
2242                 norm[0]= norm[1]= norm[2]= 0.0;
2243                 editmesh_calc_selvert_center(cent);
2244                 for (eve= em->verts.first; eve; eve= eve->next) {
2245                         if (eve->f & SELECT) {
2246                                 if (leve) {
2247                                         float tno[3];
2248                                         CalcNormFloat(cent, leve->co, eve->co, tno);
2249                                         
2250                                                 /* XXX, fixme, should be flipped intp a 
2251                                                  * consistent direction. -zr
2252                                                  */
2253                                         norm[0]+= tno[0];
2254                                         norm[1]+= tno[1];
2255                                         norm[2]+= tno[2];
2256                                 }
2257                                 leve= eve;
2258                         }
2259                 }
2260
2261                 Mat4Mul3Vecfl(G.obedit->obmat, norm);
2262                 view3d_align_axis_to_vector(v3d, axis, norm);
2263         }
2264 }
2265
2266 /* **************** VERTEX DEFORMS *************** */
2267
2268 void vertexsmooth(void)
2269 {
2270         EditMesh *em = G.editMesh;
2271         EditVert *eve;
2272         EditEdge *eed;
2273         float *adror, *adr, fac;
2274         float fvec[3];
2275         int teller=0;
2276         ModifierData *md= G.obedit->modifiers.first;
2277
2278         if(G.obedit==0) return;
2279
2280         /* count */
2281         eve= em->verts.first;
2282         while(eve) {
2283                 if(eve->f & SELECT) teller++;
2284                 eve= eve->next;
2285         }
2286         if(teller==0) return;
2287         
2288         adr=adror= (float *)MEM_callocN(3*sizeof(float *)*teller, "vertsmooth");
2289         eve= em->verts.first;
2290         while(eve) {
2291                 if(eve->f & SELECT) {
2292                         eve->vn= (EditVert *)adr;
2293                         eve->f1= 0;
2294                         eve->f2= 0;
2295                         adr+= 3;
2296                 }
2297                 eve= eve->next;
2298         }
2299
2300         /* if there is a mirror modifier with clipping, flag the verts that
2301          * are within tolerance of the plane(s) of reflection 
2302          */
2303         for (; md; md=md->next) {
2304                 if (md->type==eModifierType_Mirror) {
2305                         MirrorModifierData *mmd = (MirrorModifierData*) md;     
2306                 
2307                         if(mmd->flag & MOD_MIR_CLIPPING) {
2308                                 for (eve= em->verts.first; eve; eve= eve->next) {
2309                                         if(eve->f & SELECT) {
2310
2311                                                 switch(mmd->axis){
2312                                                         case 0:
2313                                                                 if (fabs(eve->co[0]) < mmd->tolerance)
2314                                                                         eve->f2 |= 1;
2315                                                                 break;
2316                                                         case 1:
2317                                                                 if (fabs(eve->co[1]) < mmd->tolerance)
2318                                                                         eve->f2 |= 2;
2319                                                                 break;
2320                                                         case 2:
2321                                                                 if (fabs(eve->co[2]) < mmd->tolerance)
2322                                                                         eve->f2 |= 4;
2323                                                                 break;
2324                                                 }
2325                                         }
2326                                 }
2327                         }
2328                 }
2329         }
2330         
2331         eed= em->edges.first;
2332         while(eed) {
2333                 if( (eed->v1->f & SELECT) || (eed->v2->f & SELECT) ) {
2334                         fvec[0]= (eed->v1->co[0]+eed->v2->co[0])/2.0;
2335                         fvec[1]= (eed->v1->co[1]+eed->v2->co[1])/2.0;
2336                         fvec[2]= (eed->v1->co[2]+eed->v2->co[2])/2.0;
2337                         
2338                         if((eed->v1->f & SELECT) && eed->v1->f1<255) {
2339                                 eed->v1->f1++;
2340                                 VecAddf((float *)eed->v1->vn, (float *)eed->v1->vn, fvec);
2341                         }
2342                         if((eed->v2->f & SELECT) && eed->v2->f1<255) {
2343                                 eed->v2->f1++;
2344                                 VecAddf((float *)eed->v2->vn, (float *)eed->v2->vn, fvec);
2345                         }
2346                 }
2347                 eed= eed->next;
2348         }
2349
2350         eve= em->verts.first;
2351         while(eve) {
2352                 if(eve->f & SELECT) {
2353                         if(eve->f1) {
2354                                 adr= (float *)eve->vn;
2355                                 fac= 0.5/(float)eve->f1;
2356                                 
2357                                 eve->co[0]= 0.5*eve->co[0]+fac*adr[0];
2358                                 eve->co[1]= 0.5*eve->co[1]+fac*adr[1];
2359                                 eve->co[2]= 0.5*eve->co[2]+fac*adr[2];
2360
2361                                 /* clip if needed by mirror modifier */
2362                                 if (eve->f2) {
2363                                         if (eve->f2 & 1) {
2364                                                 eve->co[0]= 0.0f;
2365                                         }
2366                                         if (eve->f2 & 2) {
2367                                                 eve->co[1]= 0.0f;
2368                                         }
2369                                         if (eve->f2 & 4) {
2370                                                 eve->co[2]= 0.0f;
2371                                         }
2372                                 }
2373                         }
2374                         eve->vn= 0;
2375                 }
2376                 eve= eve->next;
2377         }
2378         MEM_freeN(adror);
2379
2380         recalc_editnormals();
2381
2382         allqueue(REDRAWVIEW3D, 0);
2383         DAG_object_flush_update(G.scene, G.obedit, OB_RECALC_DATA);
2384         BIF_undo_push("Vertex Smooth");
2385 }
2386
2387 void vertexnoise(void)
2388 {
2389         EditMesh *em = G.editMesh;
2390         Material *ma;
2391         Tex *tex;
2392         EditVert *eve;
2393         float b2, ofs, vec[3];
2394
2395         if(G.obedit==0) return;
2396         
2397         ma= give_current_material(G.obedit, G.obedit->actcol);
2398         if(ma==0 || ma->mtex[0]==0 || ma->mtex[0]->tex==0) {
2399                 return;
2400         }
2401         tex= ma->mtex[0]->tex;
2402         
2403         ofs= tex->turbul/200.0;
2404         
2405         eve= (struct EditVert *)em->verts.first;
2406         while(eve) {
2407                 if(eve->f & SELECT) {
2408                         
2409                         if(tex->type==TEX_STUCCI) {
2410                                 
2411                                 b2= BLI_hnoise(tex->noisesize, eve->co[0], eve->co[1], eve->co[2]);
2412                                 if(tex->stype) ofs*=(b2*b2);
2413                                 vec[0]= 0.2*(b2-BLI_hnoise(tex->noisesize, eve->co[0]+ofs, eve->co[1], eve->co[2]));
2414                                 vec[1]= 0.2*(b2-BLI_hnoise(tex->noisesize, eve->co[0], eve->co[1]+ofs, eve->co[2]));
2415                                 vec[2]= 0.2*(b2-BLI_hnoise(tex->noisesize, eve->co[0], eve->co[1], eve->co[2]+ofs));
2416                                 
2417                                 VecAddf(eve->co, eve->co, vec);
2418                         }
2419                         else {
2420                                 float tin, dum;
2421                                 externtex(ma->mtex[0], eve->co, &tin, &dum, &dum, &dum, &dum);
2422                                 eve->co[2]+= 0.05*tin;
2423                         }
2424                 }
2425                 eve= eve->next;
2426         }
2427
2428         recalc_editnormals();
2429         allqueue(REDRAWVIEW3D, 0);
2430         DAG_object_flush_update(G.scene, G.obedit, OB_RECALC_DATA);
2431         BIF_undo_push("Vertex Noise");
2432 }
2433
2434 void vertices_to_sphere(void)
2435 {
2436         EditMesh *em = G.editMesh;
2437         EditVert *eve;
2438         Object *ob= OBACT;
2439         float *curs, len, vec[3], cent[3], fac, facm, imat[3][3], bmat[3][3];
2440         int tot;
2441         short perc=100;
2442         
2443         if(ob==0) return;
2444         TEST_EDITMESH
2445         
2446         if(button(&perc, 1, 100, "Percentage:")==0) return;
2447         
2448         fac= perc/100.0;
2449         facm= 1.0-fac;
2450         
2451         Mat3CpyMat4(bmat, ob->obmat);
2452         Mat3Inv(imat, bmat);
2453
2454         /* centre */
2455         curs= give_cursor();
2456         cent[0]= curs[0]-ob->obmat[3][0];
2457         cent[1]= curs[1]-ob->obmat[3][1];
2458         cent[2]= curs[2]-ob->obmat[3][2];
2459         Mat3MulVecfl(imat, cent);
2460
2461         len= 0.0;
2462         tot= 0;
2463         eve= em->verts.first;
2464         while(eve) {
2465                 if(eve->f & SELECT) {
2466                         tot++;
2467                         len+= VecLenf(cent, eve->co);
2468                 }
2469                 eve= eve->next;
2470         }
2471         len/=tot;
2472         
2473         if(len==0.0) len= 10.0;
2474         
2475         eve= em->verts.first;
2476         while(eve) {
2477                 if(eve->f & SELECT) {
2478                         vec[0]= eve->co[0]-cent[0];
2479                         vec[1]= eve->co[1]-cent[1];
2480                         vec[2]= eve->co[2]-cent[2];
2481                         
2482                         Normalise(vec);
2483                         
2484                         eve->co[0]= fac*(cent[0]+vec[0]*len) + facm*eve->co[0];
2485                         eve->co[1]= fac*(cent[1]+vec[1]*len) + facm*eve->co[1];
2486                         eve->co[2]= fac*(cent[2]+vec[2]*len) + facm*eve->co[2];
2487                         
2488                 }
2489                 eve= eve->next;
2490         }
2491         
2492         recalc_editnormals();
2493         allqueue(REDRAWVIEW3D, 0);
2494         DAG_object_flush_update(G.scene, G.obedit, OB_RECALC_DATA);
2495         BIF_undo_push("To Sphere");
2496 }
2497