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