code improvements for selecting the shortest path for mesh editmode,
[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 static EnumPropertyItem prop_similar_compare_types[] = {
675         {SIM_CMP_EQ, "EQUAL", 0, "Equal", ""},
676         {SIM_CMP_GT, "GREATER", 0, "Greater", ""},
677         {SIM_CMP_LT, "LESS", 0, "Less", ""},
678
679         {0, NULL, 0, NULL, NULL}
680 };
681
682 static EnumPropertyItem prop_similar_types[] = {
683         {SIMVERT_NORMAL, "NORMAL", 0, "Normal", ""},
684         {SIMVERT_FACE, "FACE", 0, "Amount of Adjacent Faces", ""},
685         {SIMVERT_VGROUP, "VGROUP", 0, "Vertex Groups", ""},
686         {SIMVERT_EDGE, "EDGE", 0, "Amount of connecting edges", ""},
687
688         {SIMEDGE_LENGTH, "LENGTH", 0, "Length", ""},
689         {SIMEDGE_DIR, "DIR", 0, "Direction", ""},
690         {SIMEDGE_FACE, "FACE", 0, "Amount of Faces Around an Edge", ""},
691         {SIMEDGE_FACE_ANGLE, "FACE_ANGLE", 0, "Face Angles", ""},
692         {SIMEDGE_CREASE, "CREASE", 0, "Crease", ""},
693         {SIMEDGE_BEVEL, "BEVEL", 0, "Bevel", ""},
694         {SIMEDGE_SEAM, "SEAM", 0, "Seam", ""},
695         {SIMEDGE_SHARP, "SHARP", 0, "Sharpness", ""},
696
697         {SIMFACE_MATERIAL, "MATERIAL", 0, "Material", ""},
698         {SIMFACE_IMAGE, "IMAGE", 0, "Image", ""},
699         {SIMFACE_AREA, "AREA", 0, "Area", ""},
700         {SIMFACE_SIDES, "SIDES", 0, "Polygon Sides", ""},
701         {SIMFACE_PERIMETER, "PERIMETER", 0, "Perimeter", ""},
702         {SIMFACE_NORMAL, "NORMAL", 0, "Normal", ""},
703         {SIMFACE_COPLANAR, "COPLANAR", 0, "Co-planar", ""},
704
705         {0, NULL, 0, NULL, NULL}
706 };
707
708 /* selects new faces/edges/verts based on the existing selection */
709
710 static int similar_face_select_exec(bContext *C, wmOperator *op)
711 {
712         Object *ob = CTX_data_edit_object(C);
713         BMEditMesh *em = BMEdit_FromObject(ob);
714         BMOperator bmop;
715
716         /* get the type from RNA */
717         const int type = RNA_enum_get(op->ptr, "type");
718         const float thresh = RNA_float_get(op->ptr, "threshold");
719         const int compare = RNA_enum_get(op->ptr, "compare");
720
721         /* initialize the bmop using EDBM api, which does various ui error reporting and other stuff */
722         EDBM_op_init(em, &bmop, op,
723                      "similar_faces faces=%hf type=%i thresh=%f compare=%i",
724                      BM_ELEM_SELECT, type, thresh, compare);
725
726         /* execute the operator */
727         BMO_op_exec(em->bm, &bmop);
728
729         /* clear the existing selection */
730         EDBM_flag_disable_all(em, BM_ELEM_SELECT);
731
732         /* select the output */
733         BMO_slot_buffer_hflag_enable(em->bm, &bmop, "faceout", BM_ALL, BM_ELEM_SELECT, TRUE);
734
735         /* finish the operator */
736         if (!EDBM_op_finish(em, &bmop, op, TRUE)) {
737                 return OPERATOR_CANCELLED;
738         }
739
740         EDBM_update_generic(C, em, FALSE);
741
742         /* we succeeded */
743         return OPERATOR_FINISHED;
744 }       
745
746 /* ***************************************************** */
747
748 /* EDGE GROUP */
749
750 /* wrap the above function but do selection flushing edge to face */
751 static int similar_edge_select_exec(bContext *C, wmOperator *op)
752 {
753         Object *ob = CTX_data_edit_object(C);
754         BMEditMesh *em = BMEdit_FromObject(ob);
755         BMOperator bmop;
756
757         /* get the type from RNA */
758         const int type = RNA_enum_get(op->ptr, "type");
759         const float thresh = RNA_float_get(op->ptr, "threshold");
760         const int compare = RNA_enum_get(op->ptr, "compare");
761
762         /* initialize the bmop using EDBM api, which does various ui error reporting and other stuff */
763         EDBM_op_init(em, &bmop, op,
764                      "similar_edges edges=%he type=%i thresh=%f compare=%i",
765                      BM_ELEM_SELECT, type, thresh, compare);
766
767         /* execute the operator */
768         BMO_op_exec(em->bm, &bmop);
769
770         /* clear the existing selection */
771         EDBM_flag_disable_all(em, BM_ELEM_SELECT);
772
773         /* select the output */
774         BMO_slot_buffer_hflag_enable(em->bm, &bmop, "edgeout", BM_ALL, BM_ELEM_SELECT, TRUE);
775         EDBM_selectmode_flush(em);
776
777         /* finish the operator */
778         if (!EDBM_op_finish(em, &bmop, op, TRUE)) {
779                 return OPERATOR_CANCELLED;
780         }
781
782         EDBM_update_generic(C, em, FALSE);
783
784         /* we succeeded */
785         return OPERATOR_FINISHED;
786 }
787
788 /* ********************************* */
789
790 /*
791  * VERT GROUP
792  * mode 1: same normal
793  * mode 2: same number of face users
794  * mode 3: same vertex groups
795  */
796 static int similar_vert_select_exec(bContext *C, wmOperator *op)
797 {
798         Object *ob = CTX_data_edit_object(C);
799         BMEditMesh *em = BMEdit_FromObject(ob);
800         BMOperator bmop;
801         /* get the type from RNA */
802         const int type = RNA_enum_get(op->ptr, "type");
803         float thresh = RNA_float_get(op->ptr, "threshold");
804         const int compare = RNA_enum_get(op->ptr, "compare");
805
806         /* initialize the bmop using EDBM api, which does various ui error reporting and other stuff */
807         EDBM_op_init(em, &bmop, op,
808                      "similar_verts verts=%hv type=%i thresh=%f compare=%i",
809                      BM_ELEM_SELECT, type, thresh, compare);
810
811         /* execute the operator */
812         BMO_op_exec(em->bm, &bmop);
813
814         /* clear the existing selection */
815         EDBM_flag_disable_all(em, BM_ELEM_SELECT);
816
817         /* select the output */
818         BMO_slot_buffer_hflag_enable(em->bm, &bmop, "vertout", BM_ALL, BM_ELEM_SELECT, TRUE);
819
820         /* finish the operator */
821         if (!EDBM_op_finish(em, &bmop, op, TRUE)) {
822                 return OPERATOR_CANCELLED;
823         }
824
825         EDBM_selectmode_flush(em);
826
827         EDBM_update_generic(C, em, FALSE);
828
829         /* we succeeded */
830         return OPERATOR_FINISHED;
831 }
832
833 static int edbm_select_similar_exec(bContext *C, wmOperator *op)
834 {
835         ToolSettings *ts = CTX_data_tool_settings(C);
836         PropertyRNA *prop = RNA_struct_find_property(op->ptr, "threshold");
837
838         const int type = RNA_enum_get(op->ptr, "type");
839
840         if (!RNA_property_is_set(op->ptr, prop)) {
841                 RNA_property_float_set(op->ptr, prop, ts->select_thresh);
842         }
843         else {
844                 ts->select_thresh = RNA_property_float_get(op->ptr, prop);
845         }
846
847         if      (type < 100) return similar_vert_select_exec(C, op);
848         else if (type < 200) return similar_edge_select_exec(C, op);
849         else                 return similar_face_select_exec(C, op);
850 }
851
852 static EnumPropertyItem *select_similar_type_itemf(bContext *C, PointerRNA *UNUSED(ptr), PropertyRNA *UNUSED(prop),
853                                                    int *free)
854 {
855         Object *obedit;
856
857         if (!C) /* needed for docs and i18n tools */
858                 return prop_similar_types;
859
860         obedit = CTX_data_edit_object(C);
861
862         if (obedit && obedit->type == OB_MESH) {
863                 EnumPropertyItem *item = NULL;
864                 int a, totitem = 0;
865                 BMEditMesh *em = BMEdit_FromObject(obedit);
866
867                 if (em->selectmode & SCE_SELECT_VERTEX) {
868                         for (a = SIMVERT_NORMAL; a < SIMEDGE_LENGTH; a++) {
869                                 RNA_enum_items_add_value(&item, &totitem, prop_similar_types, a);
870                         }
871                 }
872                 else if (em->selectmode & SCE_SELECT_EDGE) {
873                         for (a = SIMEDGE_LENGTH; a < SIMFACE_MATERIAL; a++) {
874                                 RNA_enum_items_add_value(&item, &totitem, prop_similar_types, a);
875                         }
876                 }
877                 else if (em->selectmode & SCE_SELECT_FACE) {
878                         for (a = SIMFACE_MATERIAL; a <= SIMFACE_COPLANAR; a++) {
879                                 RNA_enum_items_add_value(&item, &totitem, prop_similar_types, a);
880                         }
881                 }
882                 RNA_enum_item_end(&item, &totitem);
883
884                 *free = 1;
885
886                 return item;
887         }
888
889         return NULL;
890 }
891
892 void MESH_OT_select_similar(wmOperatorType *ot)
893 {
894         PropertyRNA *prop;
895
896         /* identifiers */
897         ot->name = "Select Similar";
898         ot->idname = "MESH_OT_select_similar";
899         ot->description = "Select similar vertices, edges or faces by property types";
900         
901         /* api callbacks */
902         ot->invoke = WM_menu_invoke;
903         ot->exec = edbm_select_similar_exec;
904         ot->poll = ED_operator_editmesh;
905         
906         /* flags */
907         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
908         
909         /* properties */
910         prop = ot->prop = RNA_def_enum(ot->srna, "type", prop_similar_types, SIMVERT_NORMAL, "Type", "");
911         RNA_def_enum_funcs(prop, select_similar_type_itemf);
912
913         RNA_def_enum(ot->srna, "compare", prop_similar_compare_types, SIM_CMP_EQ, "Compare", "");
914
915         RNA_def_float(ot->srna, "threshold", 0.0, 0.0, 1.0, "Threshold", "", 0.0, 1.0);
916 }
917
918 /* ***************************************************** */
919
920 /* ****************  LOOP SELECTS *************** */
921
922 static void walker_select(BMEditMesh *em, int walkercode, void *start, int select)
923 {
924         BMesh *bm = em->bm;
925         BMElem *ele;
926         BMWalker walker;
927
928         BMW_init(&walker, bm, walkercode,
929                  BMW_MASK_NOP, BMW_MASK_NOP, BMW_MASK_NOP,
930                  BMW_FLAG_TEST_HIDDEN,
931                  BMW_NIL_LAY);
932         ele = BMW_begin(&walker, start);
933         for (; ele; ele = BMW_step(&walker)) {
934                 if (!select) {
935                         BM_select_history_remove(bm, ele);
936                 }
937                 BM_elem_select_set(bm, ele, select);
938         }
939         BMW_end(&walker);
940 }
941
942 static int edbm_loop_multiselect_exec(bContext *C, wmOperator *op)
943 {
944         Object *obedit = CTX_data_edit_object(C);
945         BMEditMesh *em = BMEdit_FromObject(obedit);
946         BMEdge *eed;
947         BMEdge **edarray;
948         int edindex;
949         int looptype = RNA_boolean_get(op->ptr, "ring");
950         
951         BMIter iter;
952         int totedgesel = 0;
953
954         BM_ITER_MESH (eed, &iter, em->bm, BM_EDGES_OF_MESH) {
955                 if (BM_elem_flag_test(eed, BM_ELEM_SELECT)) {
956                         totedgesel++;
957                 }
958         }
959         
960         edarray = MEM_mallocN(sizeof(BMEdge *) * totedgesel, "edge array");
961         edindex = 0;
962         
963         BM_ITER_MESH (eed, &iter, em->bm, BM_EDGES_OF_MESH) {
964                 if (BM_elem_flag_test(eed, BM_ELEM_SELECT)) {
965                         edarray[edindex] = eed;
966                         edindex++;
967                 }
968         }
969         
970         if (looptype) {
971                 for (edindex = 0; edindex < totedgesel; edindex += 1) {
972                         eed = edarray[edindex];
973                         walker_select(em, BMW_EDGERING, eed, TRUE);
974                 }
975                 EDBM_selectmode_flush(em);
976         }
977         else {
978                 for (edindex = 0; edindex < totedgesel; edindex += 1) {
979                         eed = edarray[edindex];
980                         walker_select(em, BMW_LOOP, eed, TRUE);
981                 }
982                 EDBM_selectmode_flush(em);
983         }
984         MEM_freeN(edarray);
985 //      if (EM_texFaceCheck())
986         
987         WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit);
988
989         return OPERATOR_FINISHED;
990 }
991
992 void MESH_OT_loop_multi_select(wmOperatorType *ot)
993 {
994         /* identifiers */
995         ot->name = "Multi Select Loops";
996         ot->idname = "MESH_OT_loop_multi_select";
997         ot->description = "Select a loop of connected edges by connection type";
998         
999         /* api callbacks */
1000         ot->exec = edbm_loop_multiselect_exec;
1001         ot->poll = ED_operator_editmesh;
1002         
1003         /* flags */
1004         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1005         
1006         /* properties */
1007         RNA_def_boolean(ot->srna, "ring", 0, "Ring", "");
1008 }
1009
1010                 
1011 /* ***************** MAIN MOUSE SELECTION ************** */
1012
1013
1014 /* ***************** loop select (non modal) ************** */
1015
1016 static void mouse_mesh_loop(bContext *C, int mval[2], short extend, short ring)
1017 {
1018         ViewContext vc;
1019         BMEditMesh *em;
1020         BMEdge *eed;
1021         int select = TRUE;
1022         float dist = 50.0f;
1023         float mvalf[2];
1024
1025         em_setup_viewcontext(C, &vc);
1026         mvalf[0] = (float)(vc.mval[0] = mval[0]);
1027         mvalf[1] = (float)(vc.mval[1] = mval[1]);
1028         em = vc.em;
1029
1030         /* no afterqueue (yet), so we check it now, otherwise the bm_xxxofs indices are bad */
1031         view3d_validate_backbuf(&vc);
1032
1033         eed = EDBM_edge_find_nearest(&vc, &dist);
1034         if (eed) {
1035                 if (extend == 0) {
1036                         EDBM_flag_disable_all(em, BM_ELEM_SELECT);
1037                 }
1038         
1039                 if (BM_elem_flag_test(eed, BM_ELEM_SELECT) == 0) {
1040                         select = TRUE;
1041                 }
1042                 else if (extend) {
1043                         select = FALSE;
1044                 }
1045
1046                 if (em->selectmode & SCE_SELECT_FACE) {
1047                         walker_select(em, BMW_FACELOOP, eed, select);
1048                 }
1049                 else if (em->selectmode & SCE_SELECT_EDGE) {
1050                         if (ring)
1051                                 walker_select(em, BMW_EDGERING, eed, select);
1052                         else
1053                                 walker_select(em, BMW_LOOP, eed, select);
1054                 }
1055                 else if (em->selectmode & SCE_SELECT_VERTEX) {
1056                         if (ring)
1057                                 walker_select(em, BMW_EDGERING, eed, select);
1058
1059                         else
1060                                 walker_select(em, BMW_LOOP, eed, select);
1061                 }
1062
1063                 EDBM_selectmode_flush(em);
1064
1065                 /* sets as active, useful for other tools */
1066                 if (select) {
1067                         if (em->selectmode & SCE_SELECT_VERTEX) {
1068                                 /* Find nearest vert from mouse
1069                                  * (initialize to large values incase only one vertex can be projected) */
1070                                 float v1_co[2], v2_co[2];
1071                                 float length_1 = FLT_MAX;
1072                                 float length_2 = FLT_MAX;
1073
1074                                 /* We can't be sure this has already been set... */
1075                                 ED_view3d_init_mats_rv3d(vc.obedit, vc.rv3d);
1076
1077                                 if (ED_view3d_project_float_object(vc.ar, eed->v1->co, v1_co, V3D_PROJ_TEST_NOP) == V3D_PROJ_RET_OK) {
1078                                         length_1 = len_squared_v2v2(mvalf, v1_co);
1079                                 }
1080
1081                                 if (ED_view3d_project_float_object(vc.ar, eed->v2->co, v2_co, V3D_PROJ_TEST_NOP) == V3D_PROJ_RET_OK) {
1082                                         length_2 = len_squared_v2v2(mvalf, v2_co);
1083                                 }
1084 #if 0
1085                                 printf("mouse to v1: %f\nmouse to v2: %f\n", len_squared_v2v2(mvalf, v1_co),
1086                                        len_squared_v2v2(mvalf, v2_co));
1087 #endif
1088                                 BM_select_history_store(em->bm, (length_1 < length_2) ? eed->v1 : eed->v2);
1089                         }
1090                         else if (em->selectmode & SCE_SELECT_EDGE) {
1091                                 BM_select_history_store(em->bm, eed);
1092                         }
1093                         else if (em->selectmode & SCE_SELECT_FACE) {
1094                                 /* Select the face of eed which is the nearest of mouse. */
1095                                 BMFace *f, *efa = NULL;
1096                                 BMIter iterf;
1097                                 float best_dist = MAXFLOAT;
1098
1099                                 /* We can't be sure this has already been set... */
1100                                 ED_view3d_init_mats_rv3d(vc.obedit, vc.rv3d);
1101
1102                                 BM_ITER_ELEM(f, &iterf, eed, BM_FACES_OF_EDGE) {
1103                                         if (BM_elem_flag_test(f, BM_ELEM_SELECT)) {
1104                                                 float cent[3];
1105                                                 float co[2], tdist;
1106
1107                                                 BM_face_calc_center_mean(f, cent);
1108                                                 if (ED_view3d_project_float_object(vc.ar, cent, co, V3D_PROJ_TEST_NOP) == V3D_PROJ_RET_OK) {
1109                                                         tdist = len_squared_v2v2(mvalf, co);
1110                                                         if (tdist < best_dist) {
1111 /*                                                              printf("Best face: %p (%f)\n", f, tdist);*/
1112                                                                 best_dist = tdist;
1113                                                                 efa = f;
1114                                                         }
1115                                                 }
1116                                         }
1117                                 }
1118                                 if (efa) {
1119                                         BM_active_face_set(em->bm, efa);
1120                                         BM_select_history_store(em->bm, efa);
1121                                 }
1122                         }
1123                 }
1124
1125                 WM_event_add_notifier(C, NC_GEOM | ND_SELECT, vc.obedit);
1126         }
1127 }
1128
1129 static int edbm_select_loop_invoke(bContext *C, wmOperator *op, wmEvent *event)
1130 {
1131         
1132         view3d_operator_needs_opengl(C);
1133         
1134         mouse_mesh_loop(C, event->mval, RNA_boolean_get(op->ptr, "extend"),
1135                         RNA_boolean_get(op->ptr, "ring"));
1136         
1137         /* cannot do tweaks for as long this keymap is after transform map */
1138         return OPERATOR_FINISHED;
1139 }
1140
1141 void MESH_OT_loop_select(wmOperatorType *ot)
1142 {
1143         /* identifiers */
1144         ot->name = "Loop Select";
1145         ot->idname = "MESH_OT_loop_select";
1146         ot->description = "Select a loop of connected edges";
1147         
1148         /* api callbacks */
1149         ot->invoke = edbm_select_loop_invoke;
1150         ot->poll = ED_operator_editmesh_region_view3d;
1151         
1152         /* flags */
1153         ot->flag = OPTYPE_UNDO;
1154         
1155         /* properties */
1156         RNA_def_boolean(ot->srna, "extend", 0, "Extend Select", "Extend the selection");
1157         RNA_def_boolean(ot->srna, "ring", 0, "Select Ring", "Select ring");
1158 }
1159
1160 void MESH_OT_edgering_select(wmOperatorType *ot)
1161 {
1162         /* description */
1163         ot->name = "Edge Ring Select";
1164         ot->idname = "MESH_OT_edgering_select";
1165         ot->description = "Select an edge ring";
1166         
1167         /* callbacks */
1168         ot->invoke = edbm_select_loop_invoke;
1169         ot->poll = ED_operator_editmesh_region_view3d;
1170         
1171         /* flags */
1172         ot->flag = OPTYPE_UNDO;
1173
1174         RNA_def_boolean(ot->srna, "extend", 0, "Extend", "Extend the selection");
1175         RNA_def_boolean(ot->srna, "ring", 1, "Select Ring", "Select ring");
1176 }
1177
1178 /* ******************* edgetag_shortest_path and helpers ****************** */
1179
1180 static float edgetag_cut_cost(BMEditMesh *UNUSED(em), BMEdge *e1, BMEdge *e2, BMVert *v)
1181 {
1182         BMVert *v1 = (e1->v1 == v) ? e1->v2 : e1->v1;
1183         BMVert *v2 = (e2->v1 == v) ? e2->v2 : e2->v1;
1184         float cost, d1[3], d2[3];
1185
1186         /* The cost is based on the simple sum of the length of the two edgees... */
1187         sub_v3_v3v3(d1, v->co, v1->co);
1188         sub_v3_v3v3(d2, v2->co, v->co);
1189         cost = len_v3(d1) + len_v3(d2);
1190
1191         /* but is biased to give higher values to sharp turns, so that it will take
1192          * paths with fewer "turns" when selecting between equal-weighted paths between
1193          * the two edges */
1194         cost = cost + 0.5f * cost * (2.0f - sqrtf(fabsf(dot_v3v3(d1, d2))));
1195
1196         return cost;
1197 }
1198
1199 static void edgetag_add_adjacent(BMEditMesh *em, Heap *heap,
1200                                  BMEdge *e1, BMVert *v,
1201                                  int *prevedge, float *cost)
1202 {
1203         BMIter eiter;
1204         BMEdge *e2;
1205
1206         const int e1_index = BM_elem_index_get(e1);
1207
1208         BM_ITER_ELEM (e2, &eiter, v, BM_EDGES_OF_VERT) {
1209                 if (!BM_elem_flag_test(e2, BM_ELEM_TAG)) {
1210                         const int e2_index = BM_elem_index_get(e2);
1211                         const float cost_cut = edgetag_cut_cost(em, e1, e2, v);
1212                         const float cost_new = cost[e1_index] + cost_cut;
1213
1214                         if (cost[e2_index] > cost_new) {
1215                                 cost[e2_index] = cost_new;
1216                                 prevedge[e2_index] = e1_index;
1217                                 BLI_heap_insert(heap, cost_new, e2);
1218                         }
1219                 }
1220         }
1221 }
1222
1223 static void edgetag_context_set(BMEditMesh *em, Scene *scene, BMEdge *e, int val)
1224 {
1225         
1226         switch (scene->toolsettings->edge_mode) {
1227                 case EDGE_MODE_SELECT:
1228                         BM_edge_select_set(em->bm, e, val);
1229                         break;
1230                 case EDGE_MODE_TAG_SEAM:
1231                         BM_elem_flag_set(e, BM_ELEM_SEAM, val);
1232                         break;
1233                 case EDGE_MODE_TAG_SHARP:
1234                         BM_elem_flag_set(e, BM_ELEM_SMOOTH, !val);
1235                         break;
1236                 case EDGE_MODE_TAG_CREASE:
1237                 {
1238                         float *crease = CustomData_bmesh_get(&em->bm->edata, e->head.data, CD_CREASE);
1239                         *crease = (val) ? 1.0f : 0.0f;
1240                         break;
1241                 }
1242                 case EDGE_MODE_TAG_BEVEL:
1243                 {
1244                         float *bweight = CustomData_bmesh_get(&em->bm->edata, e->head.data, CD_BWEIGHT);
1245                         *bweight = (val) ? 1.0f : 0.0f;
1246                         break;
1247                 }
1248         }
1249 }
1250
1251 static int edgetag_context_check(Scene *scene, BMEditMesh *em, BMEdge *e)
1252 {
1253         switch (scene->toolsettings->edge_mode) {
1254                 case EDGE_MODE_SELECT:
1255                         return BM_elem_flag_test(e, BM_ELEM_SELECT) ? 1 : 0;
1256                 case EDGE_MODE_TAG_SEAM:
1257                         return BM_elem_flag_test(e, BM_ELEM_SEAM);
1258                 case EDGE_MODE_TAG_SHARP:
1259                         return !BM_elem_flag_test(e, BM_ELEM_SMOOTH);
1260                 case EDGE_MODE_TAG_CREASE:
1261                         return BM_elem_float_data_get(&em->bm->edata, e, CD_CREASE) ? 1 : 0;
1262                 case EDGE_MODE_TAG_BEVEL:
1263                         return BM_elem_float_data_get(&em->bm->edata, e, CD_BWEIGHT) ? 1 : 0;
1264         }
1265         return 0;
1266 }
1267
1268 static int edgetag_shortest_path(Scene *scene, BMEditMesh *em, BMEdge *e_src, BMEdge *e_dst)
1269 {
1270         /* BM_ELEM_TAG flag is used to store visited edges */
1271         BMEdge *e;
1272         BMIter eiter;
1273         Heap *heap;
1274         float *cost;
1275         int *prevedge;
1276         int i, totedge;
1277
1278         /* note, would pass BM_EDGE except we are looping over all edges anyway */
1279         BM_mesh_elem_index_ensure(em->bm, BM_VERT /* | BM_EDGE */);
1280
1281         BM_ITER_MESH_INDEX (e, &eiter, em->bm, BM_EDGES_OF_MESH, i) {
1282                 if (BM_elem_flag_test(e, BM_ELEM_HIDDEN) == FALSE) {
1283                         BM_elem_flag_disable(e, BM_ELEM_TAG);
1284                 }
1285                 else {
1286                         BM_elem_flag_enable(e, BM_ELEM_TAG);
1287                 }
1288
1289                 BM_elem_index_set(e, i); /* set_inline */
1290         }
1291         em->bm->elem_index_dirty &= ~BM_EDGE;
1292
1293         /* alloc */
1294         totedge = em->bm->totedge;
1295         prevedge = MEM_mallocN(sizeof(*prevedge) * totedge, "SeamPathPrevious");
1296         cost = MEM_mallocN(sizeof(*cost) * totedge, "SeamPathCost");
1297
1298         for (i = 0; i < totedge; i++) {
1299                 cost[i] = 1e20f;
1300                 prevedge[i] = -1;
1301         }
1302
1303         /*
1304          * Arrays are now filled as follows:
1305          *
1306          * As the search continues, prevedge[n] will be the previous edge on the shortest
1307          * path found so far to edge n. The visitedhash will of course contain entries
1308          * for edges that have been visited, cost[n] will contain the length of the shortest
1309          * path to edge n found so far, Finally, heap is a priority heap which is built on the
1310          * the same data as the cost array, but inverted: it is a worklist of edges prioritized
1311          * by the shortest path found so far to the edge.
1312          */
1313
1314         /* regular dijkstra shortest path, but over edges instead of vertices */
1315         heap = BLI_heap_new();
1316         BLI_heap_insert(heap, 0.0f, e_src);
1317         cost[BM_elem_index_get(e_src)] = 0.0f;
1318         EDBM_index_arrays_init(em, 1, 1, 0);
1319
1320         e = NULL;
1321         while (!BLI_heap_is_empty(heap)) {
1322                 e = BLI_heap_popmin(heap);
1323
1324                 if (e == e_dst)
1325                         break;
1326
1327                 if (BM_elem_flag_test(e, BM_ELEM_TAG)) {
1328                         continue;
1329                 }
1330
1331                 BM_elem_flag_enable(e, BM_ELEM_TAG);
1332
1333                 edgetag_add_adjacent(em, heap, e, e->v1, prevedge, cost);
1334                 edgetag_add_adjacent(em, heap, e, e->v2, prevedge, cost);
1335         }
1336         
1337         if (e == e_dst) {
1338                 short allseams = 1;
1339                 int e_index;
1340
1341                 /* Check whether the path is already completely tagged.
1342                  * if it is, the tags will be cleared instead of set. */
1343                 e_index = BM_elem_index_get(e_dst);
1344                 do {
1345                         e = EDBM_edge_at_index(em, e_index);
1346                         if (!edgetag_context_check(scene, em, e)) {
1347                                 allseams = 0;
1348                                 break;
1349                         }
1350                         e_index = prevedge[e_index];
1351                 } while (e != e_src);
1352
1353                 /* Follow path back and source and add or remove tags */
1354                 e_index = BM_elem_index_get(e_dst);
1355                 do {
1356                         e = EDBM_edge_at_index(em, e_index);
1357                         if (allseams)
1358                                 edgetag_context_set(em, scene, e, 0);
1359                         else
1360                                 edgetag_context_set(em, scene, e, 1);
1361                         e_index = prevedge[e_index];
1362                 } while (e_index != -1);
1363         }
1364
1365         EDBM_index_arrays_free(em);
1366         MEM_freeN(prevedge);
1367         MEM_freeN(cost);
1368         BLI_heap_free(heap, NULL);
1369
1370         return 1;
1371 }
1372
1373 /* ******************* mesh shortest path select, uses prev-selected edge ****************** */
1374
1375 /* since you want to create paths with multiple selects, it doesn't have extend option */
1376 static int mouse_mesh_shortest_path(bContext *C, int mval[2])
1377 {
1378         ViewContext vc;
1379         BMEditMesh *em;
1380         BMEdge *e;
1381         float dist = 75.0f;
1382         
1383         em_setup_viewcontext(C, &vc);
1384         vc.mval[0] = mval[0];
1385         vc.mval[1] = mval[1];
1386         em = vc.em;
1387         
1388         e = EDBM_edge_find_nearest(&vc, &dist);
1389         if (e) {
1390                 Mesh *me = vc.obedit->data;
1391                 int path = 0;
1392                 
1393                 if (em->bm->selected.last) {
1394                         BMEditSelection *ese = em->bm->selected.last;
1395                         
1396                         if (ese && ese->htype == BM_EDGE) {
1397                                 BMEdge *e_act;
1398                                 e_act = (BMEdge *)ese->ele;
1399                                 if (e_act != e) {
1400                                         if (edgetag_shortest_path(vc.scene, em, e_act, e)) {
1401                                                 BM_select_history_remove(em->bm, e_act);
1402                                                 path = 1;
1403                                         }
1404                                 }
1405                         }
1406                 }
1407                 if (path == 0) {
1408                         int act = (edgetag_context_check(vc.scene, em, e) == 0);
1409                         edgetag_context_set(em, vc.scene, e, act); /* switch the edge option */
1410                 }
1411                 
1412                 EDBM_selectmode_flush(em);
1413
1414                 /* even if this is selected it may not be in the selection list */
1415                 if (edgetag_context_check(vc.scene, em, e) == 0)
1416                         BM_select_history_remove(em->bm, e);
1417                 else
1418                         BM_select_history_store(em->bm, e);
1419         
1420                 /* force drawmode for mesh */
1421                 switch (CTX_data_tool_settings(C)->edge_mode) {
1422                         
1423                         case EDGE_MODE_TAG_SEAM:
1424                                 me->drawflag |= ME_DRAWSEAMS;
1425                                 ED_uvedit_live_unwrap(vc.scene, vc.obedit);
1426                                 break;
1427                         case EDGE_MODE_TAG_SHARP:
1428                                 me->drawflag |= ME_DRAWSHARP;
1429                                 break;
1430                         case EDGE_MODE_TAG_CREASE:
1431                                 me->drawflag |= ME_DRAWCREASES;
1432                                 break;
1433                         case EDGE_MODE_TAG_BEVEL:
1434                                 me->drawflag |= ME_DRAWBWEIGHTS;
1435                                 break;
1436                 }
1437                 
1438                 EDBM_update_generic(C, em, FALSE);
1439
1440                 return TRUE;
1441         }
1442         else {
1443                 return FALSE;
1444         }
1445 }
1446
1447
1448 static int edbm_shortest_path_select_invoke(bContext *C, wmOperator *UNUSED(op), wmEvent *event)
1449 {
1450         
1451         view3d_operator_needs_opengl(C);
1452
1453         if (mouse_mesh_shortest_path(C, event->mval)) {
1454                 return OPERATOR_FINISHED;
1455         }
1456         else {
1457                 return OPERATOR_PASS_THROUGH;
1458         }
1459 }
1460
1461 static int edbm_shortest_path_select_poll(bContext *C)
1462 {
1463         if (ED_operator_editmesh_region_view3d(C)) {
1464                 Object *obedit = CTX_data_edit_object(C);
1465                 BMEditMesh *em = BMEdit_FromObject(obedit);
1466                 return (em->selectmode & SCE_SELECT_EDGE) != 0;
1467         }
1468         return 0;
1469 }
1470
1471 void MESH_OT_select_shortest_path(wmOperatorType *ot)
1472 {
1473         /* identifiers */
1474         ot->name = "Shortest Path Select";
1475         ot->idname = "MESH_OT_select_shortest_path";
1476         ot->description = "Select shortest path between two selections";
1477         
1478         /* api callbacks */
1479         ot->invoke = edbm_shortest_path_select_invoke;
1480         ot->poll = edbm_shortest_path_select_poll;
1481         
1482         /* flags */
1483         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1484         
1485         /* properties */
1486         RNA_def_boolean(ot->srna, "extend", 0, "Extend Select", "");
1487 }
1488
1489 /* ************************************************** */
1490 /* here actual select happens */
1491 /* gets called via generic mouse select operator */
1492 int EDBM_select_pick(bContext *C, const int mval[2], short extend, short deselect, short toggle)
1493 {
1494         ViewContext vc;
1495         BMVert *eve = NULL;
1496         BMEdge *eed = NULL;
1497         BMFace *efa = NULL;
1498
1499         /* setup view context for argument to callbacks */
1500         em_setup_viewcontext(C, &vc);
1501         vc.mval[0] = mval[0];
1502         vc.mval[1] = mval[1];
1503
1504         if (unified_findnearest(&vc, &eve, &eed, &efa)) {
1505
1506                 /* Deselect everything */
1507                 if (extend == 0 && deselect == 0 && toggle == 0)
1508                         EDBM_flag_disable_all(vc.em, BM_ELEM_SELECT);
1509
1510                 if (efa) {
1511                         if (extend) {
1512                                 /* set the last selected face */
1513                                 BM_active_face_set(vc.em->bm, efa);
1514
1515                                 /* Work-around: deselect first, so we can guarantee it will */
1516                                 /* be active even if it was already selected */
1517                                 BM_select_history_remove(vc.em->bm, efa);
1518                                 BM_face_select_set(vc.em->bm, efa, FALSE);
1519                                 BM_select_history_store(vc.em->bm, efa);
1520                                 BM_face_select_set(vc.em->bm, efa, TRUE);
1521                         }
1522                         else if (deselect) {
1523                                 BM_select_history_remove(vc.em->bm, efa);
1524                                 BM_face_select_set(vc.em->bm, efa, FALSE);
1525                         }
1526                         else {
1527                                 /* set the last selected face */
1528                                 BM_active_face_set(vc.em->bm, efa);
1529
1530                                 if (!BM_elem_flag_test(efa, BM_ELEM_SELECT)) {
1531                                         BM_select_history_store(vc.em->bm, efa);
1532                                         BM_face_select_set(vc.em->bm, efa, TRUE);
1533                                 }
1534                                 else if (toggle) {
1535                                         BM_select_history_remove(vc.em->bm, efa);
1536                                         BM_face_select_set(vc.em->bm, efa, FALSE);
1537                                 }
1538                         }
1539                 }
1540                 else if (eed) {
1541                         if (extend) {
1542                                 /* Work-around: deselect first, so we can guarantee it will */
1543                                 /* be active even if it was already selected */
1544                                 BM_select_history_remove(vc.em->bm, eed);
1545                                 BM_edge_select_set(vc.em->bm, eed, FALSE);
1546                                 BM_select_history_store(vc.em->bm, eed);
1547                                 BM_edge_select_set(vc.em->bm, eed, TRUE);
1548                         }
1549                         else if (deselect) {
1550                                 BM_select_history_remove(vc.em->bm, eed);
1551                                 BM_edge_select_set(vc.em->bm, eed, FALSE);
1552                         }
1553                         else {
1554                                 if (!BM_elem_flag_test(eed, BM_ELEM_SELECT)) {
1555                                         BM_select_history_store(vc.em->bm, eed);
1556                                         BM_edge_select_set(vc.em->bm, eed, TRUE);
1557                                 }
1558                                 else if (toggle) {
1559                                         BM_select_history_remove(vc.em->bm, eed);
1560                                         BM_edge_select_set(vc.em->bm, eed, FALSE);
1561                                 }
1562                         }
1563                 }
1564                 else if (eve) {
1565                         if (extend) {
1566                                 /* Work-around: deselect first, so we can guarantee it will */
1567                                 /* be active even if it was already selected */
1568                                 BM_select_history_remove(vc.em->bm, eve);
1569                                 BM_vert_select_set(vc.em->bm, eve, FALSE);
1570                                 BM_select_history_store(vc.em->bm, eve);
1571                                 BM_vert_select_set(vc.em->bm, eve, TRUE);
1572                         }
1573                         else if (deselect) {
1574                                 BM_select_history_remove(vc.em->bm, eve);
1575                                 BM_vert_select_set(vc.em->bm, eve, FALSE);
1576                         }
1577                         else {
1578                                 if (!BM_elem_flag_test(eve, BM_ELEM_SELECT)) {
1579                                         BM_select_history_store(vc.em->bm, eve);
1580                                         BM_vert_select_set(vc.em->bm, eve, TRUE);
1581                                 }
1582                                 else if (toggle) {
1583                                         BM_select_history_remove(vc.em->bm, eve);
1584                                         BM_vert_select_set(vc.em->bm, eve, FALSE);
1585                                 }
1586                         }
1587                 }
1588
1589                 EDBM_selectmode_flush(vc.em);
1590
1591                 /* change active material on object */
1592                 if (efa && efa->mat_nr != vc.obedit->actcol - 1) {
1593                         vc.obedit->actcol = efa->mat_nr + 1;
1594                         vc.em->mat_nr = efa->mat_nr;
1595
1596                         WM_event_add_notifier(C, NC_MATERIAL | ND_SHADING, NULL);
1597
1598                 }
1599
1600                 WM_event_add_notifier(C, NC_GEOM | ND_SELECT, vc.obedit);
1601                 return 1;
1602         }
1603
1604         return 0;
1605 }
1606
1607 static void edbm_strip_selections(BMEditMesh *em)
1608 {
1609         BMEditSelection *ese, *nextese;
1610
1611         if (!(em->selectmode & SCE_SELECT_VERTEX)) {
1612                 ese = em->bm->selected.first;
1613                 while (ese) {
1614                         nextese = ese->next;
1615                         if (ese->htype == BM_VERT) BLI_freelinkN(&(em->bm->selected), ese);
1616                         ese = nextese;
1617                 }
1618         }
1619         if (!(em->selectmode & SCE_SELECT_EDGE)) {
1620                 ese = em->bm->selected.first;
1621                 while (ese) {
1622                         nextese = ese->next;
1623                         if (ese->htype == BM_EDGE) BLI_freelinkN(&(em->bm->selected), ese);
1624                         ese = nextese;
1625                 }
1626         }
1627         if (!(em->selectmode & SCE_SELECT_FACE)) {
1628                 ese = em->bm->selected.first;
1629                 while (ese) {
1630                         nextese = ese->next;
1631                         if (ese->htype == BM_FACE) BLI_freelinkN(&(em->bm->selected), ese);
1632                         ese = nextese;
1633                 }
1634         }
1635 }
1636
1637 /* when switching select mode, makes sure selection is consistent for editing */
1638 /* also for paranoia checks to make sure edge or face mode works */
1639 void EDBM_selectmode_set(BMEditMesh *em)
1640 {
1641         BMVert *eve;
1642         BMEdge *eed;
1643         BMFace *efa;
1644         BMIter iter;
1645         
1646         em->bm->selectmode = em->selectmode;
1647
1648         edbm_strip_selections(em); /* strip BMEditSelections from em->selected that are not relevant to new mode */
1649         
1650         if (em->selectmode & SCE_SELECT_VERTEX) {
1651                 EDBM_select_flush(em);
1652         }
1653         else if (em->selectmode & SCE_SELECT_EDGE) {
1654                 /* deselect vertices, and select again based on edge select */
1655                 eve = BM_iter_new(&iter, em->bm, BM_VERTS_OF_MESH, NULL);
1656                 for (; eve; eve = BM_iter_step(&iter)) BM_vert_select_set(em->bm, eve, FALSE);
1657                 
1658                 eed = BM_iter_new(&iter, em->bm, BM_EDGES_OF_MESH, NULL);
1659                 for (; eed; eed = BM_iter_step(&iter)) {
1660                         if (BM_elem_flag_test(eed, BM_ELEM_SELECT)) {
1661                                 BM_edge_select_set(em->bm, eed, TRUE);
1662                         }
1663                 }
1664                 
1665                 /* selects faces based on edge status */
1666                 EDBM_selectmode_flush(em);
1667         }
1668         else if (em->selectmode & SCE_SELECT_FACE) {
1669                 /* deselect eges, and select again based on face select */
1670                 eed = BM_iter_new(&iter, em->bm, BM_EDGES_OF_MESH, NULL);
1671                 for (; eed; eed = BM_iter_step(&iter)) BM_edge_select_set(em->bm, eed, FALSE);
1672                 
1673                 efa = BM_iter_new(&iter, em->bm, BM_FACES_OF_MESH, NULL);
1674                 for (; efa; efa = BM_iter_step(&iter)) {
1675                         if (BM_elem_flag_test(efa, BM_ELEM_SELECT)) {
1676                                 BM_face_select_set(em->bm, efa, TRUE);
1677                         }
1678                 }
1679         }
1680 }
1681
1682 void EDBM_selectmode_convert(BMEditMesh *em, const short selectmode_old, const short selectmode_new)
1683 {
1684         BMEdge *eed;
1685         BMFace *efa;
1686         BMIter iter;
1687
1688         /* have to find out what the selectionmode was previously */
1689         if (selectmode_old == SCE_SELECT_VERTEX) {
1690                 if (selectmode_new == SCE_SELECT_EDGE) {
1691                         /* select all edges associated with every selected vertex */
1692                         eed = BM_iter_new(&iter, em->bm, BM_EDGES_OF_MESH, NULL);
1693                         for (; eed; eed = BM_iter_step(&iter)) {
1694                                 if ((BM_elem_flag_test(eed->v1, BM_ELEM_SELECT) ||
1695                                      BM_elem_flag_test(eed->v2, BM_ELEM_SELECT)))
1696                                 {
1697                                         BM_edge_select_set(em->bm, eed, TRUE);
1698                                 }
1699                         }
1700                 }
1701                 else if (selectmode_new == SCE_SELECT_FACE) {
1702                         BMIter liter;
1703                         BMLoop *l;
1704
1705                         /* select all faces associated with every selected vertex */
1706                         efa = BM_iter_new(&iter, em->bm, BM_FACES_OF_MESH, NULL);
1707                         for (; efa; efa = BM_iter_step(&iter)) {
1708                                 l = BM_iter_new(&liter, em->bm, BM_LOOPS_OF_FACE, efa);
1709                                 for (; l; l = BM_iter_step(&liter)) {
1710                                         if (BM_elem_flag_test(l->v, BM_ELEM_SELECT)) {
1711                                                 BM_face_select_set(em->bm, efa, TRUE);
1712                                                 break;
1713                                         }
1714                                 }
1715                         }
1716                 }
1717         }
1718         else if (selectmode_old == SCE_SELECT_EDGE) {
1719                 if (selectmode_new == SCE_SELECT_FACE) {
1720                         BMIter liter;
1721                         BMLoop *l;
1722
1723                         /* select all faces associated with every selected vertex */
1724                         efa = BM_iter_new(&iter, em->bm, BM_FACES_OF_MESH, NULL);
1725                         for (; efa; efa = BM_iter_step(&iter)) {
1726                                 l = BM_iter_new(&liter, em->bm, BM_LOOPS_OF_FACE, efa);
1727                                 for (; l; l = BM_iter_step(&liter)) {
1728                                         if (BM_elem_flag_test(l->v, BM_ELEM_SELECT)) {
1729                                                 BM_face_select_set(em->bm, efa, TRUE);
1730                                                 break;
1731                                         }
1732                                 }
1733                         }
1734                 }
1735         }
1736 }
1737
1738
1739 void EDBM_deselect_by_material(BMEditMesh *em, const short index, const short select)
1740 {
1741         BMIter iter;
1742         BMFace *efa;
1743
1744         BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) {
1745                 if (BM_elem_flag_test(efa, BM_ELEM_HIDDEN))
1746                         continue;
1747                 if (efa->mat_nr == index) {
1748                         BM_face_select_set(em->bm, efa, select);
1749                 }
1750         }
1751 }
1752
1753 void EDBM_select_toggle_all(BMEditMesh *em) /* exported for UV */
1754 {
1755         if (em->bm->totvertsel || em->bm->totedgesel || em->bm->totfacesel)
1756                 EDBM_flag_disable_all(em, BM_ELEM_SELECT);
1757         else
1758                 EDBM_flag_enable_all(em, BM_ELEM_SELECT);
1759 }
1760
1761 void EDBM_select_swap(BMEditMesh *em) /* exported for UV */
1762 {
1763         BMIter iter;
1764         BMVert *eve;
1765         BMEdge *eed;
1766         BMFace *efa;
1767         
1768         if (em->bm->selectmode & SCE_SELECT_VERTEX) {
1769                 BM_ITER_MESH (eve, &iter, em->bm, BM_VERTS_OF_MESH) {
1770                         if (BM_elem_flag_test(eve, BM_ELEM_HIDDEN))
1771                                 continue;
1772                         BM_vert_select_set(em->bm, eve, !BM_elem_flag_test(eve, BM_ELEM_SELECT));
1773                 }
1774         }
1775         else if (em->selectmode & SCE_SELECT_EDGE) {
1776                 BM_ITER_MESH (eed, &iter, em->bm, BM_EDGES_OF_MESH) {
1777                         if (BM_elem_flag_test(eed, BM_ELEM_HIDDEN))
1778                                 continue;
1779                         BM_edge_select_set(em->bm, eed, !BM_elem_flag_test(eed, BM_ELEM_SELECT));
1780                 }
1781         }
1782         else {
1783                 BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) {
1784                         if (BM_elem_flag_test(efa, BM_ELEM_HIDDEN))
1785                                 continue;
1786                         BM_face_select_set(em->bm, efa, !BM_elem_flag_test(efa, BM_ELEM_SELECT));
1787                 }
1788
1789         }
1790 //      if (EM_texFaceCheck())
1791 }
1792
1793 int EDBM_select_interior_faces(BMEditMesh *em)
1794 {
1795         BMesh *bm = em->bm;
1796         BMIter iter;
1797         BMIter eiter;
1798         BMFace *efa;
1799         BMEdge *eed;
1800         int ok;
1801         int change = FALSE;
1802
1803         BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) {
1804                 if (BM_elem_flag_test(efa, BM_ELEM_HIDDEN))
1805                         continue;
1806
1807
1808                 ok = TRUE;
1809                 BM_ITER_ELEM (eed, &eiter, efa, BM_EDGES_OF_FACE) {
1810                         if (BM_edge_face_count(eed) < 3) {
1811                                 ok = FALSE;
1812                                 break;
1813                         }
1814                 }
1815
1816                 if (ok) {
1817                         BM_face_select_set(bm, efa, TRUE);
1818                         change = TRUE;
1819                 }
1820         }
1821
1822         return change;
1823 }
1824
1825 static void linked_limit_default(bContext *C, wmOperator *op)
1826 {
1827         if (!RNA_struct_property_is_set(op->ptr, "limit")) {
1828                 Object *obedit = CTX_data_edit_object(C);
1829                 BMEditMesh *em = BMEdit_FromObject(obedit);
1830                 if (em->selectmode == SCE_SELECT_FACE)
1831                         RNA_boolean_set(op->ptr, "limit", TRUE);
1832                 else
1833                         RNA_boolean_set(op->ptr, "limit", FALSE);
1834         }
1835 }
1836
1837 static int edbm_select_linked_pick_invoke(bContext *C, wmOperator *op, wmEvent *event)
1838 {
1839         Object *obedit = CTX_data_edit_object(C);
1840         ViewContext vc;
1841         BMesh *bm;
1842         BMWalker walker;
1843         BMEditMesh *em;
1844         BMVert *eve;
1845         BMEdge *e, *eed;
1846         BMFace *efa;
1847         int sel = !RNA_boolean_get(op->ptr, "deselect");
1848
1849         int limit;
1850
1851         linked_limit_default(C, op);
1852
1853         limit = RNA_boolean_get(op->ptr, "limit");
1854
1855         /* unified_finednearest needs ogl */
1856         view3d_operator_needs_opengl(C);
1857         
1858         /* setup view context for argument to callbacks */
1859         em_setup_viewcontext(C, &vc);
1860         em = vc.em;
1861
1862         if (em->bm->totedge == 0)
1863                 return OPERATOR_CANCELLED;
1864         
1865         bm = em->bm;
1866
1867         vc.mval[0] = event->mval[0];
1868         vc.mval[1] = event->mval[1];
1869         
1870         /* return warning! */
1871         
1872         if (unified_findnearest(&vc, &eve, &eed, &efa) == 0) {
1873                 WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit);
1874         
1875                 return OPERATOR_CANCELLED;
1876         }
1877         
1878         if (em->selectmode == SCE_SELECT_FACE) {
1879                 BMIter iter;
1880
1881                 if (efa == NULL)
1882                         return OPERATOR_CANCELLED;
1883
1884                 if (limit) {
1885                         /* hflag no-seam --> bmo-tag */
1886                         BM_ITER_MESH (e, &iter, bm, BM_EDGES_OF_MESH) {
1887                                 /* BMESH_TODO, don't use 'BM_ELEM_SELECT' here, its a HFLAG only! */
1888                                 BMO_elem_flag_set(bm, e, BM_ELEM_SELECT, !BM_elem_flag_test(e, BM_ELEM_SEAM));
1889                         }
1890                 }
1891
1892                 /* walk */
1893                 BMW_init(&walker, bm, BMW_ISLAND,
1894                          BMW_MASK_NOP, limit ? BM_ELEM_SELECT : BMW_MASK_NOP, BMW_MASK_NOP,
1895                          BMW_FLAG_TEST_HIDDEN,
1896                          BMW_NIL_LAY);
1897
1898                 e = BMW_begin(&walker, efa);
1899                 for (; efa; efa = BMW_step(&walker)) {
1900                         BM_face_select_set(bm, efa, sel);
1901                 }
1902                 BMW_end(&walker);
1903         }
1904         else {
1905                 if (efa) {
1906                         eed = BM_FACE_FIRST_LOOP(efa)->e;
1907                 }
1908                 else if (!eed) {
1909                         if (!eve || !eve->e)
1910                                 return OPERATOR_CANCELLED;
1911
1912                         eed = eve->e;
1913                 }
1914
1915                 BMW_init(&walker, bm, BMW_SHELL,
1916                          BMW_MASK_NOP, BMW_MASK_NOP, BMW_MASK_NOP,
1917                          BMW_FLAG_TEST_HIDDEN,
1918                          BMW_NIL_LAY);
1919
1920                 e = BMW_begin(&walker, eed->v1);
1921                 for (; e; e = BMW_step(&walker)) {
1922                         BM_edge_select_set(bm, e, sel);
1923                 }
1924                 BMW_end(&walker);
1925
1926                 EDBM_selectmode_flush(em);
1927         }
1928
1929         WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit);
1930         return OPERATOR_FINISHED;
1931 }
1932
1933 void MESH_OT_select_linked_pick(wmOperatorType *ot)
1934 {
1935         /* identifiers */
1936         ot->name = "Select Linked";
1937         ot->idname = "MESH_OT_select_linked_pick";
1938         ot->description = "(De)select all vertices linked to the edge under the mouse cursor";
1939         
1940         /* api callbacks */
1941         ot->invoke = edbm_select_linked_pick_invoke;
1942         ot->poll = ED_operator_editmesh;
1943         
1944         /* flags */
1945         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1946         
1947         RNA_def_boolean(ot->srna, "deselect", 0, "Deselect", "");
1948         RNA_def_boolean(ot->srna, "limit", 0, "Limit by Seams", "");
1949 }
1950
1951
1952 static int edbm_select_linked_exec(bContext *C, wmOperator *op)
1953 {
1954         Object *obedit = CTX_data_edit_object(C);
1955         BMEditMesh *em = BMEdit_FromObject(obedit);
1956         BMesh *bm = em->bm;
1957         BMIter iter;
1958         BMVert *v;
1959         BMEdge *e;
1960         BMWalker walker;
1961
1962         int limit;
1963
1964         linked_limit_default(C, op);
1965
1966         limit = RNA_boolean_get(op->ptr, "limit");
1967
1968         if (em->selectmode == SCE_SELECT_FACE) {
1969                 BMFace *efa;
1970
1971                 BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) {
1972                         BM_elem_flag_set(efa, BM_ELEM_TAG, (BM_elem_flag_test(efa, BM_ELEM_SELECT) &&
1973                                                             !BM_elem_flag_test(efa, BM_ELEM_HIDDEN)));
1974                 }
1975
1976                 if (limit) {
1977                         BM_ITER_MESH (e, &iter, bm, BM_EDGES_OF_MESH) {
1978                                 /* BMESH_TODO, don't use 'BM_ELEM_SELECT' here, its a HFLAG only! */
1979                                 BMO_elem_flag_set(bm, e, BM_ELEM_SELECT, !BM_elem_flag_test(e, BM_ELEM_SEAM));
1980                         }
1981                 }
1982
1983                 BMW_init(&walker, bm, BMW_ISLAND,
1984                          BMW_MASK_NOP, limit ? BM_ELEM_SELECT : BMW_MASK_NOP, BMW_MASK_NOP,
1985                          BMW_FLAG_TEST_HIDDEN,
1986                          BMW_NIL_LAY);
1987
1988                 BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) {
1989                         if (BM_elem_flag_test(efa, BM_ELEM_TAG)) {
1990                                 e = BMW_begin(&walker, efa);
1991                                 for (; efa; efa = BMW_step(&walker)) {
1992                                         BM_face_select_set(bm, efa, TRUE);
1993                                 }
1994                         }
1995                 }
1996                 BMW_end(&walker);
1997         }
1998         else {
1999                 BM_ITER_MESH (v, &iter, em->bm, BM_VERTS_OF_MESH) {
2000                         if (BM_elem_flag_test(v, BM_ELEM_SELECT)) {
2001                                 BM_elem_flag_enable(v, BM_ELEM_TAG);
2002                         }
2003                         else {
2004                                 BM_elem_flag_disable(v, BM_ELEM_TAG);
2005                         }
2006                 }
2007
2008                 BMW_init(&walker, em->bm, BMW_SHELL,
2009                          BMW_MASK_NOP, BMW_MASK_NOP, BMW_MASK_NOP,
2010                          BMW_FLAG_TEST_HIDDEN,
2011                          BMW_NIL_LAY);
2012
2013                 BM_ITER_MESH (v, &iter, em->bm, BM_VERTS_OF_MESH) {
2014                         if (BM_elem_flag_test(v, BM_ELEM_TAG)) {
2015                                 e = BMW_begin(&walker, v);
2016                                 for (; e; e = BMW_step(&walker)) {
2017                                         BM_vert_select_set(em->bm, e->v1, TRUE);
2018                                         BM_vert_select_set(em->bm, e->v2, TRUE);
2019                                 }
2020                         }
2021                 }
2022                 BMW_end(&walker);
2023         }
2024         EDBM_selectmode_flush_ex(em, SCE_SELECT_VERTEX);
2025
2026         WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit);
2027
2028         return OPERATOR_FINISHED;
2029 }
2030
2031 void MESH_OT_select_linked(wmOperatorType *ot)
2032 {
2033         /* identifiers */
2034         ot->name = "Select Linked All";
2035         ot->idname = "MESH_OT_select_linked";
2036         ot->description = "Select all vertices linked to the active mesh";
2037         
2038         /* api callbacks */
2039         ot->exec = edbm_select_linked_exec;
2040         ot->poll = ED_operator_editmesh;
2041         
2042         /* flags */
2043         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2044         
2045         RNA_def_boolean(ot->srna, "limit", 0, "Limit by Seams", "");
2046 }
2047
2048 /* ******************** **************** */
2049
2050 static int edbm_select_more_exec(bContext *C, wmOperator *UNUSED(op))
2051 {
2052         Object *obedit = CTX_data_edit_object(C);
2053         BMEditMesh *em = BMEdit_FromObject(obedit);
2054
2055         EDBM_select_more(em);
2056
2057         WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit);
2058         return OPERATOR_FINISHED;
2059 }
2060
2061 void MESH_OT_select_more(wmOperatorType *ot)
2062 {
2063         /* identifiers */
2064         ot->name = "Select More";
2065         ot->idname = "MESH_OT_select_more";
2066         ot->description = "Select more vertices, edges or faces connected to initial selection";
2067
2068         /* api callbacks */
2069         ot->exec = edbm_select_more_exec;
2070         ot->poll = ED_operator_editmesh;
2071         
2072         /* flags */
2073         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2074 }
2075
2076 static int edbm_select_less_exec(bContext *C, wmOperator *UNUSED(op))
2077 {
2078         Object *obedit = CTX_data_edit_object(C);
2079         BMEditMesh *em = BMEdit_FromObject(obedit);
2080
2081         EDBM_select_less(em);
2082
2083         WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit);
2084         return OPERATOR_FINISHED;
2085 }
2086
2087 void MESH_OT_select_less(wmOperatorType *ot)
2088 {
2089         /* identifiers */
2090         ot->name = "Select Less";
2091         ot->idname = "MESH_OT_select_less";
2092         ot->description = "Deselect vertices, edges or faces at the boundary of each selection region";
2093
2094         /* api callbacks */
2095         ot->exec = edbm_select_less_exec;
2096         ot->poll = ED_operator_editmesh;
2097         
2098         /* flags */
2099         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2100 }
2101
2102 /* Walk all reachable elements of the same type as h_act in breadth-first
2103  * order, starting from h_act. Deselects elements if the depth when they
2104  * are reached is not a multiple of "nth". */
2105 static void walker_deselect_nth(BMEditMesh *em, int nth, int offset, BMHeader *h_act)
2106 {
2107         BMElem *ele;
2108         BMesh *bm = em->bm;
2109         BMWalker walker;
2110         BMIter iter;
2111         int walktype = 0, itertype = 0, flushtype = 0;
2112         short mask_vert = 0, mask_edge = 0, mask_face = 0;
2113
2114         /* No active element from which to start - nothing to do */
2115         if (h_act == NULL) {
2116                 return;
2117         }
2118
2119         /* Determine which type of iter, walker, and select flush to use
2120          * based on type of the elements being deselected */
2121         switch (h_act->htype) {
2122                 case BM_VERT:
2123                         itertype = BM_VERTS_OF_MESH;
2124                         walktype = BMW_CONNECTED_VERTEX;
2125                         flushtype = SCE_SELECT_VERTEX;
2126                         mask_vert = BM_ELEM_SELECT;
2127                         break;
2128                 case BM_EDGE:
2129                         itertype = BM_EDGES_OF_MESH;
2130                         walktype = BMW_SHELL;
2131                         flushtype = SCE_SELECT_EDGE;
2132                         mask_edge = BM_ELEM_SELECT;
2133                         break;
2134                 case BM_FACE:
2135                         itertype = BM_FACES_OF_MESH;
2136                         walktype = BMW_ISLAND;
2137                         flushtype = SCE_SELECT_FACE;
2138                         mask_face = BM_ELEM_SELECT;
2139                         break;
2140         }
2141
2142         /* Walker restrictions uses BMO flags, not header flags,
2143          * so transfer BM_ELEM_SELECT from HFlags onto a BMO flag layer. */
2144         BMO_push(bm, NULL);
2145         BM_ITER_MESH (ele, &iter, bm, itertype) {
2146                 if (BM_elem_flag_test(ele, BM_ELEM_SELECT)) {
2147                         /* BMESH_TODO, don't use 'BM_ELEM_SELECT' here, its a HFLAG only! */
2148                         BMO_elem_flag_enable(bm, (BMElemF *)ele, BM_ELEM_SELECT);
2149                 }
2150         }
2151
2152         /* Walk over selected elements starting at active */
2153         BMW_init(&walker, bm, walktype,
2154                  mask_vert, mask_edge, mask_face,
2155                  BMW_FLAG_NOP, /* don't use BMW_FLAG_TEST_HIDDEN here since we want to desel all */
2156                  BMW_NIL_LAY);
2157
2158         /* use tag to avoid touching the same verts twice */
2159         BM_ITER_MESH (ele, &iter, bm, itertype) {
2160                 BM_elem_flag_disable(ele, BM_ELEM_TAG);
2161         }
2162
2163         BLI_assert(walker.order == BMW_BREADTH_FIRST);
2164         for (ele = BMW_begin(&walker, h_act); ele != NULL; ele = BMW_step(&walker)) {
2165                 if (!BM_elem_flag_test(ele, BM_ELEM_TAG)) {
2166                         /* Deselect elements that aren't at "nth" depth from active */
2167                         if ((offset + BMW_current_depth(&walker)) % nth) {
2168                                 BM_elem_select_set(bm, ele, FALSE);
2169                         }
2170                         BM_elem_flag_enable(ele, BM_ELEM_TAG);
2171                 }
2172         }
2173         BMW_end(&walker);
2174
2175         BMO_pop(bm);
2176
2177         /* Flush selection up */
2178         EDBM_selectmode_flush_ex(em, flushtype);
2179 }
2180
2181 static void deselect_nth_active(BMEditMesh *em, BMVert **r_eve, BMEdge **r_eed, BMFace **r_efa)
2182 {
2183         BMVert *v;
2184         BMEdge *e;
2185         BMFace *f;
2186         BMIter iter;
2187         BMEditSelection *ese;
2188
2189         *r_eve = NULL;
2190         *r_eed = NULL;
2191         *r_efa = NULL;
2192
2193         EDBM_selectmode_flush(em);
2194         ese = (BMEditSelection *)em->bm->selected.last;
2195
2196         if (ese) {
2197                 switch (ese->htype) {
2198                         case BM_VERT:
2199                                 *r_eve = (BMVert *)ese->ele;
2200                                 return;
2201                         case BM_EDGE:
2202                                 *r_eed = (BMEdge *)ese->ele;
2203                                 return;
2204                         case BM_FACE:
2205                                 *r_efa = (BMFace *)ese->ele;
2206                                 return;
2207                 }
2208         }
2209
2210         if (em->selectmode & SCE_SELECT_VERTEX) {
2211                 BM_ITER_MESH (v, &iter, em->bm, BM_VERTS_OF_MESH) {
2212                         if (BM_elem_flag_test(v, BM_ELEM_SELECT)) {
2213                                 *r_eve = v;
2214                                 return;
2215                         }
2216                 }
2217         }
2218         else if (em->selectmode & SCE_SELECT_EDGE) {
2219                 BM_ITER_MESH (e, &iter, em->bm, BM_EDGES_OF_MESH) {
2220                         if (BM_elem_flag_test(e, BM_ELEM_SELECT)) {
2221                                 *r_eed = e;
2222                                 return;
2223                         }
2224                 }
2225         }
2226         else if (em->selectmode & SCE_SELECT_FACE) {
2227                 f = BM_active_face_get(em->bm, TRUE, FALSE);
2228                 if (f) {
2229                         *r_efa = f;
2230                         return;
2231                 }
2232         }
2233 }
2234
2235 static int edbm_deselect_nth(BMEditMesh *em, int nth, int offset)
2236 {
2237         BMVert *v;
2238         BMEdge *e;
2239         BMFace *f;
2240
2241         deselect_nth_active(em, &v, &e, &f);
2242
2243         if (v) {
2244                 walker_deselect_nth(em, nth, offset, &v->head);
2245                 return 1;
2246         }
2247         else if (e) {
2248                 walker_deselect_nth(em, nth, offset, &e->head);
2249                 return 1;
2250         }
2251         else if (f) {
2252                 walker_deselect_nth(em, nth, offset, &f->head);
2253                 return 1;
2254         }
2255
2256         return 0;
2257 }
2258
2259 static int edbm_select_nth_exec(bContext *C, wmOperator *op)
2260 {
2261         Object *obedit = CTX_data_edit_object(C);
2262         BMEditMesh *em = BMEdit_FromObject(obedit);
2263         int nth = RNA_int_get(op->ptr, "nth");
2264         int offset = RNA_int_get(op->ptr, "offset");
2265
2266         offset = MIN2(nth, offset);
2267
2268         if (edbm_deselect_nth(em, nth, offset) == 0) {
2269                 BKE_report(op->reports, RPT_ERROR, "Mesh has no active vert/edge/face");
2270                 return OPERATOR_CANCELLED;
2271         }
2272
2273         EDBM_update_generic(C, em, FALSE);
2274
2275         return OPERATOR_FINISHED;
2276 }
2277
2278
2279 void MESH_OT_select_nth(wmOperatorType *ot)
2280 {
2281         /* identifiers */
2282         ot->name = "Checker Deselect";
2283         ot->idname = "MESH_OT_select_nth";
2284         ot->description = "Deselect every Nth element starting from a selected vertex, edge or face";
2285
2286         /* api callbacks */
2287         ot->exec = edbm_select_nth_exec;
2288         ot->poll = ED_operator_editmesh;
2289
2290         /* flags */
2291         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2292
2293         RNA_def_int(ot->srna, "nth", 2, 2, INT_MAX, "Nth Selection", "", 2, 100);
2294         RNA_def_int(ot->srna, "offset", 0, 0, INT_MAX, "Offset", "", 0, 100);
2295 }
2296
2297 void em_setup_viewcontext(bContext *C, ViewContext *vc)
2298 {
2299         view3d_set_viewcontext(C, vc);
2300         
2301         if (vc->obedit) {
2302                 vc->em = BMEdit_FromObject(vc->obedit);
2303         }
2304 }
2305
2306 /* poll call for mesh operators requiring a view3d context */
2307 int EM_view3d_poll(bContext *C)
2308 {
2309         if (ED_operator_editmesh(C) && ED_operator_view3d_active(C))
2310                 return 1;
2311
2312         return 0;
2313 }
2314
2315
2316 static int edbm_select_sharp_edges_exec(bContext *C, wmOperator *op)
2317 {
2318         /* Find edges that have exactly two neighboring faces,
2319          * check the angle between those faces, and if angle is
2320          * small enough, select the edge
2321          */
2322         Object *obedit = CTX_data_edit_object(C);
2323         BMEditMesh *em = BMEdit_FromObject(obedit);
2324         BMIter iter;
2325         BMEdge *e;
2326         BMLoop *l1, *l2;
2327         const float sharp = RNA_float_get(op->ptr, "sharpness");
2328
2329         BM_ITER_MESH (e, &iter, em->bm, BM_EDGES_OF_MESH) {
2330                 if (BM_elem_flag_test(e, BM_ELEM_HIDDEN) == FALSE &&
2331                     BM_edge_loop_pair(e, &l1, &l2))
2332                 {
2333                         /* edge has exactly two neighboring faces, check angle */
2334                         const float angle = angle_normalized_v3v3(l1->f->no, l2->f->no);
2335
2336                         if (fabsf(angle) > sharp) {
2337                                 BM_edge_select_set(em->bm, e, TRUE);
2338                         }
2339                 }
2340         }
2341
2342         WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit->data);
2343
2344         return OPERATOR_FINISHED;
2345 }
2346
2347 void MESH_OT_edges_select_sharp(wmOperatorType *ot)
2348 {
2349         PropertyRNA *prop;
2350
2351         /* identifiers */
2352         ot->name = "Select Sharp Edges";
2353         ot->description = "Select all sharp-enough edges";
2354         ot->idname = "MESH_OT_edges_select_sharp";
2355         
2356         /* api callbacks */
2357         ot->exec = edbm_select_sharp_edges_exec;
2358         ot->poll = ED_operator_editmesh;
2359         
2360         /* flags */
2361         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2362         
2363         /* props */
2364         prop = RNA_def_float_rotation(ot->srna, "sharpness", 0, NULL, DEG2RADF(0.01f), DEG2RADF(180.0f),
2365                                       "Sharpness", "", DEG2RADF(1.0f), DEG2RADF(180.0f));
2366         RNA_def_property_float_default(prop, DEG2RADF(30.0f));
2367 }
2368
2369 static int edbm_select_linked_flat_faces_exec(bContext *C, wmOperator *op)
2370 {
2371         Object *obedit = CTX_data_edit_object(C);
2372         BMEditMesh *em = BMEdit_FromObject(obedit);
2373         BMIter iter, liter, liter2;
2374         BMFace *f, **stack = NULL;
2375         BLI_array_declare(stack);
2376         BMLoop *l, *l2;
2377         float sharp = RNA_float_get(op->ptr, "sharpness");
2378         int i;
2379
2380         BM_ITER_MESH (f, &iter, em->bm, BM_FACES_OF_MESH) {
2381                 BM_elem_flag_disable(f, BM_ELEM_TAG);
2382         }
2383
2384         BM_ITER_MESH (f, &iter, em->bm, BM_FACES_OF_MESH) {
2385                 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))
2386                         continue;
2387
2388                 BLI_array_empty(stack);
2389                 i = 1;
2390
2391                 BLI_array_grow_one(stack);
2392                 stack[i - 1] = f;
2393
2394                 while (i) {
2395                         f = stack[i - 1];
2396                         i--;
2397
2398                         BM_face_select_set(em->bm, f, TRUE);
2399
2400                         BM_elem_flag_enable(f, BM_ELEM_TAG);
2401
2402                         BM_ITER_ELEM (l, &liter, f, BM_LOOPS_OF_FACE) {
2403                                 BM_ITER_ELEM (l2, &liter2, l, BM_LOOPS_OF_LOOP) {
2404                                         float angle;
2405
2406                                         if (BM_elem_flag_test(l2->f, BM_ELEM_TAG) || BM_elem_flag_test(l2->f, BM_ELEM_HIDDEN))
2407                                                 continue;
2408
2409                                         /* edge has exactly two neighboring faces, check angle */
2410                                         angle = angle_normalized_v3v3(f->no, l2->f->no);
2411
2412                                         /* invalidate: edge too sharp */
2413                                         if (angle < sharp) {
2414                                                 BLI_array_grow_one(stack);
2415                                                 stack[i] = l2->f;
2416                                                 i++;
2417                                         }
2418                                 }
2419                         }
2420                 }
2421         }
2422
2423         BLI_array_free(stack);
2424
2425         WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit->data);
2426
2427         return OPERATOR_FINISHED;
2428 }
2429
2430 void MESH_OT_faces_select_linked_flat(wmOperatorType *ot)
2431 {
2432         PropertyRNA *prop;
2433
2434         /* identifiers */
2435         ot->name = "Select Linked Flat Faces";
2436         ot->description = "Select linked faces by angle";
2437         ot->idname = "MESH_OT_faces_select_linked_flat";
2438         
2439         /* api callbacks */
2440         ot->exec = edbm_select_linked_flat_faces_exec;
2441         ot->poll = ED_operator_editmesh;
2442         
2443         /* flags */
2444         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2445         
2446         /* props */
2447         prop = RNA_def_float_rotation(ot->srna, "sharpness", 0, NULL, DEG2RADF(0.01f), DEG2RADF(180.0f),
2448                                       "Sharpness", "", DEG2RADF(1.0f), DEG2RADF(180.0f));
2449         RNA_def_property_float_default(prop, DEG2RADF(1.0f));
2450 }
2451
2452 static int edbm_select_non_manifold_exec(bContext *C, wmOperator *op)
2453 {
2454         Object *obedit = CTX_data_edit_object(C);
2455         BMEditMesh *em = BMEdit_FromObject(obedit);
2456         BMVert *v;
2457         BMEdge *e;
2458         BMIter iter;
2459
2460         /* Selects isolated verts, and edges that do not have 2 neighboring
2461          * faces
2462          */
2463         
2464         if (em->selectmode == SCE_SELECT_FACE) {
2465                 BKE_report(op->reports, RPT_ERROR, "Does not work in face selection mode");
2466                 return OPERATOR_CANCELLED;
2467         }
2468         
2469         BM_ITER_MESH (v, &iter, em->bm, BM_VERTS_OF_MESH) {
2470                 if (!BM_elem_flag_test(v, BM_ELEM_HIDDEN) && !BM_vert_is_manifold(v)) {
2471                         BM_vert_select_set(em->bm, v, TRUE);
2472                 }
2473         }
2474         
2475         BM_ITER_MESH (e, &iter, em->bm, BM_EDGES_OF_MESH) {
2476                 if (!BM_elem_flag_test(e, BM_ELEM_HIDDEN) && !BM_edge_is_manifold(e)) {
2477                         BM_edge_select_set(em->bm, e, TRUE);
2478                 }
2479         }
2480
2481         WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit->data);
2482
2483         return OPERATOR_FINISHED;
2484 }
2485
2486 void MESH_OT_select_non_manifold(wmOperatorType *ot)
2487 {
2488         /* identifiers */
2489         ot->name = "Select Non Manifold";
2490         ot->description = "Select all non-manifold vertices or edges";
2491         ot->idname = "MESH_OT_select_non_manifold";
2492         
2493         /* api callbacks */
2494         ot->exec = edbm_select_non_manifold_exec;
2495         ot->poll = ED_operator_editmesh;
2496         
2497         /* flags */
2498         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2499 }
2500
2501 static int edbm_select_random_exec(bContext *C, wmOperator *op)
2502 {
2503         Object *obedit = CTX_data_edit_object(C);
2504         BMEditMesh *em = BMEdit_FromObject(obedit);
2505         BMVert *eve;
2506         BMEdge *eed;
2507         BMFace *efa;
2508         BMIter iter;
2509         float randfac =  RNA_float_get(op->ptr, "percent") / 100.0f;
2510
2511         BLI_srand(BLI_rand()); /* random seed */
2512         
2513         if (!RNA_boolean_get(op->ptr, "extend"))
2514                 EDBM_flag_disable_all(em, BM_ELEM_SELECT);
2515
2516         if (em->selectmode & SCE_SELECT_VERTEX) {
2517                 BM_ITER_MESH (eve, &iter, em->bm, BM_VERTS_OF_MESH) {
2518                         if (!BM_elem_flag_test(eve, BM_ELEM_HIDDEN) && BLI_frand() < randfac) {
2519                                 BM_vert_select_set(em->bm, eve, TRUE);
2520                         }
2521                 }
2522                 EDBM_selectmode_flush(em);
2523         }
2524         else if (em->selectmode & SCE_SELECT_EDGE) {
2525                 BM_ITER_MESH (eed, &iter, em->bm, BM_EDGES_OF_MESH) {
2526                         if (!BM_elem_flag_test(eed, BM_ELEM_HIDDEN) && BLI_frand() < randfac) {
2527                                 BM_edge_select_set(em->bm, eed, TRUE);
2528                         }
2529                 }
2530                 EDBM_selectmode_flush(em);
2531         }
2532         else {
2533                 BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) {
2534                         if (!BM_elem_flag_test(efa, BM_ELEM_HIDDEN) && BLI_frand() < randfac) {
2535                                 BM_face_select_set(em->bm, efa, TRUE);
2536                         }
2537                 }
2538                 EDBM_selectmode_flush(em);
2539         }
2540         
2541         WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit->data);
2542         
2543         return OPERATOR_FINISHED;
2544 }
2545
2546 void MESH_OT_select_random(wmOperatorType *ot)
2547 {
2548         /* identifiers */
2549         ot->name = "Select Random";
2550         ot->description = "Randomly select vertices";
2551         ot->idname = "MESH_OT_select_random";
2552
2553         /* api callbacks */
2554         ot->exec = edbm_select_random_exec;
2555         ot->poll = ED_operator_editmesh;
2556
2557         /* flags */
2558         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2559         
2560         /* props */
2561         RNA_def_float_percentage(ot->srna, "percent", 50.f, 0.0f, 100.0f,
2562                                  "Percent", "Percentage of elements to select randomly", 0.f, 100.0f);
2563         RNA_def_boolean(ot->srna, "extend", 0,
2564                         "Extend Selection", "Extend selection instead of deselecting everything first");
2565 }
2566
2567 static int edbm_select_next_loop_exec(bContext *C, wmOperator *UNUSED(op))
2568 {
2569         Object *obedit = CTX_data_edit_object(C);
2570         BMEditMesh *em = BMEdit_FromObject(obedit);
2571         BMFace *f;
2572         BMVert *v;
2573         BMIter iter;
2574         
2575         BM_ITER_MESH (v, &iter, em->bm, BM_VERTS_OF_MESH) {
2576                 BM_elem_flag_disable(v, BM_ELEM_TAG);
2577         }
2578         
2579         BM_ITER_MESH (f, &iter, em->bm, BM_FACES_OF_MESH) {
2580                 BMLoop *l;
2581                 BMIter liter;
2582                 
2583                 BM_ITER_ELEM (l, &liter, f, BM_LOOPS_OF_FACE) {
2584                         if (BM_elem_flag_test(l->v, BM_ELEM_SELECT)) {
2585                                 BM_elem_flag_enable(l->next->v, BM_ELEM_TAG);
2586                                 BM_vert_select_set(em->bm, l->v, FALSE);
2587                         }
2588                 }
2589         }
2590
2591         BM_ITER_MESH (v, &iter, em->bm, BM_VERTS_OF_MESH) {
2592                 if (BM_elem_flag_test(v, BM_ELEM_TAG)) {
2593                         BM_vert_select_set(em->bm, v, TRUE);
2594                 }
2595         }
2596
2597         WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit);
2598         return OPERATOR_FINISHED;
2599 }
2600
2601 void MESH_OT_select_next_loop(wmOperatorType *ot)
2602 {
2603         /* identifiers */
2604         ot->name = "Select Next Loop";
2605         ot->idname = "MESH_OT_select_next_loop";
2606         ot->description = "Select next edge loop adjacent to a selected loop";
2607
2608         /* api callbacks */
2609         ot->exec = edbm_select_next_loop_exec;
2610         ot->poll = ED_operator_editmesh;
2611         
2612         /* flags */
2613         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2614 }
2615
2616
2617 static int edbm_region_to_loop_exec(bContext *C, wmOperator *UNUSED(op))
2618 {
2619         Object *obedit = CTX_data_edit_object(C);
2620         BMEditMesh *em = BMEdit_FromObject(obedit);
2621         BMFace *f;
2622         BMEdge *e;
2623         BMIter iter;
2624
2625         BM_mesh_elem_hflag_disable_all(em->bm, BM_EDGE, BM_ELEM_TAG, FALSE);
2626
2627         BM_ITER_MESH (f, &iter, em->bm, BM_FACES_OF_MESH) {
2628                 BMLoop *l1, *l2;
2629                 BMIter liter1, liter2;
2630                 
2631                 BM_ITER_ELEM (l1, &liter1, f, BM_LOOPS_OF_FACE) {
2632                         int tot = 0, totsel = 0;
2633                         
2634                         BM_ITER_ELEM (l2, &liter2, l1->e, BM_LOOPS_OF_EDGE) {
2635                                 tot++;
2636                                 totsel += BM_elem_flag_test(l2->f, BM_ELEM_SELECT) != 0;
2637                         }
2638                         
2639                         if ((tot != totsel && totsel > 0) || (totsel == 1 && tot == 1))
2640                                 BM_elem_flag_enable(l1->e, BM_ELEM_TAG);
2641                 }
2642         }
2643
2644         EDBM_flag_disable_all(em, BM_ELEM_SELECT);
2645         
2646         BM_ITER_MESH (e, &iter, em->bm, BM_EDGES_OF_MESH) {
2647                 if (BM_elem_flag_test(e, BM_ELEM_TAG)) {
2648                         BM_edge_select_set(em->bm, e, TRUE);
2649                 }
2650         }
2651
2652         /* If in face-only select mode, switch to edge select mode so that
2653          * an edge-only selection is not inconsistent state */
2654         if (em->selectmode == SCE_SELECT_FACE) {
2655                 em->selectmode = SCE_SELECT_EDGE;
2656                 EDBM_selectmode_set(em);
2657                 EDBM_selectmode_to_scene(C);
2658         }
2659
2660         WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit->data);
2661
2662         return OPERATOR_FINISHED;
2663 }
2664
2665 void MESH_OT_region_to_loop(wmOperatorType *ot)
2666 {
2667         /* identifiers */
2668         ot->name = "Select Boundary Loop";
2669         ot->idname = "MESH_OT_region_to_loop";
2670         ot->description = "Select boundary edges around the selected faces";
2671
2672         /* api callbacks */
2673         ot->exec = edbm_region_to_loop_exec;
2674         ot->poll = ED_operator_editmesh;
2675
2676         /* flags */
2677         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2678 }
2679
2680 static int loop_find_region(BMLoop *l, int flag,
2681                             SmallHash *fhash, BMFace ***region_out)
2682 {
2683         BLI_array_declare(region);
2684         BLI_array_declare(stack);
2685         BMFace **region = NULL;
2686         BMFace **stack = NULL;
2687         BMFace *f;
2688         
2689         BLI_array_append(stack, l->f);
2690         BLI_smallhash_insert(fhash, (uintptr_t)l->f, NULL);
2691         
2692         while (BLI_array_count(stack) > 0) {
2693                 BMIter liter1, liter2;
2694                 BMLoop *l1, *l2;
2695                 
2696                 f = BLI_array_pop(stack);
2697                 BLI_array_append(region, f);
2698                 
2699                 BM_ITER_ELEM (l1, &liter1, f, BM_LOOPS_OF_FACE) {
2700                         if (BM_elem_flag_test(l1->e, flag))
2701                                 continue;
2702                         
2703                         BM_ITER_ELEM (l2, &liter2, l1->e, BM_LOOPS_OF_EDGE) {
2704                                 if (BLI_smallhash_haskey(fhash, (uintptr_t)l2->f))
2705                                         continue;
2706                                 
2707                                 BLI_array_append(stack, l2->f);
2708                                 BLI_smallhash_insert(fhash, (uintptr_t)l2->f, NULL);
2709                         }
2710                 }
2711         }
2712         
2713         BLI_array_free(stack);
2714         
2715         *region_out = region;
2716         return BLI_array_count(region);
2717 }
2718
2719 static int verg_radial(const void *va, const void *vb)
2720 {
2721         BMEdge *e1 = *((void **)va);
2722         BMEdge *e2 = *((void **)vb);
2723         int a, b;
2724         
2725         a = BM_edge_face_count(e1);
2726         b = BM_edge_face_count(e2);
2727         
2728         if (a > b)  return -1;
2729         if (a == b) return  0;
2730         if (a < b)  return  1;
2731         
2732         return -1;
2733 }
2734
2735 static int loop_find_regions(BMEditMesh *em, int selbigger)
2736 {
2737         SmallHash visithash;
2738         BMIter iter;
2739         BMEdge *e, **edges = NULL;
2740         BLI_array_declare(edges);
2741         BMFace *f;
2742         int count = 0, i;
2743         
2744         BLI_smallhash_init(&visithash);
2745         
2746         BM_ITER_MESH (f, &iter, em->bm, BM_FACES_OF_MESH) {
2747                 BM_elem_flag_disable(f, BM_ELEM_TAG);
2748         }
2749
2750         BM_ITER_MESH (e, &iter, em->bm, BM_EDGES_OF_MESH) {
2751                 if (BM_elem_flag_test(e, BM_ELEM_SELECT)) {
2752                         BLI_array_append(edges, e);
2753                         BM_elem_flag_enable(e, BM_ELEM_TAG);
2754                 }
2755                 else {
2756                         BM_elem_flag_disable(e, BM_ELEM_TAG);
2757                 }
2758         }
2759         
2760         /* sort edges by radial cycle length */
2761         qsort(edges,  BLI_array_count(edges), sizeof(void *), verg_radial);
2762         
2763         for (i = 0; i < BLI_array_count(edges); i++) {
2764                 BMIter liter;
2765                 BMLoop *l;
2766                 BMFace **region = NULL, **region_out;
2767                 int c, tot = 0;
2768                 
2769                 e = edges[i];
2770                 
2771                 if (!BM_elem_flag_test(e, BM_ELEM_TAG))
2772                         continue;
2773                 
2774                 BM_ITER_ELEM (l, &liter, e, BM_LOOPS_OF_EDGE) {
2775                         if (BLI_smallhash_haskey(&visithash, (uintptr_t)l->f))
2776                                 continue;
2777                                                 
2778                         c = loop_find_region(l, BM_ELEM_SELECT, &visithash, &region_out);
2779
2780                         if (!region || (selbigger ? c >= tot : c < tot)) {
2781                                 /* this region is the best seen so far */
2782                                 tot = c;
2783                                 if (region) {
2784                                         /* free the previous best */
2785                                         MEM_freeN(region);
2786                                 }
2787                                 /* track the current region as the new best */
2788                                 region = region_out;
2789                         }
2790                         else {
2791                                 /* this region is not as good as best so far, just free it */
2792                                 MEM_freeN(region_out);
2793                         }
2794                 }
2795                 
2796                 if (region) {
2797                         int j;
2798                         
2799                         for (j = 0; j < tot; j++) {
2800                                 BM_elem_flag_enable(region[j], BM_ELEM_TAG);
2801                                 BM_ITER_ELEM (l, &liter, region[j], BM_LOOPS_OF_FACE) {
2802                                         BM_elem_flag_disable(l->e, BM_ELEM_TAG);
2803                                 }
2804                         }
2805                         
2806                         count += tot;
2807                         
2808                         MEM_freeN(region);
2809                 }
2810         }
2811         
2812         BLI_array_free(edges);
2813         BLI_smallhash_release(&visithash);
2814         
2815         return count;
2816 }
2817
2818 static int edbm_loop_to_region_exec(bContext *C, wmOperator *op)
2819 {
2820         Object *obedit = CTX_data_edit_object(C);
2821         BMEditMesh *em = BMEdit_FromObject(obedit);
2822         BMIter iter;
2823         BMFace *f;
2824         int selbigger = RNA_boolean_get(op->ptr, "select_bigger");
2825         int a, b;
2826
2827         /* find the set of regions with smallest number of total faces */
2828         a = loop_find_regions(em, selbigger);
2829         b = loop_find_regions(em, !selbigger);
2830         
2831         if ((a <= b) ^ selbigger) {
2832                 loop_find_regions(em, selbigger);
2833         }
2834         
2835         EDBM_flag_disable_all(em, BM_ELEM_SELECT);
2836         
2837         BM_ITER_MESH (f, &iter, em->bm, BM_FACES_OF_MESH) {
2838                 if (BM_elem_flag_test(f, BM_ELEM_TAG) && !BM_elem_flag_test(f, BM_ELEM_HIDDEN)) {
2839                         BM_face_select_set(em->bm, f, TRUE);
2840                 }
2841         }
2842         
2843         WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit->data);
2844         return OPERATOR_FINISHED;
2845 }
2846
2847 void MESH_OT_loop_to_region(wmOperatorType *ot)
2848 {
2849         /* identifiers */
2850         ot->name = "Select Loop Inner-Region";
2851         ot->idname = "MESH_OT_loop_to_region";
2852         ot->description = "Select region of faces inside of a selected loop of edges";
2853
2854         /* api callbacks */
2855         ot->exec = edbm_loop_to_region_exec;
2856         ot->poll = ED_operator_editmesh;
2857
2858         /* flags */
2859         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2860         
2861         RNA_def_boolean(ot->srna, "select_bigger", 0, "Select Bigger", "Select bigger regions instead of smaller ones");
2862 }