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