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