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