style cleanup: braces/indentation
[blender-staging.git] / source / blender / editors / mesh / editmesh_select.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * The Original Code is Copyright (C) 2004 Blender Foundation.
19  * All rights reserved.
20  *
21  * The Original Code is: all of this file.
22  *
23  * Contributor(s): none yet.
24  *
25  * ***** END GPL LICENSE BLOCK *****
26  */
27
28 /** \file blender/editors/mesh/editmesh_select.c
29  *  \ingroup edmesh
30  */
31
32 #include "MEM_guardedalloc.h"
33
34 #include "BLI_listbase.h"
35 #include "BLI_linklist.h"
36 #include "BLI_math.h"
37 #include "BLI_rand.h"
38 #include "BLI_array.h"
39 #include "BLI_smallhash.h"
40
41 #include "BKE_context.h"
42 #include "BKE_displist.h"
43 #include "BKE_report.h"
44 #include "BKE_paint.h"
45 #include "BKE_editmesh.h"
46
47 #include "IMB_imbuf_types.h"
48 #include "IMB_imbuf.h"
49
50 #include "WM_api.h"
51 #include "WM_types.h"
52
53 #include "RNA_access.h"
54 #include "RNA_define.h"
55
56 #include "ED_mesh.h"
57 #include "ED_screen.h"
58 #include "ED_view3d.h"
59
60 #include "BIF_gl.h"
61
62 #include "DNA_mesh_types.h"
63 #include "DNA_meshdata_types.h"
64 #include "DNA_object_types.h"
65
66 #include "GPU_extensions.h"
67
68 #include "UI_resources.h"
69
70 #include "mesh_intern.h"  /* own include */
71
72 /* use bmesh operator flags for a few operators */
73 #define BMO_ELE_TAG 1
74
75 /* ****************************** MIRROR **************** */
76
77 void EDBM_select_mirrored(BMEditMesh *em, bool extend,
78                           int *r_totmirr, int *r_totfail)
79 {
80         Mesh *me = (Mesh *)em->ob->data;
81         BMesh *bm = em->bm;
82         BMIter iter;
83         int totmirr = 0;
84         int totfail = 0;
85         bool use_topology = (me && (me->editflag & ME_EDIT_MIRROR_TOPO));
86
87         *r_totmirr = *r_totfail = 0;
88
89         /* select -> tag */
90         if (bm->selectmode & SCE_SELECT_VERTEX) {
91                 BMVert *v;
92                 BM_ITER_MESH (v, &iter, bm, BM_VERTS_OF_MESH) {
93                         BM_elem_flag_set(v, BM_ELEM_TAG, BM_elem_flag_test(v, BM_ELEM_SELECT));
94                 }
95         }
96         else if (em->selectmode & SCE_SELECT_EDGE) {
97                 BMEdge *e;
98                 BM_ITER_MESH (e, &iter, bm, BM_EDGES_OF_MESH) {
99                         BM_elem_flag_set(e, BM_ELEM_TAG, BM_elem_flag_test(e, BM_ELEM_SELECT));
100                 }
101         }
102         else {
103                 BMFace *f;
104                 BM_ITER_MESH (f, &iter, bm, BM_FACES_OF_MESH) {
105                         BM_elem_flag_set(f, BM_ELEM_TAG, BM_elem_flag_test(f, BM_ELEM_SELECT));
106                 }
107         }
108
109         EDBM_verts_mirror_cache_begin(em, 0, true, true, use_topology);
110
111         if (!extend)
112                 EDBM_flag_disable_all(em, BM_ELEM_SELECT);
113
114
115         if (bm->selectmode & SCE_SELECT_VERTEX) {
116                 BMVert *v;
117                 BM_ITER_MESH (v, &iter, bm, BM_VERTS_OF_MESH) {
118                         if (!BM_elem_flag_test(v, BM_ELEM_HIDDEN) && BM_elem_flag_test(v, BM_ELEM_TAG)) {
119                                 BMVert *v_mirr = EDBM_verts_mirror_get(em, v);
120                                 if (v_mirr && !BM_elem_flag_test(v_mirr, BM_ELEM_HIDDEN)) {
121                                         BM_vert_select_set(bm, v_mirr, true);
122                                         totmirr++;
123                                 }
124                                 else {
125                                         totfail++;
126                                 }
127                         }
128                 }
129         }
130         else if (em->selectmode & SCE_SELECT_EDGE) {
131                 BMEdge *e;
132                 BM_ITER_MESH (e, &iter, bm, BM_EDGES_OF_MESH) {
133                         if (!BM_elem_flag_test(e, BM_ELEM_HIDDEN) && BM_elem_flag_test(e, BM_ELEM_TAG)) {
134                                 BMEdge *e_mirr = EDBM_verts_mirror_get_edge(em, e);
135                                 if (e_mirr && !BM_elem_flag_test(e_mirr, BM_ELEM_HIDDEN)) {
136                                         BM_edge_select_set(bm, e_mirr, true);
137                                         totmirr++;
138                                 }
139                                 else {
140                                         totfail++;
141                                 }
142                         }
143                 }
144         }
145         else {
146                 BMFace *f;
147                 BM_ITER_MESH (f, &iter, bm, BM_FACES_OF_MESH) {
148                         if (!BM_elem_flag_test(f, BM_ELEM_HIDDEN) && BM_elem_flag_test(f, BM_ELEM_TAG)) {
149                                 BMFace *f_mirr = EDBM_verts_mirror_get_face(em, f);
150                                 if (f_mirr && !BM_elem_flag_test(f_mirr, BM_ELEM_HIDDEN)) {
151                                         BM_face_select_set(bm, f_mirr, true);
152                                         totmirr++;
153                                 }
154                                 else {
155                                         totfail++;
156                                 }
157                         }
158                 }
159         }
160
161         EDBM_verts_mirror_cache_end(em);
162
163         *r_totmirr = totmirr;
164         *r_totfail = totfail;
165 }
166
167 void EDBM_automerge(Scene *scene, Object *obedit, bool update, const char hflag)
168 {
169         int ok;
170         BMEditMesh *em = BKE_editmesh_from_object(obedit);
171
172         ok = BMO_op_callf(em->bm, BMO_FLAG_DEFAULTS,
173                           "automerge verts=%hv dist=%f",
174                           hflag, scene->toolsettings->doublimit);
175
176         if (LIKELY(ok) && update) {
177                 EDBM_update_generic(em, true, true);
178         }
179 }
180
181 /* ****************************** SELECTION ROUTINES **************** */
182
183 unsigned int bm_solidoffs = 0, bm_wireoffs = 0, bm_vertoffs = 0;    /* set in drawobject.c ... for colorindices */
184
185 /* facilities for border select and circle select */
186 static char *selbuf = NULL;
187
188 /* opengl doesn't support concave... */
189 static void draw_triangulated(const int mcords[][2], const short tot)
190 {
191         ListBase lb = {NULL, NULL};
192         DispList *dl;
193         float *fp;
194         int a;
195         const float z_up[3] = {0.0f, 0.0f, 1.0f};
196         
197         /* make displist */
198         dl = MEM_callocN(sizeof(DispList), "poly disp");
199         dl->type = DL_POLY;
200         dl->parts = 1;
201         dl->nr = tot;
202         dl->verts = fp = MEM_callocN(tot * 3 * sizeof(float), "poly verts");
203         BLI_addtail(&lb, dl);
204         
205         for (a = 0; a < tot; a++, fp += 3) {
206                 fp[0] = (float)mcords[a][0];
207                 fp[1] = (float)mcords[a][1];
208         }
209         
210         /* do the fill */
211         BKE_displist_fill(&lb, &lb, z_up, false);
212
213         /* do the draw */
214         dl = lb.first;  /* filldisplist adds in head of list */
215         if (dl->type == DL_INDEX3) {
216                 int *index;
217                 
218                 a = dl->parts;
219                 fp = dl->verts;
220                 index = dl->index;
221                 glBegin(GL_TRIANGLES);
222                 while (a--) {
223                         glVertex3fv(fp + 3 * index[0]);
224                         glVertex3fv(fp + 3 * index[1]);
225                         glVertex3fv(fp + 3 * index[2]);
226                         index += 3;
227                 }
228                 glEnd();
229         }
230         
231         BKE_displist_free(&lb);
232 }
233
234
235 /* reads rect, and builds selection array for quick lookup */
236 /* returns if all is OK */
237 bool EDBM_backbuf_border_init(ViewContext *vc, short xmin, short ymin, short xmax, short ymax)
238 {
239         struct ImBuf *buf;
240         unsigned int *dr;
241         int a;
242         
243         if (vc->obedit == NULL || vc->v3d->drawtype < OB_SOLID || (vc->v3d->flag & V3D_ZBUF_SELECT) == 0) {
244                 return false;
245         }
246         
247         buf = view3d_read_backbuf(vc, xmin, ymin, xmax, ymax);
248         if (buf == NULL) return false;
249         if (bm_vertoffs == 0) return false;
250
251         dr = buf->rect;
252         
253         /* build selection lookup */
254         selbuf = MEM_callocN(bm_vertoffs + 1, "selbuf");
255         
256         a = (xmax - xmin + 1) * (ymax - ymin + 1);
257         while (a--) {
258                 if (*dr > 0 && *dr <= bm_vertoffs)
259                         selbuf[*dr] = 1;
260                 dr++;
261         }
262         IMB_freeImBuf(buf);
263         return true;
264 }
265
266 int EDBM_backbuf_check(unsigned int index)
267 {
268         if (selbuf == NULL) return 1;
269         if (index > 0 && index <= bm_vertoffs)
270                 return selbuf[index];
271         return 0;
272 }
273
274 void EDBM_backbuf_free(void)
275 {
276         if (selbuf) MEM_freeN(selbuf);
277         selbuf = NULL;
278 }
279
280 /* mcords is a polygon mask
281  * - grab backbuffer,
282  * - draw with black in backbuffer, 
283  * - grab again and compare
284  * returns 'OK' 
285  */
286 bool EDBM_backbuf_border_mask_init(ViewContext *vc, const int mcords[][2], short tot, short xmin, short ymin, short xmax, short ymax)
287 {
288         unsigned int *dr, *drm;
289         struct ImBuf *buf, *bufmask;
290         int a;
291         
292         /* method in use for face selecting too */
293         if (vc->obedit == NULL) {
294                 if (!(paint_facesel_test(vc->obact) || paint_vertsel_test(vc->obact))) {
295                         return false;
296                 }
297         }
298         else if (vc->v3d->drawtype < OB_SOLID || (vc->v3d->flag & V3D_ZBUF_SELECT) == 0) {
299                 return false;
300         }
301
302         buf = view3d_read_backbuf(vc, xmin, ymin, xmax, ymax);
303         if (buf == NULL) return false;
304         if (bm_vertoffs == 0) return false;
305
306         dr = buf->rect;
307
308         if (vc->rv3d->gpuoffscreen)
309                 GPU_offscreen_bind(vc->rv3d->gpuoffscreen);
310         
311         /* draw the mask */
312         glDisable(GL_DEPTH_TEST);
313         
314         glColor3ub(0, 0, 0);
315         
316         /* yah, opengl doesn't do concave... tsk! */
317         ED_region_pixelspace(vc->ar);
318         draw_triangulated(mcords, tot);
319         
320         glBegin(GL_LINE_LOOP);  /* for zero sized masks, lines */
321         for (a = 0; a < tot; a++) {
322                 glVertex2iv(mcords[a]);
323         }
324         glEnd();
325         
326         glFinish(); /* to be sure readpixels sees mask */
327         
328         if (vc->rv3d->gpuoffscreen)
329                 GPU_offscreen_unbind(vc->rv3d->gpuoffscreen);
330         
331         /* grab mask */
332         bufmask = view3d_read_backbuf(vc, xmin, ymin, xmax, ymax);
333
334         if (bufmask == NULL) {
335                 return false;  /* only when mem alloc fails, go crash somewhere else! */
336         }
337         else {
338                 drm = bufmask->rect;
339         }
340
341         /* build selection lookup */
342         selbuf = MEM_callocN(bm_vertoffs + 1, "selbuf");
343         
344         a = (xmax - xmin + 1) * (ymax - ymin + 1);
345         while (a--) {
346                 if (*dr > 0 && *dr <= bm_vertoffs && *drm == 0) selbuf[*dr] = 1;
347                 dr++; drm++;
348         }
349         IMB_freeImBuf(buf);
350         IMB_freeImBuf(bufmask);
351
352         return true;
353 }
354
355 /* circle shaped sample area */
356 bool EDBM_backbuf_circle_init(ViewContext *vc, short xs, short ys, short rads)
357 {
358         struct ImBuf *buf;
359         unsigned int *dr;
360         short xmin, ymin, xmax, ymax, xc, yc;
361         int radsq;
362         
363         /* method in use for face selecting too */
364         if (vc->obedit == NULL) {
365                 if (!(paint_facesel_test(vc->obact) || paint_vertsel_test(vc->obact))) {
366                         return false;
367                 }
368         }
369         else if (vc->v3d->drawtype < OB_SOLID || (vc->v3d->flag & V3D_ZBUF_SELECT) == 0) {
370                 return false;
371         }
372
373         xmin = xs - rads; xmax = xs + rads;
374         ymin = ys - rads; ymax = ys + rads;
375         buf = view3d_read_backbuf(vc, xmin, ymin, xmax, ymax);
376         if (bm_vertoffs == 0) return false;
377         if (buf == NULL) return false;
378
379         dr = buf->rect;
380         
381         /* build selection lookup */
382         selbuf = MEM_callocN(bm_vertoffs + 1, "selbuf");
383         radsq = rads * rads;
384         for (yc = -rads; yc <= rads; yc++) {
385                 for (xc = -rads; xc <= rads; xc++, dr++) {
386                         if (xc * xc + yc * yc < radsq) {
387                                 if (*dr > 0 && *dr <= bm_vertoffs) selbuf[*dr] = 1;
388                         }
389                 }
390         }
391
392         IMB_freeImBuf(buf);
393         return true;
394         
395 }
396
397 static void findnearestvert__doClosest(void *userData, BMVert *eve, const float screen_co[2], int index)
398 {
399         struct { float mval_fl[2], pass, select, strict; float dist, lastIndex, closestIndex; BMVert *closest; } *data = userData;
400
401         if (data->pass == 0) {
402                 if (index <= data->lastIndex)
403                         return;
404         }
405         else {
406                 if (index > data->lastIndex)
407                         return;
408         }
409
410         if (data->dist > 3) {
411                 float dist_test = len_manhattan_v2v2(data->mval_fl, screen_co);
412                 if (BM_elem_flag_test(eve, BM_ELEM_SELECT) == data->select) {
413                         if (data->strict == 1) {
414                                 return;
415                         }
416                         else {
417                                 dist_test += 5;
418                         }
419                 }
420
421                 if (dist_test < data->dist) {
422                         data->dist = dist_test;
423                         data->closest = eve;
424                         data->closestIndex = index;
425                 }
426         }
427 }
428
429
430
431
432 static bool findnearestvert__backbufIndextest(void *handle, unsigned int index)
433 {
434         BMEditMesh *em = (BMEditMesh *)handle;
435         BMVert *eve = BM_vert_at_index(em->bm, index - 1);
436         return !(eve && BM_elem_flag_test(eve, BM_ELEM_SELECT));
437 }
438 /**
439  * findnearestvert
440  * 
441  * dist (in/out): minimal distance to the nearest and at the end, actual distance
442  * sel: selection bias
443  *      if SELECT, selected vertice are given a 5 pixel bias to make them further than unselect verts
444  *      if 0, unselected vertice are given the bias
445  * strict: if 1, the vertice corresponding to the sel parameter are ignored and not just biased 
446  */
447 BMVert *EDBM_vert_find_nearest(ViewContext *vc, float *r_dist, const bool sel, const bool strict)
448 {
449         if (vc->v3d->drawtype > OB_WIRE && (vc->v3d->flag & V3D_ZBUF_SELECT)) {
450                 float distance;
451                 unsigned int index;
452                 BMVert *eve;
453                 
454                 if (strict) {
455                         index = view3d_sample_backbuf_rect(vc, vc->mval, 50, bm_wireoffs, 0xFFFFFF, &distance,
456                                                            strict, vc->em, findnearestvert__backbufIndextest);
457                 }
458                 else {
459                         index = view3d_sample_backbuf_rect(vc, vc->mval, 50, bm_wireoffs, 0xFFFFFF, &distance,
460                                                            0, NULL, NULL);
461                 }
462                 
463                 eve = BM_vert_at_index(vc->em->bm, index - 1);
464                 
465                 if (eve && distance < *r_dist) {
466                         *r_dist = distance;
467                         return eve;
468                 }
469                 else {
470                         return NULL;
471                 }
472                         
473         }
474         else {
475                 struct { float mval_fl[2], pass, select, strict; float dist, lastIndex, closestIndex; BMVert *closest; } data;
476                 static int lastSelectedIndex = 0;
477                 static BMVert *lastSelected = NULL;
478                 
479                 if (lastSelected && BM_vert_at_index(vc->em->bm, lastSelectedIndex) != lastSelected) {
480                         lastSelectedIndex = 0;
481                         lastSelected = NULL;
482                 }
483
484                 data.lastIndex = lastSelectedIndex;
485                 data.mval_fl[0] = vc->mval[0];
486                 data.mval_fl[1] = vc->mval[1];
487                 data.select = sel ? BM_ELEM_SELECT : 0;
488                 data.dist = *r_dist;
489                 data.strict = strict;
490                 data.closest = NULL;
491                 data.closestIndex = 0;
492
493                 data.pass = 0;
494
495                 ED_view3d_init_mats_rv3d(vc->obedit, vc->rv3d);
496
497                 mesh_foreachScreenVert(vc, findnearestvert__doClosest, &data, V3D_PROJ_TEST_CLIP_DEFAULT);
498
499                 if (data.dist > 3) {
500                         data.pass = 1;
501                         mesh_foreachScreenVert(vc, findnearestvert__doClosest, &data, V3D_PROJ_TEST_CLIP_DEFAULT);
502                 }
503
504                 *r_dist = data.dist;
505                 lastSelected = data.closest;
506                 lastSelectedIndex = data.closestIndex;
507
508                 return data.closest;
509         }
510 }
511
512 /* note; uses v3d, so needs active 3d window */
513 static void findnearestedge__doClosest(void *userData, BMEdge *eed, const float screen_co_a[2], const float screen_co_b[2], int UNUSED(index))
514 {
515         struct { ViewContext vc; float mval_fl[2]; float dist; BMEdge *closest; } *data = userData;
516         int distance;
517
518         distance = dist_to_line_segment_v2(data->mval_fl, screen_co_a, screen_co_b);
519                 
520         if (BM_elem_flag_test(eed, BM_ELEM_SELECT)) {
521                 distance += 5;
522         }
523
524         if (distance < data->dist) {
525                 if (data->vc.rv3d->rflag & RV3D_CLIPPING) {
526                         float lambda = line_point_factor_v2(data->mval_fl, screen_co_a, screen_co_b);
527                         float vec[3];
528
529                         vec[0] = eed->v1->co[0] + lambda * (eed->v2->co[0] - eed->v1->co[0]);
530                         vec[1] = eed->v1->co[1] + lambda * (eed->v2->co[1] - eed->v1->co[1]);
531                         vec[2] = eed->v1->co[2] + lambda * (eed->v2->co[2] - eed->v1->co[2]);
532
533                         if (ED_view3d_clipping_test(data->vc.rv3d, vec, true) == 0) {
534                                 data->dist = distance;
535                                 data->closest = eed;
536                         }
537                 }
538                 else {
539                         data->dist = distance;
540                         data->closest = eed;
541                 }
542         }
543 }
544 BMEdge *EDBM_edge_find_nearest(ViewContext *vc, float *r_dist)
545 {
546
547         if (vc->v3d->drawtype > OB_WIRE && (vc->v3d->flag & V3D_ZBUF_SELECT)) {
548                 float distance;
549                 unsigned int index;
550                 BMEdge *eed;
551                 
552                 view3d_validate_backbuf(vc);
553                 
554                 index = view3d_sample_backbuf_rect(vc, vc->mval, 50, bm_solidoffs, bm_wireoffs, &distance, 0, NULL, NULL);
555                 eed = BM_edge_at_index(vc->em->bm, index - 1);
556                 
557                 if (eed && distance < *r_dist) {
558                         *r_dist = distance;
559                         return eed;
560                 }
561                 else {
562                         return NULL;
563                 }
564         }
565         else {
566                 struct { ViewContext vc; float mval_fl[2]; float dist; BMEdge *closest; } data;
567
568                 data.vc = *vc;
569                 data.mval_fl[0] = vc->mval[0];
570                 data.mval_fl[1] = vc->mval[1];
571                 data.dist = *r_dist;
572                 data.closest = NULL;
573                 ED_view3d_init_mats_rv3d(vc->obedit, vc->rv3d);
574
575                 mesh_foreachScreenEdge(vc, findnearestedge__doClosest, &data, V3D_PROJ_TEST_CLIP_WIN);
576
577                 *r_dist = data.dist;
578                 return data.closest;
579         }
580 }
581
582 static void findnearestface__getDistance(void *userData, BMFace *efa, const float screen_co[2], int UNUSED(index))
583 {
584         struct { float mval_fl[2]; float dist; BMFace *toFace; } *data = userData;
585
586         if (efa == data->toFace) {
587                 const float dist_test = len_manhattan_v2v2(data->mval_fl, screen_co);
588
589                 if (dist_test < data->dist) {
590                         data->dist = dist_test;
591                 }
592         }
593 }
594 static void findnearestface__doClosest(void *userData, BMFace *efa, const float screen_co[2], int index)
595 {
596         struct { float mval_fl[2], pass; float dist, lastIndex, closestIndex; BMFace *closest; } *data = userData;
597
598         if (data->pass == 0) {
599                 if (index <= data->lastIndex)
600                         return;
601         }
602         else {
603                 if (index > data->lastIndex)
604                         return;
605         }
606
607         if (data->dist > 3) {
608                 const float dist_test = len_manhattan_v2v2(data->mval_fl, screen_co);
609
610                 if (dist_test < data->dist) {
611                         data->dist = dist_test;
612                         data->closest = efa;
613                         data->closestIndex = index;
614                 }
615         }
616 }
617
618 BMFace *EDBM_face_find_nearest(ViewContext *vc, float *r_dist)
619 {
620
621         if (vc->v3d->drawtype > OB_WIRE && (vc->v3d->flag & V3D_ZBUF_SELECT)) {
622                 unsigned int index;
623                 BMFace *efa;
624
625                 view3d_validate_backbuf(vc);
626
627                 index = view3d_sample_backbuf(vc, vc->mval[0], vc->mval[1]);
628                 efa = BM_face_at_index(vc->em->bm, index - 1);
629                 
630                 if (efa) {
631                         struct { float mval_fl[2]; float dist; BMFace *toFace; } data;
632
633                         data.mval_fl[0] = vc->mval[0];
634                         data.mval_fl[1] = vc->mval[1];
635                         data.dist = FLT_MAX;
636                         data.toFace = efa;
637
638                         ED_view3d_init_mats_rv3d(vc->obedit, vc->rv3d);
639
640                         mesh_foreachScreenFace(vc, findnearestface__getDistance, &data, V3D_PROJ_TEST_CLIP_DEFAULT);
641
642                         if ((vc->em->selectmode == SCE_SELECT_FACE) || (data.dist < *r_dist)) {  /* only faces, no dist check */
643                                 *r_dist = data.dist;
644                                 return efa;
645                         }
646                 }
647                 
648                 return NULL;
649         }
650         else {
651                 struct { float mval_fl[2], pass; float dist, lastIndex, closestIndex; BMFace *closest; } data;
652                 static int lastSelectedIndex = 0;
653                 static BMFace *lastSelected = NULL;
654
655                 if (lastSelected && BM_face_at_index(vc->em->bm, lastSelectedIndex) != lastSelected) {
656                         lastSelectedIndex = 0;
657                         lastSelected = NULL;
658                 }
659
660                 data.lastIndex = lastSelectedIndex;
661                 data.mval_fl[0] = vc->mval[0];
662                 data.mval_fl[1] = vc->mval[1];
663                 data.dist = *r_dist;
664                 data.closest = NULL;
665                 data.closestIndex = 0;
666
667                 data.pass = 0;
668                 ED_view3d_init_mats_rv3d(vc->obedit, vc->rv3d);
669                 mesh_foreachScreenFace(vc, findnearestface__doClosest, &data, V3D_PROJ_TEST_CLIP_DEFAULT);
670
671                 if (data.dist > 3.0f) {
672                         data.pass = 1;
673                         mesh_foreachScreenFace(vc, findnearestface__doClosest, &data, V3D_PROJ_TEST_CLIP_DEFAULT);
674                 }
675
676                 *r_dist = data.dist;
677                 lastSelected = data.closest;
678                 lastSelectedIndex = data.closestIndex;
679
680                 return data.closest;
681         }
682 }
683
684 /* best distance based on screen coords. 
685  * use em->selectmode to define how to use 
686  * selected vertices and edges get disadvantage
687  * return 1 if found one
688  */
689 static int unified_findnearest(ViewContext *vc, BMVert **r_eve, BMEdge **r_eed, BMFace **r_efa)
690 {
691         BMEditMesh *em = vc->em;
692         float dist = 75.0f;
693         
694         *r_eve = NULL;
695         *r_eed = NULL;
696         *r_efa = NULL;
697         
698         /* no afterqueue (yet), so we check it now, otherwise the em_xxxofs indices are bad */
699         view3d_validate_backbuf(vc);
700         
701         if (em->selectmode & SCE_SELECT_VERTEX)
702                 *r_eve = EDBM_vert_find_nearest(vc, &dist, BM_ELEM_SELECT, 0);
703         if (em->selectmode & SCE_SELECT_FACE)
704                 *r_efa = EDBM_face_find_nearest(vc, &dist);
705
706         dist -= 20; /* since edges select lines, we give dots advantage of 20 pix */
707         if (em->selectmode & SCE_SELECT_EDGE)
708                 *r_eed = EDBM_edge_find_nearest(vc, &dist);
709
710         /* return only one of 3 pointers, for frontbuffer redraws */
711         if (*r_eed) {
712                 *r_efa = NULL; *r_eve = NULL;
713         }
714         else if (*r_efa) {
715                 *r_eve = NULL;
716         }
717         
718         return (*r_eve || *r_eed || *r_efa);
719 }
720
721 /* ****************  SIMILAR "group" SELECTS. FACE, EDGE AND VERTEX ************** */
722 static EnumPropertyItem prop_similar_compare_types[] = {
723         {SIM_CMP_EQ, "EQUAL", 0, "Equal", ""},
724         {SIM_CMP_GT, "GREATER", 0, "Greater", ""},
725         {SIM_CMP_LT, "LESS", 0, "Less", ""},
726
727         {0, NULL, 0, NULL, NULL}
728 };
729
730 static EnumPropertyItem prop_similar_types[] = {
731         {SIMVERT_NORMAL, "NORMAL", 0, "Normal", ""},
732         {SIMVERT_FACE, "FACE", 0, "Amount of Adjacent Faces", ""},
733         {SIMVERT_VGROUP, "VGROUP", 0, "Vertex Groups", ""},
734         {SIMVERT_EDGE, "EDGE", 0, "Amount of connecting edges", ""},
735
736         {SIMEDGE_LENGTH, "LENGTH", 0, "Length", ""},
737         {SIMEDGE_DIR, "DIR", 0, "Direction", ""},
738         {SIMEDGE_FACE, "FACE", 0, "Amount of Faces Around an Edge", ""},
739         {SIMEDGE_FACE_ANGLE, "FACE_ANGLE", 0, "Face Angles", ""},
740         {SIMEDGE_CREASE, "CREASE", 0, "Crease", ""},
741         {SIMEDGE_BEVEL, "BEVEL", 0, "Bevel", ""},
742         {SIMEDGE_SEAM, "SEAM", 0, "Seam", ""},
743         {SIMEDGE_SHARP, "SHARP", 0, "Sharpness", ""},
744 #ifdef WITH_FREESTYLE
745         {SIMEDGE_FREESTYLE, "FREESTYLE_EDGE", 0, "Freestyle Edge Marks", ""},
746 #endif
747
748         {SIMFACE_MATERIAL, "MATERIAL", 0, "Material", ""},
749         {SIMFACE_IMAGE, "IMAGE", 0, "Image", ""},
750         {SIMFACE_AREA, "AREA", 0, "Area", ""},
751         {SIMFACE_SIDES, "SIDES", 0, "Polygon Sides", ""},
752         {SIMFACE_PERIMETER, "PERIMETER", 0, "Perimeter", ""},
753         {SIMFACE_NORMAL, "NORMAL", 0, "Normal", ""},
754         {SIMFACE_COPLANAR, "COPLANAR", 0, "Co-planar", ""},
755 #ifdef WITH_FREESTYLE
756         {SIMFACE_FREESTYLE, "FREESTYLE_FACE", 0, "Freestyle Face Marks", ""},
757 #endif
758
759         {0, NULL, 0, NULL, NULL}
760 };
761
762 /* selects new faces/edges/verts based on the existing selection */
763
764 static int similar_face_select_exec(bContext *C, wmOperator *op)
765 {
766         Object *ob = CTX_data_edit_object(C);
767         BMEditMesh *em = BKE_editmesh_from_object(ob);
768         BMOperator bmop;
769
770         /* get the type from RNA */
771         const int type = RNA_enum_get(op->ptr, "type");
772         const float thresh = RNA_float_get(op->ptr, "threshold");
773         const int compare = RNA_enum_get(op->ptr, "compare");
774
775         /* initialize the bmop using EDBM api, which does various ui error reporting and other stuff */
776         EDBM_op_init(em, &bmop, op,
777                      "similar_faces faces=%hf type=%i thresh=%f compare=%i",
778                      BM_ELEM_SELECT, type, thresh, compare);
779
780         /* execute the operator */
781         BMO_op_exec(em->bm, &bmop);
782
783         /* clear the existing selection */
784         EDBM_flag_disable_all(em, BM_ELEM_SELECT);
785
786         /* select the output */
787         BMO_slot_buffer_hflag_enable(em->bm, bmop.slots_out, "faces.out", BM_FACE, BM_ELEM_SELECT, true);
788
789         /* finish the operator */
790         if (!EDBM_op_finish(em, &bmop, op, true)) {
791                 return OPERATOR_CANCELLED;
792         }
793
794         EDBM_update_generic(em, false, false);
795
796         return OPERATOR_FINISHED;
797 }       
798
799 /* ***************************************************** */
800
801 /* EDGE GROUP */
802
803 /* wrap the above function but do selection flushing edge to face */
804 static int similar_edge_select_exec(bContext *C, wmOperator *op)
805 {
806         Object *ob = CTX_data_edit_object(C);
807         BMEditMesh *em = BKE_editmesh_from_object(ob);
808         BMOperator bmop;
809
810         /* get the type from RNA */
811         const int type = RNA_enum_get(op->ptr, "type");
812         const float thresh = RNA_float_get(op->ptr, "threshold");
813         const int compare = RNA_enum_get(op->ptr, "compare");
814
815         /* initialize the bmop using EDBM api, which does various ui error reporting and other stuff */
816         EDBM_op_init(em, &bmop, op,
817                      "similar_edges edges=%he type=%i thresh=%f compare=%i",
818                      BM_ELEM_SELECT, type, thresh, compare);
819
820         /* execute the operator */
821         BMO_op_exec(em->bm, &bmop);
822
823         /* clear the existing selection */
824         EDBM_flag_disable_all(em, BM_ELEM_SELECT);
825
826         /* select the output */
827         BMO_slot_buffer_hflag_enable(em->bm, bmop.slots_out, "edges.out", BM_EDGE, BM_ELEM_SELECT, true);
828         EDBM_selectmode_flush(em);
829
830         /* finish the operator */
831         if (!EDBM_op_finish(em, &bmop, op, true)) {
832                 return OPERATOR_CANCELLED;
833         }
834
835         EDBM_update_generic(em, false, false);
836
837         return OPERATOR_FINISHED;
838 }
839
840 /* ********************************* */
841
842 /*
843  * VERT GROUP
844  * mode 1: same normal
845  * mode 2: same number of face users
846  * mode 3: same vertex groups
847  */
848 static int similar_vert_select_exec(bContext *C, wmOperator *op)
849 {
850         Object *ob = CTX_data_edit_object(C);
851         BMEditMesh *em = BKE_editmesh_from_object(ob);
852         BMOperator bmop;
853         /* get the type from RNA */
854         const int type = RNA_enum_get(op->ptr, "type");
855         const float thresh = RNA_float_get(op->ptr, "threshold");
856         const int compare = RNA_enum_get(op->ptr, "compare");
857
858         /* initialize the bmop using EDBM api, which does various ui error reporting and other stuff */
859         EDBM_op_init(em, &bmop, op,
860                      "similar_verts verts=%hv type=%i thresh=%f compare=%i",
861                      BM_ELEM_SELECT, type, thresh, compare);
862
863         /* execute the operator */
864         BMO_op_exec(em->bm, &bmop);
865
866         /* clear the existing selection */
867         EDBM_flag_disable_all(em, BM_ELEM_SELECT);
868
869         /* select the output */
870         BMO_slot_buffer_hflag_enable(em->bm, bmop.slots_out, "verts.out", BM_VERT, BM_ELEM_SELECT, true);
871
872         /* finish the operator */
873         if (!EDBM_op_finish(em, &bmop, op, true)) {
874                 return OPERATOR_CANCELLED;
875         }
876
877         EDBM_selectmode_flush(em);
878
879         EDBM_update_generic(em, false, false);
880
881         return OPERATOR_FINISHED;
882 }
883
884 static int edbm_select_similar_exec(bContext *C, wmOperator *op)
885 {
886         ToolSettings *ts = CTX_data_tool_settings(C);
887         PropertyRNA *prop = RNA_struct_find_property(op->ptr, "threshold");
888
889         const int type = RNA_enum_get(op->ptr, "type");
890
891         if (!RNA_property_is_set(op->ptr, prop)) {
892                 RNA_property_float_set(op->ptr, prop, ts->select_thresh);
893         }
894         else {
895                 ts->select_thresh = RNA_property_float_get(op->ptr, prop);
896         }
897
898         if      (type < 100) return similar_vert_select_exec(C, op);
899         else if (type < 200) return similar_edge_select_exec(C, op);
900         else                 return similar_face_select_exec(C, op);
901 }
902
903 static EnumPropertyItem *select_similar_type_itemf(bContext *C, PointerRNA *UNUSED(ptr), PropertyRNA *UNUSED(prop),
904                                                    int *free)
905 {
906         Object *obedit;
907
908         if (!C) /* needed for docs and i18n tools */
909                 return prop_similar_types;
910
911         obedit = CTX_data_edit_object(C);
912
913         if (obedit && obedit->type == OB_MESH) {
914                 EnumPropertyItem *item = NULL;
915                 int a, totitem = 0;
916                 BMEditMesh *em = BKE_editmesh_from_object(obedit);
917
918                 if (em->selectmode & SCE_SELECT_VERTEX) {
919                         for (a = SIMVERT_NORMAL; a < SIMEDGE_LENGTH; a++) {
920                                 RNA_enum_items_add_value(&item, &totitem, prop_similar_types, a);
921                         }
922                 }
923                 else if (em->selectmode & SCE_SELECT_EDGE) {
924                         for (a = SIMEDGE_LENGTH; a < SIMFACE_MATERIAL; a++) {
925                                 RNA_enum_items_add_value(&item, &totitem, prop_similar_types, a);
926                         }
927                 }
928                 else if (em->selectmode & SCE_SELECT_FACE) {
929 #ifdef WITH_FREESTYLE
930                         const int a_end = SIMFACE_FREESTYLE;
931 #else
932                         const int a_end = SIMFACE_COPLANAR;
933 #endif
934                         for (a = SIMFACE_MATERIAL; a <= a_end; a++) {
935                                 RNA_enum_items_add_value(&item, &totitem, prop_similar_types, a);
936                         }
937                 }
938                 RNA_enum_item_end(&item, &totitem);
939
940                 *free = 1;
941
942                 return item;
943         }
944
945         return NULL;
946 }
947
948 void MESH_OT_select_similar(wmOperatorType *ot)
949 {
950         PropertyRNA *prop;
951
952         /* identifiers */
953         ot->name = "Select Similar";
954         ot->idname = "MESH_OT_select_similar";
955         ot->description = "Select similar vertices, edges or faces by property types";
956         
957         /* api callbacks */
958         ot->invoke = WM_menu_invoke;
959         ot->exec = edbm_select_similar_exec;
960         ot->poll = ED_operator_editmesh;
961         
962         /* flags */
963         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
964         
965         /* properties */
966         prop = ot->prop = RNA_def_enum(ot->srna, "type", prop_similar_types, SIMVERT_NORMAL, "Type", "");
967         RNA_def_enum_funcs(prop, select_similar_type_itemf);
968
969         RNA_def_enum(ot->srna, "compare", prop_similar_compare_types, SIM_CMP_EQ, "Compare", "");
970
971         RNA_def_float(ot->srna, "threshold", 0.0, 0.0, 1.0, "Threshold", "", 0.0, 1.0);
972 }
973
974
975 /* ****************  Mode Select *************** */
976
977 static int edbm_select_mode_exec(bContext *C, wmOperator *op)
978 {
979         const int type        = RNA_enum_get(op->ptr,    "type");
980         const int action      = RNA_enum_get(op->ptr,    "action");
981         const bool use_extend = RNA_boolean_get(op->ptr, "use_extend");
982         const bool use_expand = RNA_boolean_get(op->ptr, "use_expand");
983
984         if (EDBM_selectmode_toggle(C, type, action, use_extend, use_expand)) {
985                 return OPERATOR_FINISHED;
986         }
987         else {
988                 return OPERATOR_CANCELLED;
989         }
990 }
991
992 static int edbm_select_mode_invoke(bContext *C, wmOperator *op, const wmEvent *event)
993 {
994         /* detecting these options based on shift/ctrl here is weak, but it's done
995          * to make this work when clicking buttons or menus */
996         if (!RNA_struct_property_is_set(op->ptr, "use_extend"))
997                 RNA_boolean_set(op->ptr, "use_extend", event->shift);
998         if (!RNA_struct_property_is_set(op->ptr, "use_expand"))
999                 RNA_boolean_set(op->ptr, "use_expand", event->ctrl);
1000
1001         return edbm_select_mode_exec(C, op);
1002 }
1003
1004 void MESH_OT_select_mode(wmOperatorType *ot)
1005 {
1006         PropertyRNA *prop;
1007
1008         static EnumPropertyItem elem_items[] = {
1009                 {SCE_SELECT_VERTEX, "VERT", ICON_VERTEXSEL, "Vertices", ""},
1010                 {SCE_SELECT_EDGE,   "EDGE", ICON_EDGESEL, "Edges", ""},
1011                 {SCE_SELECT_FACE,   "FACE", ICON_FACESEL, "Faces", ""},
1012                 {0, NULL, 0, NULL, NULL},
1013         };
1014
1015         static EnumPropertyItem actions_items[] = {
1016                 {0, "DISABLE", 0, "Disable", "Disable selected markers"},
1017                 {1, "ENABLE", 0, "Enable", "Enable selected markers"},
1018                 {2, "TOGGLE", 0, "Toggle", "Toggle disabled flag for selected markers"},
1019                 {0, NULL, 0, NULL, NULL}
1020         };
1021
1022         /* identifiers */
1023         ot->name = "Select Mode";
1024         ot->idname = "MESH_OT_select_mode";
1025         ot->description = "Change selection mode";
1026
1027         /* api callbacks */
1028         ot->invoke = edbm_select_mode_invoke;
1029         ot->exec = edbm_select_mode_exec;
1030         ot->poll = ED_operator_editmesh;
1031
1032         /* flags */
1033         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1034
1035         /* properties */
1036         prop = RNA_def_boolean(ot->srna, "use_extend", false, "Extend", "");
1037         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
1038         prop = RNA_def_boolean(ot->srna, "use_expand", false, "Expand", "");
1039         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
1040         ot->prop = prop = RNA_def_enum(ot->srna, "type", elem_items, 0, "Type", "");
1041         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
1042
1043         RNA_def_enum(ot->srna, "action", actions_items, 2, "Action", "Selection action to execute");
1044 }
1045
1046 /* ***************************************************** */
1047
1048 /* ****************  LOOP SELECTS *************** */
1049
1050 static void walker_select(BMEditMesh *em, int walkercode, void *start, const bool select)
1051 {
1052         BMesh *bm = em->bm;
1053         BMElem *ele;
1054         BMWalker walker;
1055
1056         BMW_init(&walker, bm, walkercode,
1057                  BMW_MASK_NOP, BMW_MASK_NOP, BMW_MASK_NOP,
1058                  BMW_FLAG_TEST_HIDDEN,
1059                  BMW_NIL_LAY);
1060
1061         for (ele = BMW_begin(&walker, start); ele; ele = BMW_step(&walker)) {
1062                 if (!select) {
1063                         BM_select_history_remove(bm, ele);
1064                 }
1065                 BM_elem_select_set(bm, ele, select);
1066         }
1067         BMW_end(&walker);
1068 }
1069
1070 static int edbm_loop_multiselect_exec(bContext *C, wmOperator *op)
1071 {
1072         Object *obedit = CTX_data_edit_object(C);
1073         BMEditMesh *em = BKE_editmesh_from_object(obedit);
1074         BMEdge *eed;
1075         BMEdge **edarray;
1076         int edindex;
1077         const bool is_ring = RNA_boolean_get(op->ptr, "ring");
1078         
1079         BMIter iter;
1080         int totedgesel = 0;
1081
1082         BM_ITER_MESH (eed, &iter, em->bm, BM_EDGES_OF_MESH) {
1083                 if (BM_elem_flag_test(eed, BM_ELEM_SELECT)) {
1084                         totedgesel++;
1085                 }
1086         }
1087         
1088         edarray = MEM_mallocN(sizeof(BMEdge *) * totedgesel, "edge array");
1089         edindex = 0;
1090         
1091         BM_ITER_MESH (eed, &iter, em->bm, BM_EDGES_OF_MESH) {
1092                 if (BM_elem_flag_test(eed, BM_ELEM_SELECT)) {
1093                         edarray[edindex] = eed;
1094                         edindex++;
1095                 }
1096         }
1097         
1098         if (is_ring) {
1099                 for (edindex = 0; edindex < totedgesel; edindex += 1) {
1100                         eed = edarray[edindex];
1101                         walker_select(em, BMW_EDGERING, eed, true);
1102                 }
1103                 EDBM_selectmode_flush(em);
1104         }
1105         else {
1106                 for (edindex = 0; edindex < totedgesel; edindex += 1) {
1107                         eed = edarray[edindex];
1108                         walker_select(em, BMW_LOOP, eed, true);
1109                 }
1110                 EDBM_selectmode_flush(em);
1111         }
1112         MEM_freeN(edarray);
1113 //      if (EM_texFaceCheck())
1114         
1115         WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit);
1116
1117         return OPERATOR_FINISHED;
1118 }
1119
1120 void MESH_OT_loop_multi_select(wmOperatorType *ot)
1121 {
1122         /* identifiers */
1123         ot->name = "Multi Select Loops";
1124         ot->idname = "MESH_OT_loop_multi_select";
1125         ot->description = "Select a loop of connected edges by connection type";
1126         
1127         /* api callbacks */
1128         ot->exec = edbm_loop_multiselect_exec;
1129         ot->poll = ED_operator_editmesh;
1130         
1131         /* flags */
1132         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1133         
1134         /* properties */
1135         RNA_def_boolean(ot->srna, "ring", 0, "Ring", "");
1136 }
1137
1138                 
1139 /* ***************** MAIN MOUSE SELECTION ************** */
1140
1141
1142 /* ***************** loop select (non modal) ************** */
1143
1144 static void mouse_mesh_loop(bContext *C, const int mval[2], bool extend, bool deselect, bool toggle, bool ring)
1145 {
1146         ViewContext vc;
1147         BMEditMesh *em;
1148         BMEdge *eed;
1149         bool select = true;
1150         float dist = 50.0f;
1151         float mvalf[2];
1152
1153         em_setup_viewcontext(C, &vc);
1154         mvalf[0] = (float)(vc.mval[0] = mval[0]);
1155         mvalf[1] = (float)(vc.mval[1] = mval[1]);
1156         em = vc.em;
1157
1158         /* no afterqueue (yet), so we check it now, otherwise the bm_xxxofs indices are bad */
1159         view3d_validate_backbuf(&vc);
1160
1161         eed = EDBM_edge_find_nearest(&vc, &dist);
1162         if (eed) {
1163                 if (extend == false && deselect == false && toggle == false) {
1164                         EDBM_flag_disable_all(em, BM_ELEM_SELECT);
1165                 }
1166         
1167                 if (extend) {
1168                         select = true;
1169                 }
1170                 else if (deselect) {
1171                         select = false;
1172                 }
1173                 else if (BM_elem_flag_test(eed, BM_ELEM_SELECT) == 0) {
1174                         select = true;
1175                 }
1176                 else if (toggle) {
1177                         select = false;
1178                 }
1179
1180                 if (em->selectmode & SCE_SELECT_FACE) {
1181                         walker_select(em, BMW_FACELOOP, eed, select);
1182                 }
1183                 else if (em->selectmode & SCE_SELECT_EDGE) {
1184                         if (ring)
1185                                 walker_select(em, BMW_EDGERING, eed, select);
1186                         else
1187                                 walker_select(em, BMW_LOOP, eed, select);
1188                 }
1189                 else if (em->selectmode & SCE_SELECT_VERTEX) {
1190                         if (ring)
1191                                 walker_select(em, BMW_EDGERING, eed, select);
1192
1193                         else
1194                                 walker_select(em, BMW_LOOP, eed, select);
1195                 }
1196
1197                 EDBM_selectmode_flush(em);
1198
1199                 /* sets as active, useful for other tools */
1200                 if (select) {
1201                         if (em->selectmode & SCE_SELECT_VERTEX) {
1202                                 /* Find nearest vert from mouse
1203                                  * (initialize to large values incase only one vertex can be projected) */
1204                                 float v1_co[2], v2_co[2];
1205                                 float length_1 = FLT_MAX;
1206                                 float length_2 = FLT_MAX;
1207
1208                                 /* We can't be sure this has already been set... */
1209                                 ED_view3d_init_mats_rv3d(vc.obedit, vc.rv3d);
1210
1211                                 if (ED_view3d_project_float_object(vc.ar, eed->v1->co, v1_co, V3D_PROJ_TEST_CLIP_NEAR) == V3D_PROJ_RET_OK) {
1212                                         length_1 = len_squared_v2v2(mvalf, v1_co);
1213                                 }
1214
1215                                 if (ED_view3d_project_float_object(vc.ar, eed->v2->co, v2_co, V3D_PROJ_TEST_CLIP_NEAR) == V3D_PROJ_RET_OK) {
1216                                         length_2 = len_squared_v2v2(mvalf, v2_co);
1217                                 }
1218 #if 0
1219                                 printf("mouse to v1: %f\nmouse to v2: %f\n", len_squared_v2v2(mvalf, v1_co),
1220                                        len_squared_v2v2(mvalf, v2_co));
1221 #endif
1222                                 BM_select_history_store(em->bm, (length_1 < length_2) ? eed->v1 : eed->v2);
1223                         }
1224                         else if (em->selectmode & SCE_SELECT_EDGE) {
1225                                 BM_select_history_store(em->bm, eed);
1226                         }
1227                         else if (em->selectmode & SCE_SELECT_FACE) {
1228                                 /* Select the face of eed which is the nearest of mouse. */
1229                                 BMFace *f, *efa = NULL;
1230                                 BMIter iterf;
1231                                 float best_dist = FLT_MAX;
1232
1233                                 /* We can't be sure this has already been set... */
1234                                 ED_view3d_init_mats_rv3d(vc.obedit, vc.rv3d);
1235
1236                                 BM_ITER_ELEM(f, &iterf, eed, BM_FACES_OF_EDGE) {
1237                                         if (BM_elem_flag_test(f, BM_ELEM_SELECT)) {
1238                                                 float cent[3];
1239                                                 float co[2], tdist;
1240
1241                                                 BM_face_calc_center_mean(f, cent);
1242                                                 if (ED_view3d_project_float_object(vc.ar, cent, co, V3D_PROJ_TEST_CLIP_NEAR) == V3D_PROJ_RET_OK) {
1243                                                         tdist = len_squared_v2v2(mvalf, co);
1244                                                         if (tdist < best_dist) {
1245 /*                                                              printf("Best face: %p (%f)\n", f, tdist);*/
1246                                                                 best_dist = tdist;
1247                                                                 efa = f;
1248                                                         }
1249                                                 }
1250                                         }
1251                                 }
1252                                 if (efa) {
1253                                         BM_mesh_active_face_set(em->bm, efa);
1254                                         BM_select_history_store(em->bm, efa);
1255                                 }
1256                         }
1257                 }
1258
1259                 WM_event_add_notifier(C, NC_GEOM | ND_SELECT, vc.obedit);
1260         }
1261 }
1262
1263 static int edbm_select_loop_invoke(bContext *C, wmOperator *op, const wmEvent *event)
1264 {
1265         
1266         view3d_operator_needs_opengl(C);
1267         
1268         mouse_mesh_loop(C, event->mval,
1269                         RNA_boolean_get(op->ptr, "extend"),
1270                         RNA_boolean_get(op->ptr, "deselect"),
1271                         RNA_boolean_get(op->ptr, "toggle"),
1272                         RNA_boolean_get(op->ptr, "ring"));
1273         
1274         /* cannot do tweaks for as long this keymap is after transform map */
1275         return OPERATOR_FINISHED;
1276 }
1277
1278 void MESH_OT_loop_select(wmOperatorType *ot)
1279 {
1280         /* identifiers */
1281         ot->name = "Loop Select";
1282         ot->idname = "MESH_OT_loop_select";
1283         ot->description = "Select a loop of connected edges";
1284         
1285         /* api callbacks */
1286         ot->invoke = edbm_select_loop_invoke;
1287         ot->poll = ED_operator_editmesh_region_view3d;
1288         
1289         /* flags */
1290         ot->flag = OPTYPE_UNDO;
1291         
1292         /* properties */
1293         RNA_def_boolean(ot->srna, "extend", 0, "Extend Select", "Extend the selection");
1294         RNA_def_boolean(ot->srna, "deselect", 0, "Deselect", "Remove from the selection");
1295         RNA_def_boolean(ot->srna, "toggle", 0, "Toggle Select", "Toggle the selection");
1296         RNA_def_boolean(ot->srna, "ring", 0, "Select Ring", "Select ring");
1297 }
1298
1299 void MESH_OT_edgering_select(wmOperatorType *ot)
1300 {
1301         /* description */
1302         ot->name = "Edge Ring Select";
1303         ot->idname = "MESH_OT_edgering_select";
1304         ot->description = "Select an edge ring";
1305         
1306         /* callbacks */
1307         ot->invoke = edbm_select_loop_invoke;
1308         ot->poll = ED_operator_editmesh_region_view3d;
1309         
1310         /* flags */
1311         ot->flag = OPTYPE_UNDO;
1312
1313         RNA_def_boolean(ot->srna, "extend", 0, "Extend", "Extend the selection");
1314         RNA_def_boolean(ot->srna, "deselect", 0, "Deselect", "Remove from the selection");
1315         RNA_def_boolean(ot->srna, "toggle", 0, "Toggle Select", "Toggle the selection");
1316         RNA_def_boolean(ot->srna, "ring", 1, "Select Ring", "Select ring");
1317 }
1318
1319 /* ******************** (de)select all operator **************** */
1320 static int edbm_select_all_exec(bContext *C, wmOperator *op)
1321 {
1322         Object *obedit = CTX_data_edit_object(C);
1323         BMEditMesh *em = BKE_editmesh_from_object(obedit);
1324         const int action = RNA_enum_get(op->ptr, "action");
1325
1326         switch (action) {
1327                 case SEL_TOGGLE:
1328                         EDBM_select_toggle_all(em);
1329                         break;
1330                 case SEL_SELECT:
1331                         EDBM_flag_enable_all(em, BM_ELEM_SELECT);
1332                         break;
1333                 case SEL_DESELECT:
1334                         EDBM_flag_disable_all(em, BM_ELEM_SELECT);
1335                         break;
1336                 case SEL_INVERT:
1337                         EDBM_select_swap(em);
1338                         EDBM_selectmode_flush(em);
1339                         break;
1340         }
1341
1342         WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit);
1343
1344         return OPERATOR_FINISHED;
1345 }
1346
1347 void MESH_OT_select_all(wmOperatorType *ot)
1348 {
1349         /* identifiers */
1350         ot->name = "(De)select All";
1351         ot->idname = "MESH_OT_select_all";
1352         ot->description = "(De)select all vertices, edges or faces";
1353
1354         /* api callbacks */
1355         ot->exec = edbm_select_all_exec;
1356         ot->poll = ED_operator_editmesh;
1357
1358         /* flags */
1359         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1360
1361         WM_operator_properties_select_all(ot);
1362 }
1363
1364 static int edbm_faces_select_interior_exec(bContext *C, wmOperator *UNUSED(op))
1365 {
1366         Object *obedit = CTX_data_edit_object(C);
1367         BMEditMesh *em = BKE_editmesh_from_object(obedit);
1368
1369         if (EDBM_select_interior_faces(em)) {
1370                 WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit);
1371
1372                 return OPERATOR_FINISHED;
1373         }
1374         else {
1375                 return OPERATOR_CANCELLED;
1376         }
1377
1378 }
1379
1380 void MESH_OT_select_interior_faces(wmOperatorType *ot)
1381 {
1382         /* identifiers */
1383         ot->name = "Select Interior Faces";
1384         ot->idname = "MESH_OT_select_interior_faces";
1385         ot->description = "Select faces where all edges have more than 2 face users";
1386
1387         /* api callbacks */
1388         ot->exec = edbm_faces_select_interior_exec;
1389         ot->poll = ED_operator_editmesh;
1390
1391         /* flags */
1392         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1393 }
1394
1395
1396 /* ************************************************** */
1397 /* here actual select happens */
1398 /* gets called via generic mouse select operator */
1399 bool EDBM_select_pick(bContext *C, const int mval[2], bool extend, bool deselect, bool toggle)
1400 {
1401         ViewContext vc;
1402         BMVert *eve = NULL;
1403         BMEdge *eed = NULL;
1404         BMFace *efa = NULL;
1405
1406         /* setup view context for argument to callbacks */
1407         em_setup_viewcontext(C, &vc);
1408         vc.mval[0] = mval[0];
1409         vc.mval[1] = mval[1];
1410
1411         if (unified_findnearest(&vc, &eve, &eed, &efa)) {
1412
1413                 /* Deselect everything */
1414                 if (extend == false && deselect == false && toggle == false)
1415                         EDBM_flag_disable_all(vc.em, BM_ELEM_SELECT);
1416
1417                 if (efa) {
1418                         if (extend) {
1419                                 /* set the last selected face */
1420                                 BM_mesh_active_face_set(vc.em->bm, efa);
1421
1422                                 /* Work-around: deselect first, so we can guarantee it will */
1423                                 /* be active even if it was already selected */
1424                                 BM_select_history_remove(vc.em->bm, efa);
1425                                 BM_face_select_set(vc.em->bm, efa, false);
1426                                 BM_select_history_store(vc.em->bm, efa);
1427                                 BM_face_select_set(vc.em->bm, efa, true);
1428                         }
1429                         else if (deselect) {
1430                                 BM_select_history_remove(vc.em->bm, efa);
1431                                 BM_face_select_set(vc.em->bm, efa, false);
1432                         }
1433                         else {
1434                                 /* set the last selected face */
1435                                 BM_mesh_active_face_set(vc.em->bm, efa);
1436
1437                                 if (!BM_elem_flag_test(efa, BM_ELEM_SELECT)) {
1438                                         BM_select_history_store(vc.em->bm, efa);
1439                                         BM_face_select_set(vc.em->bm, efa, true);
1440                                 }
1441                                 else if (toggle) {
1442                                         BM_select_history_remove(vc.em->bm, efa);
1443                                         BM_face_select_set(vc.em->bm, efa, false);
1444                                 }
1445                         }
1446                 }
1447                 else if (eed) {
1448                         if (extend) {
1449                                 /* Work-around: deselect first, so we can guarantee it will */
1450                                 /* be active even if it was already selected */
1451                                 BM_select_history_remove(vc.em->bm, eed);
1452                                 BM_edge_select_set(vc.em->bm, eed, false);
1453                                 BM_select_history_store(vc.em->bm, eed);
1454                                 BM_edge_select_set(vc.em->bm, eed, true);
1455                         }
1456                         else if (deselect) {
1457                                 BM_select_history_remove(vc.em->bm, eed);
1458                                 BM_edge_select_set(vc.em->bm, eed, false);
1459                         }
1460                         else {
1461                                 if (!BM_elem_flag_test(eed, BM_ELEM_SELECT)) {
1462                                         BM_select_history_store(vc.em->bm, eed);
1463                                         BM_edge_select_set(vc.em->bm, eed, true);
1464                                 }
1465                                 else if (toggle) {
1466                                         BM_select_history_remove(vc.em->bm, eed);
1467                                         BM_edge_select_set(vc.em->bm, eed, false);
1468                                 }
1469                         }
1470                 }
1471                 else if (eve) {
1472                         if (extend) {
1473                                 /* Work-around: deselect first, so we can guarantee it will */
1474                                 /* be active even if it was already selected */
1475                                 BM_select_history_remove(vc.em->bm, eve);
1476                                 BM_vert_select_set(vc.em->bm, eve, false);
1477                                 BM_select_history_store(vc.em->bm, eve);
1478                                 BM_vert_select_set(vc.em->bm, eve, true);
1479                         }
1480                         else if (deselect) {
1481                                 BM_select_history_remove(vc.em->bm, eve);
1482                                 BM_vert_select_set(vc.em->bm, eve, false);
1483                         }
1484                         else {
1485                                 if (!BM_elem_flag_test(eve, BM_ELEM_SELECT)) {
1486                                         BM_select_history_store(vc.em->bm, eve);
1487                                         BM_vert_select_set(vc.em->bm, eve, true);
1488                                 }
1489                                 else if (toggle) {
1490                                         BM_select_history_remove(vc.em->bm, eve);
1491                                         BM_vert_select_set(vc.em->bm, eve, false);
1492                                 }
1493                         }
1494                 }
1495
1496                 EDBM_selectmode_flush(vc.em);
1497
1498                 /* change active material on object */
1499                 if (efa && efa->mat_nr != vc.obedit->actcol - 1) {
1500                         vc.obedit->actcol = efa->mat_nr + 1;
1501                         vc.em->mat_nr = efa->mat_nr;
1502
1503                         WM_event_add_notifier(C, NC_MATERIAL | ND_SHADING_LINKS, NULL);
1504
1505                 }
1506
1507                 WM_event_add_notifier(C, NC_GEOM | ND_SELECT, vc.obedit);
1508                 return true;
1509         }
1510
1511         return false;
1512 }
1513
1514 static void edbm_strip_selections(BMEditMesh *em)
1515 {
1516         BMEditSelection *ese, *nextese;
1517
1518         if (!(em->selectmode & SCE_SELECT_VERTEX)) {
1519                 ese = em->bm->selected.first;
1520                 while (ese) {
1521                         nextese = ese->next;
1522                         if (ese->htype == BM_VERT) BLI_freelinkN(&(em->bm->selected), ese);
1523                         ese = nextese;
1524                 }
1525         }
1526         if (!(em->selectmode & SCE_SELECT_EDGE)) {
1527                 ese = em->bm->selected.first;
1528                 while (ese) {
1529                         nextese = ese->next;
1530                         if (ese->htype == BM_EDGE) BLI_freelinkN(&(em->bm->selected), ese);
1531                         ese = nextese;
1532                 }
1533         }
1534         if (!(em->selectmode & SCE_SELECT_FACE)) {
1535                 ese = em->bm->selected.first;
1536                 while (ese) {
1537                         nextese = ese->next;
1538                         if (ese->htype == BM_FACE) BLI_freelinkN(&(em->bm->selected), ese);
1539                         ese = nextese;
1540                 }
1541         }
1542 }
1543
1544 /* when switching select mode, makes sure selection is consistent for editing */
1545 /* also for paranoia checks to make sure edge or face mode works */
1546 void EDBM_selectmode_set(BMEditMesh *em)
1547 {
1548         BMVert *eve;
1549         BMEdge *eed;
1550         BMFace *efa;
1551         BMIter iter;
1552         
1553         em->bm->selectmode = em->selectmode;
1554
1555         edbm_strip_selections(em); /* strip BMEditSelections from em->selected that are not relevant to new mode */
1556         
1557         if (em->bm->totvertsel == 0 &&
1558             em->bm->totedgesel == 0 &&
1559             em->bm->totfacesel == 0)
1560         {
1561                 return;
1562         }
1563
1564         if (em->selectmode & SCE_SELECT_VERTEX) {
1565                 if (em->bm->totvertsel) {
1566                         EDBM_select_flush(em);
1567                 }
1568         }
1569         else if (em->selectmode & SCE_SELECT_EDGE) {
1570                 /* deselect vertices, and select again based on edge select */
1571                 BM_ITER_MESH (eve, &iter, em->bm, BM_VERTS_OF_MESH) {
1572                         BM_vert_select_set(em->bm, eve, false);
1573                 }
1574
1575                 if (em->bm->totedgesel) {
1576                         BM_ITER_MESH (eed, &iter, em->bm, BM_EDGES_OF_MESH) {
1577                                 if (BM_elem_flag_test(eed, BM_ELEM_SELECT)) {
1578                                         BM_edge_select_set(em->bm, eed, true);
1579                                 }
1580                         }
1581
1582                         /* selects faces based on edge status */
1583                         EDBM_selectmode_flush(em);
1584                 }
1585         }
1586         else if (em->selectmode & SCE_SELECT_FACE) {
1587                 /* deselect eges, and select again based on face select */
1588                 BM_ITER_MESH (eed, &iter, em->bm, BM_EDGES_OF_MESH) {
1589                         BM_edge_select_set(em->bm, eed, false);
1590                 }
1591
1592                 if (em->bm->totfacesel) {
1593                         efa = BM_iter_new(&iter, em->bm, BM_FACES_OF_MESH, NULL);
1594                         for (; efa; efa = BM_iter_step(&iter)) {
1595                                 if (BM_elem_flag_test(efa, BM_ELEM_SELECT)) {
1596                                         BM_face_select_set(em->bm, efa, true);
1597                                 }
1598                         }
1599                 }
1600         }
1601 }
1602
1603 /**
1604  * Flush the selection up:
1605  * - vert -> edge
1606  * - edge -> face
1607  */
1608 void EDBM_selectmode_convert(BMEditMesh *em, const short selectmode_old, const short selectmode_new)
1609 {
1610         BMEdge *eed;
1611         BMFace *efa;
1612         BMIter iter;
1613
1614         /* first tag-to-select, then select --- this avoids a feedback loop */
1615
1616         /* have to find out what the selectionmode was previously */
1617         if (selectmode_old == SCE_SELECT_VERTEX) {
1618                 if (em->bm->totvertsel == 0) {
1619                         /* pass */
1620                 }
1621                 else if (selectmode_new == SCE_SELECT_EDGE) {
1622                         /* select all edges associated with every selected vert */
1623                         BM_ITER_MESH (eed, &iter, em->bm, BM_EDGES_OF_MESH) {
1624                                 BM_elem_flag_set(eed, BM_ELEM_TAG, BM_edge_is_any_vert_flag_test(eed, BM_ELEM_SELECT));
1625                         }
1626
1627                         BM_ITER_MESH (eed, &iter, em->bm, BM_EDGES_OF_MESH) {
1628                                 if (BM_elem_flag_test(eed, BM_ELEM_TAG)) {
1629                                         BM_edge_select_set(em->bm, eed, true);
1630                                 }
1631                         }
1632                 }
1633                 else if (selectmode_new == SCE_SELECT_FACE) {
1634                         /* select all faces associated with every selected vert */
1635                         BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) {
1636                                 BM_elem_flag_set(efa, BM_ELEM_TAG, BM_face_is_any_vert_flag_test(efa, BM_ELEM_SELECT));
1637                         }
1638
1639                         BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) {
1640                                 if (BM_elem_flag_test(efa, BM_ELEM_TAG)) {
1641                                         BM_face_select_set(em->bm, efa, true);
1642                                 }
1643                         }
1644                 }
1645         }
1646         else if (selectmode_old == SCE_SELECT_EDGE) {
1647                 if (em->bm->totedgesel == 0) {
1648                         /* pass */
1649                 }
1650                 else if (selectmode_new == SCE_SELECT_FACE) {
1651                         /* select all faces associated with every selected edge */
1652                         BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) {
1653                                 BM_elem_flag_set(efa, BM_ELEM_TAG, BM_face_is_any_edge_flag_test(efa, BM_ELEM_SELECT));
1654                         }
1655
1656                         BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) {
1657                                 if (BM_elem_flag_test(efa, BM_ELEM_TAG)) {
1658                                         BM_face_select_set(em->bm, efa, true);
1659                                 }
1660                         }
1661                 }
1662         }
1663 }
1664
1665 /* user facing function, does notification and undo push */
1666 bool EDBM_selectmode_toggle(bContext *C, const short selectmode_new,
1667                             const int action, const bool use_extend, const bool use_expand)
1668 {
1669         ToolSettings *ts = CTX_data_tool_settings(C);
1670         Object *obedit = CTX_data_edit_object(C);
1671         BMEditMesh *em = NULL;
1672         bool ret = false;
1673
1674         if (obedit && obedit->type == OB_MESH) {
1675                 em = BKE_editmesh_from_object(obedit);
1676         }
1677
1678         if (em == NULL) {
1679                 return ret;
1680         }
1681
1682         switch (action) {
1683                 case -1:
1684                         /* already set */
1685                         break;
1686                 case 0:  /* disable */
1687                         /* check we have something to do */
1688                         if ((em->selectmode & selectmode_new) == 0) {
1689                                 return false;
1690                         }
1691                         em->selectmode &= ~selectmode_new;
1692                         break;
1693                 case 1:  /* enable */
1694                         /* check we have something to do */
1695                         if ((em->selectmode & selectmode_new) != 0) {
1696                                 return false;
1697                         }
1698                         em->selectmode |= selectmode_new;
1699                         break;
1700                 case 2:  /* toggle */
1701                         /* can't disable this flag if its the only one set */
1702                         if (em->selectmode == selectmode_new) {
1703                                 return false;
1704                         }
1705                         em->selectmode ^= selectmode_new;
1706                         break;
1707                 default:
1708                         BLI_assert(0);
1709         }
1710
1711         switch (selectmode_new) {
1712                 case SCE_SELECT_VERTEX:
1713                         if (use_extend == 0 || em->selectmode == 0)
1714                                 em->selectmode = SCE_SELECT_VERTEX;
1715                         ts->selectmode = em->selectmode;
1716                         EDBM_selectmode_set(em);
1717                         ret = true;
1718                         break;
1719                 case SCE_SELECT_EDGE:
1720                         if (use_extend == 0 || em->selectmode == 0) {
1721                                 if (use_expand) {
1722                                         const short selmode_max = highest_order_bit_s(ts->selectmode);
1723                                         if (selmode_max == SCE_SELECT_VERTEX) {
1724                                                 EDBM_selectmode_convert(em, selmode_max, SCE_SELECT_EDGE);
1725                                         }
1726                                 }
1727                                 em->selectmode = SCE_SELECT_EDGE;
1728                         }
1729                         ts->selectmode = em->selectmode;
1730                         EDBM_selectmode_set(em);
1731                         ret = true;
1732                         break;
1733                 case SCE_SELECT_FACE:
1734                         if (use_extend == 0 || em->selectmode == 0) {
1735                                 if (use_expand) {
1736                                         const short selmode_max = highest_order_bit_s(ts->selectmode);
1737                                         if (ELEM(selmode_max, SCE_SELECT_VERTEX, SCE_SELECT_EDGE)) {
1738                                                 EDBM_selectmode_convert(em, selmode_max, SCE_SELECT_FACE);
1739                                         }
1740                                 }
1741
1742                                 em->selectmode = SCE_SELECT_FACE;
1743                         }
1744                         ts->selectmode = em->selectmode;
1745                         EDBM_selectmode_set(em);
1746                         ret = true;
1747                         break;
1748                 default:
1749                         BLI_assert(0);
1750                         break;
1751         }
1752
1753         if (ret == true) {
1754                 WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit->data);
1755                 WM_main_add_notifier(NC_SCENE | ND_TOOLSETTINGS, NULL);
1756         }
1757
1758         return ret;
1759 }
1760
1761 /**
1762  * Use to disable a selectmode if its enabled, Using another mode as a fallback
1763  * if the disabled mode is the only mode set.
1764  *
1765  * \return true if the mode is changed.
1766  */
1767 bool EDBM_selectmode_disable(Scene *scene, BMEditMesh *em,
1768                              const short selectmode_disable,
1769                              const short selectmode_fallback)
1770 {
1771         /* note essential, but switch out of vertex mode since the
1772          * selected regions wont be nicely isolated after flushing */
1773         if (em->selectmode & selectmode_disable) {
1774                 if (em->selectmode == selectmode_disable) {
1775                         em->selectmode = selectmode_fallback;
1776                 }
1777                 else {
1778                         em->selectmode &= ~selectmode_disable;
1779                 }
1780                 scene->toolsettings->selectmode = em->selectmode;
1781                 EDBM_selectmode_set(em);
1782
1783                 WM_main_add_notifier(NC_SCENE | ND_TOOLSETTINGS, scene);
1784
1785                 return true;
1786         }
1787         else {
1788                 return false;
1789         }
1790 }
1791
1792 void EDBM_deselect_by_material(BMEditMesh *em, const short index, const short select)
1793 {
1794         BMIter iter;
1795         BMFace *efa;
1796
1797         BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) {
1798                 if (BM_elem_flag_test(efa, BM_ELEM_HIDDEN))
1799                         continue;
1800                 if (efa->mat_nr == index) {
1801                         BM_face_select_set(em->bm, efa, select);
1802                 }
1803         }
1804 }
1805
1806 void EDBM_select_toggle_all(BMEditMesh *em) /* exported for UV */
1807 {
1808         if (em->bm->totvertsel || em->bm->totedgesel || em->bm->totfacesel)
1809                 EDBM_flag_disable_all(em, BM_ELEM_SELECT);
1810         else
1811                 EDBM_flag_enable_all(em, BM_ELEM_SELECT);
1812 }
1813
1814 void EDBM_select_swap(BMEditMesh *em) /* exported for UV */
1815 {
1816         BMIter iter;
1817         BMVert *eve;
1818         BMEdge *eed;
1819         BMFace *efa;
1820         
1821         if (em->bm->selectmode & SCE_SELECT_VERTEX) {
1822                 BM_ITER_MESH (eve, &iter, em->bm, BM_VERTS_OF_MESH) {
1823                         if (BM_elem_flag_test(eve, BM_ELEM_HIDDEN))
1824                                 continue;
1825                         BM_vert_select_set(em->bm, eve, !BM_elem_flag_test(eve, BM_ELEM_SELECT));
1826                 }
1827         }
1828         else if (em->selectmode & SCE_SELECT_EDGE) {
1829                 BM_ITER_MESH (eed, &iter, em->bm, BM_EDGES_OF_MESH) {
1830                         if (BM_elem_flag_test(eed, BM_ELEM_HIDDEN))
1831                                 continue;
1832                         BM_edge_select_set(em->bm, eed, !BM_elem_flag_test(eed, BM_ELEM_SELECT));
1833                 }
1834         }
1835         else {
1836                 BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) {
1837                         if (BM_elem_flag_test(efa, BM_ELEM_HIDDEN))
1838                                 continue;
1839                         BM_face_select_set(em->bm, efa, !BM_elem_flag_test(efa, BM_ELEM_SELECT));
1840                 }
1841
1842         }
1843 //      if (EM_texFaceCheck())
1844 }
1845
1846 bool EDBM_select_interior_faces(BMEditMesh *em)
1847 {
1848         BMesh *bm = em->bm;
1849         BMIter iter;
1850         BMIter eiter;
1851         BMFace *efa;
1852         BMEdge *eed;
1853         bool ok;
1854         bool change = false;
1855
1856         BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) {
1857                 if (BM_elem_flag_test(efa, BM_ELEM_HIDDEN))
1858                         continue;
1859
1860
1861                 ok = true;
1862                 BM_ITER_ELEM (eed, &eiter, efa, BM_EDGES_OF_FACE) {
1863                         if (BM_edge_face_count(eed) < 3) {
1864                                 ok = false;
1865                                 break;
1866                         }
1867                 }
1868
1869                 if (ok) {
1870                         BM_face_select_set(bm, efa, true);
1871                         change = true;
1872                 }
1873         }
1874
1875         return change;
1876 }
1877
1878
1879 /************************ Select Linked Operator *************************/
1880
1881 static void linked_limit_default(bContext *C, wmOperator *op)
1882 {
1883         if (!RNA_struct_property_is_set(op->ptr, "limit")) {
1884                 Object *obedit = CTX_data_edit_object(C);
1885                 BMEditMesh *em = BKE_editmesh_from_object(obedit);
1886                 if (em->selectmode == SCE_SELECT_FACE)
1887                         RNA_boolean_set(op->ptr, "limit", true);
1888                 else
1889                         RNA_boolean_set(op->ptr, "limit", false);
1890         }
1891 }
1892
1893 static int edbm_select_linked_exec(bContext *C, wmOperator *op)
1894 {
1895         Object *obedit = CTX_data_edit_object(C);
1896         BMEditMesh *em = BKE_editmesh_from_object(obedit);
1897         BMesh *bm = em->bm;
1898         BMIter iter;
1899         BMVert *v;
1900         BMEdge *e;
1901         BMWalker walker;
1902
1903         int limit;
1904
1905         linked_limit_default(C, op);
1906
1907         limit = RNA_boolean_get(op->ptr, "limit");
1908
1909         if (em->selectmode == SCE_SELECT_FACE) {
1910                 BMFace *efa;
1911
1912                 BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) {
1913                         BM_elem_flag_set(efa, BM_ELEM_TAG, (BM_elem_flag_test(efa, BM_ELEM_SELECT) &&
1914                                                             !BM_elem_flag_test(efa, BM_ELEM_HIDDEN)));
1915                 }
1916
1917                 if (limit) {
1918                         /* grr, shouldn't need to alloc BMO flags here */
1919                         BM_mesh_elem_toolflags_ensure(bm);
1920                         BM_ITER_MESH (e, &iter, bm, BM_EDGES_OF_MESH) {
1921                                 BMO_elem_flag_set(bm, e, BMO_ELE_TAG, !BM_elem_flag_test(e, BM_ELEM_SEAM));
1922                         }
1923                 }
1924
1925                 BMW_init(&walker, bm, BMW_ISLAND,
1926                          BMW_MASK_NOP, limit ? BMO_ELE_TAG : BMW_MASK_NOP, BMW_MASK_NOP,
1927                          BMW_FLAG_TEST_HIDDEN,
1928                          BMW_NIL_LAY);
1929
1930                 BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) {
1931                         if (BM_elem_flag_test(efa, BM_ELEM_TAG)) {
1932                                 for (efa = BMW_begin(&walker, efa); efa; efa = BMW_step(&walker)) {
1933                                         BM_face_select_set(bm, efa, true);
1934                                 }
1935                         }
1936                 }
1937                 BMW_end(&walker);
1938
1939                 if (limit) {
1940                         BM_mesh_elem_toolflags_clear(bm);
1941                 }
1942         }
1943         else {
1944                 BM_ITER_MESH (v, &iter, em->bm, BM_VERTS_OF_MESH) {
1945                         if (BM_elem_flag_test(v, BM_ELEM_SELECT)) {
1946                                 BM_elem_flag_enable(v, BM_ELEM_TAG);
1947                         }
1948                         else {
1949                                 BM_elem_flag_disable(v, BM_ELEM_TAG);
1950                         }
1951                 }
1952
1953                 BMW_init(&walker, em->bm, BMW_SHELL,
1954                          BMW_MASK_NOP, BMW_MASK_NOP, BMW_MASK_NOP,
1955                          BMW_FLAG_TEST_HIDDEN,
1956                          BMW_NIL_LAY);
1957
1958                 BM_ITER_MESH (v, &iter, em->bm, BM_VERTS_OF_MESH) {
1959                         if (BM_elem_flag_test(v, BM_ELEM_TAG)) {
1960                                 for (e = BMW_begin(&walker, v); e; e = BMW_step(&walker)) {
1961                                         BM_edge_select_set(em->bm, e, true);
1962                                 }
1963                         }
1964                 }
1965                 BMW_end(&walker);
1966
1967                 EDBM_selectmode_flush(em);
1968         }
1969
1970         WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit);
1971
1972         return OPERATOR_FINISHED;
1973 }
1974
1975 void MESH_OT_select_linked(wmOperatorType *ot)
1976 {
1977         /* identifiers */
1978         ot->name = "Select Linked All";
1979         ot->idname = "MESH_OT_select_linked";
1980         ot->description = "Select all vertices linked to the active mesh";
1981
1982         /* api callbacks */
1983         ot->exec = edbm_select_linked_exec;
1984         ot->poll = ED_operator_editmesh;
1985
1986         /* flags */
1987         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1988
1989         RNA_def_boolean(ot->srna, "limit", 0, "Limit by Seams", "");
1990 }
1991
1992 static int edbm_select_linked_pick_invoke(bContext *C, wmOperator *op, const wmEvent *event)
1993 {
1994         Object *obedit = CTX_data_edit_object(C);
1995         ViewContext vc;
1996         BMesh *bm;
1997         BMWalker walker;
1998         BMEditMesh *em;
1999         BMVert *eve;
2000         BMEdge *e, *eed;
2001         BMFace *efa;
2002         int sel = !RNA_boolean_get(op->ptr, "deselect");
2003
2004         int limit;
2005
2006         linked_limit_default(C, op);
2007
2008         limit = RNA_boolean_get(op->ptr, "limit");
2009
2010         /* unified_finednearest needs ogl */
2011         view3d_operator_needs_opengl(C);
2012         
2013         /* setup view context for argument to callbacks */
2014         em_setup_viewcontext(C, &vc);
2015         em = vc.em;
2016
2017         if (em->bm->totedge == 0)
2018                 return OPERATOR_CANCELLED;
2019         
2020         bm = em->bm;
2021
2022         vc.mval[0] = event->mval[0];
2023         vc.mval[1] = event->mval[1];
2024         
2025         /* return warning! */
2026         
2027         if (unified_findnearest(&vc, &eve, &eed, &efa) == 0) {
2028                 WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit);
2029         
2030                 return OPERATOR_CANCELLED;
2031         }
2032         
2033         if (em->selectmode == SCE_SELECT_FACE) {
2034                 BMIter iter;
2035
2036                 if (efa == NULL)
2037                         return OPERATOR_CANCELLED;
2038
2039                 if (limit) {
2040                         /* grr, shouldn't need to alloc BMO flags here */
2041                         BM_mesh_elem_toolflags_ensure(bm);
2042                         /* hflag no-seam --> bmo-tag */
2043                         BM_ITER_MESH (e, &iter, bm, BM_EDGES_OF_MESH) {
2044                                 BMO_elem_flag_set(bm, e, BMO_ELE_TAG, !BM_elem_flag_test(e, BM_ELEM_SEAM));
2045                         }
2046                 }
2047
2048                 /* walk */
2049                 BMW_init(&walker, bm, BMW_ISLAND,
2050                          BMW_MASK_NOP, limit ? BMO_ELE_TAG : BMW_MASK_NOP, BMW_MASK_NOP,
2051                          BMW_FLAG_TEST_HIDDEN,
2052                          BMW_NIL_LAY);
2053
2054                 for (efa = BMW_begin(&walker, efa); efa; efa = BMW_step(&walker)) {
2055                         BM_face_select_set(bm, efa, sel);
2056                 }
2057                 BMW_end(&walker);
2058         }
2059         else {
2060                 if (efa) {
2061                         eed = BM_FACE_FIRST_LOOP(efa)->e;
2062                 }
2063                 else if (!eed) {
2064                         if (!eve || !eve->e)
2065                                 return OPERATOR_CANCELLED;
2066
2067                         eed = eve->e;
2068                 }
2069
2070                 BMW_init(&walker, bm, BMW_SHELL,
2071                          BMW_MASK_NOP, BMW_MASK_NOP, BMW_MASK_NOP,
2072                          BMW_FLAG_TEST_HIDDEN,
2073                          BMW_NIL_LAY);
2074
2075                 for (e = BMW_begin(&walker, eed->v1); e; e = BMW_step(&walker)) {
2076                         BM_edge_select_set(bm, e, sel);
2077                 }
2078                 BMW_end(&walker);
2079
2080                 EDBM_selectmode_flush(em);
2081         }
2082
2083         WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit);
2084
2085         return OPERATOR_FINISHED;
2086 }
2087
2088 void MESH_OT_select_linked_pick(wmOperatorType *ot)
2089 {
2090         /* identifiers */
2091         ot->name = "Select Linked";
2092         ot->idname = "MESH_OT_select_linked_pick";
2093         ot->description = "(De)select all vertices linked to the edge under the mouse cursor";
2094         
2095         /* api callbacks */
2096         ot->invoke = edbm_select_linked_pick_invoke;
2097         ot->poll = ED_operator_editmesh;
2098         
2099         /* flags */
2100         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2101         
2102         RNA_def_boolean(ot->srna, "deselect", 0, "Deselect", "");
2103         RNA_def_boolean(ot->srna, "limit", 0, "Limit by Seams", "");
2104 }
2105
2106
2107 static int edbm_select_face_by_sides_exec(bContext *C, wmOperator *op)
2108 {
2109         Object *obedit = CTX_data_edit_object(C);
2110         BMEditMesh *em = BKE_editmesh_from_object(obedit);
2111         BMFace *efa;
2112         BMIter iter;
2113         const int numverts = RNA_int_get(op->ptr, "number");
2114         const int type = RNA_enum_get(op->ptr, "type");
2115
2116         if (!RNA_boolean_get(op->ptr, "extend"))
2117                 EDBM_flag_disable_all(em, BM_ELEM_SELECT);
2118
2119         BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) {
2120
2121                 int select;
2122
2123                 switch (type) {
2124                         case 0:
2125                                 select = (efa->len < numverts);
2126                                 break;
2127                         case 1:
2128                                 select = (efa->len == numverts);
2129                                 break;
2130                         case 2:
2131                                 select = (efa->len > numverts);
2132                                 break;
2133                         case 3:
2134                                 select = (efa->len != numverts);
2135                                 break;
2136                         default:
2137                                 BLI_assert(0);
2138                                 select = false;
2139                                 break;
2140                 }
2141
2142                 if (select) {
2143                         BM_face_select_set(em->bm, efa, true);
2144                 }
2145         }
2146
2147         EDBM_selectmode_flush(em);
2148
2149         WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit->data);
2150         return OPERATOR_FINISHED;
2151 }
2152
2153 void MESH_OT_select_face_by_sides(wmOperatorType *ot)
2154 {
2155         static const EnumPropertyItem type_items[] = {
2156                 {0, "LESS", 0, "Less Than", ""},
2157                 {1, "EQUAL", 0, "Equal To", ""},
2158                 {2, "GREATER", 0, "Greater Than", ""},
2159                 {3, "NOTEQUAL", 0, "Not Equal To", ""},
2160                 {0, NULL, 0, NULL, NULL}
2161         };
2162
2163         /* identifiers */
2164         ot->name = "Select Faces by Sides";
2165         ot->description = "Select vertices or faces by the number of polygon sides";
2166         ot->idname = "MESH_OT_select_face_by_sides";
2167
2168         /* api callbacks */
2169         ot->exec = edbm_select_face_by_sides_exec;
2170         ot->poll = ED_operator_editmesh;
2171
2172         /* flags */
2173         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2174
2175         /* properties */
2176         RNA_def_int(ot->srna, "number", 4, 3, INT_MAX, "Number of Vertices", "", 3, INT_MAX);
2177         RNA_def_enum(ot->srna, "type", type_items, 1, "Type", "Type of comparison to make");
2178         RNA_def_boolean(ot->srna, "extend", true, "Extend", "Extend the selection");
2179 }
2180
2181
2182 static int edbm_select_loose_exec(bContext *C, wmOperator *op)
2183 {
2184         Object *obedit = CTX_data_edit_object(C);
2185         BMEditMesh *em = BKE_editmesh_from_object(obedit);
2186         BMesh *bm = em->bm;
2187         BMIter iter;
2188
2189         if (!RNA_boolean_get(op->ptr, "extend"))
2190                 EDBM_flag_disable_all(em, BM_ELEM_SELECT);
2191
2192         if (em->selectmode & SCE_SELECT_VERTEX) {
2193                 BMVert *eve;
2194                 BM_ITER_MESH (eve, &iter, bm, BM_VERTS_OF_MESH) {
2195                         if (!eve->e) {
2196                                 BM_vert_select_set(bm, eve, true);
2197                         }
2198                 }
2199         }
2200
2201         if (em->selectmode & SCE_SELECT_EDGE) {
2202                 BMEdge *eed;
2203                 BM_ITER_MESH (eed, &iter, bm, BM_EDGES_OF_MESH) {
2204                         if (BM_edge_is_wire(eed)) {
2205                                 BM_edge_select_set(bm, eed, true);
2206                         }
2207                 }
2208         }
2209
2210         if (em->selectmode & SCE_SELECT_FACE) {
2211                 BMFace *efa;
2212                 BM_ITER_MESH (efa, &iter, bm, BM_FACES_OF_MESH) {
2213                         BMIter liter;
2214                         BMLoop *l;
2215                         bool is_loose = true;
2216                         BM_ITER_ELEM (l, &liter, efa, BM_LOOPS_OF_FACE) {
2217                                 if (!BM_edge_is_boundary(l->e)) {
2218                                         is_loose = false;
2219                                         break;
2220                                 }
2221                         }
2222                         if (is_loose) {
2223                                 BM_face_select_set(bm, efa, true);
2224                         }
2225                 }
2226         }
2227
2228         EDBM_selectmode_flush(em);
2229
2230         WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit->data);
2231         return OPERATOR_FINISHED;
2232 }
2233
2234 void MESH_OT_select_loose(wmOperatorType *ot)
2235 {
2236         /* identifiers */
2237         ot->name = "Select Loose Geometry";
2238         ot->description = "Select loose geometry based on the selection mode";
2239         ot->idname = "MESH_OT_select_loose";
2240
2241         /* api callbacks */
2242         ot->exec = edbm_select_loose_exec;
2243         ot->poll = ED_operator_editmesh;
2244
2245         /* flags */
2246         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2247
2248         /* props */
2249         RNA_def_boolean(ot->srna, "extend", false, "Extend", "Extend the selection");
2250 }
2251
2252
2253 static int edbm_select_mirror_exec(bContext *C, wmOperator *op)
2254 {
2255         Object *obedit = CTX_data_edit_object(C);
2256         BMEditMesh *em = BKE_editmesh_from_object(obedit);
2257         bool extend = RNA_boolean_get(op->ptr, "extend");
2258
2259         if (em->bm->totvert && em->bm->totvertsel) {
2260                 int totmirr, totfail;
2261
2262                 EDBM_select_mirrored(em, extend, &totmirr, &totfail);
2263                 if (totmirr) {
2264                         EDBM_selectmode_flush(em);
2265                         WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit->data);
2266                 }
2267
2268                 ED_mesh_report_mirror_ex(op, totmirr, totfail, em->bm->selectmode);
2269         }
2270
2271         return OPERATOR_FINISHED;
2272 }
2273
2274 void MESH_OT_select_mirror(wmOperatorType *ot)
2275 {
2276         /* identifiers */
2277         ot->name = "Select Mirror";
2278         ot->description = "Select mesh items at mirrored locations";
2279         ot->idname = "MESH_OT_select_mirror";
2280
2281         /* api callbacks */
2282         ot->exec = edbm_select_mirror_exec;
2283         ot->poll = ED_operator_editmesh;
2284
2285         /* flags */
2286         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2287
2288         /* props */
2289         RNA_def_boolean(ot->srna, "extend", 0, "Extend", "Extend the existing selection");
2290 }
2291
2292 /* ******************** **************** */
2293
2294 static int edbm_select_more_exec(bContext *C, wmOperator *UNUSED(op))
2295 {
2296         Object *obedit = CTX_data_edit_object(C);
2297         BMEditMesh *em = BKE_editmesh_from_object(obedit);
2298
2299         EDBM_select_more(em);
2300
2301         WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit);
2302         return OPERATOR_FINISHED;
2303 }
2304
2305 void MESH_OT_select_more(wmOperatorType *ot)
2306 {
2307         /* identifiers */
2308         ot->name = "Select More";
2309         ot->idname = "MESH_OT_select_more";
2310         ot->description = "Select more vertices, edges or faces connected to initial selection";
2311
2312         /* api callbacks */
2313         ot->exec = edbm_select_more_exec;
2314         ot->poll = ED_operator_editmesh;
2315         
2316         /* flags */
2317         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2318 }
2319
2320 static int edbm_select_less_exec(bContext *C, wmOperator *UNUSED(op))
2321 {
2322         Object *obedit = CTX_data_edit_object(C);
2323         BMEditMesh *em = BKE_editmesh_from_object(obedit);
2324
2325         EDBM_select_less(em);
2326
2327         WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit);
2328         return OPERATOR_FINISHED;
2329 }
2330
2331 void MESH_OT_select_less(wmOperatorType *ot)
2332 {
2333         /* identifiers */
2334         ot->name = "Select Less";
2335         ot->idname = "MESH_OT_select_less";
2336         ot->description = "Deselect vertices, edges or faces at the boundary of each selection region";
2337
2338         /* api callbacks */
2339         ot->exec = edbm_select_less_exec;
2340         ot->poll = ED_operator_editmesh;
2341         
2342         /* flags */
2343         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2344 }
2345
2346 /* Walk all reachable elements of the same type as h_act in breadth-first
2347  * order, starting from h_act. Deselects elements if the depth when they
2348  * are reached is not a multiple of "nth". */
2349 static void walker_deselect_nth(BMEditMesh *em, int nth, int offset, BMHeader *h_act)
2350 {
2351         BMElem *ele;
2352         BMesh *bm = em->bm;
2353         BMWalker walker;
2354         BMIter iter;
2355         int walktype = 0, itertype = 0, flushtype = 0;
2356         short mask_vert = 0, mask_edge = 0, mask_face = 0;
2357
2358         /* No active element from which to start - nothing to do */
2359         if (h_act == NULL) {
2360                 return;
2361         }
2362
2363         /* Determine which type of iter, walker, and select flush to use
2364          * based on type of the elements being deselected */
2365         switch (h_act->htype) {
2366                 case BM_VERT:
2367                         itertype = BM_VERTS_OF_MESH;
2368                         walktype = BMW_CONNECTED_VERTEX;
2369                         flushtype = SCE_SELECT_VERTEX;
2370                         mask_vert = BMO_ELE_TAG;
2371                         break;
2372                 case BM_EDGE:
2373                         itertype = BM_EDGES_OF_MESH;
2374                         walktype = BMW_SHELL;
2375                         flushtype = SCE_SELECT_EDGE;
2376                         mask_edge = BMO_ELE_TAG;
2377                         break;
2378                 case BM_FACE:
2379                         itertype = BM_FACES_OF_MESH;
2380                         walktype = BMW_ISLAND;
2381                         flushtype = SCE_SELECT_FACE;
2382                         mask_face = BMO_ELE_TAG;
2383                         break;
2384         }
2385
2386         /* grr, shouldn't need to alloc BMO flags here */
2387         BM_mesh_elem_toolflags_ensure(bm);
2388
2389         /* Walker restrictions uses BMO flags, not header flags,
2390          * so transfer BM_ELEM_SELECT from HFlags onto a BMO flag layer. */
2391         BMO_push(bm, NULL);
2392         BM_ITER_MESH (ele, &iter, bm, itertype) {
2393                 if (BM_elem_flag_test(ele, BM_ELEM_SELECT)) {
2394                         BMO_elem_flag_enable(bm, (BMElemF *)ele, BMO_ELE_TAG);
2395                 }
2396         }
2397
2398         /* Walk over selected elements starting at active */
2399         BMW_init(&walker, bm, walktype,
2400                  mask_vert, mask_edge, mask_face,
2401                  BMW_FLAG_NOP, /* don't use BMW_FLAG_TEST_HIDDEN here since we want to desel all */
2402                  BMW_NIL_LAY);
2403
2404         /* use tag to avoid touching the same verts twice */
2405         BM_ITER_MESH (ele, &iter, bm, itertype) {
2406                 BM_elem_flag_disable(ele, BM_ELEM_TAG);
2407         }
2408
2409         BLI_assert(walker.order == BMW_BREADTH_FIRST);
2410         for (ele = BMW_begin(&walker, h_act); ele != NULL; ele = BMW_step(&walker)) {
2411                 if (!BM_elem_flag_test(ele, BM_ELEM_TAG)) {
2412                         /* Deselect elements that aren't at "nth" depth from active */
2413                         if ((offset + BMW_current_depth(&walker)) % nth) {
2414                                 BM_elem_select_set(bm, ele, false);
2415                         }
2416                         BM_elem_flag_enable(ele, BM_ELEM_TAG);
2417                 }
2418         }
2419         BMW_end(&walker);
2420
2421         BMO_pop(bm);
2422
2423         /* Flush selection up */
2424         EDBM_selectmode_flush_ex(em, flushtype);
2425 }
2426
2427 static void deselect_nth_active(BMEditMesh *em, BMVert **r_eve, BMEdge **r_eed, BMFace **r_efa)
2428 {
2429         BMVert *v;
2430         BMEdge *e;
2431         BMFace *f;
2432         BMIter iter;
2433         BMElem *ele;
2434
2435         *r_eve = NULL;
2436         *r_eed = NULL;
2437         *r_efa = NULL;
2438
2439         EDBM_selectmode_flush(em);
2440         ele = BM_mesh_active_elem_get(em->bm);
2441
2442         if (ele) {
2443                 switch (ele->head.htype) {
2444                         case BM_VERT:
2445                                 *r_eve = (BMVert *)ele;
2446                                 return;
2447                         case BM_EDGE:
2448                                 *r_eed = (BMEdge *)ele;
2449                                 return;
2450                         case BM_FACE:
2451                                 *r_efa = (BMFace *)ele;
2452                                 return;
2453                 }
2454         }
2455
2456         if (em->selectmode & SCE_SELECT_VERTEX) {
2457                 BM_ITER_MESH (v, &iter, em->bm, BM_VERTS_OF_MESH) {
2458                         if (BM_elem_flag_test(v, BM_ELEM_SELECT)) {
2459                                 *r_eve = v;
2460                                 return;
2461                         }
2462                 }
2463         }
2464         else if (em->selectmode & SCE_SELECT_EDGE) {
2465                 BM_ITER_MESH (e, &iter, em->bm, BM_EDGES_OF_MESH) {
2466                         if (BM_elem_flag_test(e, BM_ELEM_SELECT)) {
2467                                 *r_eed = e;
2468                                 return;
2469                         }
2470                 }
2471         }
2472         else if (em->selectmode & SCE_SELECT_FACE) {
2473                 f = BM_mesh_active_face_get(em->bm, true, false);
2474                 if (f) {
2475                         *r_efa = f;
2476                         return;
2477                 }
2478         }
2479 }
2480
2481 static bool edbm_deselect_nth(BMEditMesh *em, int nth, int offset)
2482 {
2483         BMVert *v;
2484         BMEdge *e;
2485         BMFace *f;
2486
2487         deselect_nth_active(em, &v, &e, &f);
2488
2489         if (v) {
2490                 walker_deselect_nth(em, nth, offset, &v->head);
2491                 return true;
2492         }
2493         else if (e) {
2494                 walker_deselect_nth(em, nth, offset, &e->head);
2495                 return true;
2496         }
2497         else if (f) {
2498                 walker_deselect_nth(em, nth, offset, &f->head);
2499                 return true;
2500         }
2501
2502         return false;
2503 }
2504
2505 static int edbm_select_nth_exec(bContext *C, wmOperator *op)
2506 {
2507         Object *obedit = CTX_data_edit_object(C);
2508         BMEditMesh *em = BKE_editmesh_from_object(obedit);
2509         const int nth = RNA_int_get(op->ptr, "nth");
2510         int offset = RNA_int_get(op->ptr, "offset");
2511
2512         /* so input of offset zero ends up being (nth - 1) */
2513         offset = (offset + (nth - 1)) % nth;
2514
2515         if (edbm_deselect_nth(em, nth, offset) == false) {
2516                 BKE_report(op->reports, RPT_ERROR, "Mesh has no active vert/edge/face");
2517                 return OPERATOR_CANCELLED;
2518         }
2519
2520         EDBM_update_generic(em, false, false);
2521
2522         return OPERATOR_FINISHED;
2523 }
2524
2525
2526 void MESH_OT_select_nth(wmOperatorType *ot)
2527 {
2528         /* identifiers */
2529         ot->name = "Checker Deselect";
2530         ot->idname = "MESH_OT_select_nth";
2531         ot->description = "Deselect every Nth element starting from the active vertex, edge or face";
2532
2533         /* api callbacks */
2534         ot->exec = edbm_select_nth_exec;
2535         ot->poll = ED_operator_editmesh;
2536
2537         /* flags */
2538         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2539
2540         RNA_def_int(ot->srna, "nth", 2, 2, INT_MAX, "Nth Selection", "", 2, 100);
2541         RNA_def_int(ot->srna, "offset", 0, 0, INT_MAX, "Offset", "", 0, 100);
2542 }
2543
2544 void em_setup_viewcontext(bContext *C, ViewContext *vc)
2545 {
2546         view3d_set_viewcontext(C, vc);
2547         
2548         if (vc->obedit) {
2549                 vc->em = BKE_editmesh_from_object(vc->obedit);
2550         }
2551 }
2552
2553
2554 static int edbm_select_sharp_edges_exec(bContext *C, wmOperator *op)
2555 {
2556         /* Find edges that have exactly two neighboring faces,
2557          * check the angle between those faces, and if angle is
2558          * small enough, select the edge
2559          */
2560         Object *obedit = CTX_data_edit_object(C);
2561         BMEditMesh *em = BKE_editmesh_from_object(obedit);
2562         BMIter iter;
2563         BMEdge *e;
2564         BMLoop *l1, *l2;
2565         const float sharp = RNA_float_get(op->ptr, "sharpness");
2566
2567         BM_ITER_MESH (e, &iter, em->bm, BM_EDGES_OF_MESH) {
2568                 if (BM_elem_flag_test(e, BM_ELEM_HIDDEN) == false &&
2569                     BM_edge_loop_pair(e, &l1, &l2))
2570                 {
2571                         /* edge has exactly two neighboring faces, check angle */
2572                         const float angle = angle_normalized_v3v3(l1->f->no, l2->f->no);
2573
2574                         if (fabsf(angle) > sharp) {
2575                                 BM_edge_select_set(em->bm, e, true);
2576                         }
2577                 }
2578         }
2579
2580         WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit->data);
2581
2582         return OPERATOR_FINISHED;
2583 }
2584
2585 void MESH_OT_edges_select_sharp(wmOperatorType *ot)
2586 {
2587         PropertyRNA *prop;
2588
2589         /* identifiers */
2590         ot->name = "Select Sharp Edges";
2591         ot->description = "Select all sharp-enough edges";
2592         ot->idname = "MESH_OT_edges_select_sharp";
2593         
2594         /* api callbacks */
2595         ot->exec = edbm_select_sharp_edges_exec;
2596         ot->poll = ED_operator_editmesh;
2597         
2598         /* flags */
2599         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2600         
2601         /* props */
2602         prop = RNA_def_float_rotation(ot->srna, "sharpness", 0, NULL, DEG2RADF(0.01f), DEG2RADF(180.0f),
2603                                       "Sharpness", "", DEG2RADF(1.0f), DEG2RADF(180.0f));
2604         RNA_def_property_float_default(prop, DEG2RADF(30.0f));
2605 }
2606
2607 static int edbm_select_linked_flat_faces_exec(bContext *C, wmOperator *op)
2608 {
2609         Object *obedit = CTX_data_edit_object(C);
2610         BMEditMesh *em = BKE_editmesh_from_object(obedit);
2611         BMesh *bm = em->bm;
2612
2613         BMFace **stack = MEM_mallocN(sizeof(BMFace *) * bm->totface, __func__);
2614         STACK_DECLARE(stack);
2615
2616         BMIter iter, liter, liter2;
2617         BMFace *f;
2618         BMLoop *l, *l2;
2619         const float angle_limit = RNA_float_get(op->ptr, "sharpness");
2620
2621         BM_mesh_elem_hflag_disable_all(bm, BM_VERT, BM_ELEM_TAG, false);
2622
2623
2624         BM_ITER_MESH (f, &iter, bm, BM_FACES_OF_MESH) {
2625                 if ((BM_elem_flag_test(f, BM_ELEM_HIDDEN) != 0) ||
2626                     (BM_elem_flag_test(f, BM_ELEM_TAG)    != 0) ||
2627                     (BM_elem_flag_test(f, BM_ELEM_SELECT) == 0))
2628                 {
2629                         continue;
2630                 }
2631
2632                 STACK_INIT(stack);
2633
2634                 do {
2635                         BM_face_select_set(bm, f, true);
2636
2637                         BM_elem_flag_enable(f, BM_ELEM_TAG);
2638
2639                         BM_ITER_ELEM (l, &liter, f, BM_LOOPS_OF_FACE) {
2640                                 BM_ITER_ELEM (l2, &liter2, l, BM_LOOPS_OF_LOOP) {
2641                                         float angle;
2642
2643                                         if (BM_elem_flag_test(l2->f, BM_ELEM_TAG) ||
2644                                             BM_elem_flag_test(l2->f, BM_ELEM_HIDDEN))
2645                                         {
2646                                                 continue;
2647                                         }
2648
2649                                         angle = angle_normalized_v3v3(f->no, l2->f->no);
2650
2651                                         if (angle < angle_limit) {
2652                                                 STACK_PUSH(stack, l2->f);
2653                                         }
2654                                 }
2655                         }
2656                 } while ((f = STACK_POP(stack)));
2657         }
2658
2659         STACK_FREE(stack);
2660
2661         MEM_freeN(stack);
2662
2663         WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit->data);
2664
2665         return OPERATOR_FINISHED;
2666 }
2667
2668 void MESH_OT_faces_select_linked_flat(wmOperatorType *ot)
2669 {
2670         PropertyRNA *prop;
2671
2672         /* identifiers */
2673         ot->name = "Select Linked Flat Faces";
2674         ot->description = "Select linked faces by angle";
2675         ot->idname = "MESH_OT_faces_select_linked_flat";
2676         
2677         /* api callbacks */
2678         ot->exec = edbm_select_linked_flat_faces_exec;
2679         ot->poll = ED_operator_editmesh;
2680         
2681         /* flags */
2682         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2683         
2684         /* props */
2685         prop = RNA_def_float_rotation(ot->srna, "sharpness", 0, NULL, DEG2RADF(0.01f), DEG2RADF(180.0f),
2686                                       "Sharpness", "", DEG2RADF(1.0f), DEG2RADF(180.0f));
2687         RNA_def_property_float_default(prop, DEG2RADF(1.0f));
2688 }
2689
2690 static int edbm_select_non_manifold_exec(bContext *C, wmOperator *op)
2691 {
2692         Object *obedit = CTX_data_edit_object(C);
2693         BMEditMesh *em = BKE_editmesh_from_object(obedit);
2694         BMVert *v;
2695         BMEdge *e;
2696         BMIter iter;
2697
2698         if (!RNA_boolean_get(op->ptr, "extend"))
2699                 EDBM_flag_disable_all(em, BM_ELEM_SELECT);
2700
2701         /* Selects isolated verts, and edges that do not have 2 neighboring
2702          * faces
2703          */
2704         
2705         if (em->selectmode == SCE_SELECT_FACE) {
2706                 BKE_report(op->reports, RPT_ERROR, "Does not work in face selection mode");
2707                 return OPERATOR_CANCELLED;
2708         }
2709         
2710         BM_ITER_MESH (v, &iter, em->bm, BM_VERTS_OF_MESH) {
2711                 if (!BM_elem_flag_test(v, BM_ELEM_HIDDEN) && !BM_vert_is_manifold(v)) {
2712                         BM_vert_select_set(em->bm, v, true);
2713                 }
2714         }
2715         
2716         BM_ITER_MESH (e, &iter, em->bm, BM_EDGES_OF_MESH) {
2717                 if (!BM_elem_flag_test(e, BM_ELEM_HIDDEN) && !BM_edge_is_manifold(e)) {
2718                         BM_edge_select_set(em->bm, e, true);
2719                 }
2720         }
2721
2722         WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit->data);
2723
2724         EDBM_selectmode_flush(em);
2725
2726         return OPERATOR_FINISHED;
2727 }
2728
2729 void MESH_OT_select_non_manifold(wmOperatorType *ot)
2730 {
2731         /* identifiers */
2732         ot->name = "Select Non Manifold";
2733         ot->description = "Select all non-manifold vertices or edges";
2734         ot->idname = "MESH_OT_select_non_manifold";
2735         
2736         /* api callbacks */
2737         ot->exec = edbm_select_non_manifold_exec;
2738         ot->poll = ED_operator_editmesh;
2739         
2740         /* flags */
2741         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2742
2743         /* props */
2744         RNA_def_boolean(ot->srna, "extend", true, "Extend", "Extend the selection");
2745 }
2746
2747 static int edbm_select_random_exec(bContext *C, wmOperator *op)
2748 {
2749         Object *obedit = CTX_data_edit_object(C);
2750         BMEditMesh *em = BKE_editmesh_from_object(obedit);
2751         BMVert *eve;
2752         BMEdge *eed;
2753         BMFace *efa;
2754         BMIter iter;
2755         const float randfac =  RNA_float_get(op->ptr, "percent") / 100.0f;
2756
2757         if (!RNA_boolean_get(op->ptr, "extend"))
2758                 EDBM_flag_disable_all(em, BM_ELEM_SELECT);
2759
2760         if (em->selectmode & SCE_SELECT_VERTEX) {
2761                 BM_ITER_MESH (eve, &iter, em->bm, BM_VERTS_OF_MESH) {
2762                         if (!BM_elem_flag_test(eve, BM_ELEM_HIDDEN) && BLI_frand() < randfac) {
2763                                 BM_vert_select_set(em->bm, eve, true);
2764                         }
2765                 }
2766                 EDBM_selectmode_flush(em);
2767         }
2768         else if (em->selectmode & SCE_SELECT_EDGE) {
2769                 BM_ITER_MESH (eed, &iter, em->bm, BM_EDGES_OF_MESH) {
2770                         if (!BM_elem_flag_test(eed, BM_ELEM_HIDDEN) && BLI_frand() < randfac) {
2771                                 BM_edge_select_set(em->bm, eed, true);
2772                         }
2773                 }
2774                 EDBM_selectmode_flush(em);
2775         }
2776         else {
2777                 BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) {
2778                         if (!BM_elem_flag_test(efa, BM_ELEM_HIDDEN) && BLI_frand() < randfac) {
2779                                 BM_face_select_set(em->bm, efa, true);
2780                         }
2781                 }
2782                 EDBM_selectmode_flush(em);
2783         }
2784         
2785         WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit->data);
2786         
2787         return OPERATOR_FINISHED;
2788 }
2789
2790 void MESH_OT_select_random(wmOperatorType *ot)
2791 {
2792         /* identifiers */
2793         ot->name = "Select Random";
2794         ot->description = "Randomly select vertices";
2795         ot->idname = "MESH_OT_select_random";
2796
2797         /* api callbacks */
2798         ot->exec = edbm_select_random_exec;
2799         ot->poll = ED_operator_editmesh;
2800
2801         /* flags */
2802         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2803         
2804         /* props */
2805         RNA_def_float_percentage(ot->srna, "percent", 50.f, 0.0f, 100.0f,
2806                                  "Percent", "Percentage of elements to select randomly", 0.f, 100.0f);
2807         RNA_def_boolean(ot->srna, "extend", false, "Extend", "Extend the selection");
2808 }
2809
2810 static int edbm_select_ungrouped_poll(bContext *C)
2811 {
2812         if (ED_operator_editmesh(C)) {
2813                 Object *obedit = CTX_data_edit_object(C);
2814                 BMEditMesh *em = BKE_editmesh_from_object(obedit);
2815                 const int cd_dvert_offset = CustomData_get_offset(&em->bm->vdata, CD_MDEFORMVERT);
2816
2817                 if ((em->selectmode & SCE_SELECT_VERTEX) == 0) {
2818                         CTX_wm_operator_poll_msg_set(C, "Must be in vertex selection mode");
2819                 }
2820                 else if (obedit->defbase.first == NULL || cd_dvert_offset == -1) {
2821                         CTX_wm_operator_poll_msg_set(C, "No weights/vertex groups on object");
2822                 }
2823                 else {
2824                         return true;
2825                 }
2826         }
2827         return false;
2828 }
2829
2830 static int edbm_select_ungrouped_exec(bContext *C, wmOperator *op)
2831 {
2832         Object *obedit = CTX_data_edit_object(C);
2833         BMEditMesh *em = BKE_editmesh_from_object(obedit);
2834         const int cd_dvert_offset = CustomData_get_offset(&em->bm->vdata, CD_MDEFORMVERT);
2835
2836         BMVert *eve;
2837         BMIter iter;
2838
2839         if (!RNA_boolean_get(op->ptr, "extend")) {
2840                 EDBM_flag_disable_all(em, BM_ELEM_SELECT);
2841         }
2842
2843         BM_ITER_MESH (eve, &iter, em->bm, BM_VERTS_OF_MESH) {
2844                 if (!BM_elem_flag_test(eve, BM_ELEM_HIDDEN)) {
2845                         MDeformVert *dv = BM_ELEM_CD_GET_VOID_P(eve, cd_dvert_offset);
2846                         /* no dv or dv set with no weight */
2847                         if (ELEM(NULL, dv, dv->dw)) {
2848                                 BM_vert_select_set(em->bm, eve, true);
2849                         }
2850                 }
2851         }
2852
2853         EDBM_selectmode_flush(em);
2854         WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit->data);
2855
2856         return OPERATOR_FINISHED;
2857 }
2858
2859 void MESH_OT_select_ungrouped(wmOperatorType *ot)
2860 {
2861         /* identifiers */
2862         ot->name = "Select Ungrouped";
2863         ot->idname = "MESH_OT_select_ungrouped";
2864         ot->description = "Select vertices without a group";
2865
2866         /* api callbacks */
2867         ot->exec = edbm_select_ungrouped_exec;
2868         ot->poll = edbm_select_ungrouped_poll;
2869
2870         /* flags */
2871         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2872
2873         RNA_def_boolean(ot->srna, "extend", false, "Extend", "Extend the selection");
2874 }
2875
2876
2877 /* BMESH_TODO - some way to select on an arbitrary axis */
2878 static int edbm_select_axis_exec(bContext *C, wmOperator *op)
2879 {
2880         Object *obedit = CTX_data_edit_object(C);
2881         BMEditMesh *em = BKE_editmesh_from_object(obedit);
2882         BMesh *bm = em->bm;
2883         BMVert *v_act = BM_mesh_active_vert_get(bm);
2884         const int axis = RNA_enum_get(op->ptr, "axis");
2885         const int mode = RNA_enum_get(op->ptr, "mode"); /* -1 == aligned, 0 == neg, 1 == pos */
2886
2887         if (v_act == NULL) {
2888                 BKE_report(op->reports, RPT_WARNING, "This operator requires an active vertex (last selected)");
2889                 return OPERATOR_CANCELLED;
2890         }
2891         else {
2892                 BMVert *v;
2893                 BMIter iter;
2894                 const float limit =  CTX_data_tool_settings(C)->doublimit; // XXX
2895                 float value = v_act->co[axis];
2896
2897                 if (mode == 0)
2898                         value -= limit;
2899                 else if (mode == 1)
2900                         value += limit;
2901
2902                 BM_ITER_MESH (v, &iter, bm, BM_VERTS_OF_MESH) {
2903                         if (!BM_elem_flag_test(v, BM_ELEM_HIDDEN)) {
2904                                 switch (mode) {
2905                                         case -1: /* aligned */
2906                                                 if (fabsf(v->co[axis] - value) < limit)
2907                                                         BM_vert_select_set(bm, v, true);
2908                                                 break;
2909                                         case 0: /* neg */
2910                                                 if (v->co[axis] > value)
2911                                                         BM_vert_select_set(bm, v, true);
2912                                                 break;
2913                                         case 1: /* pos */
2914                                                 if (v->co[axis] < value)
2915                                                         BM_vert_select_set(bm, v, true);
2916                                                 break;
2917                                 }
2918                         }
2919                 }
2920         }
2921
2922         EDBM_selectmode_flush(em);
2923         WM_event_add_notifier(C, NC_GEOM | ND_DATA, obedit->data);
2924
2925         return OPERATOR_FINISHED;
2926 }
2927
2928 void MESH_OT_select_axis(wmOperatorType *ot)
2929 {
2930         static EnumPropertyItem axis_mode_items[] = {
2931                 {0,  "POSITIVE", 0, "Positive Axis", ""},
2932                 {1,  "NEGATIVE", 0, "Negative Axis", ""},
2933                 {-1, "ALIGNED",  0, "Aligned Axis", ""},
2934                 {0, NULL, 0, NULL, NULL}
2935         };
2936
2937         static EnumPropertyItem axis_items_xyz[] = {
2938                 {0, "X_AXIS", 0, "X Axis", ""},
2939                 {1, "Y_AXIS", 0, "Y Axis", ""},
2940                 {2, "Z_AXIS", 0, "Z Axis", ""},
2941                 {0, NULL, 0, NULL, NULL}
2942         };
2943
2944         /* identifiers */
2945         ot->name = "Select Axis";
2946         ot->description = "Select all data in the mesh on a single axis";
2947         ot->idname = "MESH_OT_select_axis";
2948
2949         /* api callbacks */
2950         ot->exec = edbm_select_axis_exec;
2951         ot->poll = ED_operator_editmesh;
2952
2953         /* flags */
2954         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2955
2956         /* properties */
2957         RNA_def_enum(ot->srna, "mode", axis_mode_items, 0, "Axis Mode", "Axis side to use when selecting");
2958         RNA_def_enum(ot->srna, "axis", axis_items_xyz, 0, "Axis", "Select the axis to compare each vertex on");
2959 }
2960
2961
2962 static int edbm_select_next_loop_exec(bContext *C, wmOperator *UNUSED(op))
2963 {
2964         Object *obedit = CTX_data_edit_object(C);
2965         BMEditMesh *em = BKE_editmesh_from_object(obedit);
2966         BMFace *f;
2967         BMVert *v;
2968         BMIter iter;
2969         
2970         BM_ITER_MESH (v, &iter, em->bm, BM_VERTS_OF_MESH) {
2971                 BM_elem_flag_disable(v, BM_ELEM_TAG);
2972         }
2973         
2974         BM_ITER_MESH (f, &iter, em->bm, BM_FACES_OF_MESH) {
2975                 BMLoop *l;
2976                 BMIter liter;
2977                 
2978                 BM_ITER_ELEM (l, &liter, f, BM_LOOPS_OF_FACE) {
2979                         if (BM_elem_flag_test(l->v, BM_ELEM_SELECT)) {
2980                                 BM_elem_flag_enable(l->next->v, BM_ELEM_TAG);
2981                                 BM_vert_select_set(em->bm, l->v, false);
2982                         }
2983                 }
2984         }
2985
2986         BM_ITER_MESH (v, &iter, em->bm, BM_VERTS_OF_MESH) {
2987                 if (BM_elem_flag_test(v, BM_ELEM_TAG)) {
2988                         BM_vert_select_set(em->bm, v, true);
2989                 }
2990         }
2991
2992         WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit);
2993         return OPERATOR_FINISHED;
2994 }
2995
2996 void MESH_OT_select_next_loop(wmOperatorType *ot)
2997 {
2998         /* identifiers */
2999         ot->name = "Select Next Loop";
3000         ot->idname = "MESH_OT_select_next_loop";
3001         ot->description = "Select next edge loop adjacent to a selected loop";
3002
3003         /* api callbacks */
3004         ot->exec = edbm_select_next_loop_exec;
3005         ot->poll = ED_operator_editmesh;
3006         
3007         /* flags */
3008         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
3009 }
3010
3011
3012 static int edbm_region_to_loop_exec(bContext *C, wmOperator *UNUSED(op))
3013 {
3014         Object *obedit = CTX_data_edit_object(C);
3015         BMEditMesh *em = BKE_editmesh_from_object(obedit);
3016         BMFace *f;
3017         BMEdge *e;
3018         BMIter iter;
3019
3020         BM_mesh_elem_hflag_disable_all(em->bm, BM_EDGE, BM_ELEM_TAG, false);
3021
3022         BM_ITER_MESH (f, &iter, em->bm, BM_FACES_OF_MESH) {
3023                 BMLoop *l1, *l2;
3024                 BMIter liter1, liter2;
3025                 
3026                 BM_ITER_ELEM (l1, &liter1, f, BM_LOOPS_OF_FACE) {
3027                         int tot = 0, totsel = 0;
3028                         
3029                         BM_ITER_ELEM (l2, &liter2, l1->e, BM_LOOPS_OF_EDGE) {
3030                                 tot++;
3031                                 totsel += BM_elem_flag_test(l2->f, BM_ELEM_SELECT) != 0;
3032                         }
3033                         
3034                         if ((tot != totsel && totsel > 0) || (totsel == 1 && tot == 1))
3035                                 BM_elem_flag_enable(l1->e, BM_ELEM_TAG);
3036                 }
3037         }
3038
3039         EDBM_flag_disable_all(em, BM_ELEM_SELECT);
3040         
3041         BM_ITER_MESH (e, &iter, em->bm, BM_EDGES_OF_MESH) {
3042                 if (BM_elem_flag_test(e, BM_ELEM_TAG)) {
3043                         BM_edge_select_set(em->bm, e, true);
3044                 }
3045         }
3046
3047         /* If in face-only select mode, switch to edge select mode so that
3048          * an edge-only selection is not inconsistent state */
3049         if (em->selectmode == SCE_SELECT_FACE) {
3050                 em->selectmode = SCE_SELECT_EDGE;
3051                 EDBM_selectmode_set(em);
3052                 EDBM_selectmode_to_scene(C);
3053         }
3054
3055         WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit->data);
3056
3057         return OPERATOR_FINISHED;
3058 }
3059
3060 void MESH_OT_region_to_loop(wmOperatorType *ot)
3061 {
3062         /* identifiers */
3063         ot->name = "Select Boundary Loop";
3064         ot->idname = "MESH_OT_region_to_loop";
3065         ot->description = "Select boundary edges around the selected faces";
3066
3067         /* api callbacks */
3068         ot->exec = edbm_region_to_loop_exec;
3069         ot->poll = ED_operator_editmesh;
3070
3071         /* flags */
3072         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
3073 }
3074
3075 static int loop_find_region(BMLoop *l, int flag,
3076                             SmallHash *fhash, BMFace ***region_out)
3077 {
3078         BLI_array_declare(region);
3079         BLI_array_declare(stack);
3080         BMFace **region = NULL;
3081         BMFace **stack = NULL;
3082         BMFace *f;
3083         
3084         BLI_array_append(stack, l->f);
3085         BLI_smallhash_insert(fhash, (uintptr_t)l->f, NULL);
3086         
3087         while (BLI_array_count(stack) > 0) {
3088                 BMIter liter1, liter2;
3089                 BMLoop *l1, *l2;
3090                 
3091                 f = BLI_array_pop(stack);
3092                 BLI_array_append(region, f);
3093                 
3094                 BM_ITER_ELEM (l1, &liter1, f, BM_LOOPS_OF_FACE) {
3095                         if (BM_elem_flag_test(l1->e, flag))
3096                                 continue;
3097                         
3098                         BM_ITER_ELEM (l2, &liter2, l1->e, BM_LOOPS_OF_EDGE) {
3099                                 if (BLI_smallhash_haskey(fhash, (uintptr_t)l2->f))
3100                                         continue;
3101                                 
3102                                 BLI_array_append(stack, l2->f);
3103                                 BLI_smallhash_insert(fhash, (uintptr_t)l2->f, NULL);
3104                         }
3105                 }
3106         }
3107         
3108         BLI_array_free(stack);
3109         
3110         *region_out = region;
3111         return BLI_array_count(region);
3112 }
3113
3114 static int verg_radial(const void *va, const void *vb)
3115 {
3116         BMEdge *e1 = *((void **)va);
3117         BMEdge *e2 = *((void **)vb);
3118         int a, b;
3119