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