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