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