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