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