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