Undo revision 23130 which was a merge with 2.5, a messy one because I did something...
[blender.git] / source / blender / editors / mesh / editmesh_mods.c
1 /**
2  * $Id: 
3  *
4  * ***** BEGIN GPL LICENSE BLOCK *****
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version 2
9  * of the License, or (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software Foundation,
18  * Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
19  *
20  * The Original Code is Copyright (C) 2004 Blender Foundation.
21  * All rights reserved.
22  *
23  * The Original Code is: all of this file.
24  *
25  * Contributor(s): none yet.
26  *
27  * ***** END GPL LICENSE BLOCK *****
28  */
29
30 /*
31
32 editmesh_mods.c, UI level access, no geometry changes 
33
34 */
35
36 #include <stdlib.h>
37 #include <string.h>
38 #include <math.h>
39
40 #include "MEM_guardedalloc.h"
41
42 #include "MTC_matrixops.h"
43
44 #include "DNA_mesh_types.h"
45 #include "DNA_material_types.h"
46 #include "DNA_meshdata_types.h"
47 #include "DNA_modifier_types.h"
48 #include "DNA_object_types.h"
49 #include "DNA_texture_types.h"
50 #include "DNA_scene_types.h"
51 #include "DNA_screen_types.h"
52 #include "DNA_space_types.h"
53 #include "DNA_view3d_types.h"
54
55 #include "BLI_blenlib.h"
56 #include "BLI_arithb.h"
57 #include "BLI_editVert.h"
58 #include "BLI_rand.h"
59
60 #include "BKE_context.h"
61 #include "BKE_displist.h"
62 #include "BKE_depsgraph.h"
63 #include "BKE_DerivedMesh.h"
64 #include "BKE_customdata.h"
65 #include "BKE_global.h"
66 #include "BKE_mesh.h"
67 #include "BKE_material.h"
68 #include "BKE_paint.h"
69 #include "BKE_texture.h"
70 #include "BKE_utildefines.h"
71 #include "BKE_report.h"
72
73 #include "IMB_imbuf_types.h"
74 #include "IMB_imbuf.h"
75
76 #include "RE_render_ext.h"  /* externtex */
77
78 #include "WM_api.h"
79 #include "WM_types.h"
80
81 #include "RNA_access.h"
82 #include "RNA_define.h"
83
84 #include "ED_mesh.h"
85 #include "ED_screen.h"
86 #include "ED_view3d.h"
87
88 #include "BIF_gl.h"
89 #include "BIF_glutil.h"
90
91 #include "mesh_intern.h"
92
93 #include "BLO_sys_types.h" // for intptr_t support
94
95 /* XXX */
96 static void waitcursor(int val) {}
97 static int pupmenu() {return 0;}
98
99 /* ****************************** MIRROR **************** */
100
101 void EM_select_mirrored(Object *obedit, EditMesh *em)
102 {
103         if(em->selectmode & SCE_SELECT_VERTEX) {
104                 EditVert *eve, *v1;
105                 
106                 for(eve= em->verts.first; eve; eve= eve->next) {
107                         if(eve->f & SELECT) {
108                                 v1= editmesh_get_x_mirror_vert(obedit, em, eve->co);
109                                 if(v1) {
110                                         eve->f &= ~SELECT;
111                                         v1->f |= SELECT;
112                                 }
113                         }
114                 }
115         }
116 }
117
118 void EM_automerge(int update) 
119 {
120 // XXX  int len;
121         
122 //      if ((scene->automerge) &&
123 //              (obedit && obedit->type==OB_MESH) &&
124 //              (((Mesh*)obedit->data)->mr==NULL)
125 //        ) {
126 //              len = removedoublesflag(1, 1, scene->toolsettings->doublimit);
127 //              if (len) {
128 //                      em->totvert -= len; /* saves doing a countall */
129 //                      if (update) {
130 //                              DAG_object_flush_update(scene, obedit, OB_RECALC_DATA);
131 //                      }
132 //              }
133 //      }
134 }
135
136 /* ****************************** SELECTION ROUTINES **************** */
137
138 unsigned int em_solidoffs=0, em_wireoffs=0, em_vertoffs=0;      /* set in drawobject.c ... for colorindices */
139
140 /* facilities for border select and circle select */
141 static char *selbuf= NULL;
142
143 /* opengl doesn't support concave... */
144 static void draw_triangulated(short mcords[][2], short tot)
145 {
146         ListBase lb={NULL, NULL};
147         DispList *dl;
148         float *fp;
149         int a;
150         
151         /* make displist */
152         dl= MEM_callocN(sizeof(DispList), "poly disp");
153         dl->type= DL_POLY;
154         dl->parts= 1;
155         dl->nr= tot;
156         dl->verts= fp=  MEM_callocN(tot*3*sizeof(float), "poly verts");
157         BLI_addtail(&lb, dl);
158         
159         for(a=0; a<tot; a++, fp+=3) {
160                 fp[0]= (float)mcords[a][0];
161                 fp[1]= (float)mcords[a][1];
162         }
163         
164         /* do the fill */
165         filldisplist(&lb, &lb);
166
167         /* do the draw */
168         dl= lb.first;   /* filldisplist adds in head of list */
169         if(dl->type==DL_INDEX3) {
170                 int *index;
171                 
172                 a= dl->parts;
173                 fp= dl->verts;
174                 index= dl->index;
175                 glBegin(GL_TRIANGLES);
176                 while(a--) {
177                         glVertex3fv(fp+3*index[0]);
178                         glVertex3fv(fp+3*index[1]);
179                         glVertex3fv(fp+3*index[2]);
180                         index+= 3;
181                 }
182                 glEnd();
183         }
184         
185         freedisplist(&lb);
186 }
187
188
189 /* reads rect, and builds selection array for quick lookup */
190 /* returns if all is OK */
191 int EM_init_backbuf_border(ViewContext *vc, short xmin, short ymin, short xmax, short ymax)
192 {
193         struct ImBuf *buf;
194         unsigned int *dr;
195         int a;
196         
197         if(vc->obedit==NULL || vc->v3d->drawtype<OB_SOLID || (vc->v3d->flag & V3D_ZBUF_SELECT)==0) return 0;
198         
199         buf= view3d_read_backbuf(vc, xmin, ymin, xmax, ymax);
200         if(buf==NULL) return 0;
201         if(em_vertoffs==0) return 0;
202
203         dr = buf->rect;
204         
205         /* build selection lookup */
206         selbuf= MEM_callocN(em_vertoffs+1, "selbuf");
207         
208         a= (xmax-xmin+1)*(ymax-ymin+1);
209         while(a--) {
210                 if(*dr>0 && *dr<=em_vertoffs) 
211                         selbuf[*dr]= 1;
212                 dr++;
213         }
214         IMB_freeImBuf(buf);
215         return 1;
216 }
217
218 int EM_check_backbuf(unsigned int index)
219 {
220         if(selbuf==NULL) return 1;
221         if(index>0 && index<=em_vertoffs)
222                 return selbuf[index];
223         return 0;
224 }
225
226 void EM_free_backbuf(void)
227 {
228         if(selbuf) MEM_freeN(selbuf);
229         selbuf= NULL;
230 }
231
232 /* mcords is a polygon mask
233    - grab backbuffer,
234    - draw with black in backbuffer, 
235    - grab again and compare
236    returns 'OK' 
237 */
238 int EM_mask_init_backbuf_border(ViewContext *vc, short mcords[][2], short tot, short xmin, short ymin, short xmax, short ymax)
239 {
240         unsigned int *dr, *drm;
241         struct ImBuf *buf, *bufmask;
242         int a;
243         
244         /* method in use for face selecting too */
245         if(vc->obedit==NULL) {
246                 if(paint_facesel_test(vc->obact));
247                 else return 0;
248         }
249         else if(vc->v3d->drawtype<OB_SOLID || (vc->v3d->flag & V3D_ZBUF_SELECT)==0) return 0;
250
251         buf= view3d_read_backbuf(vc, xmin, ymin, xmax, ymax);
252         if(buf==NULL) return 0;
253         if(em_vertoffs==0) return 0;
254
255         dr = buf->rect;
256
257         /* draw the mask */
258         glDisable(GL_DEPTH_TEST);
259         
260         glColor3ub(0, 0, 0);
261         
262         /* yah, opengl doesn't do concave... tsk! */
263         ED_region_pixelspace(vc->ar);
264         draw_triangulated(mcords, tot); 
265         
266         glBegin(GL_LINE_LOOP);  /* for zero sized masks, lines */
267         for(a=0; a<tot; a++) glVertex2s(mcords[a][0], mcords[a][1]);
268         glEnd();
269         
270         glFinish();     /* to be sure readpixels sees mask */
271         
272         /* grab mask */
273         bufmask= view3d_read_backbuf(vc, xmin, ymin, xmax, ymax);
274         drm = bufmask->rect;
275         if(bufmask==NULL) return 0; /* only when mem alloc fails, go crash somewhere else! */
276         
277         /* build selection lookup */
278         selbuf= MEM_callocN(em_vertoffs+1, "selbuf");
279         
280         a= (xmax-xmin+1)*(ymax-ymin+1);
281         while(a--) {
282                 if(*dr>0 && *dr<=em_vertoffs && *drm==0) selbuf[*dr]= 1;
283                 dr++; drm++;
284         }
285         IMB_freeImBuf(buf);
286         IMB_freeImBuf(bufmask);
287         return 1;
288         
289 }
290
291 /* circle shaped sample area */
292 int EM_init_backbuf_circle(ViewContext *vc, short xs, short ys, short rads)
293 {
294         struct ImBuf *buf;
295         unsigned int *dr;
296         short xmin, ymin, xmax, ymax, xc, yc;
297         int radsq;
298         
299         /* method in use for face selecting too */
300         if(vc->obedit==NULL) {
301                 if(paint_facesel_test(vc->obact));
302                 else return 0;
303         }
304         else if(vc->v3d->drawtype<OB_SOLID || (vc->v3d->flag & V3D_ZBUF_SELECT)==0) return 0;
305         
306         xmin= xs-rads; xmax= xs+rads;
307         ymin= ys-rads; ymax= ys+rads;
308         buf= view3d_read_backbuf(vc, xmin, ymin, xmax, ymax);
309         if(em_vertoffs==0) return 0;
310         if(buf==NULL) return 0;
311
312         dr = buf->rect;
313         
314         /* build selection lookup */
315         selbuf= MEM_callocN(em_vertoffs+1, "selbuf");
316         radsq= rads*rads;
317         for(yc= -rads; yc<=rads; yc++) {
318                 for(xc= -rads; xc<=rads; xc++, dr++) {
319                         if(xc*xc + yc*yc < radsq) {
320                                 if(*dr>0 && *dr<=em_vertoffs) selbuf[*dr]= 1;
321                         }
322                 }
323         }
324
325         IMB_freeImBuf(buf);
326         return 1;
327         
328 }
329
330 static void findnearestvert__doClosest(void *userData, EditVert *eve, int x, int y, int index)
331 {
332         struct { short mval[2], pass, select, strict; int dist, lastIndex, closestIndex; EditVert *closest; } *data = userData;
333
334         if (data->pass==0) {
335                 if (index<=data->lastIndex)
336                         return;
337         } else {
338                 if (index>data->lastIndex)
339                         return;
340         }
341
342         if (data->dist>3) {
343                 int temp = abs(data->mval[0] - x) + abs(data->mval[1]- y);
344                 if ((eve->f&1) == data->select) {
345                         if (data->strict == 1)
346                                 return;
347                         else
348                                 temp += 5;
349                 }
350
351                 if (temp<data->dist) {
352                         data->dist = temp;
353                         data->closest = eve;
354                         data->closestIndex = index;
355                 }
356         }
357 }
358
359
360
361
362 static unsigned int findnearestvert__backbufIndextest(void *handle, unsigned int index)
363 {
364         EditMesh *em= (EditMesh *)handle;
365         EditVert *eve = BLI_findlink(&em->verts, index-1);
366
367         if(eve && (eve->f & SELECT)) return 0;
368         return 1; 
369 }
370 /**
371  * findnearestvert
372  * 
373  * dist (in/out): minimal distance to the nearest and at the end, actual distance
374  * sel: selection bias
375  *              if SELECT, selected vertice are given a 5 pixel bias to make them farter than unselect verts
376  *              if 0, unselected vertice are given the bias
377  * strict: if 1, the vertice corresponding to the sel parameter are ignored and not just biased 
378  */
379 EditVert *findnearestvert(ViewContext *vc, int *dist, short sel, short strict)
380 {
381         if(vc->v3d->drawtype>OB_WIRE && (vc->v3d->flag & V3D_ZBUF_SELECT)){
382                 int distance;
383                 unsigned int index;
384                 EditVert *eve;
385                 
386                 if(strict) index = view3d_sample_backbuf_rect(vc, vc->mval, 50, em_wireoffs, 0xFFFFFF, &distance, strict, vc->em, findnearestvert__backbufIndextest); 
387                 else index = view3d_sample_backbuf_rect(vc, vc->mval, 50, em_wireoffs, 0xFFFFFF, &distance, 0, NULL, NULL); 
388                 
389                 eve = BLI_findlink(&vc->em->verts, index-1);
390                 
391                 if(eve && distance < *dist) {
392                         *dist = distance;
393                         return eve;
394                 } else {
395                         return NULL;
396                 }
397                         
398         }
399         else {
400                 struct { short mval[2], pass, select, strict; int dist, lastIndex, closestIndex; EditVert *closest; } data;
401                 static int lastSelectedIndex=0;
402                 static EditVert *lastSelected=NULL;
403
404                 if (lastSelected && BLI_findlink(&vc->em->verts, lastSelectedIndex)!=lastSelected) {
405                         lastSelectedIndex = 0;
406                         lastSelected = NULL;
407                 }
408
409                 data.lastIndex = lastSelectedIndex;
410                 data.mval[0] = vc->mval[0];
411                 data.mval[1] = vc->mval[1];
412                 data.select = sel;
413                 data.dist = *dist;
414                 data.strict = strict;
415                 data.closest = NULL;
416                 data.closestIndex = 0;
417
418                 data.pass = 0;
419                 mesh_foreachScreenVert(vc, findnearestvert__doClosest, &data, 1);
420
421                 if (data.dist>3) {
422                         data.pass = 1;
423                         mesh_foreachScreenVert(vc, findnearestvert__doClosest, &data, 1);
424                 }
425
426                 *dist = data.dist;
427                 lastSelected = data.closest;
428                 lastSelectedIndex = data.closestIndex;
429
430                 return data.closest;
431         }
432 }
433
434 /* returns labda for closest distance v1 to line-piece v2-v3 */
435 static float labda_PdistVL2Dfl( float *v1, float *v2, float *v3) 
436 {
437         float rc[2], len;
438         
439         rc[0]= v3[0]-v2[0];
440         rc[1]= v3[1]-v2[1];
441         len= rc[0]*rc[0]+ rc[1]*rc[1];
442         if(len==0.0f)
443                 return 0.0f;
444         
445         return ( rc[0]*(v1[0]-v2[0]) + rc[1]*(v1[1]-v2[1]) )/len;
446 }
447
448 /* note; uses v3d, so needs active 3d window */
449 static void findnearestedge__doClosest(void *userData, EditEdge *eed, int x0, int y0, int x1, int y1, int index)
450 {
451         struct { ViewContext vc; float mval[2]; int dist; EditEdge *closest; } *data = userData;
452         float v1[2], v2[2];
453         int distance;
454                 
455         v1[0] = x0;
456         v1[1] = y0;
457         v2[0] = x1;
458         v2[1] = y1;
459                 
460         distance= PdistVL2Dfl(data->mval, v1, v2);
461                 
462         if(eed->f & SELECT) distance+=5;
463         if(distance < data->dist) {
464                 if(data->vc.rv3d->rflag & RV3D_CLIPPING) {
465                         float labda= labda_PdistVL2Dfl(data->mval, v1, v2);
466                         float vec[3];
467
468                         vec[0]= eed->v1->co[0] + labda*(eed->v2->co[0] - eed->v1->co[0]);
469                         vec[1]= eed->v1->co[1] + labda*(eed->v2->co[1] - eed->v1->co[1]);
470                         vec[2]= eed->v1->co[2] + labda*(eed->v2->co[2] - eed->v1->co[2]);
471                         Mat4MulVecfl(data->vc.obedit->obmat, vec);
472
473                         if(view3d_test_clipping(data->vc.rv3d, vec)==0) {
474                                 data->dist = distance;
475                                 data->closest = eed;
476                         }
477                 }
478                 else {
479                         data->dist = distance;
480                         data->closest = eed;
481                 }
482         }
483 }
484 EditEdge *findnearestedge(ViewContext *vc, int *dist)
485 {
486
487         if(vc->v3d->drawtype>OB_WIRE && (vc->v3d->flag & V3D_ZBUF_SELECT)) {
488                 int distance;
489                 unsigned int index = view3d_sample_backbuf_rect(vc, vc->mval, 50, em_solidoffs, em_wireoffs, &distance,0, NULL, NULL);
490                 EditEdge *eed = BLI_findlink(&vc->em->edges, index-1);
491
492                 if (eed && distance<*dist) {
493                         *dist = distance;
494                         return eed;
495                 } else {
496                         return NULL;
497                 }
498         }
499         else {
500                 struct { ViewContext vc; float mval[2]; int dist; EditEdge *closest; } data;
501
502                 data.vc= *vc;
503                 data.mval[0] = vc->mval[0];
504                 data.mval[1] = vc->mval[1];
505                 data.dist = *dist;
506                 data.closest = NULL;
507
508                 mesh_foreachScreenEdge(vc, findnearestedge__doClosest, &data, 2);
509
510                 *dist = data.dist;
511                 return data.closest;
512         }
513 }
514
515 static void findnearestface__getDistance(void *userData, EditFace *efa, int x, int y, int index)
516 {
517         struct { short mval[2]; int dist; EditFace *toFace; } *data = userData;
518
519         if (efa==data->toFace) {
520                 int temp = abs(data->mval[0]-x) + abs(data->mval[1]-y);
521
522                 if (temp<data->dist)
523                         data->dist = temp;
524         }
525 }
526 static void findnearestface__doClosest(void *userData, EditFace *efa, int x, int y, int index)
527 {
528         struct { short mval[2], pass; int dist, lastIndex, closestIndex; EditFace *closest; } *data = userData;
529
530         if (data->pass==0) {
531                 if (index<=data->lastIndex)
532                         return;
533         } else {
534                 if (index>data->lastIndex)
535                         return;
536         }
537
538         if (data->dist>3) {
539                 int temp = abs(data->mval[0]-x) + abs(data->mval[1]-y);
540
541                 if (temp<data->dist) {
542                         data->dist = temp;
543                         data->closest = efa;
544                         data->closestIndex = index;
545                 }
546         }
547 }
548 static EditFace *findnearestface(ViewContext *vc, int *dist)
549 {
550
551         if(vc->v3d->drawtype>OB_WIRE && (vc->v3d->flag & V3D_ZBUF_SELECT)) {
552                 unsigned int index = view3d_sample_backbuf(vc, vc->mval[0], vc->mval[1]);
553                 EditFace *efa = BLI_findlink(&vc->em->faces, index-1);
554
555                 if (efa) {
556                         struct { short mval[2]; int dist; EditFace *toFace; } data;
557
558                         data.mval[0] = vc->mval[0];
559                         data.mval[1] = vc->mval[1];
560                         data.dist = 0x7FFF;             /* largest short */
561                         data.toFace = efa;
562
563                         mesh_foreachScreenFace(vc, findnearestface__getDistance, &data);
564
565                         if(vc->em->selectmode == SCE_SELECT_FACE || data.dist<*dist) {  /* only faces, no dist check */
566                                 *dist= data.dist;
567                                 return efa;
568                         }
569                 }
570                 
571                 return NULL;
572         }
573         else {
574                 struct { short mval[2], pass; int dist, lastIndex, closestIndex; EditFace *closest; } data;
575                 static int lastSelectedIndex=0;
576                 static EditFace *lastSelected=NULL;
577
578                 if (lastSelected && BLI_findlink(&vc->em->faces, lastSelectedIndex)!=lastSelected) {
579                         lastSelectedIndex = 0;
580                         lastSelected = NULL;
581                 }
582
583                 data.lastIndex = lastSelectedIndex;
584                 data.mval[0] = vc->mval[0];
585                 data.mval[1] = vc->mval[1];
586                 data.dist = *dist;
587                 data.closest = NULL;
588                 data.closestIndex = 0;
589
590                 data.pass = 0;
591                 mesh_foreachScreenFace(vc, findnearestface__doClosest, &data);
592
593                 if (data.dist>3) {
594                         data.pass = 1;
595                         mesh_foreachScreenFace(vc, findnearestface__doClosest, &data);
596                 }
597
598                 *dist = data.dist;
599                 lastSelected = data.closest;
600                 lastSelectedIndex = data.closestIndex;
601
602                 return data.closest;
603         }
604 }
605
606 /* best distance based on screen coords. 
607    use em->selectmode to define how to use 
608    selected vertices and edges get disadvantage
609    return 1 if found one
610 */
611 static int unified_findnearest(ViewContext *vc, EditVert **eve, EditEdge **eed, EditFace **efa) 
612 {
613         EditMesh *em= vc->em;
614         int dist= 75;
615         
616         *eve= NULL;
617         *eed= NULL;
618         *efa= NULL;
619         
620         /* no afterqueue (yet), so we check it now, otherwise the em_xxxofs indices are bad */
621         view3d_validate_backbuf(vc);
622         
623         if(em->selectmode & SCE_SELECT_VERTEX)
624                 *eve= findnearestvert(vc, &dist, SELECT, 0);
625         if(em->selectmode & SCE_SELECT_FACE)
626                 *efa= findnearestface(vc, &dist);
627
628         dist-= 20;      /* since edges select lines, we give dots advantage of 20 pix */
629         if(em->selectmode & SCE_SELECT_EDGE)
630                 *eed= findnearestedge(vc, &dist);
631
632         /* return only one of 3 pointers, for frontbuffer redraws */
633         if(*eed) {
634                 *efa= NULL; *eve= NULL;
635         }
636         else if(*efa) {
637                 *eve= NULL;
638         }
639         
640         return (*eve || *eed || *efa);
641 }
642
643
644 /* ****************  SIMILAR "group" SELECTS. FACE, EDGE AND VERTEX ************** */
645
646 /* selects new faces/edges/verts based on the existing selection */
647
648 /* FACES GROUP */
649
650 #define SIMFACE_MATERIAL        201
651 #define SIMFACE_IMAGE           202
652 #define SIMFACE_AREA            203
653 #define SIMFACE_PERIMETER       204
654 #define SIMFACE_NORMAL          205
655 #define SIMFACE_COPLANAR        206
656
657 static EnumPropertyItem prop_simface_types[] = {
658         {SIMFACE_MATERIAL, "MATERIAL", 0, "Material", ""},
659         {SIMFACE_IMAGE, "IMAGE", 0, "Image", ""},
660         {SIMFACE_AREA, "AREA", 0, "Area", ""},
661         {SIMFACE_PERIMETER, "PERIMETER", 0, "Perimeter", ""},
662         {SIMFACE_NORMAL, "NORMAL", 0, "Normal", ""},
663         {SIMFACE_COPLANAR, "COPLANAR", 0, "Co-planar", ""},
664         {0, NULL, 0, NULL, NULL}
665 };
666
667
668 /* this as a way to compare the ares, perim  of 2 faces thay will scale to different sizes
669 *0.5 so smaller faces arnt ALWAYS selected with a thresh of 1.0 */
670 #define SCALE_CMP(a,b) ((a+a*thresh >= b) && (a-(a*thresh*0.5) <= b))
671
672 static int similar_face_select__internal(Scene *scene, EditMesh *em, int mode)
673 {
674         EditFace *efa, *base_efa=NULL;
675         unsigned int selcount=0; /*count how many new faces we select*/
676         
677         /*deselcount, count how many deselected faces are left, so we can bail out early
678         also means that if there are no deselected faces, we can avoid a lot of looping */
679         unsigned int deselcount=0; 
680         float thresh= scene->toolsettings->select_thresh;
681         short ok=0;
682         
683         for(efa= em->faces.first; efa; efa= efa->next) {
684                 if (!efa->h) {
685                         if (efa->f & SELECT) {
686                                 efa->f1=1;
687                                 ok=1;
688                         } else {
689                                 efa->f1=0;
690                                 deselcount++; /* a deselected face we may select later */
691                         }
692                 }
693         }
694         
695         if (!ok || !deselcount) /* no data selected OR no more data to select */
696                 return 0;
697         
698         if (mode==SIMFACE_AREA) {
699                 for(efa= em->faces.first; efa; efa= efa->next) {
700                         efa->tmp.fp= EM_face_area(efa);
701                 }
702         } else if (mode==SIMFACE_PERIMETER) {
703                 for(efa= em->faces.first; efa; efa= efa->next) {
704                         efa->tmp.fp= EM_face_perimeter(efa);
705                 }
706         }
707         
708         for(base_efa= em->faces.first; base_efa; base_efa= base_efa->next) {
709                 if (base_efa->f1) { /* This was one of the faces originaly selected */
710                         if (mode==SIMFACE_MATERIAL) { /* same material */
711                                 for(efa= em->faces.first; efa; efa= efa->next) {
712                                         if (
713                                                 !(efa->f & SELECT) &&
714                                                 !efa->h &&
715                                                 base_efa->mat_nr == efa->mat_nr
716                                         ) {
717                                                 EM_select_face(efa, 1);
718                                                 selcount++;
719                                                 deselcount--;
720                                                 if (!deselcount) /*have we selected all posible faces?, if so return*/
721                                                         return selcount;
722                                         }
723                                 }
724                         } else if (mode==SIMFACE_IMAGE) { /* same image */
725                                 MTFace *tf, *base_tf;
726
727                                 base_tf = (MTFace*)CustomData_em_get(&em->fdata, base_efa->data,
728                                                                      CD_MTFACE);
729
730                                 if(!base_tf)
731                                         return selcount;
732
733                                 for(efa= em->faces.first; efa; efa= efa->next) {
734                                         if (!(efa->f & SELECT) && !efa->h) {
735                                                 tf = (MTFace*)CustomData_em_get(&em->fdata, efa->data,
736                                                                                 CD_MTFACE);
737
738                                                 if(base_tf->tpage == tf->tpage) {
739                                                         EM_select_face(efa, 1);
740                                                         selcount++;
741                                                         deselcount--;
742                                                         if (!deselcount) /*have we selected all posible faces?, if so return*/
743                                                                 return selcount;
744                                                 }
745                                         }
746                                 }
747                         } else if (mode==SIMFACE_AREA || mode==SIMFACE_PERIMETER) { /* same area OR same perimeter, both use the same temp var */
748                                 for(efa= em->faces.first; efa; efa= efa->next) {
749                                         if (
750                                                 (!(efa->f & SELECT) && !efa->h) &&
751                                                 SCALE_CMP(base_efa->tmp.fp, efa->tmp.fp)
752                                         ) {
753                                                 EM_select_face(efa, 1);
754                                                 selcount++;
755                                                 deselcount--;
756                                                 if (!deselcount) /*have we selected all posible faces?, if so return*/
757                                                         return selcount;
758                                         }
759                                 }
760                         } else if (mode==SIMFACE_NORMAL) {
761                                 float angle;
762                                 for(efa= em->faces.first; efa; efa= efa->next) {
763                                         if (!(efa->f & SELECT) && !efa->h) {
764                                                 angle= VecAngle2(base_efa->n, efa->n);
765                                                 if (angle/180.0<=thresh) {
766                                                         EM_select_face(efa, 1);
767                                                         selcount++;
768                                                         deselcount--;
769                                                         if (!deselcount) /*have we selected all posible faces?, if so return*/
770                                                                 return selcount;
771                                                 }
772                                         }
773                                 }
774                         } else if (mode==SIMFACE_COPLANAR) { /* same planer */
775                                 float angle, base_dot, dot;
776                                 base_dot= Inpf(base_efa->cent, base_efa->n);
777                                 for(efa= em->faces.first; efa; efa= efa->next) {
778                                         if (!(efa->f & SELECT) && !efa->h) {
779                                                 angle= VecAngle2(base_efa->n, efa->n);
780                                                 if (angle/180.0<=thresh) {
781                                                         dot=Inpf(efa->cent, base_efa->n);
782                                                         if (fabs(base_dot-dot) <= thresh) {
783                                                                 EM_select_face(efa, 1);
784                                                                 selcount++;
785                                                                 deselcount--;
786                                                                 if (!deselcount) /*have we selected all posible faces?, if so return*/
787                                                                         return selcount;
788                                                         }
789                                                 }
790                                         }
791                                 }
792                         }
793                 }
794         } /* end base_efa loop */
795         return selcount;
796 }
797
798 static int similar_face_select_exec(bContext *C, wmOperator *op)
799 {
800         Scene *scene= CTX_data_scene(C);
801         Object *obedit= CTX_data_edit_object(C);
802         Mesh *me= obedit->data;
803         EditMesh *em= BKE_mesh_get_editmesh(me); 
804
805         int selcount = similar_face_select__internal(scene, em, RNA_int_get(op->ptr, "type"));
806         
807         if (selcount) {
808                 /* here was an edge-mode only select flush case, has to be generalized */
809                 EM_selectmode_flush(em);
810                 WM_event_add_notifier(C, NC_OBJECT|ND_GEOM_SELECT, obedit);
811                 BKE_mesh_end_editmesh(me, em);
812                 return OPERATOR_FINISHED;
813         }
814         
815         BKE_mesh_end_editmesh(me, em);
816         return OPERATOR_CANCELLED;
817 }       
818
819 /* ***************************************************** */
820
821 /* EDGE GROUP */
822
823 #define SIMEDGE_LENGTH          101
824 #define SIMEDGE_DIR                     102
825 #define SIMEDGE_FACE            103
826 #define SIMEDGE_FACE_ANGLE      104
827 #define SIMEDGE_CREASE          105
828 #define SIMEDGE_SEAM            106
829 #define SIMEDGE_SHARP           107
830
831 static EnumPropertyItem prop_simedge_types[] = {
832         {SIMEDGE_LENGTH, "LENGTH", 0, "Length", ""},
833         {SIMEDGE_DIR, "DIR", 0, "Direction", ""},
834         {SIMEDGE_FACE, "FACE", 0, "Amount of Vertices in Face", ""},
835         {SIMEDGE_FACE_ANGLE, "FACE_ANGLE", 0, "Face Angles", ""},
836         {SIMEDGE_CREASE, "CREASE", 0, "Crease", ""},
837         {SIMEDGE_SEAM, "SEAM", 0, "Seam", ""},
838         {SIMEDGE_SHARP, "SHARP", 0, "Sharpness", ""},
839         {0, NULL, 0, NULL, NULL}
840 };
841
842 static int similar_edge_select__internal(Scene *scene, EditMesh *em, int mode)
843 {
844         EditEdge *eed, *base_eed=NULL;
845         unsigned int selcount=0; /* count how many new edges we select*/
846         
847         /*count how many visible selected edges there are,
848         so we can return when there are none left */
849         unsigned int deselcount=0;
850         
851         short ok=0;
852         float thresh= scene->toolsettings->select_thresh;
853         
854         for(eed= em->edges.first; eed; eed= eed->next) {
855                 if (!eed->h) {
856                         if (eed->f & SELECT) {
857                                 eed->f1=1;
858                                 ok=1;
859                         } else {
860                                 eed->f1=0;
861                                 deselcount++;
862                         }
863                         /* set all eed->tmp.l to 0 we use it later.
864                         for counting face users*/
865                         eed->tmp.l=0;
866                         eed->f2=0; /* only for mode SIMEDGE_FACE_ANGLE, edge animations */
867                 }
868         }
869         
870         if (!ok || !deselcount) /* no data selected OR no more data to select*/
871                 return 0;
872         
873         if (mode==SIMEDGE_LENGTH) { /*store length*/
874                 for(eed= em->edges.first; eed; eed= eed->next) {
875                         if (!eed->h) /* dont calc data for hidden edges*/
876                                 eed->tmp.fp= VecLenf(eed->v1->co, eed->v2->co);
877                 }
878         } else if (mode==SIMEDGE_FACE) { /*store face users*/
879                 EditFace *efa;
880                 /* cound how many faces each edge uses use tmp->l */
881                 for(efa= em->faces.first; efa; efa= efa->next) {
882                         efa->e1->tmp.l++;
883                         efa->e2->tmp.l++;
884                         efa->e3->tmp.l++;
885                         if (efa->e4) efa->e4->tmp.l++;
886                 }
887         } else if (mode==SIMEDGE_FACE_ANGLE) { /*store edge angles */
888                 EditFace *efa;
889                 int j;
890                 /* cound how many faces each edge uses use tmp.l */
891                 for(efa= em->faces.first; efa; efa= efa->next) {
892                         /* here we use the edges temp data to assign a face
893                         if a face has alredy been assigned (eed->f2==1)
894                         we calculate the angle between the current face and
895                         the edges previously found face.
896                         store the angle in eed->tmp.fp (loosing the face eed->tmp.f)
897                         but tagging eed->f2==2, so we know not to look at it again.
898                         This only works for edges that connect to 2 faces. but its good enough
899                         */
900                         
901                         /* se we can loop through face edges*/
902                         j=0;
903                         eed= efa->e1;
904                         while (j<4) {
905                                 if (j==1) eed= efa->e2;
906                                 else if (j==2) eed= efa->e3;
907                                 else if (j==3) {
908                                         eed= efa->e4;
909                                         if (!eed)
910                                                 break;
911                                 } /* done looping */
912                                 
913                                 if (!eed->h) { /* dont calc data for hidden edges*/
914                                         if (eed->f2==2)
915                                                 break;
916                                         else if (eed->f2==0) /* first access, assign the face */
917                                                 eed->tmp.f= efa;
918                                         else if (eed->f2==1) /* second, we assign the angle*/
919                                                 eed->tmp.fp= VecAngle2(eed->tmp.f->n, efa->n)/180;
920                                         eed->f2++; /* f2==0 no face assigned. f2==1 one face found. f2==2 angle calculated.*/
921                                 }
922                                 j++;
923                         }
924                 }
925         }
926         
927         for(base_eed= em->edges.first; base_eed; base_eed= base_eed->next) {
928                 if (base_eed->f1) {
929                         if (mode==SIMEDGE_LENGTH) { /* same length */
930                                 for(eed= em->edges.first; eed; eed= eed->next) {
931                                         if (
932                                                 !(eed->f & SELECT) &&
933                                                 !eed->h &&
934                                                 SCALE_CMP(base_eed->tmp.fp, eed->tmp.fp)
935                                         ) {
936                                                 EM_select_edge(eed, 1);
937                                                 selcount++;
938                                                 deselcount--;
939                                                 if (!deselcount) /*have we selected all posible faces?, if so return*/
940                                                         return selcount;
941                                         }
942                                 }
943                         } else if (mode==SIMEDGE_DIR) { /* same direction */
944                                 float base_dir[3], dir[3], angle;
945                                 VecSubf(base_dir, base_eed->v1->co, base_eed->v2->co);
946                                 for(eed= em->edges.first; eed; eed= eed->next) {
947                                         if (!(eed->f & SELECT) && !eed->h) {
948                                                 VecSubf(dir, eed->v1->co, eed->v2->co);
949                                                 angle= VecAngle2(base_dir, dir);
950                                                 
951                                                 if (angle>90) /* use the smallest angle between the edges */
952                                                         angle= fabs(angle-180.0f);
953                                                 
954                                                 if (angle/90.0<=thresh) {
955                                                         EM_select_edge(eed, 1);
956                                                         selcount++;
957                                                         deselcount--;
958                                                         if (!deselcount) /*have we selected all posible faces?, if so return*/
959                                                                 return selcount;
960                                                 }
961                                         }
962                                 }
963                         } else if (mode==SIMEDGE_FACE) { /* face users */                               
964                                 for(eed= em->edges.first; eed; eed= eed->next) {
965                                         if (
966                                                 !(eed->f & SELECT) &&
967                                                 !eed->h &&
968                                                 base_eed->tmp.l==eed->tmp.l
969                                         ) {
970                                                 EM_select_edge(eed, 1);
971                                                 selcount++;
972                                                 deselcount--;
973                                                 if (!deselcount) /*have we selected all posible faces?, if so return*/
974                                                         return selcount;
975                                         }
976                                 }
977                         } else if (mode==SIMEDGE_FACE_ANGLE && base_eed->f2==2) { /* edge angles, f2==2 means the edge has an angle. */                         
978                                 for(eed= em->edges.first; eed; eed= eed->next) {
979                                         if (
980                                                 !(eed->f & SELECT) &&
981                                                 !eed->h &&
982                                                 eed->f2==2 &&
983                                                 (fabs(base_eed->tmp.fp-eed->tmp.fp)<=thresh)
984                                         ) {
985                                                 EM_select_edge(eed, 1);
986                                                 selcount++;
987                                                 deselcount--;
988                                                 if (!deselcount) /*have we selected all posible faces?, if so return*/
989                                                         return selcount;
990                                         }
991                                 }
992                         } else if (mode==SIMEDGE_CREASE) { /* edge crease */
993                                 for(eed= em->edges.first; eed; eed= eed->next) {
994                                         if (
995                                                 !(eed->f & SELECT) &&
996                                                 !eed->h &&
997                                                 (fabs(base_eed->crease-eed->crease) <= thresh)
998                                         ) {
999                                                 EM_select_edge(eed, 1);
1000                                                 selcount++;
1001                                                 deselcount--;
1002                                                 if (!deselcount) /*have we selected all posible faces?, if so return*/
1003                                                         return selcount;
1004                                         }
1005                                 }
1006                         } else if (mode==SIMEDGE_SEAM) { /* edge seam */
1007                                 for(eed= em->edges.first; eed; eed= eed->next) {
1008                                         if (
1009                                                 !(eed->f & SELECT) &&
1010                                                 !eed->h &&
1011                                                 (eed->seam == base_eed->seam)
1012                                         ) {
1013                                                 EM_select_edge(eed, 1);
1014                                                 selcount++;
1015                                                 deselcount--;
1016                                                 if (!deselcount) /*have we selected all posible faces?, if so return*/
1017                                                         return selcount;
1018                                         }
1019                                 }
1020                         } else if (mode==SIMEDGE_SHARP) { /* edge sharp */
1021                                 for(eed= em->edges.first; eed; eed= eed->next) {
1022                                         if (
1023                                                 !(eed->f & SELECT) &&
1024                                                 !eed->h &&
1025                                                 (eed->sharp == base_eed->sharp)
1026                                         ) {
1027                                                 EM_select_edge(eed, 1);
1028                                                 selcount++;
1029                                                 deselcount--;
1030                                                 if (!deselcount) /*have we selected all posible faces?, if so return*/
1031                                                         return selcount;
1032                                         }
1033                                 }
1034                         }
1035                 }
1036         }       
1037         return selcount;
1038 }
1039 /* wrap the above function but do selection flushing edge to face */
1040 static int similar_edge_select_exec(bContext *C, wmOperator *op)
1041 {
1042         Scene *scene= CTX_data_scene(C);
1043         Object *obedit= CTX_data_edit_object(C);
1044         Mesh *me= obedit->data;
1045         EditMesh *em= BKE_mesh_get_editmesh(me); 
1046
1047         int selcount = similar_edge_select__internal(scene, em, RNA_int_get(op->ptr, "type"));
1048         
1049         if (selcount) {
1050                 /* here was an edge-mode only select flush case, has to be generalized */
1051                 EM_selectmode_flush(em);
1052                 WM_event_add_notifier(C, NC_OBJECT|ND_GEOM_SELECT, obedit);
1053                 BKE_mesh_end_editmesh(me, em);
1054                 return OPERATOR_FINISHED;
1055         }
1056         
1057         BKE_mesh_end_editmesh(me, em);
1058         return OPERATOR_CANCELLED;
1059 }
1060
1061 /* ********************************* */
1062
1063 /*
1064 VERT GROUP
1065  mode 1: same normal
1066  mode 2: same number of face users
1067  mode 3: same vertex groups
1068 */
1069
1070 #define SIMVERT_NORMAL  0
1071 #define SIMVERT_FACE    1
1072 #define SIMVERT_VGROUP  2
1073
1074 static EnumPropertyItem prop_simvertex_types[] = {
1075         {SIMVERT_NORMAL, "NORMAL", 0, "Normal", ""},
1076         {SIMVERT_FACE, "FACE", 0, "Amount of Vertices in Face", ""},
1077         {SIMVERT_VGROUP, "VGROUP", 0, "Vertex Groups", ""},
1078         {0, NULL, 0, NULL, NULL}
1079 };
1080
1081
1082 static int similar_vert_select_exec(bContext *C, wmOperator *op)
1083 {
1084         Scene *scene= CTX_data_scene(C);
1085         Object *obedit= CTX_data_edit_object(C);
1086         Mesh *me= obedit->data;
1087         EditMesh *em= BKE_mesh_get_editmesh(me); 
1088         EditVert *eve, *base_eve=NULL;
1089         unsigned int selcount=0; /* count how many new edges we select*/
1090         
1091         /*count how many visible selected edges there are,
1092         so we can return when there are none left */
1093         unsigned int deselcount=0;
1094         int mode= RNA_enum_get(op->ptr, "type");
1095         
1096         short ok=0;
1097         float thresh= scene->toolsettings->select_thresh;
1098         
1099         for(eve= em->verts.first; eve; eve= eve->next) {
1100                 if (!eve->h) {
1101                         if (eve->f & SELECT) {
1102                                 eve->f1=1;
1103                                 ok=1;
1104                         } else {
1105                                 eve->f1=0;
1106                                 deselcount++;
1107                         }
1108                         /* set all eve->tmp.l to 0 we use them later.*/
1109                         eve->tmp.l=0;
1110                 }
1111                 
1112         }
1113         
1114         if (!ok || !deselcount) { /* no data selected OR no more data to select*/
1115                 BKE_mesh_end_editmesh(me, em);
1116                 return 0;
1117         }
1118         
1119         if(mode == SIMVERT_FACE) {
1120                 /* store face users */
1121                 EditFace *efa;
1122                 
1123                 /* count how many faces each edge uses use tmp->l */
1124                 for(efa= em->faces.first; efa; efa= efa->next) {
1125                         efa->v1->tmp.l++;
1126                         efa->v2->tmp.l++;
1127                         efa->v3->tmp.l++;
1128                         if (efa->v4) efa->v4->tmp.l++;
1129                 }
1130         }
1131         
1132         
1133         for(base_eve= em->verts.first; base_eve; base_eve= base_eve->next) {
1134                 if (base_eve->f1) {
1135                                 
1136                         if(mode == SIMVERT_NORMAL) {
1137                                 float angle;
1138                                 for(eve= em->verts.first; eve; eve= eve->next) {
1139                                         if (!(eve->f & SELECT) && !eve->h) {
1140                                                 angle= VecAngle2(base_eve->no, eve->no);
1141                                                 if (angle/180.0<=thresh) {
1142                                                         eve->f |= SELECT;
1143                                                         selcount++;
1144                                                         deselcount--;
1145                                                         if (!deselcount) {/*have we selected all posible faces?, if so return*/
1146                                                                 BKE_mesh_end_editmesh(me, em);
1147                                                                 return selcount;
1148                                                         }
1149                                                 }
1150                                         }
1151                                 }
1152                         }
1153                         else if(mode == SIMVERT_FACE) {
1154                                 for(eve= em->verts.first; eve; eve= eve->next) {
1155                                         if (
1156                                                 !(eve->f & SELECT) &&
1157                                                 !eve->h &&
1158                                                 base_eve->tmp.l==eve->tmp.l
1159                                         ) {
1160                                                 eve->f |= SELECT;
1161                                                 selcount++;
1162                                                 deselcount--;
1163                                                 if (!deselcount) {/*have we selected all posible faces?, if so return*/
1164                                                         BKE_mesh_end_editmesh(me, em);
1165                                                         return selcount;
1166                                                 }
1167                                         }
1168                                 }
1169                         } 
1170                         else if(mode == SIMVERT_VGROUP) {
1171                                 MDeformVert *dvert, *base_dvert;
1172                                 short i, j; /* weight index */
1173
1174                                 base_dvert= CustomData_em_get(&em->vdata, base_eve->data,
1175                                         CD_MDEFORMVERT);
1176
1177                                 if (!base_dvert || base_dvert->totweight == 0) {
1178                                         BKE_mesh_end_editmesh(me, em);
1179                                         return selcount;
1180                                 }
1181                                 
1182                                 for(eve= em->verts.first; eve; eve= eve->next) {
1183                                         dvert= CustomData_em_get(&em->vdata, eve->data,
1184                                                 CD_MDEFORMVERT);
1185
1186                                         if (dvert && !(eve->f & SELECT) && !eve->h && dvert->totweight) {
1187                                                 /* do the extra check for selection in the following if, so were not
1188                                                 checking verts that may be alredy selected */
1189                                                 for (i=0; base_dvert->totweight >i && !(eve->f & SELECT); i++) { 
1190                                                         for (j=0; dvert->totweight >j; j++) {
1191                                                                 if (base_dvert->dw[i].def_nr==dvert->dw[j].def_nr) {
1192                                                                         eve->f |= SELECT;
1193                                                                         selcount++;
1194                                                                         deselcount--;
1195                                                                         if (!deselcount) { /*have we selected all posible faces?, if so return*/
1196                                                                                 BKE_mesh_end_editmesh(me, em);
1197                                                                                 return selcount;
1198                                                                         }
1199                                                                         break;
1200                                                                 }
1201                                                         }
1202                                                 }
1203                                         }
1204                                 }
1205                         }
1206                 }
1207         } /* end basevert loop */
1208
1209         if(selcount) {
1210                 WM_event_add_notifier(C, NC_OBJECT|ND_GEOM_SELECT, obedit);
1211                 BKE_mesh_end_editmesh(me, em);
1212                 return OPERATOR_FINISHED;
1213         }
1214
1215         BKE_mesh_end_editmesh(me, em);
1216         return OPERATOR_CANCELLED;
1217 }
1218
1219 static int select_similar_exec(bContext *C, wmOperator *op)
1220 {
1221         int type= RNA_enum_get(op->ptr, "type");
1222
1223         if(type < 100)
1224                 return similar_vert_select_exec(C, op);
1225         else if(type < 200)
1226                 return similar_edge_select_exec(C, op);
1227         else
1228                 return similar_face_select_exec(C, op);
1229 }
1230
1231 static EnumPropertyItem *select_similar_type_itemf(bContext *C, PointerRNA *ptr, int *free)
1232 {
1233         Object *obedit;
1234         EnumPropertyItem *item= NULL;
1235         int totitem= 0;
1236         
1237         if(C==NULL) {
1238                 /* needed for doc generation */
1239                 RNA_enum_items_add(&item, &totitem, prop_simvertex_types);
1240                 RNA_enum_items_add(&item, &totitem, prop_simedge_types);
1241                 RNA_enum_items_add(&item, &totitem, prop_simface_types);
1242                 RNA_enum_item_end(&item, &totitem);
1243                 *free= 1;
1244                 
1245                 return item;
1246         }
1247         
1248         obedit= CTX_data_edit_object(C);
1249         
1250         if(obedit && obedit->type == OB_MESH) {
1251                 EditMesh *em= BKE_mesh_get_editmesh(obedit->data); 
1252
1253                 if(em->selectmode & SCE_SELECT_VERTEX)
1254                         RNA_enum_items_add(&item, &totitem, prop_simvertex_types);
1255                 else if(em->selectmode & SCE_SELECT_EDGE)
1256                         RNA_enum_items_add(&item, &totitem, prop_simedge_types);
1257                 else if(em->selectmode & SCE_SELECT_FACE)
1258                         RNA_enum_items_add(&item, &totitem, prop_simface_types);
1259                 RNA_enum_item_end(&item, &totitem);
1260
1261                 *free= 1;
1262
1263                 return item;
1264         }
1265         
1266         return NULL;
1267 }
1268
1269 void MESH_OT_select_similar(wmOperatorType *ot)
1270 {
1271         PropertyRNA *prop;
1272
1273         /* identifiers */
1274         ot->name= "Select Similar";
1275         ot->description= "Select similar vertices, edges or faces by property types.";
1276         ot->idname= "MESH_OT_select_similar";
1277         
1278         /* api callbacks */
1279         ot->invoke= WM_menu_invoke;
1280         ot->exec= select_similar_exec;
1281         ot->poll= ED_operator_editmesh;
1282         
1283         /* flags */
1284         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1285         
1286         /* properties */
1287         prop= RNA_def_enum(ot->srna, "type", prop_simvertex_types, 0, "Type", "");
1288         RNA_def_enum_funcs(prop, select_similar_type_itemf);
1289 }
1290
1291 /* ******************************************* */
1292
1293
1294 int mesh_layers_menu_charlen(CustomData *data, int type)
1295 {
1296         int i, len = 0;
1297         /* see if there is a duplicate */
1298         for(i=0; i<data->totlayer; i++) {
1299                 if((&data->layers[i])->type == type) {
1300                         /* we could count the chars here but we'll just assumeme each
1301                          * is 32 chars with some room for the menu text - 40 should be fine */
1302                         len+=40; 
1303                 }
1304         }
1305         return len;
1306 }
1307
1308 /* this function adds menu text into an existing string.
1309  * this string's size should be allocated with mesh_layers_menu_charlen */
1310 void mesh_layers_menu_concat(CustomData *data, int type, char *str) 
1311 {
1312         int i, count = 0;
1313         char *str_pt = str;
1314         CustomDataLayer *layer;
1315         
1316         /* see if there is a duplicate */
1317         for(i=0; i<data->totlayer; i++) {
1318                 layer = &data->layers[i];
1319                 if(layer->type == type) {
1320                         str_pt += sprintf(str_pt, "%s%%x%d|", layer->name, count);
1321                         count++;
1322                 }
1323         }
1324 }
1325
1326 int mesh_layers_menu(CustomData *data, int type) {
1327         int ret;
1328         char *str_pt, *str;
1329         
1330         str_pt = str = MEM_mallocN(mesh_layers_menu_charlen(data, type) + 18, "layer menu");
1331         str[0] = '\0';
1332         
1333         str_pt += sprintf(str_pt, "Layers%%t|");
1334         
1335         mesh_layers_menu_concat(data, type, str_pt);
1336         
1337         ret = pupmenu(str);
1338         MEM_freeN(str);
1339         return ret;
1340 }
1341
1342 void EM_mesh_copy_edge(EditMesh *em, short type) 
1343 {
1344         EditSelection *ese;
1345         short change=0;
1346         
1347         EditEdge *eed, *eed_act;
1348         float vec[3], vec_mid[3], eed_len, eed_len_act;
1349         
1350         if (!em) return;
1351         
1352         ese = em->selected.last;
1353         if (!ese) return;
1354         
1355         eed_act = (EditEdge*)ese->data;
1356         
1357         switch (type) {
1358         case 1: /* copy crease */
1359                 for(eed=em->edges.first; eed; eed=eed->next) {
1360                         if (eed->f & SELECT && eed != eed_act && eed->crease != eed_act->crease) {
1361                                 eed->crease = eed_act->crease;
1362                                 change = 1;
1363                         }
1364                 }
1365                 break;
1366         case 2: /* copy bevel weight */
1367                 for(eed=em->edges.first; eed; eed=eed->next) {
1368                         if (eed->f & SELECT && eed != eed_act && eed->bweight != eed_act->bweight) {
1369                                 eed->bweight = eed_act->bweight;
1370                                 change = 1;
1371                         }
1372                 }
1373                 break;
1374
1375         case 3: /* copy length */
1376                 eed_len_act = VecLenf(eed_act->v1->co, eed_act->v2->co);
1377                 for(eed=em->edges.first; eed; eed=eed->next) {
1378                         if (eed->f & SELECT && eed != eed_act) {
1379
1380                                 eed_len = VecLenf(eed->v1->co, eed->v2->co);
1381
1382                                 if (eed_len == eed_len_act) continue;
1383                                 /* if this edge is zero length we cont do anything with it*/
1384                                 if (eed_len == 0.0f) continue;
1385                                 if (eed_len_act == 0.0f) {
1386                                         VecAddf(vec_mid, eed->v1->co, eed->v2->co);
1387                                         VecMulf(vec_mid, 0.5);
1388                                         VECCOPY(eed->v1->co, vec_mid);
1389                                         VECCOPY(eed->v2->co, vec_mid);
1390                                 } else {
1391                                         /* copy the edge length */
1392                                         VecAddf(vec_mid, eed->v1->co, eed->v2->co);
1393                                         VecMulf(vec_mid, 0.5);
1394
1395                                         /* SCALE 1 */
1396                                         VecSubf(vec, eed->v1->co, vec_mid);
1397                                         VecMulf(vec, eed_len_act/eed_len);
1398                                         VecAddf(eed->v1->co, vec, vec_mid);
1399
1400                                         /* SCALE 2 */
1401                                         VecSubf(vec, eed->v2->co, vec_mid);
1402                                         VecMulf(vec, eed_len_act/eed_len);
1403                                         VecAddf(eed->v2->co, vec, vec_mid);
1404                                 }
1405                                 change = 1;
1406                         }
1407                 }
1408
1409                 if (change)
1410                         recalc_editnormals(em);
1411
1412                 break;
1413         }
1414         
1415         if (change) {
1416 //              DAG_object_flush_update(scene, obedit, OB_RECALC_DATA);
1417                 
1418         }
1419 }
1420
1421 void EM_mesh_copy_face(EditMesh *em, wmOperator *op, short type)
1422 {
1423         short change=0;
1424         
1425         EditFace *efa, *efa_act;
1426         MTFace *tf, *tf_act = NULL;
1427         MCol *mcol, *mcol_act = NULL;
1428         if (!em) return;
1429         efa_act = EM_get_actFace(em, 0);
1430         
1431         if (!efa_act) return;
1432         
1433         tf_act =        CustomData_em_get(&em->fdata, efa_act->data, CD_MTFACE);
1434         mcol_act =      CustomData_em_get(&em->fdata, efa_act->data, CD_MCOL);
1435         
1436         switch (type) {
1437         case 1: /* copy material */
1438                 for(efa=em->faces.first; efa; efa=efa->next) {
1439                         if (efa->f & SELECT && efa->mat_nr != efa_act->mat_nr) {
1440                                 efa->mat_nr = efa_act->mat_nr;
1441                                 change = 1;
1442                         }
1443                 }
1444                 break;
1445         case 2: /* copy image */
1446                 if (!tf_act) {
1447                         BKE_report(op->reports, RPT_ERROR, "Mesh has no uv/image layers.");
1448                         return;
1449                 }
1450                 for(efa=em->faces.first; efa; efa=efa->next) {
1451                         if (efa->f & SELECT && efa != efa_act) {
1452                                 tf = CustomData_em_get(&em->fdata, efa->data, CD_MTFACE);
1453                                 if (tf_act->tpage) {
1454                                         tf->tpage = tf_act->tpage;
1455                                         tf->mode |= TF_TEX;
1456                                 } else {
1457                                         tf->tpage = NULL;
1458                                         tf->mode &= ~TF_TEX;
1459                                 }
1460                                 tf->tile= tf_act->tile;
1461                                 change = 1;
1462                         }
1463                 }
1464                 break;
1465
1466         case 3: /* copy UV's */
1467                 if (!tf_act) {
1468                         BKE_report(op->reports, RPT_ERROR, "Mesh has no uv/image layers.");
1469                         return;
1470                 }
1471                 for(efa=em->faces.first; efa; efa=efa->next) {
1472                         if (efa->f & SELECT && efa != efa_act) {
1473                                 tf = CustomData_em_get(&em->fdata, efa->data, CD_MTFACE);
1474                                 memcpy(tf->uv, tf_act->uv, sizeof(tf->uv));
1475                                 change = 1;
1476                         }
1477                 }
1478                 break;
1479         case 4: /* mode's */
1480                 if (!tf_act) {
1481                         BKE_report(op->reports, RPT_ERROR, "Mesh has no uv/image layers.");
1482                         return;
1483                 }
1484                 for(efa=em->faces.first; efa; efa=efa->next) {
1485                         if (efa->f & SELECT && efa != efa_act) {
1486                                 tf = CustomData_em_get(&em->fdata, efa->data, CD_MTFACE);
1487                                 tf->mode= tf_act->mode;
1488                                 change = 1;
1489                         }
1490                 }
1491                 break;
1492         case 5: /* copy transp's */
1493                 if (!tf_act) {
1494                         BKE_report(op->reports, RPT_ERROR, "Mesh has no uv/image layers.");
1495                         return;
1496                 }
1497                 for(efa=em->faces.first; efa; efa=efa->next) {
1498                         if (efa->f & SELECT && efa != efa_act) {
1499                                 tf = CustomData_em_get(&em->fdata, efa->data, CD_MTFACE);
1500                                 tf->transp= tf_act->transp;
1501                                 change = 1;
1502                         }
1503                 }
1504                 break;
1505
1506         case 6: /* copy vcols's */
1507                 if (!mcol_act) {
1508                         BKE_report(op->reports, RPT_ERROR, "Mesh has no color layers.");
1509                         return;
1510                 } else {
1511                         /* guess the 4th color if needs be */
1512                         float val =- 1;
1513
1514                         if (!efa_act->v4) {
1515                                 /* guess the othe vale, we may need to use it
1516                                  * 
1517                                  * Modifying the 4th value of the mcol is ok here since its not seen
1518                                  * on a triangle
1519                                  * */
1520                                 val = ((float)(mcol_act->r +  (mcol_act+1)->r + (mcol_act+2)->r)) / 3; CLAMP(val, 0, 255);
1521                                 (mcol_act+3)->r = (char)val;
1522
1523                                 val = ((float)(mcol_act->g +  (mcol_act+1)->g + (mcol_act+2)->g)) / 3; CLAMP(val, 0, 255);
1524                                 (mcol_act+3)->g = (char)val;
1525
1526                                 val = ((float)(mcol_act->b +  (mcol_act+1)->b + (mcol_act+2)->b)) / 3; CLAMP(val, 0, 255);
1527                                 (mcol_act+3)->b = (char)val;
1528                         } 
1529
1530
1531                         for(efa=em->faces.first; efa; efa=efa->next) {
1532                                 if (efa->f & SELECT && efa != efa_act) {
1533                                         /* TODO - make copy from tri to quad guess the 4th vert */
1534                                         mcol = CustomData_em_get(&em->fdata, efa->data, CD_MCOL);
1535                                         memcpy(mcol, mcol_act, sizeof(MCol)*4); 
1536                                         change = 1;
1537                                 }
1538                         }
1539                 }
1540                 break;
1541         }
1542         
1543         if (change) {
1544 //              DAG_object_flush_update(scene, obedit, OB_RECALC_DATA);
1545                 
1546         }
1547 }
1548
1549
1550 void EM_mesh_copy_face_layer(EditMesh *em, wmOperator *op, short type) 
1551 {
1552         short change=0;
1553         
1554         EditFace *efa;
1555         MTFace *tf, *tf_from;
1556         MCol *mcol, *mcol_from;
1557         
1558         if (!em) return;
1559         
1560         switch(type) {
1561         case 7:
1562         case 8:
1563         case 9:
1564                 if (CustomData_number_of_layers(&em->fdata, CD_MTFACE)<2) {
1565                         BKE_report(op->reports, RPT_ERROR, "mesh does not have multiple uv/image layers");
1566                         return;
1567                 } else {
1568                         int layer_orig_idx, layer_idx;
1569
1570                         layer_idx = mesh_layers_menu(&em->fdata, CD_MTFACE);
1571                         if (layer_idx<0) return;
1572
1573                         /* warning, have not updated mesh pointers however this is not needed since we swicth back */
1574                         layer_orig_idx = CustomData_get_active_layer(&em->fdata, CD_MTFACE);
1575                         if (layer_idx==layer_orig_idx)
1576                                 return;
1577
1578                         /* get the tfaces */
1579                         CustomData_set_layer_active(&em->fdata, CD_MTFACE, (int)layer_idx);
1580                         /* store the tfaces in our temp */
1581                         for(efa=em->faces.first; efa; efa=efa->next) {
1582                                 if (efa->f & SELECT) {
1583                                         efa->tmp.p = CustomData_em_get(&em->fdata, efa->data, CD_MTFACE);
1584                                 }       
1585                         }
1586                         CustomData_set_layer_active(&em->fdata, CD_MTFACE, layer_orig_idx);
1587                 }
1588                 break;
1589
1590         case 10: /* select vcol layers - make sure this stays in sync with above code */
1591                 if (CustomData_number_of_layers(&em->fdata, CD_MCOL)<2) {
1592                         BKE_report(op->reports, RPT_ERROR, "mesh does not have multiple color layers");
1593                         return;
1594                 } else {
1595                         int layer_orig_idx, layer_idx;
1596
1597                         layer_idx = mesh_layers_menu(&em->fdata, CD_MCOL);
1598                         if (layer_idx<0) return;
1599
1600                         /* warning, have not updated mesh pointers however this is not needed since we swicth back */
1601                         layer_orig_idx = CustomData_get_active_layer(&em->fdata, CD_MCOL);
1602                         if (layer_idx==layer_orig_idx)
1603                                 return;
1604
1605                         /* get the tfaces */
1606                         CustomData_set_layer_active(&em->fdata, CD_MCOL, (int)layer_idx);
1607                         /* store the tfaces in our temp */
1608                         for(efa=em->faces.first; efa; efa=efa->next) {
1609                                 if (efa->f & SELECT) {
1610                                         efa->tmp.p = CustomData_em_get(&em->fdata, efa->data, CD_MCOL);
1611                                 }       
1612                         }
1613                         CustomData_set_layer_active(&em->fdata, CD_MCOL, layer_orig_idx);
1614
1615                 }
1616                 break;
1617         }
1618
1619         /* layer copy only - sanity checks done above */
1620         switch (type) {
1621         case 7: /* copy UV's only */
1622                 for(efa=em->faces.first; efa; efa=efa->next) {
1623                         if (efa->f & SELECT) {
1624                                 tf_from = (MTFace *)efa->tmp.p; /* not active but easier to use this way */
1625                                 tf = CustomData_em_get(&em->fdata, efa->data, CD_MTFACE);
1626                                 memcpy(tf->uv, tf_from->uv, sizeof(tf->uv));
1627                                 change = 1;
1628                         }
1629                 }
1630                 break;
1631         case 8: /* copy image settings only */
1632                 for(efa=em->faces.first; efa; efa=efa->next) {
1633                         if (efa->f & SELECT) {
1634                                 tf_from = (MTFace *)efa->tmp.p; /* not active but easier to use this way */
1635                                 tf = CustomData_em_get(&em->fdata, efa->data, CD_MTFACE);
1636                                 if (tf_from->tpage) {
1637                                         tf->tpage = tf_from->tpage;
1638                                         tf->mode |= TF_TEX;
1639                                 } else {
1640                                         tf->tpage = NULL;
1641                                         tf->mode &= ~TF_TEX;
1642                                 }
1643                                 tf->tile= tf_from->tile;
1644                                 change = 1;
1645                         }
1646                 }
1647                 break;
1648         case 9: /* copy all tface info */
1649                 for(efa=em->faces.first; efa; efa=efa->next) {
1650                         if (efa->f & SELECT) {
1651                                 tf_from = (MTFace *)efa->tmp.p; /* not active but easier to use this way */
1652                                 tf = CustomData_em_get(&em->fdata, efa->data, CD_MTFACE);
1653                                 memcpy(tf->uv, ((MTFace *)efa->tmp.p)->uv, sizeof(tf->uv));
1654                                 tf->tpage = tf_from->tpage;
1655                                 tf->mode = tf_from->mode;
1656                                 tf->transp = tf_from->transp;
1657                                 change = 1;
1658                         }
1659                 }
1660                 break;
1661         case 10:
1662                 for(efa=em->faces.first; efa; efa=efa->next) {
1663                         if (efa->f & SELECT) {
1664                                 mcol_from = (MCol *)efa->tmp.p; 
1665                                 mcol = CustomData_em_get(&em->fdata, efa->data, CD_MCOL);
1666                                 memcpy(mcol, mcol_from, sizeof(MCol)*4);        
1667                                 change = 1;
1668                         }
1669                 }
1670                 break;
1671         }
1672
1673         if (change) {
1674 //              DAG_object_flush_update(scene, obedit, OB_RECALC_DATA);
1675                 
1676         }
1677 }
1678
1679
1680 /* ctrl+c in mesh editmode */
1681 void mesh_copy_menu(EditMesh *em, wmOperator *op)
1682 {
1683         EditSelection *ese;
1684         int ret;
1685         if (!em) return;
1686         
1687         ese = em->selected.last;
1688         
1689         /* Faces can have a NULL ese, so dont return on a NULL ese here */
1690         
1691         if(ese && ese->type == EDITVERT) {
1692                 /* EditVert *ev, *ev_act = (EditVert*)ese->data;
1693                 ret= pupmenu(""); */
1694         } else if(ese && ese->type == EDITEDGE) {
1695                 ret= pupmenu("Copy Active Edge to Selected%t|Crease%x1|Bevel Weight%x2|Length%x3");
1696                 if (ret<1) return;
1697                 
1698                 EM_mesh_copy_edge(em, ret);
1699                 
1700         } else if(ese==NULL || ese->type == EDITFACE) {
1701                 ret= pupmenu(
1702                         "Copy Face Selected%t|"
1703                         "Active Material%x1|Active Image%x2|Active UV Coords%x3|"
1704                         "Active Mode%x4|Active Transp%x5|Active Vertex Colors%x6|%l|"
1705
1706                         "TexFace UVs from layer%x7|"
1707                         "TexFace Images from layer%x8|"
1708                         "TexFace All from layer%x9|"
1709                         "Vertex Colors from layer%x10");
1710                 if (ret<1) return;
1711                 
1712                 if (ret<=6) {
1713                         EM_mesh_copy_face(em, op, ret);
1714                 } else {
1715                         EM_mesh_copy_face_layer(em, op, ret);
1716                 }
1717         }
1718 }
1719
1720
1721 /* ****************  LOOP SELECTS *************** */
1722
1723 /* selects quads in loop direction of indicated edge */
1724 /* only flush over edges with valence <= 2 */
1725 void faceloop_select(EditMesh *em, EditEdge *startedge, int select)
1726 {
1727         EditEdge *eed;
1728         EditFace *efa;
1729         int looking= 1;
1730         
1731         /* in eed->f1 we put the valence (amount of faces in edge) */
1732         /* in eed->f2 we put tagged flag as correct loop */
1733         /* in efa->f1 we put tagged flag as correct to select */
1734
1735         for(eed= em->edges.first; eed; eed= eed->next) {
1736                 eed->f1= 0;
1737                 eed->f2= 0;
1738         }
1739         for(efa= em->faces.first; efa; efa= efa->next) {
1740                 efa->f1= 0;
1741                 if(efa->h==0) {
1742                         efa->e1->f1++;
1743                         efa->e2->f1++;
1744                         efa->e3->f1++;
1745                         if(efa->e4) efa->e4->f1++;
1746                 }
1747         }
1748         
1749         /* tag startedge OK*/
1750         startedge->f2= 1;
1751         
1752         while(looking) {
1753                 looking= 0;
1754                 
1755                 for(efa= em->faces.first; efa; efa= efa->next) {
1756                         if(efa->h==0 && efa->e4 && efa->f1==0) {        /* not done quad */
1757                                 if(efa->e1->f1<=2 && efa->e2->f1<=2 && efa->e3->f1<=2 && efa->e4->f1<=2) { /* valence ok */
1758
1759                                         /* if edge tagged, select opposing edge and mark face ok */
1760                                         if(efa->e1->f2) {
1761                                                 efa->e3->f2= 1;
1762                                                 efa->f1= 1;
1763                                                 looking= 1;
1764                                         }
1765                                         else if(efa->e2->f2) {
1766                                                 efa->e4->f2= 1;
1767                                                 efa->f1= 1;
1768                                                 looking= 1;
1769                                         }
1770                                         if(efa->e3->f2) {
1771                                                 efa->e1->f2= 1;
1772                                                 efa->f1= 1;
1773                                                 looking= 1;
1774                                         }
1775                                         if(efa->e4->f2) {
1776                                                 efa->e2->f2= 1;
1777                                                 efa->f1= 1;
1778                                                 looking= 1;
1779                                         }
1780                                 }
1781                         }
1782                 }
1783         }
1784         
1785         /* (de)select the faces */
1786         if(select!=2) {
1787                 for(efa= em->faces.first; efa; efa= efa->next) {
1788                         if(efa->f1) EM_select_face(efa, select);
1789                 }
1790         }
1791 }
1792
1793
1794 /* helper for edgeloop_select, checks for eed->f2 tag in faces */
1795 static int edge_not_in_tagged_face(EditMesh *em, EditEdge *eed)
1796 {
1797         EditFace *efa;
1798         
1799         for(efa= em->faces.first; efa; efa= efa->next) {
1800                 if(efa->h==0) {
1801                         if(efa->e1==eed || efa->e2==eed || efa->e3==eed || efa->e4==eed) {      /* edge is in face */
1802                                 if(efa->e1->f2 || efa->e2->f2 || efa->e3->f2 || (efa->e4 && efa->e4->f2)) {     /* face is tagged */
1803                                         return 0;
1804                                 }
1805                         }
1806                 }
1807         }
1808         return 1;
1809 }
1810
1811 /* selects or deselects edges that:
1812 - if edges has 2 faces:
1813         - has vertices with valence of 4
1814         - not shares face with previous edge
1815 - if edge has 1 face:
1816         - has vertices with valence 4
1817         - not shares face with previous edge
1818         - but also only 1 face
1819 - if edge no face:
1820         - has vertices with valence 2
1821 */
1822 static void edgeloop_select(EditMesh *em, EditEdge *starteed, int select)
1823 {
1824         EditVert *eve;
1825         EditEdge *eed;
1826         EditFace *efa;
1827         int looking= 1;
1828         
1829         /* in f1 we put the valence (amount of edges in a vertex, or faces in edge) */
1830         /* in eed->f2 and efa->f1 we put tagged flag as correct loop */
1831         for(eve= em->verts.first; eve; eve= eve->next) {
1832                 eve->f1= 0;
1833                 eve->f2= 0;
1834         }
1835         for(eed= em->edges.first; eed; eed= eed->next) {
1836                 eed->f1= 0;
1837                 eed->f2= 0;
1838                 if((eed->h & 1)==0) {   /* fgon edges add to valence too */
1839                         eed->v1->f1++; eed->v2->f1++;
1840                 }
1841         }
1842         for(efa= em->faces.first; efa; efa= efa->next) {
1843                 efa->f1= 0;
1844                 if(efa->h==0) {
1845                         efa->e1->f1++;
1846                         efa->e2->f1++;
1847                         efa->e3->f1++;
1848                         if(efa->e4) efa->e4->f1++;
1849                 }
1850         }
1851         
1852         /* looped edges & vertices get tagged f2 */
1853         starteed->f2= 1;
1854         if(starteed->v1->f1<5) starteed->v1->f2= 1;
1855         if(starteed->v2->f1<5) starteed->v2->f2= 1;
1856         /* sorry, first edge isnt even ok */
1857         if(starteed->v1->f2==0 && starteed->v2->f2==0) looking= 0;
1858         
1859         while(looking) {
1860                 looking= 0;
1861                 
1862                 /* find correct valence edges which are not tagged yet, but connect to tagged one */
1863                 for(eed= em->edges.first; eed; eed= eed->next) {
1864                         if(eed->h==0 && eed->f2==0) { /* edge not hidden, not tagged */
1865                                 if( (eed->v1->f1<5 && eed->v1->f2) || (eed->v2->f1<5 && eed->v2->f2)) { /* valence of vertex OK, and is tagged */
1866                                         /* new edge is not allowed to be in face with tagged edge */
1867                                         if(edge_not_in_tagged_face(em, eed)) {
1868                                                 if(eed->f1==starteed->f1) {     /* same amount of faces */
1869                                                         looking= 1;
1870                                                         eed->f2= 1;
1871                                                         if(eed->v2->f1<5) eed->v2->f2= 1;
1872                                                         if(eed->v1->f1<5) eed->v1->f2= 1;
1873                                                 }
1874                                         }
1875                                 }
1876                         }
1877                 }
1878         }
1879         /* and we do the select */
1880         for(eed= em->edges.first; eed; eed= eed->next) {
1881                 if(eed->f2) EM_select_edge(eed, select);
1882         }
1883 }
1884
1885 /* 
1886    Almostly exactly the same code as faceloop select
1887 */
1888 static void edgering_select(EditMesh *em, EditEdge *startedge, int select)
1889 {
1890         EditEdge *eed;
1891         EditFace *efa;
1892         int looking= 1;
1893         
1894         /* in eed->f1 we put the valence (amount of faces in edge) */
1895         /* in eed->f2 we put tagged flag as correct loop */
1896         /* in efa->f1 we put tagged flag as correct to select */
1897
1898         for(eed= em->edges.first; eed; eed= eed->next) {
1899                 eed->f1= 0;
1900                 eed->f2= 0;
1901         }
1902         for(efa= em->faces.first; efa; efa= efa->next) {
1903                 efa->f1= 0;
1904                 if(efa->h==0) {
1905                         efa->e1->f1++;
1906                         efa->e2->f1++;
1907                         efa->e3->f1++;
1908                         if(efa->e4) efa->e4->f1++;
1909                 }
1910         }
1911         
1912         /* tag startedge OK */
1913         startedge->f2= 1;
1914         
1915         while(looking) {
1916                 looking= 0;
1917                 
1918                 for(efa= em->faces.first; efa; efa= efa->next) {
1919                         if(efa->e4 && efa->f1==0 && !efa->h) {  /* not done quad */
1920                                 if(efa->e1->f1<=2 && efa->e2->f1<=2 && efa->e3->f1<=2 && efa->e4->f1<=2) { /* valence ok */
1921
1922                                         /* if edge tagged, select opposing edge and mark face ok */
1923                                         if(efa->e1->f2) {
1924                                                 efa->e3->f2= 1;
1925                                                 efa->f1= 1;
1926                                                 looking= 1;
1927                                         }
1928                                         else if(efa->e2->f2) {
1929                                                 efa->e4->f2= 1;
1930                                                 efa->f1= 1;
1931                                                 looking= 1;
1932                                         }
1933                                         if(efa->e3->f2) {
1934                                                 efa->e1->f2= 1;
1935                                                 efa->f1= 1;
1936                                                 looking= 1;
1937                                         }
1938                                         if(efa->e4->f2) {
1939                                                 efa->e2->f2= 1;
1940                                                 efa->f1= 1;
1941                                                 looking= 1;
1942                                         }
1943                                 }
1944                         }
1945                 }
1946         }
1947         
1948         /* (de)select the edges */
1949         for(eed= em->edges.first; eed; eed= eed->next) {
1950                 if(eed->f2) EM_select_edge(eed, select);
1951         }
1952 }
1953
1954 static int loop_multiselect(bContext *C, wmOperator *op)
1955 {
1956         Object *obedit= CTX_data_edit_object(C);
1957         EditMesh *em= BKE_mesh_get_editmesh(((Mesh *)obedit->data));
1958         EditEdge *eed;
1959         EditEdge **edarray;
1960         int edindex, edfirstcount;
1961         int looptype= RNA_boolean_get(op->ptr, "ring");
1962         
1963         /* sets em->totedgesel */
1964         EM_nedges_selected(em);
1965         
1966         edarray = MEM_mallocN(sizeof(EditEdge*)*em->totedgesel,"edge array");
1967         edindex = 0;
1968         edfirstcount = em->totedgesel;
1969         
1970         for(eed=em->edges.first; eed; eed=eed->next){
1971                 if(eed->f&SELECT){
1972                         edarray[edindex] = eed;
1973                         edindex += 1;
1974                 }
1975         }
1976         
1977         if(looptype){
1978                 for(edindex = 0; edindex < edfirstcount; edindex +=1){
1979                         eed = edarray[edindex];
1980                         edgering_select(em, eed,SELECT);
1981                 }
1982                 EM_selectmode_flush(em);
1983         }
1984         else{
1985                 for(edindex = 0; edindex < edfirstcount; edindex +=1){
1986                         eed = edarray[edindex];
1987                         edgeloop_select(em, eed,SELECT);
1988                 }
1989                 EM_selectmode_flush(em);
1990         }
1991         MEM_freeN(edarray);
1992 //      if (EM_texFaceCheck())
1993         
1994         WM_event_add_notifier(C, NC_OBJECT|ND_GEOM_SELECT, obedit);
1995
1996         BKE_mesh_end_editmesh(obedit->data, em);
1997         return OPERATOR_FINISHED;       
1998 }
1999
2000 void MESH_OT_loop_multi_select(wmOperatorType *ot)
2001 {
2002         /* identifiers */
2003         ot->name= "Multi Select Loops";
2004         ot->description= "Select a loop of connected edges by connection type.";
2005         ot->idname= "MESH_OT_loop_multi_select";
2006         
2007         /* api callbacks */
2008         ot->exec= loop_multiselect;
2009         ot->poll= ED_operator_editmesh;
2010         
2011         /* flags */
2012         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
2013         
2014         /* properties */
2015         RNA_def_boolean(ot->srna, "ring", 0, "Ring", "");
2016 }
2017
2018                 
2019 /* ***************** MAIN MOUSE SELECTION ************** */
2020
2021
2022 /* ***************** loop select (non modal) ************** */
2023
2024 static void mouse_mesh_loop(bContext *C, short mval[2], short extend, short ring)
2025 {
2026         ViewContext vc;
2027         EditMesh *em;
2028         EditEdge *eed;
2029         int select= 1;
2030         int dist= 50;
2031         
2032         em_setup_viewcontext(C, &vc);
2033         vc.mval[0]= mval[0];
2034         vc.mval[1]= mval[1];
2035         em= vc.em;
2036         
2037         eed= findnearestedge(&vc, &dist);
2038         if(eed) {
2039                 if(extend==0) EM_clear_flag_all(em, SELECT);
2040         
2041                 if((eed->f & SELECT)==0) select=1;
2042                 else if(extend) select=0;
2043
2044                 if(em->selectmode & SCE_SELECT_FACE) {
2045                         faceloop_select(em, eed, select);
2046                 }
2047                 else if(em->selectmode & SCE_SELECT_EDGE) {
2048                         if(ring)
2049                                 edgering_select(em, eed, select);
2050                         else
2051                                 edgeloop_select(em, eed, select);
2052                 }
2053                 else if(em->selectmode & SCE_SELECT_VERTEX) {
2054                         if(ring)
2055                                 edgering_select(em, eed, select);
2056                         else 
2057                                 edgeloop_select(em, eed, select);
2058                 }
2059
2060                 EM_selectmode_flush(em);
2061 //                      if (EM_texFaceCheck())
2062                 
2063                 WM_event_add_notifier(C, NC_OBJECT|ND_GEOM_SELECT, vc.obedit);
2064         }
2065 }
2066
2067 static int mesh_select_loop_invoke(bContext *C, wmOperator *op, wmEvent *event)
2068 {
2069         
2070         view3d_operator_needs_opengl(C);
2071         
2072         mouse_mesh_loop(C, event->mval, RNA_boolean_get(op->ptr, "extend"),
2073                                         RNA_boolean_get(op->ptr, "ring"));
2074         
2075         /* cannot do tweaks for as long this keymap is after transform map */
2076         return OPERATOR_FINISHED;
2077 }
2078
2079 void MESH_OT_loop_select(wmOperatorType *ot)
2080 {
2081         /* identifiers */
2082         ot->name= "Loop Select";
2083         ot->description= "Select a loop of connected edges.";
2084         ot->idname= "MESH_OT_loop_select";
2085         
2086         /* api callbacks */
2087         ot->invoke= mesh_select_loop_invoke;
2088         ot->poll= ED_operator_editmesh;
2089         
2090         /* flags */
2091         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
2092         
2093         /* properties */
2094         RNA_def_boolean(ot->srna, "extend", 0, "Extend Select", "");
2095         RNA_def_boolean(ot->srna, "ring", 0, "Select Ring", "");
2096 }
2097
2098 /* ******************* mesh shortest path select, uses prev-selected edge ****************** */
2099
2100 /* since you want to create paths with multiple selects, it doesn't have extend option */
2101 static void mouse_mesh_shortest_path(bContext *C, short mval[2])
2102 {
2103         ViewContext vc;
2104         EditMesh *em;
2105         EditEdge *eed;
2106         int dist= 50;
2107         
2108         em_setup_viewcontext(C, &vc);
2109         vc.mval[0]= mval[0];
2110         vc.mval[1]= mval[1];
2111         em= vc.em;
2112         
2113         eed= findnearestedge(&vc, &dist);
2114         if(eed) {
2115                 Mesh *me= vc.obedit->data;
2116                 int path = 0;
2117                 
2118                 if (em->selected.last) {
2119                         EditSelection *ese = em->selected.last;
2120                         
2121                         if(ese && ese->type == EDITEDGE) {
2122                                 EditEdge *eed_act;
2123                                 eed_act = (EditEdge*)ese->data;
2124                                 if (eed_act != eed) {
2125                                         if (edgetag_shortest_path(vc.scene, em, eed_act, eed)) {
2126                                                 EM_remove_selection(em, eed_act, EDITEDGE);
2127                                                 path = 1;
2128                                         }
2129                                 }
2130                         }
2131                 }
2132                 if (path==0) {
2133                         int act = (edgetag_context_check(vc.scene, eed)==0);
2134                         edgetag_context_set(vc.scene, eed, act); /* switch the edge option */
2135                 }
2136                 
2137                 EM_selectmode_flush(em);
2138
2139                 /* even if this is selected it may not be in the selection list */
2140                 if(edgetag_context_check(vc.scene, eed)==0)
2141                         EM_remove_selection(em, eed, EDITEDGE);
2142                 else
2143                         EM_store_selection(em, eed, EDITEDGE);
2144         
2145                 /* force drawmode for mesh */
2146                 switch (vc.scene->toolsettings->edge_mode) {
2147                         
2148                         case EDGE_MODE_TAG_SEAM:
2149                                 me->drawflag |= ME_DRAWSEAMS;
2150                                 break;
2151                         case EDGE_MODE_TAG_SHARP:
2152                                 me->drawflag |= ME_DRAWSHARP;
2153                                 break;
2154                         case EDGE_MODE_TAG_CREASE:      
2155                                 me->drawflag |= ME_DRAWCREASES;
2156                                 break;
2157                         case EDGE_MODE_TAG_BEVEL:
2158                                 me->drawflag |= ME_DRAWBWEIGHTS;
2159                                 break;
2160                 }
2161                 
2162                 DAG_object_flush_update(vc.scene, vc.obedit, OB_RECALC_DATA);
2163         
2164                 WM_event_add_notifier(C, NC_OBJECT|ND_GEOM_SELECT, vc.obedit);
2165         }
2166 }
2167
2168
2169 static int mesh_shortest_path_select_invoke(bContext *C, wmOperator *op, wmEvent *event)
2170 {
2171         
2172         view3d_operator_needs_opengl(C);
2173
2174         mouse_mesh_shortest_path(C, event->mval);
2175         
2176         return OPERATOR_FINISHED;
2177 }
2178         
2179 void MESH_OT_select_shortest_path(wmOperatorType *ot)
2180 {
2181         /* identifiers */
2182         ot->name= "Shortest Path Select";
2183         ot->description= "Select shortest path between two selections.";
2184         ot->idname= "MESH_OT_select_shortest_path";
2185         
2186         /* api callbacks */
2187         ot->invoke= mesh_shortest_path_select_invoke;
2188         ot->poll= ED_operator_editmesh;
2189         
2190         /* flags */
2191         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
2192         
2193         /* properties */
2194         RNA_def_boolean(ot->srna, "extend", 0, "Extend Select", "");
2195 }
2196
2197
2198 /* ************************************************** */
2199
2200
2201 /* here actual select happens */
2202 /* gets called via generic mouse select operator */
2203 void mouse_mesh(bContext *C, short mval[2], short extend)
2204 {
2205         ViewContext vc;
2206         EditVert *eve;
2207         EditEdge *eed;
2208         EditFace *efa;
2209         
2210         /* setup view context for argument to callbacks */
2211         em_setup_viewcontext(C, &vc);
2212         vc.mval[0]= mval[0];
2213         vc.mval[1]= mval[1];
2214         
2215         if(unified_findnearest(&vc, &eve, &eed, &efa)) {
2216                 
2217                 if(extend==0) EM_clear_flag_all(vc.em, SELECT);
2218                 
2219                 if(efa) {
2220                         /* set the last selected face */
2221                         EM_set_actFace(vc.em, efa);
2222                         
2223                         if( (efa->f & SELECT)==0 ) {
2224                                 EM_store_selection(vc.em, efa, EDITFACE);
2225                                 EM_select_face_fgon(vc.em, efa, 1);
2226                         }
2227                         else if(extend) {
2228                                 EM_remove_selection(vc.em, efa, EDITFACE);
2229                                 EM_select_face_fgon(vc.em, efa, 0);
2230                         }
2231                 }
2232                 else if(eed) {
2233                         if((eed->f & SELECT)==0) {
2234                                 EM_store_selection(vc.em, eed, EDITEDGE);
2235                                 EM_select_edge(eed, 1);
2236                         }
2237                         else if(extend) {
2238                                 EM_remove_selection(vc.em, eed, EDITEDGE);
2239                                 EM_select_edge(eed, 0);
2240                         }
2241                 }
2242                 else if(eve) {
2243                         if((eve->f & SELECT)==0) {
2244                                 eve->f |= SELECT;
2245                                 EM_store_selection(vc.em, eve, EDITVERT);
2246                         }
2247                         else if(extend){ 
2248                                 EM_remove_selection(vc.em, eve, EDITVERT);
2249                                 eve->f &= ~SELECT;
2250                         }
2251                 }
2252                 
2253                 EM_selectmode_flush(vc.em);
2254                   
2255 //              if (EM_texFaceCheck()) {
2256
2257                 if (efa && efa->mat_nr != vc.obedit->actcol-1) {
2258                         vc.obedit->actcol= efa->mat_nr+1;
2259                         vc.em->mat_nr= efa->mat_nr;
2260 //                      BIF_preview_changed(ID_MA);
2261                 }
2262         }
2263
2264         WM_event_add_notifier(C, NC_OBJECT|ND_GEOM_SELECT, vc.obedit);
2265         
2266 }
2267
2268 /* *********** select linked ************* */
2269
2270 /* for use with selectconnected_delimit_mesh only! */
2271 #define is_edge_delimit_ok(eed) ((eed->tmp.l == 1) && (eed->seam==0))
2272 #define is_face_tag(efa) is_edge_delimit_ok(efa->e1) || is_edge_delimit_ok(efa->e2) || is_edge_delimit_ok(efa->e3) || (efa->v4 && is_edge_delimit_ok(efa->e4))
2273
2274 #define face_tag(efa)\
2275 if(efa->v4)     efa->tmp.l=             efa->e1->tmp.l= efa->e2->tmp.l= efa->e3->tmp.l= efa->e4->tmp.l= 1;\
2276 else            efa->tmp.l=             efa->e1->tmp.l= efa->e2->tmp.l= efa->e3->tmp.l= 1;
2277
2278 /* all - 1) use all faces for extending the selection  2) only use the mouse face
2279 * sel - 1) select  0) deselect 
2280 * */
2281
2282 /* legacy warning, this function combines too much :) */
2283 static int select_linked_limited_invoke(ViewContext *vc, short all, short sel)
2284 {
2285         EditMesh *em= vc->em;
2286         EditFace *efa;
2287         EditEdge *eed;
2288         EditVert *eve;
2289         short done=1, change=0;
2290         
2291         if(em->faces.first==0) return OPERATOR_CANCELLED;
2292         
2293         /* flag all edges+faces as off*/
2294         for(eed= em->edges.first; eed; eed= eed->next)
2295                 eed->tmp.l=0;
2296         
2297         for(efa= em->faces.first; efa; efa= efa->next) {
2298                 efa->tmp.l = 0;
2299         }
2300         
2301         if (all) {
2302                 // XXX verts?
2303                 for(eed= em->edges.first; eed; eed= eed->next) {
2304                         if(eed->f & SELECT)
2305                                 eed->tmp.l= 1;
2306                 }
2307                 for(efa= em->faces.first; efa; efa= efa->next) {
2308                         
2309                         if (efa->f & SELECT) {
2310                                 face_tag(efa);
2311                         } else {
2312                                 efa->tmp.l = 0;
2313                         }
2314                 }
2315         } 
2316         else {
2317                 if( unified_findnearest(vc, &eve, &eed, &efa) ) {
2318                         
2319                         if(efa) {
2320                                 efa->tmp.l = 1;
2321                                 face_tag(efa);
2322                         }
2323                         else if(eed)
2324                                 eed->tmp.l= 1;
2325                         else {
2326                                 for(eed= em->edges.first; eed; eed= eed->next)
2327                                         if(eed->v1==eve || eed->v2==eve)
2328                                                 break;
2329                                 eed->tmp.l= 1;
2330                         }
2331                 }
2332                 else
2333                         return OPERATOR_FINISHED;
2334         }
2335         
2336         while(done==1) {
2337                 done= 0;
2338                 /* simple algo - select all faces that have a selected edge
2339                 * this intern selects the edge, repeat until nothing is left to do */
2340                 for(efa= em->faces.first; efa; efa= efa->next) {
2341                         if ((efa->tmp.l == 0) && (!efa->h)) {
2342                                 if (is_face_tag(efa)) {
2343                                         face_tag(efa);
2344                                         done= 1;
2345                                 }
2346                         }
2347                 }
2348         }
2349         
2350         for(efa= em->faces.first; efa; efa= efa->next) {
2351                 if (efa->tmp.l) {
2352                         if (sel) {
2353                                 if (!(efa->f & SELECT)) {
2354                                         EM_select_face(efa, 1);
2355                                         change = 1;
2356                                 }
2357                         } else {
2358                                 if (efa->f & SELECT) {
2359                                         EM_select_face(efa, 0);
2360                                         change = 1;
2361                                 }
2362                         }
2363                 }
2364         }
2365         
2366         if (!change)
2367                 return OPERATOR_CANCELLED;
2368         
2369         if (!sel) /* make sure de-selecting faces didnt de-select the verts/edges connected to selected faces, this is common with boundries */
2370                 for(efa= em->faces.first; efa; efa= efa->next)
2371                         if (efa->f & SELECT)
2372                                 EM_select_face(efa, 1);
2373         
2374         //      if (EM_texFaceCheck())
2375         
2376         return OPERATOR_FINISHED;
2377 }
2378
2379 #undef is_edge_delimit_ok
2380 #undef is_face_tag
2381 #undef face_tag
2382
2383 static int select_linked_pick_invoke(bContext *C, wmOperator *op, wmEvent *event)
2384 {
2385         Object *obedit= CTX_data_edit_object(C);
2386         ViewContext vc;
2387         EditVert *eve, *v1, *v2;
2388         EditEdge *eed;
2389         EditFace *efa;
2390         short done=1, toggle=0;
2391         int sel= !RNA_boolean_get(op->ptr, "deselect");
2392         int limit= RNA_boolean_get(op->ptr, "limit");
2393         
2394         /* unified_finednearest needs ogl */
2395         view3d_operator_needs_opengl(C);
2396         
2397         /* setup view context for argument to callbacks */
2398         em_setup_viewcontext(C, &vc);
2399         
2400         if(vc.em->edges.first==0) return OPERATOR_CANCELLED;
2401         
2402         vc.mval[0]= event->mval[0];
2403         vc.mval[1]= event->mval[1];
2404         
2405         /* return warning! */
2406         if(limit) {
2407                 int retval= select_linked_limited_invoke(&vc, 0, sel);
2408                 WM_event_add_notifier(C, NC_OBJECT|ND_GEOM_SELECT, obedit);
2409                 return retval;
2410         }
2411         
2412         if( unified_findnearest(&vc, &eve, &eed, &efa)==0 ) {
2413                 WM_event_add_notifier(C, NC_OBJECT|ND_GEOM_SELECT, obedit);
2414         
2415                 return OPERATOR_CANCELLED;
2416         }
2417
2418         /* clear test flags */
2419         for(v1= vc.em->verts.first; v1; v1= v1->next) v1->f1= 0;
2420         
2421         /* start vertex/face/edge */
2422         if(eve) eve->f1= 1;
2423         else if(eed) eed->v1->f1= eed->v2->f1= 1;
2424         else efa->v1->f1= efa->v2->f1= efa->v3->f1= 1;
2425         
2426         /* set flag f1 if affected */
2427         while(done==1) {
2428                 done= 0;
2429                 toggle++;
2430                 
2431                 if(toggle & 1) eed= vc.em->edges.first;
2432                 else eed= vc.em->edges.last;
2433                 
2434                 while(eed) {
2435                         v1= eed->v1;
2436                         v2= eed->v2;
2437                         
2438                         if(eed->h==0) {
2439                                 if(v1->f1 && v2->f1==0) {
2440                                         v2->f1= 1;
2441                                         done= 1;
2442                                 }
2443                                 else if(v1->f1==0 && v2->f1) {
2444                                         v1->f1= 1;
2445                                         done= 1;
2446                                 }
2447                         }
2448                         
2449                         if(toggle & 1) eed= eed->next;
2450                         else eed= eed->prev;
2451                 }
2452         }
2453         
2454         /* now use vertex f1 flag to select/deselect */
2455         for(eed= vc.em->edges.first; eed; eed= eed->next) {
2456                 if(eed->v1->f1 && eed->v2->f1) 
2457                         EM_select_edge(eed, sel);
2458         }
2459         for(efa= vc.em->faces.first; efa; efa= efa->next) {
2460                 if(efa->v1->f1 && efa->v2->f1 && efa->v3->f1 && (efa->v4==NULL || efa->v4->f1)) 
2461                         EM_select_face(efa, sel);
2462         }
2463         /* no flush needed, connected geometry is done */
2464         
2465 //      if (EM_texFaceCheck())
2466         
2467         WM_event_add_notifier(C, NC_OBJECT|ND_GEOM_SELECT, obedit);
2468         return OPERATOR_FINISHED;       
2469 }
2470
2471 void MESH_OT_select_linked_pick(wmOperatorType *ot)
2472 {
2473         /* identifiers */
2474         ot->name= "Select Linked";
2475         ot->description= "(un)select all vertices linked to the active mesh.";
2476         ot->idname= "MESH_OT_select_linked_pick";
2477         
2478         /* api callbacks */
2479         ot->invoke= select_linked_pick_invoke;
2480         ot->poll= ED_operator_editmesh;
2481         
2482         /* flags */
2483         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
2484         
2485         RNA_def_boolean(ot->srna, "deselect", 0, "Deselect", "");
2486         RNA_def_boolean(ot->srna, "limit", 0, "Limit by Seams", "");
2487 }
2488
2489
2490 /* ************************* */
2491
2492 void selectconnected_mesh_all(EditMesh *em)
2493 {
2494         EditVert *v1,*v2;
2495         EditEdge *eed;
2496         short done=1, toggle=0;
2497         
2498         if(em->edges.first==0) return;
2499         
2500         while(done==1) {
2501                 done= 0;
2502                 
2503                 toggle++;
2504                 if(toggle & 1) eed= em->edges.first;
2505                 else eed= em->edges.last;
2506                 
2507                 while(eed) {
2508                         v1= eed->v1;
2509                         v2= eed->v2;
2510                         if(eed->h==0) {
2511                                 if(v1->f & SELECT) {
2512                                         if( (v2->f & SELECT)==0 ) {
2513                                                 v2->f |= SELECT;
2514                                                 done= 1;
2515                                         }
2516                                 }
2517                                 else if(v2->f & SELECT) {
2518                                         if( (v1->f & SELECT)==0 ) {
2519                                                 v1->f |= SELECT;
2520                                                 done= 1;
2521                                         }
2522                                 }
2523                         }
2524                         if(toggle & 1) eed= eed->next;
2525                         else eed= eed->prev;
2526                 }
2527         }
2528         
2529         /* now use vertex select flag to select rest */
2530         EM_select_flush(em);
2531         
2532         //      if (EM_texFaceCheck())
2533 }
2534
2535 static int select_linked_exec(bContext *C, wmOperator *op)
2536 {
2537         Object *obedit= CTX_data_edit_object(C);
2538         EditMesh *em= BKE_mesh_get_editmesh(obedit->data);
2539         
2540         if( RNA_boolean_get(op->ptr, "limit") ) {
2541                 ViewContext vc;
2542                 em_setup_viewcontext(C, &vc);
2543                 select_linked_limited_invoke(&vc, 1, 1);
2544         }
2545         else
2546                 selectconnected_mesh_all(em);
2547         
2548         WM_event_add_notifier(C, NC_OBJECT|ND_GEOM_SELECT, obedit);
2549
2550         BKE_mesh_end_editmesh(obedit->data, em);
2551         return OPERATOR_FINISHED;       
2552 }
2553
2554 void MESH_OT_select_linked(wmOperatorType *ot)
2555 {
2556         /* identifiers */
2557         ot->name= "Select Linked All";
2558         ot->description= "Select all vertices linked to the active mesh.";
2559         ot->idname= "MESH_OT_select_linked";
2560         
2561         /* api callbacks */
2562         ot->exec= select_linked_exec;
2563         ot->poll= ED_operator_editmesh;
2564         
2565         /* flags */
2566         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
2567         
2568         RNA_def_boolean(ot->srna, "limit", 0, "Limit by Seams", "");
2569 }
2570
2571
2572 /* ************************* */
2573
2574 /* swap is 0 or 1, if 1 it hides not selected */
2575 void EM_hide_mesh(EditMesh *em, int swap)
2576 {
2577         EditVert *eve;
2578         EditEdge *eed;
2579         EditFace *efa;
2580         int a;
2581         
2582         if(em==NULL) return;
2583
2584         /* hide happens on least dominant select mode, and flushes up, not down! (helps preventing errors in subsurf) */
2585         /*  - vertex hidden, always means edge is hidden too
2586                 - edge hidden, always means face is hidden too
2587                 - face hidden, only set face hide
2588                 - then only flush back down what's absolute hidden
2589         */
2590         if(em->selectmode & SCE_SELECT_VERTEX) {
2591                 for(eve= em->verts.first; eve; eve= eve->next) {
2592                         if((eve->f & SELECT)!=swap) {
2593                                 eve->f &= ~SELECT;
2594                                 eve->h= 1;
2595                         }
2596                 }
2597         
2598                 for(eed= em->edges.first; eed; eed= eed->next) {
2599                         if(eed->v1->h || eed->v2->h) {
2600                                 eed->h |= 1;
2601                                 eed->f &= ~SELECT;
2602                         }
2603                 }
2604         
2605                 for(efa= em->faces.first; efa; efa= efa->next) {
2606                         if(efa->e1->h & 1 || efa->e2->h & 1 || efa->e3->h & 1 || (efa->e4 && efa->e4->h & 1)) {
2607                                 efa->h= 1;
2608                                 efa->f &= ~SELECT;
2609                         }
2610                 }
2611         }
2612         else if(em->selectmode & SCE_SELECT_EDGE) {
2613
2614                 for(eed= em->edges.first; eed; eed= eed->next) {
2615                         if((eed->f & SELECT)!=swap) {
2616                                 eed->h |= 1;
2617                                 EM_select_edge(eed, 0);
2618                         }
2619                 }
2620
2621                 for(efa= em->faces.first; efa; efa= efa->next) {
2622                         if(efa->e1->h & 1 || efa->e2->h & 1 || efa->e3->h & 1 || (efa->e4 && efa->e4->h & 1)) {
2623                                 efa->h= 1;
2624                                 efa->f &= ~SELECT;
2625                         }
2626                 }
2627         }
2628         else {
2629
2630                 for(efa= em->faces.first; efa; efa= efa->next) {
2631                         if((efa->f & SELECT)!=swap) {
2632                                 efa->h= 1;
2633                                 EM_select_face(efa, 0);
2634                         }
2635                 }
2636         }
2637         
2638         /* flush down, only whats 100% hidden */
2639         for(eve= em->verts.first; eve; eve= eve->next) eve->f1= 0;
2640         for(eed= em->edges.first; eed; eed= eed->next) eed->f1= 0;
2641         
2642         if(em->selectmode & SCE_SELECT_FACE) {
2643                 for(efa= em->faces.first; efa; efa= efa->next) {
2644                         if(efa->h) a= 1; else a= 2;
2645                         efa->e1->f1 |= a;
2646                         efa->e2->f1 |= a;
2647                         efa->e3->f1 |= a;
2648                         if(efa->e4) efa->e4->f1 |= a;
2649                         /* When edges are not delt with in their own loop, we need to explicitly re-selct select edges that are joined to unselected faces */
2650                         if (swap && (em->selectmode == SCE_SELECT_FACE) && (efa->f & SELECT)) {
2651                                 EM_select_face(efa, 1);
2652                         }
2653                 }
2654         }
2655         
2656         if(em->selectmode >= SCE_SELECT_EDGE) {
2657                 for(eed= em->edges.first; eed; eed= eed->next) {
2658                         if(eed->f1==1) eed->h |= 1;
2659                         if(eed->h & 1) a= 1; else a= 2;
2660                         eed->v1->f1 |= a;
2661                         eed->v2->f1 |= a;
2662                 }
2663         }
2664
2665         if(em->selectmode >= SCE_SELECT_VERTEX) {
2666                 for(eve= em->verts.first; eve; eve= eve->next) {
2667                         if(eve->f1==1) eve->h= 1;
2668                 }
2669         }
2670         
2671         em->totedgesel= em->totfacesel= em->totvertsel= 0;
2672 //      if(EM_texFaceCheck())
2673
2674         //      DAG_object_flush_update(scene, obedit, OB_RECALC_DATA); 
2675 }
2676
2677 static int hide_mesh_exec(bContext *C, wmOperator *op)
2678 {
2679         Object *obedit= CTX_data_edit_object(C);
2680         EditMesh *em= BKE_mesh_get_editmesh(((Mesh *)obedit->data));
2681         
2682         EM_hide_mesh(em, RNA_boolean_get(op->ptr, "unselected"));
2683                 
2684         WM_event_add_notifier(C, NC_OBJECT|ND_GEOM_SELECT, obedit);
2685
2686         BKE_mesh_end_editmesh(obedit->data, em);
2687         return OPERATOR_FINISHED;       
2688 }
2689
2690 void MESH_OT_hide(wmOperatorType *ot)
2691 {
2692         /* identifiers */
2693         ot->name= "Hide Selection";
2694         ot->description= "Hide (un)selected vertices, edges or faces.";
2695         ot->idname= "MESH_OT_hide";
2696         
2697         /* api callbacks */
2698         ot->exec= hide_mesh_exec;
2699         ot->poll= ED_operator_editmesh;
2700         
2701         /* flags */
2702         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
2703         
2704         /* props */
2705         RNA_def_boolean(ot->srna, "unselected", 0, "Unselected", "Hide unselected rather than selected.");
2706 }
2707
2708 void EM_reveal_mesh(EditMesh *em)
2709 {
2710         EditVert *eve;
2711         EditEdge *eed;
2712         EditFace *efa;
2713         
2714         if(em==NULL) return;
2715
2716         for(eve= em->verts.first; eve; eve= eve->next) {
2717                 if(eve->h) {
2718                         eve->h= 0;
2719                         eve->f |= SELECT;
2720                 }
2721         }
2722         for(eed= em->edges.first; eed; eed= eed->next) {
2723                 if(eed->h & 1) {
2724                         eed->h &= ~1;
2725                         if(em->selectmode & SCE_SELECT_VERTEX); 
2726                         else EM_select_edge(eed, 1);
2727                 }
2728         }
2729         for(efa= em->faces.first; efa; efa= efa->next) {
2730                 if(efa->h) {
2731                         efa->h= 0;
2732                         if(em->selectmode & (SCE_SELECT_EDGE|SCE_SELECT_VERTEX)); 
2733                         else EM_select_face(efa, 1);
2734                 }
2735         }
2736
2737         EM_fgon_flags(em);      /* redo flags and indices for fgons */
2738         EM_selectmode_flush(em);
2739
2740 //      if (EM_texFaceCheck())
2741 //      DAG_object_flush_update(scene, obedit, OB_RECALC_DATA); 
2742 }
2743
2744 static int reveal_mesh_exec(bContext *C, wmOperator *op)
2745 {
2746         Object *obedit= CTX_data_edit_object(C);
2747         EditMesh *em= BKE_mesh_get_editmesh(((Mesh *)obedit->data));
2748         
2749         EM_reveal_mesh(em);
2750
2751         WM_event_add_notifier(C, NC_OBJECT|ND_GEOM_SELECT, obedit);
2752
2753         BKE_mesh_end_editmesh(obedit->data, em);
2754         return OPERATOR_FINISHED;       
2755 }
2756
2757 void MESH_OT_reveal(wmOperatorType *ot)
2758 {
2759         /* identifiers */
2760         ot->name= "Reveal Hidden";
2761         ot->description= "Reveal all hidden vertices, edges and faces.";
2762         ot->idname= "MESH_OT_reveal";
2763         
2764         /* api callbacks */
2765         ot->exec= reveal_mesh_exec;
2766         ot->poll= ED_operator_editmesh;
2767         
2768         /* flags */
2769         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
2770 }
2771
2772 int select_by_number_vertices_exec(bContext *C, wmOperator *op)
2773 {
2774         Object *obedit= CTX_data_edit_object(C);
2775         EditMesh *em= BKE_mesh_get_editmesh(((Mesh *)obedit->data));
2776         EditFace *efa;
2777         int numverts= RNA_enum_get(op->ptr, "type");
2778
2779         /* Selects trias/qiads or isolated verts, and edges that do not have 2 neighboring
2780          * faces
2781          */
2782
2783         /* for loose vertices/edges, we first select all, loop below will deselect */
2784         if(numverts==5) {
2785                 EM_set_flag_all(em, SELECT);
2786         }
2787         else if(em->selectmode!=SCE_SELECT_FACE) {
2788                 BKE_report(op->reports, RPT_ERROR, "Only works in face selection mode");
2789                 return OPERATOR_CANCELLED;
2790         }
2791         
2792         for(efa= em->faces.first; efa; efa= efa->next) {
2793                 if (efa->e4) {
2794                         EM_select_face(efa, (numverts==4) );
2795                 }
2796                 else {
2797                         EM_select_face(efa, (numverts==3) );
2798                 }
2799         }
2800
2801         WM_event_add_notifier(C, NC_OBJECT|ND_GEOM_SELECT, obedit);
2802         
2803         return OPERATOR_FINISHED;
2804 }
2805
2806 void MESH_OT_select_by_number_vertices(wmOperatorType *ot)
2807 {
2808         static const EnumPropertyItem type_items[]= {
2809                 {3, "TRIANGLES", 0, "Triangles", NULL},
2810                 {4, "QUADS", 0, "Triangles", NULL},
2811                 {5, "OTHER", 0, "Other", NULL},
2812                 {0, NULL, 0, NULL, NULL}};
2813
2814         /* identifiers */
2815         ot->name= "Select by Number of Vertices";
2816         ot->description= "Select vertices or faces by vertex count.";
2817         ot->idname= "MESH_OT_select_by_number_vertices";
2818         
2819         /* api callbacks */
2820         ot->exec= select_by_number_vertices_exec;
2821         ot->poll= ED_operator_editmesh;
2822         
2823         /* flags */
2824         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
2825         
2826         /* props */
2827         RNA_def_enum(ot->srna, "type", type_items, 3, "Type", "Type of elements to select.");
2828 }
2829
2830 static int select_sharp_edges_exec(bContext *C, wmOperator *op)
2831 {
2832         /* Find edges that have exactly two neighboring faces,
2833         * check the angle between those faces, and if angle is
2834         * small enough, select the edge
2835         */
2836         Object *obedit= CTX_data_edit_object(C);
2837         EditMesh *em= BKE_mesh_get_editmesh(((Mesh *)obedit->data));
2838         EditEdge *eed;
2839         EditFace *efa;
2840         EditFace **efa1;
2841         EditFace **efa2;
2842         intptr_t edgecount = 0, i = 0;
2843         float sharpness, fsharpness;
2844         
2845         /* 'standard' behaviour - check if selected, then apply relevant selection */
2846         
2847         if(em->selectmode==SCE_SELECT_FACE) {
2848                 BKE_report(op->reports, RPT_ERROR, "Doesn't work in face selection mode");
2849                 BKE_mesh_end_editmesh(obedit->data, em);
2850                 return OPERATOR_CANCELLED;
2851         }
2852
2853         sharpness= RNA_float_get(op->ptr, "sharpness");
2854         fsharpness = ((180.0 - sharpness) * M_PI) / 180.0;
2855
2856         /* count edges, use tmp.l  */
2857         eed= em->edges.first;
2858         while(eed) {
2859                 edgecount++;
2860                 eed->tmp.l = i;
2861                 eed= eed->next;
2862                 ++i;
2863         }
2864
2865         /* for each edge, we want a pointer to two adjacent faces */
2866         efa1 = MEM_callocN(edgecount*sizeof(EditFace *), 
2867                                            "pairs of edit face pointers");
2868         efa2 = MEM_callocN(edgecount*sizeof(EditFace *), 
2869                                            "pairs of edit face pointers");
2870
2871 #define face_table_edge(eed) { \
2872                 i = eed->tmp.l; \
2873                 if (i != -1) { \
2874                         if (efa1[i]) { \
2875                                 if (efa2[i]) { \
2876                                         /* invalidate, edge has more than two neighbors */ \
2877                                         eed->tmp.l = -1; \
2878                                 } \
2879                                 else { \
2880                                         efa2[i] = efa; \
2881                                 } \
2882                         } \
2883                         else { \
2884                                 efa1[i] = efa; \
2885                         } \
2886                 } \
2887         }
2888
2889         /* find the adjacent faces of each edge, we want only two */
2890         efa= em->faces.first;
2891         while(efa) {
2892                 face_table_edge(efa->e1);
2893                 face_table_edge(efa->e2);
2894                 face_table_edge(efa->e3);
2895                 if (efa->e4) {
2896                         face_table_edge(efa->e4);
2897                 }
2898                 efa= efa->next;
2899         }
2900
2901 #undef face_table_edge
2902
2903         eed = em->edges.first;
2904         while(eed) {
2905                 i = eed->tmp.l;
2906                 if (i != -1) { 
2907                         /* edge has two or less neighboring faces */
2908                         if ( (efa1[i]) && (efa2[i]) ) { 
2909                                 /* edge has exactly two neighboring faces, check angle */
2910                                 float angle;
2911                                 angle = saacos(efa1[i]->n[0]*efa2[i]->n[0] +
2912                                                            efa1[i]->n[1]*efa2[i]->n[1] +
2913                                                            efa1[i]->n[2]*efa2[i]->n[2]);
2914                                 if (fabs(angle) >= fsharpness)
2915                                         EM_select_edge(eed, 1);
2916                         }
2917                 }
2918
2919                 eed= eed->next;
2920         }
2921
2922         MEM_freeN(efa1);
2923         MEM_freeN(efa2);
2924
2925 //      if (EM_texFaceCheck())
2926         
2927         WM_event_add_notifier(C, NC_OBJECT|ND_GEOM_SELECT, obedit); //TODO is this needed ?
2928
2929         BKE_mesh_end_editmesh(obedit->data, em);
2930         return OPERATOR_FINISHED;       
2931 }
2932
2933 void MESH_OT_edges_select_sharp(wmOperatorType *ot)
2934 {
2935         /* identifiers */
2936         ot->name= "Select Sharp Edges";
2937         ot->description= "Marked selected edges as sharp.";
2938         ot->idname= "MESH_OT_edges_select_sharp";
2939         
2940         /* api callbacks */
2941         ot->exec= select_sharp_edges_exec;
2942         ot->poll= ED_operator_editmesh;
2943         
2944         /* flags */
2945         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
2946         
2947         /* props */
2948         RNA_def_float(ot->srna, "sharpness", 0.01f, 0.0f, FLT_MAX, "sharpness", "", 0.0f, 180.0f);
2949 }
2950
2951
2952 static void select_linked_flat_faces(EditMesh *em, wmOperator *op, float sharpness)
2953 {
2954         /* Find faces that are linked to selected faces that are 
2955          * relatively flat (angle between faces is higher than
2956          * specified angle)
2957          */
2958         EditEdge *eed;
2959         EditFace *efa;
2960         EditFace **efa1;
2961         EditFace **efa2;
2962         intptr_t edgecount = 0, i, faceselcount=0, faceselcountold=0;
2963         float fsharpness;
2964         
2965         if(em->selectmode!=SCE_SELECT_FACE) {
2966                 BKE_report(op->reports, RPT_ERROR, "Only works in face selection mode");
2967                 return;
2968         }
2969
2970         fsharpness = ((180.0 - sharpness) * M_PI) / 180.0;
2971
2972         i=0;
2973         /* count edges, use tmp.l */
2974         eed= em->edges.first;
2975         while(eed) {
2976                 edgecount++;
2977                 eed->tmp.l = i;
2978                 eed= eed->next;
2979                 ++i;
2980         }
2981
2982         /* for each edge, we want a pointer to two adjacent faces */
2983         efa1 = MEM_callocN(edgecount*sizeof(EditFace *), 
2984                                            "pairs of edit face pointers");
2985         efa2 = MEM_callocN(edgecount*sizeof(EditFace *), 
2986                                            "pairs of edit face pointers");
2987
2988 #define face_table_edge(eed) { \
2989                 i = eed->tmp.l; \
2990                 if (i != -1) { \
2991                         if (efa1[i]) { \
2992                                 if (efa2[i]) { \
2993                                         /* invalidate, edge has more than two neighbors */ \
2994