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