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