Merged changes in the trunk up to revision 44039.
[blender-staging.git] / source / blender / editors / mesh / editmesh_mods.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_mods.c
29  *  \ingroup edmesh
30  */
31
32
33 /*
34
35 editmesh_mods.c, UI level access, no geometry changes 
36
37 */
38
39 #include <stdlib.h>
40 #include <string.h>
41
42 #include "MEM_guardedalloc.h"
43
44 #include "DNA_material_types.h"
45 #include "DNA_meshdata_types.h"
46 #include "DNA_modifier_types.h"
47 #include "DNA_object_types.h"
48 #include "DNA_scene_types.h"
49
50 #include "BLI_blenlib.h"
51 #include "BLI_math.h"
52 #include "BLI_editVert.h"
53 #include "BLI_rand.h"
54 #include "BLI_utildefines.h"
55
56 #include "BKE_context.h"
57 #include "BKE_displist.h"
58 #include "BKE_depsgraph.h"
59 #include "BKE_mesh.h"
60 #include "BKE_material.h"
61 #include "BKE_paint.h"
62 #include "BKE_report.h"
63 #include "BKE_texture.h"
64
65 #include "IMB_imbuf_types.h"
66 #include "IMB_imbuf.h"
67
68 #include "RE_render_ext.h"  /* externtex */
69
70 #include "WM_api.h"
71 #include "WM_types.h"
72
73
74 #include "RNA_access.h"
75 #include "RNA_define.h"
76
77 #include "ED_mesh.h"
78 #include "ED_screen.h"
79 #include "ED_view3d.h"
80 #include "ED_uvedit.h"
81
82 #include "BIF_gl.h"
83
84 #include "mesh_intern.h"
85
86 #include "BLO_sys_types.h" // for intptr_t support
87
88 /* XXX */
89 static void waitcursor(int UNUSED(val)) {}
90 static int pupmenu(const char *UNUSED(arg)) {return 0;}
91
92 /* ****************************** MIRROR **************** */
93
94 void EM_cache_x_mirror_vert(struct Object *ob, struct EditMesh *em)
95 {
96         EditVert *eve, *eve_mirror;
97         int index= 0;
98
99         for(eve= em->verts.first; eve; eve= eve->next) {
100                 eve->tmp.v= NULL;
101         }
102
103         for(eve= em->verts.first; eve; eve= eve->next, index++) {
104                 if(eve->tmp.v==NULL) {
105                         eve_mirror = editmesh_get_x_mirror_vert(ob, em, eve, eve->co, index);
106                         if(eve_mirror) {
107                                 eve->tmp.v= eve_mirror;
108                                 eve_mirror->tmp.v = eve;
109                         }
110                 }
111         }
112 }
113
114 static void EM_select_mirrored(Object *obedit, EditMesh *em, int extend)
115 {
116
117         EditVert *eve;
118
119         EM_cache_x_mirror_vert(obedit, em);
120
121         for(eve= em->verts.first; eve; eve= eve->next) {
122                 if(eve->f & SELECT && eve->tmp.v && (eve->tmp.v != eve->tmp.v->tmp.v)) {
123                         eve->tmp.v->f |= SELECT;
124
125                         if(extend==FALSE)
126                                 eve->f &= ~SELECT;
127
128                         /* remove the interference */
129                         eve->tmp.v->tmp.v= NULL;
130                         eve->tmp.v= NULL;
131                 }
132         }
133 }
134
135 void EM_automerge(Scene *scene, Object *obedit, int update)
136 {
137         Mesh *me= obedit ? obedit->data : NULL; /* can be NULL */
138         /* int len; */ /* UNUSED */
139
140         if ((scene->toolsettings->automerge) &&
141                 (obedit && obedit->type==OB_MESH && (obedit->mode & OB_MODE_EDIT))
142           ) {
143                 EditMesh *em= me->edit_mesh;
144                 int totvert= em->totvert, totedge= em->totedge, totface= em->totface;
145
146                 /* len = */ /* UNUSED */ removedoublesflag(em, 1, 1, scene->toolsettings->doublimit);
147                 if (totvert != em->totvert || totedge != em->totedge || totface != em->totface) {
148                         if (update) {
149                                 DAG_id_tag_update(&me->id, 0);
150                         }
151                 }
152         }
153 }
154
155 /* ****************************** SELECTION ROUTINES **************** */
156
157 unsigned int em_solidoffs=0, em_wireoffs=0, em_vertoffs=0;      /* set in drawobject.c ... for colorindices */
158
159 /* facilities for border select and circle select */
160 static char *selbuf= NULL;
161
162 /* opengl doesn't support concave... */
163 static void draw_triangulated(int mcords[][2], short tot)
164 {
165         ListBase lb={NULL, NULL};
166         DispList *dl;
167         float *fp;
168         int a;
169         
170         /* make displist */
171         dl= MEM_callocN(sizeof(DispList), "poly disp");
172         dl->type= DL_POLY;
173         dl->parts= 1;
174         dl->nr= tot;
175         dl->verts= fp=  MEM_callocN(tot*3*sizeof(float), "poly verts");
176         BLI_addtail(&lb, dl);
177         
178         for(a=0; a<tot; a++, fp+=3) {
179                 fp[0]= (float)mcords[a][0];
180                 fp[1]= (float)mcords[a][1];
181         }
182         
183         /* do the fill */
184         filldisplist(&lb, &lb, 0);
185
186         /* do the draw */
187         dl= lb.first;   /* filldisplist adds in head of list */
188         if(dl->type==DL_INDEX3) {
189                 int *index;
190                 
191                 a= dl->parts;
192                 fp= dl->verts;
193                 index= dl->index;
194                 glBegin(GL_TRIANGLES);
195                 while(a--) {
196                         glVertex3fv(fp+3*index[0]);
197                         glVertex3fv(fp+3*index[1]);
198                         glVertex3fv(fp+3*index[2]);
199                         index+= 3;
200                 }
201                 glEnd();
202         }
203         
204         freedisplist(&lb);
205 }
206
207
208 /* reads rect, and builds selection array for quick lookup */
209 /* returns if all is OK */
210 int EM_init_backbuf_border(ViewContext *vc, short xmin, short ymin, short xmax, short ymax)
211 {
212         struct ImBuf *buf;
213         unsigned int *dr;
214         int a;
215         
216         if(vc->obedit==NULL || vc->v3d->drawtype<OB_SOLID || (vc->v3d->flag & V3D_ZBUF_SELECT)==0) return 0;
217         
218         buf= view3d_read_backbuf(vc, xmin, ymin, xmax, ymax);
219         if(buf==NULL) return 0;
220         if(em_vertoffs==0) return 0;
221
222         dr = buf->rect;
223         
224         /* build selection lookup */
225         selbuf= MEM_callocN(em_vertoffs+1, "selbuf");
226         
227         a= (xmax-xmin+1)*(ymax-ymin+1);
228         while(a--) {
229                 if(*dr>0 && *dr<=em_vertoffs) 
230                         selbuf[*dr]= 1;
231                 dr++;
232         }
233         IMB_freeImBuf(buf);
234         return 1;
235 }
236
237 int EM_check_backbuf(unsigned int index)
238 {
239         if(selbuf==NULL) return 1;
240         if(index>0 && index<=em_vertoffs)
241                 return selbuf[index];
242         return 0;
243 }
244
245 void EM_free_backbuf(void)
246 {
247         if(selbuf) MEM_freeN(selbuf);
248         selbuf= NULL;
249 }
250
251 /* mcords is a polygon mask
252    - grab backbuffer,
253    - draw with black in backbuffer, 
254    - grab again and compare
255    returns 'OK' 
256 */
257 int EM_mask_init_backbuf_border(ViewContext *vc, int mcords[][2], short tot, short xmin, short ymin, short xmax, short ymax)
258 {
259         unsigned int *dr, *drm;
260         struct ImBuf *buf, *bufmask;
261         int a;
262         GLboolean is_cull;
263         
264         /* method in use for face selecting too */
265         if(vc->obedit==NULL) {
266                 if(paint_facesel_test(vc->obact));
267                 else if(paint_vertsel_test(vc->obact));
268                 else return 0;
269         }
270         else if(vc->v3d->drawtype<OB_SOLID || (vc->v3d->flag & V3D_ZBUF_SELECT)==0) return 0;
271
272         buf= view3d_read_backbuf(vc, xmin, ymin, xmax, ymax);
273         if(buf==NULL) return 0;
274         if(em_vertoffs==0) return 0;
275
276         dr = buf->rect;
277
278         /* draw the mask */
279         glDisable(GL_DEPTH_TEST);
280         
281         glColor3ub(0, 0, 0);
282
283         /* some opengl drivers have problems with draw direction */
284         glGetBooleanv(GL_CULL_FACE, &is_cull);
285         if(is_cull) glDisable(GL_CULL_FACE);
286         
287         /* yah, opengl doesn't do concave... tsk! */
288         ED_region_pixelspace(vc->ar);
289         draw_triangulated(mcords, tot);
290         
291         glBegin(GL_LINE_LOOP);  /* for zero sized masks, lines */
292         for(a=0; a<tot; a++) glVertex2iv(mcords[a]);
293         glEnd();
294         
295         glFinish();     /* to be sure readpixels sees mask */
296         
297         /* grab mask */
298         bufmask= view3d_read_backbuf(vc, xmin, ymin, xmax, ymax);
299         drm = bufmask->rect;
300         if(bufmask==NULL) return 0; /* only when mem alloc fails, go crash somewhere else! */
301         
302         /* build selection lookup */
303         selbuf= MEM_callocN(em_vertoffs+1, "selbuf");
304         
305         a= (xmax-xmin+1)*(ymax-ymin+1);
306         while(a--) {
307                 if(*dr>0 && *dr<=em_vertoffs && *drm==0) selbuf[*dr]= 1;
308                 dr++; drm++;
309         }
310         IMB_freeImBuf(buf);
311         IMB_freeImBuf(bufmask);
312         
313         if(is_cull) glEnable(GL_CULL_FACE);
314
315         return 1;
316         
317 }
318
319 /* circle shaped sample area */
320 int EM_init_backbuf_circle(ViewContext *vc, short xs, short ys, short rads)
321 {
322         struct ImBuf *buf;
323         unsigned int *dr;
324         short xmin, ymin, xmax, ymax, xc, yc;
325         int radsq;
326         
327         /* method in use for face selecting too */
328         if(vc->obedit==NULL) {
329                 if(paint_facesel_test(vc->obact));
330                 else if (paint_vertsel_test(vc->obact));
331                 else return 0;
332         }
333         else if(vc->v3d->drawtype<OB_SOLID || (vc->v3d->flag & V3D_ZBUF_SELECT)==0) return 0;
334         
335         xmin= xs-rads; xmax= xs+rads;
336         ymin= ys-rads; ymax= ys+rads;
337         buf= view3d_read_backbuf(vc, xmin, ymin, xmax, ymax);
338         if(em_vertoffs==0) return 0;
339         if(buf==NULL) return 0;
340
341         dr = buf->rect;
342         
343         /* build selection lookup */
344         selbuf= MEM_callocN(em_vertoffs+1, "selbuf");
345         radsq= rads*rads;
346         for(yc= -rads; yc<=rads; yc++) {
347                 for(xc= -rads; xc<=rads; xc++, dr++) {
348                         if(xc*xc + yc*yc < radsq) {
349                                 if(*dr>0 && *dr<=em_vertoffs) selbuf[*dr]= 1;
350                         }
351                 }
352         }
353
354         IMB_freeImBuf(buf);
355         return 1;
356         
357 }
358
359 static void findnearestvert__doClosest(void *userData, EditVert *eve, int x, int y, int index)
360 {
361         struct { int mval[2]; short pass, select, strict; int dist, lastIndex, closestIndex; EditVert *closest; } *data = userData;
362
363         if (data->pass==0) {
364                 if (index<=data->lastIndex)
365                         return;
366         } else {
367                 if (index>data->lastIndex)
368                         return;
369         }
370
371         if (data->dist>3) {
372                 int temp = abs(data->mval[0] - x) + abs(data->mval[1]- y);
373                 if ((eve->f&1) == data->select) {
374                         if (data->strict == 1)
375                                 return;
376                         else
377                                 temp += 5;
378                 }
379
380                 if (temp<data->dist) {
381                         data->dist = temp;
382                         data->closest = eve;
383                         data->closestIndex = index;
384                 }
385         }
386 }
387
388
389
390
391 static unsigned int findnearestvert__backbufIndextest(void *handle, unsigned int index)
392 {
393         EditMesh *em= (EditMesh *)handle;
394         EditVert *eve = BLI_findlink(&em->verts, index-1);
395
396         if(eve && (eve->f & SELECT)) return 0;
397         return 1; 
398 }
399 /**
400  * findnearestvert
401  * 
402  * dist (in/out): minimal distance to the nearest and at the end, actual distance
403  * sel: selection bias
404  *              if SELECT, selected vertice are given a 5 pixel bias to make them farter than unselect verts
405  *              if 0, unselected vertice are given the bias
406  * strict: if 1, the vertice corresponding to the sel parameter are ignored and not just biased 
407  */
408 EditVert *findnearestvert(ViewContext *vc, int *dist, short sel, short strict)
409 {
410         if(vc->v3d->drawtype>OB_WIRE && (vc->v3d->flag & V3D_ZBUF_SELECT)){
411                 int distance;
412                 unsigned int index;
413                 EditVert *eve;
414                 
415                 if(strict) index = view3d_sample_backbuf_rect(vc, vc->mval, 50, em_wireoffs, 0xFFFFFF, &distance, strict, vc->em, findnearestvert__backbufIndextest); 
416                 else index = view3d_sample_backbuf_rect(vc, vc->mval, 50, em_wireoffs, 0xFFFFFF, &distance, 0, NULL, NULL); 
417                 
418                 eve = BLI_findlink(&vc->em->verts, index-1);
419                 
420                 if(eve && distance < *dist) {
421                         *dist = distance;
422                         return eve;
423                 } else {
424                         return NULL;
425                 }
426                         
427         }
428         else {
429                 struct { int mval[2]; short pass, select, strict; int dist, lastIndex, closestIndex; EditVert *closest; } data;
430                 static int lastSelectedIndex=0;
431                 static EditVert *lastSelected=NULL;
432
433                 if (lastSelected && BLI_findlink(&vc->em->verts, lastSelectedIndex)!=lastSelected) {
434                         lastSelectedIndex = 0;
435                         lastSelected = NULL;
436                 }
437
438                 data.lastIndex = lastSelectedIndex;
439                 data.mval[0] = vc->mval[0];
440                 data.mval[1] = vc->mval[1];
441                 data.select = sel;
442                 data.dist = *dist;
443                 data.strict = strict;
444                 data.closest = NULL;
445                 data.closestIndex = 0;
446
447                 data.pass = 0;
448
449                 ED_view3d_init_mats_rv3d(vc->obedit, vc->rv3d);
450
451                 mesh_foreachScreenVert(vc, findnearestvert__doClosest, &data, V3D_CLIP_TEST_RV3D_CLIPPING);
452
453                 if (data.dist>3) {
454                         data.pass = 1;
455                         mesh_foreachScreenVert(vc, findnearestvert__doClosest, &data, V3D_CLIP_TEST_RV3D_CLIPPING);
456                 }
457
458                 *dist = data.dist;
459                 lastSelected = data.closest;
460                 lastSelectedIndex = data.closestIndex;
461
462                 return data.closest;
463         }
464 }
465
466 /* returns labda for closest distance v1 to line-piece v2-v3 */
467 static float labda_PdistVL2Dfl( float *v1, float *v2, float *v3) 
468 {
469         float rc[2], len;
470         
471         rc[0]= v3[0]-v2[0];
472         rc[1]= v3[1]-v2[1];
473         len= rc[0]*rc[0]+ rc[1]*rc[1];
474         if(len==0.0f)
475                 return 0.0f;
476         
477         return ( rc[0]*(v1[0]-v2[0]) + rc[1]*(v1[1]-v2[1]) )/len;
478 }
479
480 /* note; uses v3d, so needs active 3d window */
481 static void findnearestedge__doClosest(void *userData, EditEdge *eed, int x0, int y0, int x1, int y1, int UNUSED(index))
482 {
483         struct { ViewContext vc; float mval[2]; int dist; EditEdge *closest; } *data = userData;
484         float v1[2], v2[2];
485         int distance;
486
487         ED_view3d_local_clipping(data->vc.rv3d, data->vc.obedit->obmat); /* for local clipping lookups */
488
489         v1[0] = x0;
490         v1[1] = y0;
491         v2[0] = x1;
492         v2[1] = y1;
493
494         distance= dist_to_line_segment_v2(data->mval, v1, v2);
495
496
497         if(eed->f & SELECT) distance+=5;
498         if(distance < data->dist) {
499                 if(data->vc.rv3d->rflag & RV3D_CLIPPING) {
500                         float labda= labda_PdistVL2Dfl(data->mval, v1, v2);
501                         float vec[3];
502
503                         vec[0]= eed->v1->co[0] + labda*(eed->v2->co[0] - eed->v1->co[0]);
504                         vec[1]= eed->v1->co[1] + labda*(eed->v2->co[1] - eed->v1->co[1]);
505                         vec[2]= eed->v1->co[2] + labda*(eed->v2->co[2] - eed->v1->co[2]);
506
507                         if(ED_view3d_test_clipping(data->vc.rv3d, vec, 1)==0) {
508                                 data->dist = distance;
509                                 data->closest = eed;
510                         }
511                 }
512                 else {
513                         data->dist = distance;
514                         data->closest = eed;
515                 }
516         }
517 }
518 EditEdge *findnearestedge(ViewContext *vc, int *dist)
519 {
520
521         if(vc->v3d->drawtype>OB_WIRE && (vc->v3d->flag & V3D_ZBUF_SELECT)) {
522                 int distance;
523                 unsigned int index = view3d_sample_backbuf_rect(vc, vc->mval, 50, em_solidoffs, em_wireoffs, &distance,0, NULL, NULL);
524                 EditEdge *eed = BLI_findlink(&vc->em->edges, index-1);
525
526                 if (eed && distance<*dist) {
527                         *dist = distance;
528                         return eed;
529                 } else {
530                         return NULL;
531                 }
532         }
533         else {
534                 struct { ViewContext vc; float mval[2]; int dist; EditEdge *closest; } data;
535
536                 data.vc= *vc;
537                 data.mval[0] = vc->mval[0];
538                 data.mval[1] = vc->mval[1];
539                 data.dist = *dist;
540                 data.closest = NULL;
541
542                 ED_view3d_init_mats_rv3d(vc->obedit, vc->rv3d);
543                 mesh_foreachScreenEdge(vc, findnearestedge__doClosest, &data, V3D_CLIP_TEST_REGION);
544
545                 *dist = data.dist;
546                 return data.closest;
547         }
548 }
549
550 static void findnearestface__getDistance(void *userData, EditFace *efa, int x, int y, int UNUSED(index))
551 {
552         struct { int mval[2]; int dist; EditFace *toFace; } *data = userData;
553
554         if (efa==data->toFace) {
555                 int temp = abs(data->mval[0]-x) + abs(data->mval[1]-y);
556
557                 if (temp<data->dist)
558                         data->dist = temp;
559         }
560 }
561 static void findnearestface__doClosest(void *userData, EditFace *efa, int x, int y, int index)
562 {
563         struct { int mval[2]; short pass; int dist, lastIndex, closestIndex; EditFace *closest; } *data = userData;
564
565         if (data->pass==0) {
566                 if (index<=data->lastIndex)
567                         return;
568         } else {
569                 if (index>data->lastIndex)
570                         return;
571         }
572
573         if (data->dist>3) {
574                 int temp = abs(data->mval[0]-x) + abs(data->mval[1]-y);
575
576                 if (temp<data->dist) {
577                         data->dist = temp;
578                         data->closest = efa;
579                         data->closestIndex = index;
580                 }
581         }
582 }
583 static EditFace *findnearestface(ViewContext *vc, int *dist)
584 {
585
586         if(vc->v3d->drawtype>OB_WIRE && (vc->v3d->flag & V3D_ZBUF_SELECT)) {
587                 unsigned int index = view3d_sample_backbuf(vc, vc->mval[0], vc->mval[1]);
588                 EditFace *efa = BLI_findlink(&vc->em->faces, index-1);
589
590                 if (efa) {
591                         struct { int mval[2]; int dist; EditFace *toFace; } data;
592
593                         data.mval[0] = vc->mval[0];
594                         data.mval[1] = vc->mval[1];
595                         data.dist = 0x7FFF;             /* largest short */
596                         data.toFace = efa;
597
598                         ED_view3d_init_mats_rv3d(vc->obedit, vc->rv3d);
599                         mesh_foreachScreenFace(vc, findnearestface__getDistance, &data);
600
601                         if(vc->em->selectmode == SCE_SELECT_FACE || data.dist<*dist) {  /* only faces, no dist check */
602                                 *dist= data.dist;
603                                 return efa;
604                         }
605                 }
606                 
607                 return NULL;
608         }
609         else {
610                 struct { int mval[2]; short pass; int dist, lastIndex, closestIndex; EditFace *closest; } data;
611                 static int lastSelectedIndex=0;
612                 static EditFace *lastSelected=NULL;
613
614                 if (lastSelected && BLI_findlink(&vc->em->faces, lastSelectedIndex)!=lastSelected) {
615                         lastSelectedIndex = 0;
616                         lastSelected = NULL;
617                 }
618
619                 data.lastIndex = lastSelectedIndex;
620                 data.mval[0] = vc->mval[0];
621                 data.mval[1] = vc->mval[1];
622                 data.dist = *dist;
623                 data.closest = NULL;
624                 data.closestIndex = 0;
625
626                 data.pass = 0;
627
628                 ED_view3d_init_mats_rv3d(vc->obedit, vc->rv3d);
629                 mesh_foreachScreenFace(vc, findnearestface__doClosest, &data);
630
631                 if (data.dist>3) {
632                         data.pass = 1;
633                         mesh_foreachScreenFace(vc, findnearestface__doClosest, &data);
634                 }
635
636                 *dist = data.dist;
637                 lastSelected = data.closest;
638                 lastSelectedIndex = data.closestIndex;
639
640                 return data.closest;
641         }
642 }
643
644 /* best distance based on screen coords. 
645    use em->selectmode to define how to use 
646    selected vertices and edges get disadvantage
647    return 1 if found one
648 */
649 static int unified_findnearest(ViewContext *vc, EditVert **eve, EditEdge **eed, EditFace **efa) 
650 {
651         EditMesh *em= vc->em;
652         int dist= 75;
653         
654         *eve= NULL;
655         *eed= NULL;
656         *efa= NULL;
657         
658         /* no afterqueue (yet), so we check it now, otherwise the em_xxxofs indices are bad */
659         view3d_validate_backbuf(vc);
660         
661         if(em->selectmode & SCE_SELECT_VERTEX)
662                 *eve= findnearestvert(vc, &dist, SELECT, 0);
663         if(em->selectmode & SCE_SELECT_FACE)
664                 *efa= findnearestface(vc, &dist);
665
666         dist-= 20;      /* since edges select lines, we give dots advantage of 20 pix */
667         if(em->selectmode & SCE_SELECT_EDGE)
668                 *eed= findnearestedge(vc, &dist);
669
670         /* return only one of 3 pointers, for frontbuffer redraws */
671         if(*eed) {
672                 *efa= NULL; *eve= NULL;
673         }
674         else if(*efa) {
675                 *eve= NULL;
676         }
677         
678         return (*eve || *eed || *efa);
679 }
680
681
682 /* ****************  SIMILAR "group" SELECTS. FACE, EDGE AND VERTEX ************** */
683
684 /* selects new faces/edges/verts based on the existing selection */
685
686 /* VERT GROUP */
687
688 #define SIMVERT_NORMAL  0
689 #define SIMVERT_FACE    1
690 #define SIMVERT_VGROUP  2
691 #define SIMVERT_TOT             3
692
693 /* EDGE GROUP */
694
695 #define SIMEDGE_LENGTH          101
696 #define SIMEDGE_DIR                     102
697 #define SIMEDGE_FACE            103
698 #define SIMEDGE_FACE_ANGLE      104
699 #define SIMEDGE_CREASE          105
700 #define SIMEDGE_SEAM            106
701 #define SIMEDGE_SHARP           107
702 #define SIMEDGE_TOT                     108
703 #define SIMEDGE_FREESTYLE       109
704
705 /* FACE GROUP */
706
707 #define SIMFACE_MATERIAL        201
708 #define SIMFACE_IMAGE           202
709 #define SIMFACE_AREA            203
710 #define SIMFACE_PERIMETER       204
711 #define SIMFACE_NORMAL          205
712 #define SIMFACE_COPLANAR        206
713 #define SIMFACE_TOT                     207
714
715 static EnumPropertyItem prop_similar_types[] = {
716         {SIMVERT_NORMAL, "NORMAL", 0, "Normal", ""},
717         {SIMVERT_FACE, "FACE", 0, "Amount of Vertices in Face", ""},
718         {SIMVERT_VGROUP, "VGROUP", 0, "Vertex Groups", ""},
719         {SIMEDGE_LENGTH, "LENGTH", 0, "Length", ""},
720         {SIMEDGE_DIR, "DIR", 0, "Direction", ""},
721         {SIMEDGE_FACE, "FACE", 0, "Amount of Vertices in Face", ""},
722         {SIMEDGE_FACE_ANGLE, "FACE_ANGLE", 0, "Face Angles", ""},
723         {SIMEDGE_CREASE, "CREASE", 0, "Crease", ""},
724         {SIMEDGE_SEAM, "SEAM", 0, "Seam", ""},
725         {SIMEDGE_SHARP, "SHARP", 0, "Sharpness", ""},
726         {SIMEDGE_FREESTYLE, "FREESTYLE", 0, "Freestyle Edge Mark", ""},
727         {SIMFACE_MATERIAL, "MATERIAL", 0, "Material", ""},
728         {SIMFACE_IMAGE, "IMAGE", 0, "Image", ""},
729         {SIMFACE_AREA, "AREA", 0, "Area", ""},
730         {SIMFACE_PERIMETER, "PERIMETER", 0, "Perimeter", ""},
731         {SIMFACE_NORMAL, "NORMAL", 0, "Normal", ""},
732         {SIMFACE_COPLANAR, "COPLANAR", 0, "Co-planar", ""},
733         {0, NULL, 0, NULL, NULL}
734 };
735
736
737 /* this as a way to compare the ares, perim  of 2 faces thay will scale to different sizes
738 *0.5 so smaller faces arnt ALWAYS selected with a thresh of 1.0 */
739 #define SCALE_CMP(a,b) ((a+a*thresh >= b) && (a-(a*thresh*0.5f) <= b))
740
741 static int similar_face_select__internal(EditMesh *em, int mode, float thresh)
742 {
743         EditFace *efa, *base_efa=NULL;
744         unsigned int selcount=0; /*count how many new faces we select*/
745         
746         /*deselcount, count how many deselected faces are left, so we can bail out early
747         also means that if there are no deselected faces, we can avoid a lot of looping */
748         unsigned int deselcount=0; 
749         short ok=0;
750         
751         for(efa= em->faces.first; efa; efa= efa->next) {
752                 if (!efa->h) {
753                         if (efa->f & SELECT) {
754                                 efa->f1=1;
755                                 ok=1;
756                         } else {
757                                 efa->f1=0;
758                                 deselcount++; /* a deselected face we may select later */
759                         }
760                 }
761         }
762         
763         if (!ok || !deselcount) /* no data selected OR no more data to select */
764                 return 0;
765         
766         if (mode==SIMFACE_AREA) {
767                 for(efa= em->faces.first; efa; efa= efa->next) {
768                         efa->tmp.fp= EM_face_area(efa);
769                 }
770         } else if (mode==SIMFACE_PERIMETER) {
771                 for(efa= em->faces.first; efa; efa= efa->next) {
772                         efa->tmp.fp= EM_face_perimeter(efa);
773                 }
774         }
775         
776         for(base_efa= em->faces.first; base_efa; base_efa= base_efa->next) {
777                 if (base_efa->f1) { /* This was one of the faces originaly selected */
778                         if (mode==SIMFACE_MATERIAL) { /* same material */
779                                 for(efa= em->faces.first; efa; efa= efa->next) {
780                                         if (
781                                                 !(efa->f & SELECT) &&
782                                                 !efa->h &&
783                                                 base_efa->mat_nr == efa->mat_nr
784                                         ) {
785                                                 EM_select_face(efa, 1);
786                                                 selcount++;
787                                                 deselcount--;
788                                                 if (!deselcount) /*have we selected all posible faces?, if so return*/
789                                                         return selcount;
790                                         }
791                                 }
792                         } else if (mode==SIMFACE_IMAGE) { /* same image */
793                                 MTFace *tf, *base_tf;
794
795                                 base_tf = (MTFace*)CustomData_em_get(&em->fdata, base_efa->data,
796                                                                                                          CD_MTFACE);
797
798                                 if(!base_tf)
799                                         return selcount;
800
801                                 for(efa= em->faces.first; efa; efa= efa->next) {
802                                         if (!(efa->f & SELECT) && !efa->h) {
803                                                 tf = (MTFace*)CustomData_em_get(&em->fdata, efa->data,
804                                                                                                                 CD_MTFACE);
805
806                                                 if(base_tf->tpage == tf->tpage) {
807                                                         EM_select_face(efa, 1);
808                                                         selcount++;
809                                                         deselcount--;
810                                                         if (!deselcount) /*have we selected all posible faces?, if so return*/
811                                                                 return selcount;
812                                                 }
813                                         }
814                                 }
815                         } else if (mode==SIMFACE_AREA || mode==SIMFACE_PERIMETER) { /* same area OR same perimeter, both use the same temp var */
816                                 for(efa= em->faces.first; efa; efa= efa->next) {
817                                         if (
818                                                 (!(efa->f & SELECT) && !efa->h) &&
819                                                 SCALE_CMP(base_efa->tmp.fp, efa->tmp.fp)
820                                         ) {
821                                                 EM_select_face(efa, 1);
822                                                 selcount++;
823                                                 deselcount--;
824                                                 if (!deselcount) /*have we selected all posible faces?, if so return*/
825                                                         return selcount;
826                                         }
827                                 }
828                         } else if (mode==SIMFACE_NORMAL) {
829                                 float angle;
830                                 for(efa= em->faces.first; efa; efa= efa->next) {
831                                         if (!(efa->f & SELECT) && !efa->h) {
832                                                 angle= RAD2DEGF(angle_v3v3(base_efa->n, efa->n));
833                                                 if (angle/180.0f<=thresh) {
834                                                         EM_select_face(efa, 1);
835                                                         selcount++;
836                                                         deselcount--;
837                                                         if (!deselcount) /*have we selected all posible faces?, if so return*/
838                                                                 return selcount;
839                                                 }
840                                         }
841                                 }
842                         } else if (mode==SIMFACE_COPLANAR) { /* same planer */
843                                 float angle, base_dot, dot;
844                                 base_dot= dot_v3v3(base_efa->cent, base_efa->n);
845                                 for(efa= em->faces.first; efa; efa= efa->next) {
846                                         if (!(efa->f & SELECT) && !efa->h) {
847                                                 angle= RAD2DEGF(angle_v3v3(base_efa->n, efa->n));
848                                                 if (angle/180.0f<=thresh) {
849                                                         dot=dot_v3v3(efa->cent, base_efa->n);
850                                                         if (fabsf(base_dot-dot) <= thresh) {
851                                                                 EM_select_face(efa, 1);
852                                                                 selcount++;
853                                                                 deselcount--;
854                                                                 if (!deselcount) /*have we selected all posible faces?, if so return*/
855                                                                         return selcount;
856                                                         }
857                                                 }
858                                         }
859                                 }
860                         }
861                 }
862         } /* end base_efa loop */
863         return selcount;
864 }
865
866 static int similar_face_select_exec(bContext *C, wmOperator *op)
867 {
868         Object *obedit= CTX_data_edit_object(C);
869         Mesh *me= obedit->data;
870         EditMesh *em= BKE_mesh_get_editmesh(me); 
871
872         int selcount = similar_face_select__internal(em, RNA_enum_get(op->ptr, "type"), RNA_float_get(op->ptr, "threshold"));
873         
874         if (selcount) {
875                 /* here was an edge-mode only select flush case, has to be generalized */
876                 EM_selectmode_flush(em);
877                 WM_event_add_notifier(C, NC_GEOM|ND_SELECT, obedit->data);
878         }
879         
880         BKE_mesh_end_editmesh(me, em);
881         return OPERATOR_FINISHED;
882 }       
883
884 /* ***************************************************** */
885
886 static int similar_edge_select__internal(EditMesh *em, int mode, float thresh)
887 {
888         EditEdge *eed, *base_eed=NULL;
889         unsigned int selcount=0; /* count how many new edges we select*/
890         
891         /*count how many visible selected edges there are,
892         so we can return when there are none left */
893         unsigned int deselcount=0;
894         
895         short ok=0;
896         
897         for(eed= em->edges.first; eed; eed= eed->next) {
898                 if (!eed->h) {
899                         if (eed->f & SELECT) {
900                                 eed->f1=1;
901                                 ok=1;
902                         } else {
903                                 eed->f1=0;
904                                 deselcount++;
905                         }
906                         /* set all eed->tmp.l to 0 we use it later.
907                         for counting face users*/
908                         eed->tmp.l=0;
909                         eed->f2=0; /* only for mode SIMEDGE_FACE_ANGLE, edge animations */
910                 }
911         }
912         
913         if (!ok || !deselcount) /* no data selected OR no more data to select*/
914                 return 0;
915         
916         if (mode==SIMEDGE_LENGTH) { /*store length*/
917                 for(eed= em->edges.first; eed; eed= eed->next) {
918                         if (!eed->h) /* dont calc data for hidden edges*/
919                                 eed->tmp.fp= len_v3v3(eed->v1->co, eed->v2->co);
920                 }
921         } else if (mode==SIMEDGE_FACE) { /*store face users*/
922                 EditFace *efa;
923                 /* cound how many faces each edge uses use tmp->l */
924                 for(efa= em->faces.first; efa; efa= efa->next) {
925                         efa->e1->tmp.l++;
926                         efa->e2->tmp.l++;
927                         efa->e3->tmp.l++;
928                         if (efa->e4) efa->e4->tmp.l++;
929                 }
930         } else if (mode==SIMEDGE_FACE_ANGLE) { /*store edge angles */
931                 EditFace *efa;
932                 int j;
933                 /* cound how many faces each edge uses use tmp.l */
934                 for(efa= em->faces.first; efa; efa= efa->next) {
935                         /* here we use the edges temp data to assign a face
936                         if a face has already been assigned (eed->f2==1)
937                         we calculate the angle between the current face and
938                         the edges previously found face.
939                         store the angle in eed->tmp.fp (loosing the face eed->tmp.f)
940                         but tagging eed->f2==2, so we know not to look at it again.
941                         This only works for edges that connect to 2 faces. but its good enough
942                         */
943                         
944                         /* se we can loop through face edges*/
945                         j=0;
946                         eed= efa->e1;
947                         while (j<4) {
948                                 if (j==1) eed= efa->e2;
949                                 else if (j==2) eed= efa->e3;
950                                 else if (j==3) {
951                                         eed= efa->e4;
952                                         if (!eed)
953                                                 break;
954                                 } /* done looping */
955                                 
956                                 if (!eed->h) { /* dont calc data for hidden edges*/
957                                         if (eed->f2==2)
958                                                 break;
959                                         else if (eed->f2==0) /* first access, assign the face */
960                                                 eed->tmp.f= efa;
961                                         else if (eed->f2==1) /* second, we assign the angle*/
962                                                 eed->tmp.fp= RAD2DEGF(angle_v3v3(eed->tmp.f->n, efa->n))/180;
963                                         eed->f2++; /* f2==0 no face assigned. f2==1 one face found. f2==2 angle calculated.*/
964                                 }
965                                 j++;
966                         }
967                 }
968         }
969         
970         for(base_eed= em->edges.first; base_eed; base_eed= base_eed->next) {
971                 if (base_eed->f1) {
972                         if (mode==SIMEDGE_LENGTH) { /* same length */
973                                 for(eed= em->edges.first; eed; eed= eed->next) {
974                                         if (
975                                                 !(eed->f & SELECT) &&
976                                                 !eed->h &&
977                                                 SCALE_CMP(base_eed->tmp.fp, eed->tmp.fp)
978                                         ) {
979                                                 EM_select_edge(eed, 1);
980                                                 selcount++;
981                                                 deselcount--;
982                                                 if (!deselcount) /*have we selected all posible faces?, if so return*/
983                                                         return selcount;
984                                         }
985                                 }
986                         } else if (mode==SIMEDGE_DIR) { /* same direction */
987                                 float base_dir[3], dir[3], angle;
988                                 sub_v3_v3v3(base_dir, base_eed->v1->co, base_eed->v2->co);
989                                 for(eed= em->edges.first; eed; eed= eed->next) {
990                                         if (!(eed->f & SELECT) && !eed->h) {
991                                                 sub_v3_v3v3(dir, eed->v1->co, eed->v2->co);
992                                                 angle= RAD2DEGF(angle_v3v3(base_dir, dir));
993                                                 
994                                                 if (angle>90.0f) /* use the smallest angle between the edges */
995                                                         angle= fabsf(angle-180.0f);
996                                                 
997                                                 if (angle / 90.0f<=thresh) {
998                                                         EM_select_edge(eed, 1);
999                                                         selcount++;
1000                                                         deselcount--;
1001                                                         if (!deselcount) /*have we selected all posible faces?, if so return*/
1002                                                                 return selcount;
1003                                                 }
1004                                         }
1005                                 }
1006                         } else if (mode==SIMEDGE_FACE) { /* face users */                               
1007                                 for(eed= em->edges.first; eed; eed= eed->next) {
1008                                         if (
1009                                                 !(eed->f & SELECT) &&
1010                                                 !eed->h &&
1011                                                 base_eed->tmp.l==eed->tmp.l
1012                                         ) {
1013                                                 EM_select_edge(eed, 1);
1014                                                 selcount++;
1015                                                 deselcount--;
1016                                                 if (!deselcount) /*have we selected all posible faces?, if so return*/
1017                                                         return selcount;
1018                                         }
1019                                 }
1020                         } else if (mode==SIMEDGE_FACE_ANGLE && base_eed->f2==2) { /* edge angles, f2==2 means the edge has an angle. */                         
1021                                 for(eed= em->edges.first; eed; eed= eed->next) {
1022                                         if (
1023                                                 !(eed->f & SELECT) &&
1024                                                 !eed->h &&
1025                                                 eed->f2==2 &&
1026                                                 (fabsf(base_eed->tmp.fp-eed->tmp.fp)<=thresh)
1027                                         ) {
1028                                                 EM_select_edge(eed, 1);
1029                                                 selcount++;
1030                                                 deselcount--;
1031                                                 if (!deselcount) /*have we selected all posible faces?, if so return*/
1032                                                         return selcount;
1033                                         }
1034                                 }
1035                         } else if (mode==SIMEDGE_CREASE) { /* edge crease */
1036                                 for(eed= em->edges.first; eed; eed= eed->next) {
1037                                         if (
1038                                                 !(eed->f & SELECT) &&
1039                                                 !eed->h &&
1040                                                 (fabsf(base_eed->crease-eed->crease) <= thresh)
1041                                         ) {
1042                                                 EM_select_edge(eed, 1);
1043                                                 selcount++;
1044                                                 deselcount--;
1045                                                 if (!deselcount) /*have we selected all posible faces?, if so return*/
1046                                                         return selcount;
1047                                         }
1048                                 }
1049                         } else if (mode==SIMEDGE_SEAM) { /* edge seam */
1050                                 for(eed= em->edges.first; eed; eed= eed->next) {
1051                                         if (
1052                                                 !(eed->f & SELECT) &&
1053                                                 !eed->h &&
1054                                                 (eed->seam == base_eed->seam)
1055                                         ) {
1056                                                 EM_select_edge(eed, 1);
1057                                                 selcount++;
1058                                                 deselcount--;
1059                                                 if (!deselcount) /*have we selected all posible faces?, if so return*/
1060                                                         return selcount;
1061                                         }
1062                                 }
1063                         } else if (mode==SIMEDGE_SHARP) { /* edge sharp */
1064                                 for(eed= em->edges.first; eed; eed= eed->next) {
1065                                         if (
1066                                                 !(eed->f & SELECT) &&
1067                                                 !eed->h &&
1068                                                 (eed->sharp == base_eed->sharp)
1069                                         ) {
1070                                                 EM_select_edge(eed, 1);
1071                                                 selcount++;
1072                                                 deselcount--;
1073                                                 if (!deselcount) /*have we selected all posible faces?, if so return*/
1074                                                         return selcount;
1075                                         }
1076                                 }
1077                         } else if (mode==SIMEDGE_FREESTYLE) { /* Freestyle edge mark */
1078                                 for(eed= em->edges.first; eed; eed= eed->next) {
1079                                         if (
1080                                                 !(eed->f & SELECT) &&
1081                                                 !eed->h &&
1082                                                 (eed->freestyle == base_eed->freestyle)
1083                                         ) {
1084                                                 EM_select_edge(eed, 1);
1085                                                 selcount++;
1086                                                 deselcount--;
1087                                                 if (!deselcount) /*have we selected all posible faces?, if so return*/
1088                                                         return selcount;
1089                                         }
1090                                 }
1091                         }
1092                 }
1093         }       
1094         return selcount;
1095 }
1096 /* wrap the above function but do selection flushing edge to face */
1097 static int similar_edge_select_exec(bContext *C, wmOperator *op)
1098 {
1099         Object *obedit= CTX_data_edit_object(C);
1100         Mesh *me= obedit->data;
1101         EditMesh *em= BKE_mesh_get_editmesh(me); 
1102
1103         int selcount = similar_edge_select__internal(em, RNA_enum_get(op->ptr, "type"), RNA_float_get(op->ptr, "threshold"));
1104         
1105         if (selcount) {
1106                 /* here was an edge-mode only select flush case, has to be generalized */
1107                 EM_selectmode_flush(em);
1108                 WM_event_add_notifier(C, NC_GEOM|ND_SELECT, obedit->data);
1109         }
1110
1111         BKE_mesh_end_editmesh(me, em);
1112         return OPERATOR_FINISHED;
1113 }
1114
1115 /* ********************************* */
1116
1117 static int similar_vert_select_exec(bContext *C, wmOperator *op)
1118 {
1119         Object *obedit= CTX_data_edit_object(C);
1120         Mesh *me= obedit->data;
1121         EditMesh *em= BKE_mesh_get_editmesh(me); 
1122         EditVert *eve, *base_eve=NULL;
1123         unsigned int selcount=0; /* count how many new edges we select*/
1124         
1125         /*count how many visible selected edges there are,
1126         so we can return when there are none left */
1127         unsigned int deselcount=0;
1128         int mode= RNA_enum_get(op->ptr, "type");
1129         float thresh = RNA_float_get(op->ptr, "threshold");
1130         
1131         short ok=0;
1132         
1133         for(eve= em->verts.first; eve; eve= eve->next) {
1134                 if (!eve->h) {
1135                         if (eve->f & SELECT) {
1136                                 eve->f1=1;
1137                                 ok=1;
1138                         } else {
1139                                 eve->f1=0;
1140                                 deselcount++;
1141                         }
1142                         /* set all eve->tmp.l to 0 we use them later.*/
1143                         eve->tmp.l=0;
1144                 }
1145                 
1146         }
1147         
1148         if (!ok || !deselcount) { /* no data selected OR no more data to select*/
1149                 BKE_mesh_end_editmesh(me, em);
1150                 return OPERATOR_CANCELLED;
1151         }
1152         
1153         if(mode == SIMVERT_FACE) {
1154                 /* store face users */
1155                 EditFace *efa;
1156                 
1157                 /* count how many faces each edge uses use tmp->l */
1158                 for(efa= em->faces.first; efa; efa= efa->next) {
1159                         efa->v1->tmp.l++;
1160                         efa->v2->tmp.l++;
1161                         efa->v3->tmp.l++;
1162                         if (efa->v4) efa->v4->tmp.l++;
1163                 }
1164         }
1165         
1166         
1167         for(base_eve= em->verts.first; base_eve; base_eve= base_eve->next) {
1168                 if (base_eve->f1) {
1169                                 
1170                         if(mode == SIMVERT_NORMAL) {
1171                                 float angle;
1172                                 for(eve= em->verts.first; eve; eve= eve->next) {
1173                                         if (!(eve->f & SELECT) && !eve->h) {
1174                                                 angle= RAD2DEGF(angle_v3v3(base_eve->no, eve->no));
1175                                                 if (angle/180.0f<=thresh) {
1176                                                         eve->f |= SELECT;
1177                                                         selcount++;
1178                                                         deselcount--;
1179                                                         if (!deselcount) {/*have we selected all posible faces?, if so return*/
1180                                                                 BKE_mesh_end_editmesh(me, em);
1181                                                                 return OPERATOR_FINISHED;
1182                                                         }
1183                                                 }
1184                                         }
1185                                 }
1186                         }
1187                         else if(mode == SIMVERT_FACE) {
1188                                 for(eve= em->verts.first; eve; eve= eve->next) {
1189                                         if (
1190                                                 !(eve->f & SELECT) &&
1191                                                 !eve->h &&
1192                                                 base_eve->tmp.l==eve->tmp.l
1193                                         ) {
1194                                                 eve->f |= SELECT;
1195                                                 selcount++;
1196                                                 deselcount--;
1197                                                 if (!deselcount) {/*have we selected all posible faces?, if so return*/
1198                                                         BKE_mesh_end_editmesh(me, em);
1199                                                         return OPERATOR_FINISHED;
1200                                                 }
1201                                         }
1202                                 }
1203                         } 
1204                         else if(mode == SIMVERT_VGROUP) {
1205                                 MDeformVert *dvert, *base_dvert;
1206                                 short i, j; /* weight index */
1207
1208                                 base_dvert= CustomData_em_get(&em->vdata, base_eve->data,
1209                                         CD_MDEFORMVERT);
1210
1211                                 if (!base_dvert || base_dvert->totweight == 0) {
1212                                         BKE_mesh_end_editmesh(me, em);
1213                                         return OPERATOR_FINISHED;
1214                                 }
1215                                 
1216                                 for(eve= em->verts.first; eve; eve= eve->next) {
1217                                         dvert= CustomData_em_get(&em->vdata, eve->data,
1218                                                 CD_MDEFORMVERT);
1219
1220                                         if (dvert && !(eve->f & SELECT) && !eve->h && dvert->totweight) {
1221                                                 /* do the extra check for selection in the following if, so were not
1222                                                 checking verts that may be already selected */
1223                                                 for (i=0; base_dvert->totweight >i && !(eve->f & SELECT); i++) { 
1224                                                         for (j=0; dvert->totweight >j; j++) {
1225                                                                 if (base_dvert->dw[i].def_nr==dvert->dw[j].def_nr) {
1226                                                                         eve->f |= SELECT;
1227                                                                         selcount++;
1228                                                                         deselcount--;
1229                                                                         if (!deselcount) { /*have we selected all posible faces?, if so return*/
1230                                                                                 BKE_mesh_end_editmesh(me, em);
1231                                                                                 return OPERATOR_FINISHED;
1232                                                                         }
1233                                                                         break;
1234                                                                 }
1235                                                         }
1236                                                 }
1237                                         }
1238                                 }
1239                         }
1240                 }
1241         } /* end basevert loop */
1242
1243         if(selcount) {
1244                 WM_event_add_notifier(C, NC_GEOM|ND_SELECT, obedit->data);
1245         }
1246
1247         BKE_mesh_end_editmesh(me, em);
1248         return OPERATOR_FINISHED;
1249 }
1250
1251 static int select_similar_exec(bContext *C, wmOperator *op)
1252 {
1253         int type= RNA_enum_get(op->ptr, "type");
1254
1255         if(type < 100)
1256                 return similar_vert_select_exec(C, op);
1257         else if(type < 200)
1258                 return similar_edge_select_exec(C, op);
1259         else
1260                 return similar_face_select_exec(C, op);
1261 }
1262
1263 static EnumPropertyItem *select_similar_type_itemf(bContext *C, PointerRNA *UNUSED(ptr), PropertyRNA *UNUSED(prop), int *free)
1264 {
1265         Object *obedit= CTX_data_edit_object(C);
1266         EnumPropertyItem *item= NULL;
1267         int a, totitem= 0;
1268
1269         if (C == NULL) {
1270                 return prop_similar_types;
1271         }
1272                 
1273         if(obedit && obedit->type == OB_MESH) {
1274                 EditMesh *em= BKE_mesh_get_editmesh(obedit->data); 
1275
1276                 if(em->selectmode & SCE_SELECT_VERTEX) {
1277                         for(a=SIMVERT_NORMAL; a<=SIMVERT_TOT; a++)
1278                                 RNA_enum_items_add_value(&item, &totitem, prop_similar_types, a);
1279                 }
1280                 else if(em->selectmode & SCE_SELECT_EDGE) {
1281                         for(a=SIMEDGE_LENGTH; a<=SIMEDGE_TOT; a++)
1282                                 RNA_enum_items_add_value(&item, &totitem, prop_similar_types, a);
1283                 }
1284                 else if(em->selectmode & SCE_SELECT_FACE) {
1285                         for(a=SIMFACE_MATERIAL; a<=SIMFACE_TOT; a++)
1286                                 RNA_enum_items_add_value(&item, &totitem, prop_similar_types, a);
1287                 }
1288         }
1289
1290         RNA_enum_item_end(&item, &totitem);
1291         *free= 1;
1292
1293         return item;
1294 }
1295
1296 void MESH_OT_select_similar(wmOperatorType *ot)
1297 {
1298         PropertyRNA *prop;
1299
1300         /* identifiers */
1301         ot->name= "Select Similar";
1302         ot->description= "Select similar vertices, edges or faces by property types";
1303         ot->idname= "MESH_OT_select_similar";
1304         
1305         /* api callbacks */
1306         ot->invoke= WM_menu_invoke;
1307         ot->exec= select_similar_exec;
1308         ot->poll= ED_operator_editmesh;
1309         
1310         /* flags */
1311         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1312         
1313         /* properties */
1314         prop= RNA_def_enum(ot->srna, "type", prop_similar_types, SIMVERT_NORMAL, "Type", "");
1315         RNA_def_enum_funcs(prop, select_similar_type_itemf);
1316         ot->prop= prop;
1317         RNA_def_float(ot->srna, "threshold", 0.01f, 0.0f, FLT_MAX, "Threshold", "", 0.0f, 100.f);
1318 }
1319
1320 /* ******************************************* */
1321
1322
1323 int mesh_layers_menu_charlen(CustomData *data, int type)
1324 {
1325         int i, len = 0;
1326         /* see if there is a duplicate */
1327         for(i=0; i<data->totlayer; i++) {
1328                 if((&data->layers[i])->type == type) {
1329                         /* we could count the chars here but we'll just assumeme each
1330                          * is 32 chars with some room for the menu text - 40 should be fine */
1331                         len+=40; 
1332                 }
1333         }
1334         return len;
1335 }
1336
1337 /* this function adds menu text into an existing string.
1338  * this string's size should be allocated with mesh_layers_menu_charlen */
1339 void mesh_layers_menu_concat(CustomData *data, int type, char *str) 
1340 {
1341         int i, count = 0;
1342         char *str_pt = str;
1343         CustomDataLayer *layer;
1344         
1345         /* see if there is a duplicate */
1346         for(i=0; i<data->totlayer; i++) {
1347                 layer = &data->layers[i];
1348                 if(layer->type == type) {
1349                         str_pt += sprintf(str_pt, "%s%%x%d|", layer->name, count);
1350                         count++;
1351                 }
1352         }
1353 }
1354
1355 int mesh_layers_menu(CustomData *data, int type)
1356 {
1357         int ret;
1358         char *str_pt, *str;
1359         
1360         str_pt = str = MEM_mallocN(mesh_layers_menu_charlen(data, type) + 18, "layer menu");
1361         str[0] = '\0';
1362         
1363         str_pt += sprintf(str_pt, "Layers%%t|");
1364         
1365         mesh_layers_menu_concat(data, type, str_pt);
1366         
1367         ret = pupmenu(str);
1368         MEM_freeN(str);
1369         return ret;
1370 }
1371
1372 static void EM_mesh_copy_edge(EditMesh *em, short type) 
1373 {
1374         EditSelection *ese;
1375         short change=0;
1376         
1377         EditEdge *eed, *eed_act;
1378         float vec[3], vec_mid[3], eed_len, eed_len_act;
1379         
1380         if (!em) return;
1381         
1382         ese = em->selected.last;
1383         if (!ese) return;
1384         
1385         eed_act = (EditEdge*)ese->data;
1386         
1387         switch (type) {
1388         case 1: /* copy crease */
1389                 for(eed=em->edges.first; eed; eed=eed->next) {
1390                         if (eed->f & SELECT && eed != eed_act && eed->crease != eed_act->crease) {
1391                                 eed->crease = eed_act->crease;
1392                                 change = 1;
1393                         }
1394                 }
1395                 break;
1396         case 2: /* copy bevel weight */
1397                 for(eed=em->edges.first; eed; eed=eed->next) {
1398                         if (eed->f & SELECT && eed != eed_act && eed->bweight != eed_act->bweight) {
1399                                 eed->bweight = eed_act->bweight;
1400                                 change = 1;
1401                         }
1402                 }
1403                 break;
1404
1405         case 3: /* copy length */
1406                 eed_len_act = len_v3v3(eed_act->v1->co, eed_act->v2->co);
1407                 for(eed=em->edges.first; eed; eed=eed->next) {
1408                         if (eed->f & SELECT && eed != eed_act) {
1409
1410                                 eed_len = len_v3v3(eed->v1->co, eed->v2->co);
1411
1412                                 if (eed_len == eed_len_act) continue;
1413                                 /* if this edge is zero length we cont do anything with it*/
1414                                 if (eed_len == 0.0f) continue;
1415                                 if (eed_len_act == 0.0f) {
1416                                         add_v3_v3v3(vec_mid, eed->v1->co, eed->v2->co);
1417                                         mul_v3_fl(vec_mid, 0.5);
1418                                         VECCOPY(eed->v1->co, vec_mid);
1419                                         VECCOPY(eed->v2->co, vec_mid);
1420                                 } else {
1421                                         /* copy the edge length */
1422                                         add_v3_v3v3(vec_mid, eed->v1->co, eed->v2->co);
1423                                         mul_v3_fl(vec_mid, 0.5);
1424
1425                                         /* SCALE 1 */
1426                                         sub_v3_v3v3(vec, eed->v1->co, vec_mid);
1427                                         mul_v3_fl(vec, eed_len_act/eed_len);
1428                                         add_v3_v3v3(eed->v1->co, vec, vec_mid);
1429
1430                                         /* SCALE 2 */
1431                                         sub_v3_v3v3(vec, eed->v2->co, vec_mid);
1432                                         mul_v3_fl(vec, eed_len_act/eed_len);
1433                                         add_v3_v3v3(eed->v2->co, vec, vec_mid);
1434                                 }
1435                                 change = 1;
1436                         }
1437                 }
1438
1439                 if (change)
1440                         recalc_editnormals(em);
1441
1442                 break;
1443         }
1444         
1445         if (change) {
1446 //              DAG_id_tag_update(obedit->data, 0);
1447                 
1448         }
1449 }
1450
1451 static void EM_mesh_copy_face(EditMesh *em, wmOperator *op, short type)
1452 {
1453         short change=0;
1454         
1455         EditFace *efa, *efa_act;
1456         MTFace *tf, *tf_act = NULL;
1457         MCol *mcol, *mcol_act = NULL;
1458         if (!em) return;
1459         efa_act = EM_get_actFace(em, 0);
1460         
1461         if (!efa_act) return;
1462         
1463         tf_act =        CustomData_em_get(&em->fdata, efa_act->data, CD_MTFACE);
1464         mcol_act =      CustomData_em_get(&em->fdata, efa_act->data, CD_MCOL);
1465         
1466         switch (type) {
1467         case 1: /* copy material */
1468                 for(efa=em->faces.first; efa; efa=efa->next) {
1469                         if (efa->f & SELECT && efa->mat_nr != efa_act->mat_nr) {
1470                                 efa->mat_nr = efa_act->mat_nr;
1471                                 change = 1;
1472                         }
1473                 }
1474                 break;
1475         case 2: /* copy image */
1476                 if (!tf_act) {
1477                         BKE_report(op->reports, RPT_WARNING, "Mesh has no uv/image layers");
1478                         return;
1479                 }
1480                 for(efa=em->faces.first; efa; efa=efa->next) {
1481                         if (efa->f & SELECT && efa != efa_act) {
1482                                 tf = CustomData_em_get(&em->fdata, efa->data, CD_MTFACE);
1483                                 if (tf_act->tpage) {
1484                                         tf->tpage = tf_act->tpage;
1485                                 } else {
1486                                         tf->tpage = NULL;
1487                                 }
1488                                 tf->tile= tf_act->tile;
1489                                 change = 1;
1490                         }
1491                 }
1492                 break;
1493
1494         case 3: /* copy UV's */
1495                 if (!tf_act) {
1496                         BKE_report(op->reports, RPT_WARNING, "Mesh has no uv/image layers");
1497                         return;
1498                 }
1499                 for(efa=em->faces.first; efa; efa=efa->next) {
1500                         if (efa->f & SELECT && efa != efa_act) {
1501                                 tf = CustomData_em_get(&em->fdata, efa->data, CD_MTFACE);
1502                                 memcpy(tf->uv, tf_act->uv, sizeof(tf->uv));
1503                                 change = 1;
1504                         }
1505                 }
1506                 break;
1507         case 4: /* mode's */
1508                 if (!tf_act) {
1509                         BKE_report(op->reports, RPT_WARNING, "Mesh has no uv/image layers");
1510                         return;
1511                 }
1512                 for(efa=em->faces.first; efa; efa=efa->next) {
1513                         if (efa->f & SELECT && efa != efa_act) {
1514                                 tf = CustomData_em_get(&em->fdata, efa->data, CD_MTFACE);
1515                                 tf->mode= tf_act->mode;
1516                                 change = 1;
1517                         }
1518                 }
1519                 break;
1520         case 5: /* copy transp's */
1521                 if (!tf_act) {
1522                         BKE_report(op->reports, RPT_WARNING, "Mesh has no uv/image layers");
1523                         return;
1524                 }
1525                 for(efa=em->faces.first; efa; efa=efa->next) {
1526                         if (efa->f & SELECT && efa != efa_act) {
1527                                 tf = CustomData_em_get(&em->fdata, efa->data, CD_MTFACE);
1528                                 tf->transp= tf_act->transp;
1529                                 change = 1;
1530                         }
1531                 }
1532                 break;
1533
1534         case 6: /* copy vcols's */
1535                 if (!mcol_act) {
1536                         BKE_report(op->reports, RPT_WARNING, "Mesh has no color layers");
1537                         return;
1538                 } else {
1539                         /* guess the 4th color if needs be */
1540                         float val =- 1;
1541
1542                         if (!efa_act->v4) {
1543                                 /* guess the othe vale, we may need to use it
1544                                  * 
1545                                  * Modifying the 4th value of the mcol is ok here since its not seen
1546                                  * on a triangle
1547                                  * */
1548                                 val = ((float)(mcol_act->r +  (mcol_act+1)->r + (mcol_act+2)->r)) / 3; CLAMP(val, 0, 255);
1549                                 (mcol_act+3)->r = (char)val;
1550
1551                                 val = ((float)(mcol_act->g +  (mcol_act+1)->g + (mcol_act+2)->g)) / 3; CLAMP(val, 0, 255);
1552                                 (mcol_act+3)->g = (char)val;
1553
1554                                 val = ((float)(mcol_act->b +  (mcol_act+1)->b + (mcol_act+2)->b)) / 3; CLAMP(val, 0, 255);
1555                                 (mcol_act+3)->b = (char)val;
1556                         } 
1557
1558
1559                         for(efa=em->faces.first; efa; efa=efa->next) {
1560                                 if (efa->f & SELECT && efa != efa_act) {
1561                                         /* TODO - make copy from tri to quad guess the 4th vert */
1562                                         mcol = CustomData_em_get(&em->fdata, efa->data, CD_MCOL);
1563                                         memcpy(mcol, mcol_act, sizeof(MCol)*4); 
1564                                         change = 1;
1565                                 }
1566                         }
1567                 }
1568                 break;
1569         }
1570         
1571         if (change) {
1572 //              DAG_id_tag_update(obedit->data, 0);
1573                 
1574         }
1575 }
1576
1577
1578 void EM_mesh_copy_face_layer(EditMesh *em, wmOperator *op, short type) 
1579 {
1580         short change=0;
1581         
1582         EditFace *efa;
1583         MTFace *tf, *tf_from;
1584         MCol *mcol, *mcol_from;
1585         
1586         if (!em) return;
1587         
1588         switch(type) {
1589         case 7:
1590         case 8:
1591         case 9:
1592                 if (CustomData_number_of_layers(&em->fdata, CD_MTFACE)<2) {
1593                         BKE_report(op->reports, RPT_WARNING, "mesh does not have multiple uv/image layers");
1594                         return;
1595                 } else {
1596                         int layer_orig_idx, layer_idx;
1597
1598                         layer_idx = mesh_layers_menu(&em->fdata, CD_MTFACE);
1599                         if (layer_idx<0) return;
1600
1601                         /* warning, have not updated mesh pointers however this is not needed since we swicth back */
1602                         layer_orig_idx = CustomData_get_active_layer(&em->fdata, CD_MTFACE);
1603                         if (layer_idx==layer_orig_idx)
1604                                 return;
1605
1606                         /* get the tfaces */
1607                         CustomData_set_layer_active(&em->fdata, CD_MTFACE, (int)layer_idx);
1608                         /* store the tfaces in our temp */
1609                         for(efa=em->faces.first; efa; efa=efa->next) {
1610                                 if (efa->f & SELECT) {
1611                                         efa->tmp.p = CustomData_em_get(&em->fdata, efa->data, CD_MTFACE);
1612                                 }       
1613                         }
1614                         CustomData_set_layer_active(&em->fdata, CD_MTFACE, layer_orig_idx);
1615                 }
1616                 break;
1617
1618         case 10: /* select vcol layers - make sure this stays in sync with above code */
1619                 if (CustomData_number_of_layers(&em->fdata, CD_MCOL)<2) {
1620                         BKE_report(op->reports, RPT_WARNING, "mesh does not have multiple color layers");
1621                         return;
1622                 } else {
1623                         int layer_orig_idx, layer_idx;
1624
1625                         layer_idx = mesh_layers_menu(&em->fdata, CD_MCOL);
1626                         if (layer_idx<0) return;
1627
1628                         /* warning, have not updated mesh pointers however this is not needed since we swicth back */
1629                         layer_orig_idx = CustomData_get_active_layer(&em->fdata, CD_MCOL);
1630                         if (layer_idx==layer_orig_idx)
1631                                 return;
1632
1633                         /* get the tfaces */
1634                         CustomData_set_layer_active(&em->fdata, CD_MCOL, (int)layer_idx);
1635                         /* store the tfaces in our temp */
1636                         for(efa=em->faces.first; efa; efa=efa->next) {
1637                                 if (efa->f & SELECT) {
1638                                         efa->tmp.p = CustomData_em_get(&em->fdata, efa->data, CD_MCOL);
1639                                 }       
1640                         }
1641                         CustomData_set_layer_active(&em->fdata, CD_MCOL, layer_orig_idx);
1642
1643                 }
1644                 break;
1645         }
1646
1647         /* layer copy only - sanity checks done above */
1648         switch (type) {
1649         case 7: /* copy UV's only */
1650                 for(efa=em->faces.first; efa; efa=efa->next) {
1651                         if (efa->f & SELECT) {
1652                                 tf_from = (MTFace *)efa->tmp.p; /* not active but easier to use this way */
1653                                 tf = CustomData_em_get(&em->fdata, efa->data, CD_MTFACE);
1654                                 memcpy(tf->uv, tf_from->uv, sizeof(tf->uv));
1655                                 change = 1;
1656                         }
1657                 }
1658                 break;
1659         case 8: /* copy image settings only */
1660                 for(efa=em->faces.first; efa; efa=efa->next) {
1661                         if (efa->f & SELECT) {
1662                                 tf_from = (MTFace *)efa->tmp.p; /* not active but easier to use this way */
1663                                 tf = CustomData_em_get(&em->fdata, efa->data, CD_MTFACE);
1664                                 if (tf_from->tpage) {
1665                                         tf->tpage = tf_from->tpage;
1666                                 } else {
1667                                         tf->tpage = NULL;
1668                                 }
1669                                 tf->tile= tf_from->tile;
1670                                 change = 1;
1671                         }
1672                 }
1673                 break;
1674         case 9: /* copy all tface info */
1675                 for(efa=em->faces.first; efa; efa=efa->next) {
1676                         if (efa->f & SELECT) {
1677                                 tf_from = (MTFace *)efa->tmp.p; /* not active but easier to use this way */
1678                                 tf = CustomData_em_get(&em->fdata, efa->data, CD_MTFACE);
1679                                 memcpy(tf->uv, ((MTFace *)efa->tmp.p)->uv, sizeof(tf->uv));
1680                                 tf->tpage = tf_from->tpage;
1681                                 tf->mode = tf_from->mode;
1682                                 tf->transp = tf_from->transp;
1683                                 change = 1;
1684                         }
1685                 }
1686                 break;
1687         case 10:
1688                 for(efa=em->faces.first; efa; efa=efa->next) {
1689                         if (efa->f & SELECT) {
1690                                 mcol_from = (MCol *)efa->tmp.p; 
1691                                 mcol = CustomData_em_get(&em->fdata, efa->data, CD_MCOL);
1692                                 memcpy(mcol, mcol_from, sizeof(MCol)*4);        
1693                                 change = 1;
1694                         }
1695                 }
1696                 break;
1697         }
1698
1699         if (change) {
1700 //              DAG_id_tag_update(obedit->data, 0);
1701                 
1702         }
1703 }
1704
1705
1706 /* ctrl+c in mesh editmode */
1707 static void UNUSED_FUNCTION(mesh_copy_menu)(EditMesh *em, wmOperator *op)
1708 {
1709         EditSelection *ese;
1710         int ret;
1711         if (!em) return;
1712         
1713         ese = em->selected.last;
1714         
1715         /* Faces can have a NULL ese, so dont return on a NULL ese here */
1716         
1717         if(ese && ese->type == EDITVERT) {
1718                 /* EditVert *ev, *ev_act = (EditVert*)ese->data;
1719                 ret= pupmenu(""); */
1720         } else if(ese && ese->type == EDITEDGE) {
1721                 ret= pupmenu("Copy Active Edge to Selected%t|Crease%x1|Bevel Weight%x2|Length%x3");
1722                 if (ret<1) return;
1723                 
1724                 EM_mesh_copy_edge(em, ret);
1725                 
1726         } else if(ese==NULL || ese->type == EDITFACE) {
1727                 ret= pupmenu(
1728                         "Copy Face Selected%t|"
1729                         "Active Material%x1|Active Image%x2|Active UV Coords%x3|"
1730                         "Active Mode%x4|Active Transp%x5|Active Vertex Colors%x6|%l|"
1731
1732                         "TexFace UVs from layer%x7|"
1733                         "TexFace Images from layer%x8|"
1734                         "TexFace All from layer%x9|"
1735                         "Vertex Colors from layer%x10");
1736                 if (ret<1) return;
1737                 
1738                 if (ret<=6) {
1739                         EM_mesh_copy_face(em, op, ret);
1740                 } else {
1741                         EM_mesh_copy_face_layer(em, op, ret);
1742                 }
1743         }
1744 }
1745
1746 /* ****************  LOOP SELECTS *************** */
1747
1748 /* selects quads in loop direction of indicated edge */
1749 /* only flush over edges with valence <= 2 */
1750 void faceloop_select(EditMesh *em, EditEdge *startedge, int select)
1751 {
1752         EditEdge *eed;
1753         EditFace *efa;
1754         int looking= 1;
1755         
1756         /* in eed->f1 we put the valence (amount of faces in edge) */
1757         /* in eed->f2 we put tagged flag as correct loop */
1758         /* in efa->f1 we put tagged flag as correct to select */
1759
1760         for(eed= em->edges.first; eed; eed= eed->next) {
1761                 eed->f1= 0;
1762                 eed->f2= 0;
1763         }
1764         for(efa= em->faces.first; efa; efa= efa->next) {
1765                 efa->f1= 0;
1766                 if(efa->h==0) {
1767                         efa->e1->f1++;
1768                         efa->e2->f1++;
1769                         efa->e3->f1++;
1770                         if(efa->e4) efa->e4->f1++;
1771                 }
1772         }
1773         
1774         /* tag startedge OK*/
1775         startedge->f2= 1;
1776         
1777         while(looking) {
1778                 looking= 0;
1779                 
1780                 for(efa= em->faces.first; efa; efa= efa->next) {
1781                         if(efa->h==0 && efa->e4 && efa->f1==0) {        /* not done quad */
1782                                 if(efa->e1->f1<=2 && efa->e2->f1<=2 && efa->e3->f1<=2 && efa->e4->f1<=2) { /* valence ok */
1783
1784                                         /* if edge tagged, select opposing edge and mark face ok */
1785                                         if(efa->e1->f2) {
1786                                                 efa->e3->f2= 1;
1787                                                 efa->f1= 1;
1788                                                 looking= 1;
1789                                         }
1790                                         else if(efa->e2->f2) {
1791                                                 efa->e4->f2= 1;
1792                                                 efa->f1= 1;
1793                                                 looking= 1;
1794                                         }
1795                                         if(efa->e3->f2) {
1796                                                 efa->e1->f2= 1;
1797                                                 efa->f1= 1;
1798                                                 looking= 1;
1799                                         }
1800                                         if(efa->e4->f2) {
1801                                                 efa->e2->f2= 1;
1802                                                 efa->f1= 1;
1803                                                 looking= 1;
1804                                         }
1805                                 }
1806                         }
1807                 }
1808         }
1809         
1810         /* (de)select the faces */
1811         if(select!=2) {
1812                 for(efa= em->faces.first; efa; efa= efa->next) {
1813                         if(efa->f1) EM_select_face(efa, select);
1814                 }
1815         }
1816 }
1817
1818
1819 /* helper for edgeloop_select, checks for eed->f2 tag in faces */
1820 static int edge_not_in_tagged_face(EditMesh *em, EditEdge *eed)
1821 {
1822         EditFace *efa;
1823         
1824         for(efa= em->faces.first; efa; efa= efa->next) {
1825                 if(efa->h==0) {
1826                         if(efa->e1==eed || efa->e2==eed || efa->e3==eed || efa->e4==eed) {      /* edge is in face */
1827                                 if(efa->e1->f2 || efa->e2->f2 || efa->e3->f2 || (efa->e4 && efa->e4->f2)) {     /* face is tagged */
1828                                         return 0;
1829                                 }
1830                         }
1831                 }
1832         }
1833         return 1;
1834 }
1835
1836 static void ensure_ed_vert_sel(EditMesh *em)
1837 {
1838         EditEdge *eed;
1839
1840         /* EM_selectmode_flush() doesnt take into account that deselected edges
1841          * may be still connected to selected edges [#26885] */
1842         for(eed= em->edges.first; eed; eed= eed->next) {
1843                 if(eed->f & SELECT) {
1844                         eed->v1->f |= SELECT;
1845                         eed->v2->f |= SELECT;
1846                 }
1847         }
1848 }
1849
1850 /* selects or deselects edges that:
1851 - if edges has 2 faces:
1852         - has vertices with valence of 4
1853         - not shares face with previous edge
1854 - if edge has 1 face:
1855         - has vertices with valence 4
1856         - not shares face with previous edge
1857         - but also only 1 face
1858 - if edge no face:
1859         - has vertices with valence 2
1860 */
1861 static void edgeloop_select(EditMesh *em, EditEdge *starteed, int select)
1862 {
1863         EditVert *eve;
1864         EditEdge *eed;
1865         EditFace *efa;
1866         int looking= 1;
1867         
1868         /* in f1 we put the valence (amount of edges in a vertex, or faces in edge) */
1869         /* in eed->f2 and efa->f1 we put tagged flag as correct loop */
1870         for(eve= em->verts.first; eve; eve= eve->next) {
1871                 eve->f1= 0;
1872                 eve->f2= 0;
1873         }
1874         for(eed= em->edges.first; eed; eed= eed->next) {
1875                 eed->f1= 0;
1876                 eed->f2= 0;
1877                 if((eed->h & 1)==0) {   /* fgon edges add to valence too */
1878                         eed->v1->f1++; eed->v2->f1++;
1879                 }
1880         }
1881         for(efa= em->faces.first; efa; efa= efa->next) {
1882                 efa->f1= 0;
1883                 if(efa->h==0) {
1884                         efa->e1->f1++;
1885                         efa->e2->f1++;
1886                         efa->e3->f1++;
1887                         if(efa->e4) efa->e4->f1++;
1888                 }
1889         }
1890         
1891         /* looped edges & vertices get tagged f2 */
1892         starteed->f2= 1;
1893         if(starteed->v1->f1<5) starteed->v1->f2= 1;
1894         if(starteed->v2->f1<5) starteed->v2->f2= 1;
1895         /* sorry, first edge isnt even ok */
1896         if(starteed->v1->f2==0 && starteed->v2->f2==0) looking= 0;
1897         
1898         while(looking) {
1899                 looking= 0;
1900                 
1901                 /* find correct valence edges which are not tagged yet, but connect to tagged one */
1902                 for(eed= em->edges.first; eed; eed= eed->next) {
1903                         if(eed->h==0 && eed->f2==0) { /* edge not hidden, not tagged */
1904                                 if( (eed->v1->f1<5 && eed->v1->f2) || (eed->v2->f1<5 && eed->v2->f2)) { /* valence of vertex OK, and is tagged */
1905                                         /* new edge is not allowed to be in face with tagged edge */
1906                                         if(edge_not_in_tagged_face(em, eed)) {
1907                                                 if(eed->f1==starteed->f1) {     /* same amount of faces */
1908                                                         looking= 1;
1909                                                         eed->f2= 1;
1910                                                         if(eed->v2->f1<5) eed->v2->f2= 1;
1911                                                         if(eed->v1->f1<5) eed->v1->f2= 1;
1912                                                 }
1913                                         }
1914                                 }
1915                         }
1916                 }
1917         }
1918         /* and we do the select */
1919         for(eed= em->edges.first; eed; eed= eed->next) {
1920                 if(eed->f2) EM_select_edge(eed, select);
1921         }
1922
1923         if(select == FALSE && !(em->selectmode & SCE_SELECT_VERTEX)) { /* only when not in vert sel [#26931] */
1924                 ensure_ed_vert_sel(em);
1925         }
1926 }
1927
1928 /* 
1929    Almostly exactly the same code as faceloop select
1930 */
1931 static void edgering_select(EditMesh *em, EditEdge *startedge, int select)
1932 {
1933         EditEdge *eed;
1934         EditFace *efa;
1935         int looking= 1;
1936         
1937         /* in eed->f1 we put the valence (amount of faces in edge) */
1938         /* in eed->f2 we put tagged flag as correct loop */
1939         /* in efa->f1 we put tagged flag as correct to select */
1940
1941         for(eed= em->edges.first; eed; eed= eed->next) {
1942                 eed->f1= 0;
1943                 eed->f2= 0;
1944         }
1945         for(efa= em->faces.first; efa; efa= efa->next) {
1946                 efa->f1= 0;
1947                 if(efa->h==0) {
1948                         efa->e1->f1++;
1949                         efa->e2->f1++;
1950                         efa->e3->f1++;
1951                         if(efa->e4) efa->e4->f1++;
1952                 }
1953         }
1954         
1955         /* tag startedge OK */
1956         startedge->f2= 1;
1957         
1958         while(looking) {
1959                 looking= 0;
1960                 
1961                 for(efa= em->faces.first; efa; efa= efa->next) {
1962                         if(efa->e4 && efa->f1==0 && !efa->h) {  /* not done quad */
1963                                 if(efa->e1->f1<=2 && efa->e2->f1<=2 && efa->e3->f1<=2 && efa->e4->f1<=2) { /* valence ok */
1964
1965                                         /* if edge tagged, select opposing edge and mark face ok */
1966                                         if(efa->e1->f2) {
1967                                                 efa->e3->f2= 1;
1968                                                 efa->f1= 1;
1969                                                 looking= 1;
1970                                         }
1971                                         else if(efa->e2->f2) {
1972                                                 efa->e4->f2= 1;
1973                                                 efa->f1= 1;
1974                                                 looking= 1;
1975                                         }
1976                                         if(efa->e3->f2) {
1977                                                 efa->e1->f2= 1;
1978                                                 efa->f1= 1;
1979                                                 looking= 1;
1980                                         }
1981                                         if(efa->e4->f2) {
1982                                                 efa->e2->f2= 1;
1983                                                 efa->f1= 1;
1984                                                 looking= 1;
1985                                         }
1986                                 }
1987                         }
1988                 }
1989         }
1990         
1991         /* (de)select the edges */
1992         for(eed= em->edges.first; eed; eed= eed->next) {
1993                         if(eed->f2) EM_select_edge(eed, select);
1994         }
1995
1996         if(select == FALSE && !(em->selectmode & SCE_SELECT_VERTEX)) { /* only when not in vert sel [#26931] */
1997                 ensure_ed_vert_sel(em);
1998         }
1999 }
2000
2001 static int loop_multiselect(bContext *C, wmOperator *op)
2002 {
2003         Object *obedit= CTX_data_edit_object(C);
2004         EditMesh *em= BKE_mesh_get_editmesh(((Mesh *)obedit->data));
2005         EditEdge *eed;
2006         EditEdge **edarray;
2007         int edindex, edfirstcount;
2008         int looptype= RNA_boolean_get(op->ptr, "ring");
2009         
2010         /* sets em->totedgesel */
2011         EM_nedges_selected(em);
2012         
2013         edarray = MEM_mallocN(sizeof(EditEdge*)*em->totedgesel,"edge array");
2014         edindex = 0;
2015         edfirstcount = em->totedgesel;
2016         
2017         for(eed=em->edges.first; eed; eed=eed->next){
2018                 if(eed->f&SELECT){
2019                         edarray[edindex] = eed;
2020                         edindex += 1;
2021                 }
2022         }
2023         
2024         if(looptype){
2025                 for(edindex = 0; edindex < edfirstcount; edindex +=1){
2026                         eed = edarray[edindex];
2027                         edgering_select(em, eed,SELECT);
2028                 }
2029                 EM_selectmode_flush(em);
2030         }
2031         else{
2032                 for(edindex = 0; edindex < edfirstcount; edindex +=1){
2033                         eed = edarray[edindex];
2034                         edgeloop_select(em, eed,SELECT);
2035                 }
2036                 EM_selectmode_flush(em);
2037         }
2038         MEM_freeN(edarray);
2039 //      if (EM_texFaceCheck())
2040         
2041         WM_event_add_notifier(C, NC_GEOM|ND_SELECT, obedit->data);
2042
2043         BKE_mesh_end_editmesh(obedit->data, em);
2044         return OPERATOR_FINISHED;       
2045 }
2046
2047 void MESH_OT_loop_multi_select(wmOperatorType *ot)
2048 {
2049         /* identifiers */
2050         ot->name= "Multi Select Loops";
2051         ot->description= "Select a loop of connected edges by connection type";
2052         ot->idname= "MESH_OT_loop_multi_select";
2053         
2054         /* api callbacks */
2055         ot->exec= loop_multiselect;
2056         ot->poll= ED_operator_editmesh;
2057         
2058         /* flags */
2059         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
2060         
2061         /* properties */
2062         RNA_def_boolean(ot->srna, "ring", 0, "Ring", "");
2063 }
2064
2065                 
2066 /* ***************** MAIN MOUSE SELECTION ************** */
2067
2068
2069 /* ***************** loop select (non modal) ************** */
2070
2071 static void mouse_mesh_loop(bContext *C, const int mval[2], short extend, short ring)
2072 {
2073         ViewContext vc;
2074         EditMesh *em;
2075         EditEdge *eed;
2076         int select= 1;
2077         int dist= 50;
2078         
2079         em_setup_viewcontext(C, &vc);
2080         vc.mval[0]= mval[0];
2081         vc.mval[1]= mval[1];
2082         em= vc.em;
2083
2084         /* no afterqueue (yet), so we check it now, otherwise the em_xxxofs indices are bad */
2085         view3d_validate_backbuf(&vc);
2086         
2087         eed= findnearestedge(&vc, &dist);
2088         if(eed) {
2089                 if(extend==0) EM_clear_flag_all(em, SELECT);
2090         
2091                 if((eed->f & SELECT)==0) select=1;
2092                 else if(extend) select=0;
2093
2094                 if(em->selectmode & SCE_SELECT_FACE) {
2095                         faceloop_select(em, eed, select);
2096                 }
2097                 else if(em->selectmode & SCE_SELECT_EDGE) {
2098                         if(ring)
2099                                 edgering_select(em, eed, select);
2100                         else
2101                                 edgeloop_select(em, eed, select);
2102                 }
2103                 else if(em->selectmode & SCE_SELECT_VERTEX) {
2104                         if(ring)
2105                                 edgering_select(em, eed, select);
2106                         else 
2107                                 edgeloop_select(em, eed, select);
2108                 }
2109
2110                 EM_selectmode_flush(em);
2111 //                      if (EM_texFaceCheck())
2112                 
2113                 /* sets as active, useful for other tools */
2114                 if(select) {
2115                         if(em->selectmode & SCE_SELECT_VERTEX)
2116                                 EM_store_selection(em, eed->v1, EDITVERT);
2117                         if(em->selectmode & SCE_SELECT_EDGE)
2118                                 EM_store_selection(em, eed, EDITEDGE);
2119                 }
2120
2121                 WM_event_add_notifier(C, NC_GEOM|ND_SELECT, vc.obedit->data);
2122         }
2123 }
2124
2125 static int mesh_select_loop_invoke(bContext *C, wmOperator *op, wmEvent *event)
2126 {
2127         
2128         view3d_operator_needs_opengl(C);
2129         
2130         mouse_mesh_loop(C, event->mval, RNA_boolean_get(op->ptr, "extend"),
2131                                         RNA_boolean_get(op->ptr, "ring"));
2132         
2133         /* cannot do tweaks for as long this keymap is after transform map */
2134         return OPERATOR_FINISHED;
2135 }
2136
2137 void MESH_OT_loop_select(wmOperatorType *ot)
2138 {
2139         /* identifiers */
2140         ot->name= "Loop Select";
2141         ot->description= "Select a loop of connected edges";
2142         ot->idname= "MESH_OT_loop_select";
2143         
2144         /* api callbacks */
2145         ot->invoke= mesh_select_loop_invoke;
2146         ot->poll= ED_operator_editmesh_region_view3d;
2147         
2148         /* flags */
2149         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
2150         
2151         /* properties */
2152         RNA_def_boolean(ot->srna, "extend", 0, "Extend Select", "");
2153         RNA_def_boolean(ot->srna, "ring", 0, "Select Ring", "");
2154 }
2155
2156 /* ******************* mesh shortest path select, uses prev-selected edge ****************** */
2157
2158 /* since you want to create paths with multiple selects, it doesn't have extend option */
2159 static void mouse_mesh_shortest_path(bContext *C, const int mval[2])
2160 {
2161         ViewContext vc;
2162         EditMesh *em;
2163         EditEdge *eed, *eed_act= NULL;
2164         int dist= 50;
2165         
2166         em_setup_viewcontext(C, &vc);
2167         vc.mval[0]= mval[0];
2168         vc.mval[1]= mval[1];
2169         em= vc.em;
2170         
2171         /* no afterqueue (yet), so we check it now, otherwise the em_xxxofs indices are bad */
2172         view3d_validate_backbuf(&vc);
2173         
2174         eed= findnearestedge(&vc, &dist);
2175         if(eed) {
2176                 Mesh *me= vc.obedit->data;
2177                 int path = 0;
2178                 
2179                 if (em->selected.last) {
2180                         EditSelection *ese = em->selected.last;
2181                         
2182                         if(ese && ese->type == EDITEDGE) {
2183                                 eed_act = (EditEdge*)ese->data;
2184                                 if (eed_act != eed) {
2185                                         if (edgetag_shortest_path(vc.scene, em, eed_act, eed)) { /* <- this is where the magic happens */
2186                                                 EM_remove_selection(em, eed_act, EDITEDGE);
2187                                                 path = 1;
2188                                         }
2189                                 }
2190                         }
2191                 }
2192                 if (path==0) {
2193                         int act = (edgetag_context_check(vc.scene, eed)==0);
2194                         edgetag_context_set(vc.scene, eed, act); /* switch the edge option */
2195                 }
2196
2197                 /* even if this is selected it may not be in the selection list */
2198                 if(edgetag_context_check(vc.scene, eed)==0) {
2199                         EM_remove_selection(em, eed, EDITEDGE);
2200                 }
2201                 else {
2202                         /* other modes need to keep the last edge tagged */
2203                         if(eed_act) {
2204                                 if(vc.scene->toolsettings->edge_mode!=EDGE_MODE_SELECT) {
2205                                         /* for non-select modes, always de-select the previous active edge */
2206                                         EM_select_edge(eed_act, 0);
2207                                 }
2208                         }
2209
2210                         /* set the new edge active */
2211                         EM_select_edge(eed, 1);
2212                         EM_store_selection(em, eed, EDITEDGE);
2213                 }
2214
2215                 EM_selectmode_flush(em);
2216         
2217                 /* force drawmode for mesh */
2218                 switch (vc.scene->toolsettings->edge_mode) {
2219                         
2220                         case EDGE_MODE_TAG_SEAM:
2221                                 me->drawflag |= ME_DRAWSEAMS;
2222                                 break;
2223                         case EDGE_MODE_TAG_SHARP:
2224                                 me->drawflag |= ME_DRAWSHARP;
2225                                 break;
2226                         case EDGE_MODE_TAG_CREASE:      
2227                                 me->drawflag |= ME_DRAWCREASES;
2228                                 break;
2229                         case EDGE_MODE_TAG_BEVEL:
2230                                 me->drawflag |= ME_DRAWBWEIGHTS;
2231                                 break;
2232                         case EDGE_MODE_TAG_FREESTYLE:
2233                                 me->drawflag |= ME_DRAW_FREESTYLE_EDGE;
2234                                 break;
2235                 }
2236
2237                 /* live unwrap while tagging */
2238                 if(     (vc.scene->toolsettings->edge_mode_live_unwrap) &&
2239                         (vc.scene->toolsettings->edge_mode == EDGE_MODE_TAG_SEAM) &&
2240                         (CustomData_has_layer(&em->fdata, CD_MTFACE))
2241                 ) {
2242                         ED_unwrap_lscm(vc.scene, vc.obedit, FALSE); /* unwrap all not just sel */
2243                 }
2244
2245                 DAG_id_tag_update(vc.obedit->data, 0);
2246                 WM_event_add_notifier(C, NC_GEOM|ND_SELECT, vc.obedit->data);
2247         }
2248 }
2249
2250
2251 static int mesh_shortest_path_select_invoke(bContext *C, wmOperator *UNUSED(op), wmEvent *event)
2252 {
2253         
2254         view3d_operator_needs_opengl(C);
2255
2256         mouse_mesh_shortest_path(C, event->mval);
2257         
2258         return OPERATOR_FINISHED;
2259 }
2260
2261 static int mesh_shortest_path_select_poll(bContext *C)
2262 {
2263         if(ED_operator_editmesh_region_view3d(C)) {
2264                 Object *obedit= CTX_data_edit_object(C);
2265                 EditMesh *em= BKE_mesh_get_editmesh(obedit->data);
2266                 return (em->selectmode & SCE_SELECT_EDGE);
2267         }
2268         return 0;
2269 }
2270         
2271 void MESH_OT_select_shortest_path(wmOperatorType *ot)
2272 {
2273         /* identifiers */
2274         ot->name= "Shortest Path Select";
2275         ot->description= "Select shortest path between two selections";
2276         ot->idname= "MESH_OT_select_shortest_path";
2277         
2278         /* api callbacks */
2279         ot->invoke= mesh_shortest_path_select_invoke;
2280         ot->poll= mesh_shortest_path_select_poll;
2281         
2282         /* flags */
2283         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
2284         
2285         /* properties */
2286         RNA_def_boolean(ot->srna, "extend", 0, "Extend Select", "");
2287 }
2288
2289
2290 /* ************************************************** */
2291
2292
2293 /* here actual select happens */
2294 /* gets called via generic mouse select operator */
2295 int mouse_mesh(bContext *C, const int mval[2], short extend)
2296 {
2297         ViewContext vc;
2298         EditVert *eve;
2299         EditEdge *eed;
2300         EditFace *efa;
2301         
2302         /* setup view context for argument to callbacks */
2303         em_setup_viewcontext(C, &vc);
2304         vc.mval[0]= mval[0];
2305         vc.mval[1]= mval[1];
2306         
2307         if(unified_findnearest(&vc, &eve, &eed, &efa)) {
2308                 
2309                 if(extend==0) EM_clear_flag_all(vc.em, SELECT);
2310                 
2311                 if(efa) {
2312                         /* set the last selected face */
2313                         EM_set_actFace(vc.em, efa);
2314                         
2315                         if( (efa->f & SELECT)==0 ) {
2316                                 EM_store_selection(vc.em, efa, EDITFACE);
2317                                 EM_select_face_fgon(vc.em, efa, 1);
2318                         }
2319                         else if(extend) {
2320                                 EM_remove_selection(vc.em, efa, EDITFACE);
2321                                 EM_select_face_fgon(vc.em, efa, 0);
2322                         }
2323                 }
2324                 else if(eed) {
2325                         if((eed->f & SELECT)==0) {
2326                                 EM_store_selection(vc.em, eed, EDITEDGE);
2327                                 EM_select_edge(eed, 1);
2328                         }
2329                         else if(extend) {
2330                                 EM_remove_selection(vc.em, eed, EDITEDGE);
2331                                 EM_select_edge(eed, 0);
2332                         }
2333                 }
2334                 else if(eve) {
2335                         if((eve->f & SELECT)==0) {
2336                                 eve->f |= SELECT;
2337                                 EM_store_selection(vc.em, eve, EDITVERT);
2338                         }
2339                         else if(extend){ 
2340                                 EM_remove_selection(vc.em, eve, EDITVERT);
2341                                 eve->f &= ~SELECT;
2342                         }
2343                 }
2344                 
2345                 EM_selectmode_flush(vc.em);
2346                   
2347 //              if (EM_texFaceCheck()) {
2348
2349                 if (efa && efa->mat_nr != vc.obedit->actcol-1) {
2350                         vc.obedit->actcol= efa->mat_nr+1;
2351                         vc.em->mat_nr= efa->mat_nr;
2352                         WM_event_add_notifier(C, NC_MATERIAL|ND_SHADING, NULL);
2353                 }
2354
2355                 WM_event_add_notifier(C, NC_GEOM|ND_SELECT, vc.obedit->data);
2356
2357                 return 1;
2358         }
2359         
2360         return 0;
2361 }
2362
2363 /* *********** select linked ************* */
2364
2365 /* for use with selectconnected_delimit_mesh only! */
2366 #define is_edge_delimit_ok(eed) ((eed->tmp.l == 1) && (eed->seam==0))
2367 #define is_face_tag(efa) is_edge_delimit_ok(efa->e1) || is_edge_delimit_ok(efa->e2) || is_edge_delimit_ok(efa->e3) || (efa->v4 && is_edge_delimit_ok(efa->e4))
2368
2369 #define face_tag(efa)\
2370 if(efa->v4)     efa->tmp.l=             efa->e1->tmp.l= efa->e2->tmp.l= efa->e3->tmp.l= efa->e4->tmp.l= 1;\
2371 else            efa->tmp.l=             efa->e1->tmp.l= efa->e2->tmp.l= efa->e3->tmp.l= 1;
2372
2373 /* all - 1) use all faces for extending the selection  2) only use the mouse face
2374 * sel - 1) select  0) deselect 
2375 * */
2376
2377 /* legacy warning, this function combines too much :) */
2378 static int select_linked_limited_invoke(ViewContext *vc, short all, short sel)
2379 {
2380         EditMesh *em= vc->em;
2381         EditFace *efa;
2382         EditEdge *eed;
2383         EditVert *eve;
2384         short done=1, change=0;
2385         
2386         if(em->faces.first==0) return OPERATOR_CANCELLED;
2387         
2388         /* flag all edges+faces as off*/
2389         for(eed= em->edges.first; eed; eed= eed->next)
2390                 eed->tmp.l=0;
2391         
2392         for(efa= em->faces.first; efa; efa= efa->next) {
2393                 efa->tmp.l = 0;
2394         }
2395         
2396         if (all) {
2397                 // XXX verts?
2398                 for(eed= em->edges.first; eed; eed= eed->next) {
2399                         if(eed->f & SELECT)
2400                                 eed->tmp.l= 1;
2401                 }
2402                 for(efa= em->faces.first; efa; efa= efa->next) {
2403                         
2404                         if (efa->f & SELECT) {
2405                                 face_tag(efa);
2406                         } else {
2407                                 efa->tmp.l = 0;
2408                         }
2409                 }
2410         } 
2411         else {
2412                 if( unified_findnearest(vc, &eve, &eed, &efa) ) {
2413                         
2414                         if(efa) {
2415                                 efa->tmp.l = 1;
2416                                 face_tag(efa);
2417                         }
2418                         else if(eed)
2419                                 eed->tmp.l= 1;
2420                         else {
2421                                 for(eed= em->edges.first; eed; eed= eed->next)
2422                                         if(eed->v1==eve || eed->v2==eve)
2423                                                 break;
2424                                 eed->tmp.l= 1;
2425                         }
2426                 }
2427                 else
2428                         return OPERATOR_FINISHED;
2429         }
2430         
2431         while(done==1) {
2432                 done= 0;
2433                 /* simple algo - select all faces that have a selected edge
2434                 * this intern selects the edge, repeat until nothing is left to do */
2435                 for(efa= em->faces.first; efa; efa= efa->next) {
2436                         if ((efa->tmp.l == 0) && (!efa->h)) {
2437                                 if (is_face_tag(efa)) {
2438                                         face_tag(efa);
2439                                         done= 1;
2440                                 }
2441                         }
2442                 }
2443         }
2444         
2445         for(efa= em->faces.first; efa; efa= efa->next) {
2446                 if (efa->tmp.l) {
2447                         if (sel) {
2448                                 if (!(efa->f & SELECT)) {
2449                                         EM_select_face(efa, 1);
2450                                         change = 1;
2451                                 }
2452                         } else {
2453                                 if (efa->f & SELECT) {
2454                                         EM_select_face(efa, 0);
2455                                         change = 1;
2456                                 }
2457                         }
2458                 }
2459         }
2460         
2461         if (!change)
2462                 return OPERATOR_CANCELLED;
2463         
2464         if (!sel) /* make sure de-selecting faces didnt de-select the verts/edges connected to selected faces, this is common with boundaries */
2465                 for(efa= em->faces.first; efa; efa= efa->next)
2466                         if (efa->f & SELECT)
2467                                 EM_select_face(efa, 1);
2468         
2469         //      if (EM_texFaceCheck())
2470         
2471         return OPERATOR_FINISHED;
2472 }
2473
2474 #undef is_edge_delimit_ok
2475 #undef is_face_tag
2476 #undef face_tag
2477
2478 static void linked_limit_default(bContext *C, wmOperator *op)
2479 {
2480         if(!RNA_struct_property_is_set(op->ptr, "limit")) {
2481                 Object *obedit= CTX_data_edit_object(C);
2482                 EditMesh *em= BKE_mesh_get_editmesh(obedit->data);
2483                 if(em->selectmode == SCE_SELECT_FACE)
2484                         RNA_boolean_set(op->ptr, "limit", TRUE);
2485                 else
2486                         RNA_boolean_set(op->ptr, "limit", FALSE);
2487         }
2488 }
2489
2490 static int select_linked_pick_invoke(bContext *C, wmOperator *op, wmEvent *event)
2491 {
2492         Object *obedit= CTX_data_edit_object(C);
2493         ViewContext vc;
2494         EditVert *eve, *v1, *v2;
2495         EditEdge *eed;
2496         EditFace *efa;
2497         short done=1, toggle=0;
2498         int sel= !RNA_boolean_get(op->ptr, "deselect");
2499         int limit;
2500         
2501         linked_limit_default(C, op);
2502
2503         limit = RNA_boolean_get(op->ptr, "limit");
2504
2505         /* unified_finednearest needs ogl */
2506         view3d_operator_needs_opengl(C);
2507         
2508         /* setup view context for argument to callbacks */
2509         em_setup_viewcontext(C, &vc);
2510         
2511         if(vc.em->edges.first==0) return OPERATOR_CANCELLED;
2512         
2513         vc.mval[0]= event->mval[0];
2514         vc.mval[1]= event->mval[1];
2515         
2516         /* return warning! */
2517         if(limit) {
2518                 int retval= select_linked_limited_invoke(&vc, 0, sel);
2519                 WM_event_add_notifier(C, NC_GEOM|ND_SELECT, obedit->data);
2520                 return retval;
2521         }
2522         
2523         if( unified_findnearest(&vc, &eve, &eed, &efa)==0 ) {
2524                 WM_event_add_notifier(C, NC_GEOM|ND_SELECT, obedit->data);
2525         
2526                 return OPERATOR_CANCELLED;
2527         }
2528
2529         /* clear test flags */
2530         for(v1= vc.em->verts.first; v1; v1= v1->next) v1->f1= 0;
2531         
2532         /* start vertex/face/edge */
2533         if(eve) eve->f1= 1;
2534         else if(eed) eed->v1->f1= eed->v2->f1= 1;
2535         else efa->v1->f1= efa->v2->f1= efa->v3->f1= 1;
2536         
2537         /* set flag f1 if affected */
2538         while(done==1) {
2539                 done= 0;
2540                 toggle++;
2541                 
2542                 if(toggle & 1) eed= vc.em->edges.first;
2543                 else eed= vc.em->edges.last;
2544                 
2545                 while(eed) {
2546                         v1= eed->v1;
2547                         v2= eed->v2;
2548                         
2549                         if(eed->h==0) {
2550                                 if(v1->f1 && v2->f1==0) {
2551                                         v2->f1= 1;
2552                                         done= 1;
2553                                 }
2554                                 else if(v1->f1==0 && v2->f1) {
2555                                         v1->f1= 1;
2556                                         done= 1;
2557                                 }
2558                         }
2559                         
2560                         if(toggle & 1) eed= eed->next;
2561                         else eed= eed->prev;
2562                 }
2563         }
2564         
2565         /* now use vertex f1 flag to select/deselect */
2566         for(eed= vc.em->edges.first; eed; eed= eed->next) {
2567                 if(eed->v1->f1 && eed->v2->f1) 
2568                         EM_select_edge(eed, sel);
2569         }
2570         for(efa= vc.em->faces.first; efa; efa= efa->next) {
2571                 if(efa->v1->f1 && efa->v2->f1 && efa->v3->f1 && (efa->v4==NULL || efa->v4->f1)) 
2572                         EM_select_face(efa, sel);
2573         }
2574         /* no flush needed, connected geometry is done */
2575         
2576 //      if (EM_texFaceCheck())
2577         
2578         WM_event_add_notifier(C, NC_GEOM|ND_SELECT, obedit->data);
2579         return OPERATOR_FINISHED;       
2580 }
2581
2582 void MESH_OT_select_linked_pick(wmOperatorType *ot)
2583 {
2584         /* identifiers */
2585         ot->name= "Select Linked";
2586         ot->description= "(un)select all vertices linked to the active mesh";
2587         ot->idname= "MESH_OT_select_linked_pick";
2588         
2589         /* api callbacks */
2590         ot->invoke= select_linked_pick_invoke;
2591         ot->poll= ED_operator_editmesh_region_view3d;
2592         
2593         /* flags */
2594         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
2595         
2596         RNA_def_boolean(ot->srna, "deselect", 0, "Deselect", "");
2597         RNA_def_boolean(ot->srna, "limit", 0, "Limit by Seams", "Limit selection by seam boundaries (faces only)");
2598 }
2599
2600
2601 /* ************************* */
2602
2603 void selectconnected_mesh_all(EditMesh *em)
2604 {
2605         EditVert *v1,*v2;
2606         EditEdge *eed;
2607         short done=1, toggle=0;
2608         
2609         if(em->edges.first==0) return;
2610         
2611         while(done==1) {
2612                 done= 0;
2613                 
2614                 toggle++;
2615                 if(toggle & 1) eed= em->edges.first;
2616                 else eed= em->edges.last;
2617                 
2618                 while(eed) {
2619                         v1= eed->v1;
2620                         v2= eed->v2;
2621                         if(eed->h==0) {
2622                                 if(v1->f & SELECT) {
2623                                         if( (v2->f & SELECT)==0 ) {
2624                                                 v2->f |= SELECT;
2625                                                 done= 1;
2626                                         }
2627                                 }
2628                                 else if(v2->f & SELECT) {
2629                                         if( (v1->f & SELECT)==0 ) {
2630                                                 v1->f |= SELECT;
2631                                                 done= 1;
2632                                         }
2633                                 }
2634                         }
2635                         if(toggle & 1) eed= eed->next;
2636                         else eed= eed->prev;
2637                 }
2638         }
2639         
2640         /* now use vertex select flag to select rest */
2641         EM_select_flush(em);
2642         
2643         //      if (EM_texFaceCheck())
2644 }
2645
2646 static int select_linked_exec(bContext *C, wmOperator *op)
2647 {
2648         Object *obedit= CTX_data_edit_object(C);
2649         EditMesh *em= BKE_mesh_get_editmesh(obedit->data);
2650         
2651         if( RNA_boolean_get(op->ptr, "limit") ) {
2652                 ViewContext vc;
2653                 em_setup_viewcontext(C, &vc);
2654                 select_linked_limited_invoke(&vc, 1, 1);
2655         }
2656         else
2657                 selectconnected_mesh_all(em);
2658         
2659         WM_event_add_notifier(C, NC_GEOM|ND_SELECT, obedit->data);
2660
2661         BKE_mesh_end_editmesh(obedit->data, em);
2662         return OPERATOR_FINISHED;       
2663 }
2664
2665 static int select_linked_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(event))
2666 {
2667         linked_limit_default(C, op);
2668         return select_linked_exec(C, op);
2669 }
2670
2671 void MESH_OT_select_linked(wmOperatorType *ot)
2672 {
2673         /* identifiers */
2674         ot->name= "Select Linked All";
2675         ot->description= "Select all vertices linked to the active mesh";
2676         ot->idname= "MESH_OT_select_linked";
2677         
2678         /* api callbacks */
2679         ot->exec= select_linked_exec;
2680         ot->invoke= select_linked_invoke;
2681         ot->poll= ED_operator_editmesh;
2682         
2683         /* flags */
2684         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
2685         
2686         RNA_def_boolean(ot->srna, "limit", 0, "Limit by Seams", "Limit selection by seam boundaries (faces only)");
2687 }
2688
2689
2690 /* ************************* */
2691
2692 /* swap is 0 or 1, if 1 it hides not selected */
2693 void EM_hide_mesh(EditMesh *em, int swap)
2694 {
2695         EditVert *eve;
2696         EditEdge *eed;
2697         EditFace *efa;
2698         int a;
2699         
2700         if(em==NULL) return;
2701
2702         /* hide happens on least dominant select mode, and flushes up, not down! (helps preventing errors in subsurf) */
2703         /*  - vertex hidden, always means edge is hidden too
2704                 - edge hidden, always means face is hidden too
2705                 - face hidden, only set face hide
2706                 - then only flush back down what's absolute hidden
2707         */
2708         if(em->selectmode & SCE_SELECT_VERTEX) {
2709                 for(eve= em->verts.first; eve; eve= eve->next) {
2710                         if((eve->f & SELECT)!=swap) {
2711                                 eve->f &= ~SELECT;
2712                                 eve->h= 1;
2713                         }
2714                 }
2715         
2716                 for(eed= em->edges.first; eed; eed= eed->next) {
2717                         if(eed->v1->h || eed->v2->h) {
2718                                 eed->h |= 1;
2719                                 eed->f &= ~SELECT;
2720                         }
2721                 }
2722         
2723                 for(efa= em->faces.first; efa; efa= efa->next) {
2724                         if(efa->e1->h & 1 || efa->e2->h & 1 || efa->e3->h & 1 || (efa->e4 && efa->e4->h & 1)) {
2725                                 efa->h= 1;
2726                                 efa->f &= ~SELECT;
2727                         }
2728                 }
2729         }
2730         else if(em->selectmode & SCE_SELECT_EDGE) {
2731
2732                 for(eed= em->edges.first; eed; eed= eed->next) {
2733                         if((eed->f & SELECT)!=swap) {
2734                                 eed->h |= 1;
2735                                 EM_select_edge(eed, 0);
2736                         }
2737                 }
2738
2739                 for(efa= em->faces.first; efa; efa= efa->next) {
2740                         if(efa->e1->h & 1 || efa->e2->h & 1 || efa->e3->h & 1 || (efa->e4 && efa->e4->h & 1)) {
2741                                 efa->h= 1;
2742                                 efa->f &= ~SELECT;
2743                         }
2744                 }
2745         }
2746         else {
2747
2748                 for(efa= em->faces.first; efa; efa= efa->next) {
2749                         if((efa->f & SELECT)!=swap) {
2750                                 efa->h= 1;
2751                                 EM_select_face(efa, 0);
2752                         }
2753                 }
2754         }
2755         
2756         /* flush down, only whats 100% hidden */
2757         for(eve= em->verts.first; eve; eve= eve->next) eve->f1= 0;
2758         for(eed= em->edges.first; eed; eed= eed->next) eed->f1= 0;
2759         
2760         if(em->selectmode & SCE_SELECT_FACE) {
2761                 for(efa= em->faces.first; efa; efa= efa->next) {
2762                         if(efa->h) a= 1; else a= 2;
2763                         efa->e1->f1 |= a;
2764                         efa->e2->f1 |= a;
2765                         efa->e3->f1 |= a;
2766                         if(efa->e4) efa->e4->f1 |= a;
2767                         /* When edges are not delt with in their own loop, we need to explicitly re-selct select edges that are joined to unselected faces */
2768                         if (swap && (em->selectmode == SCE_SELECT_FACE) && (efa->f & SELECT)) {
2769                                 EM_select_face(efa, 1);
2770                         }
2771                 }
2772         }
2773         
2774         if(em->selectmode >= SCE_SELECT_EDGE) {
2775                 for(eed= em->edges.first; eed; eed= eed->next) {
2776                         if(eed->f1==1) eed->h |= 1;
2777                         if(eed->h & 1) a= 1; else a= 2;
2778                         eed->v1->f1 |= a;
2779                         eed->v2->f1 |= a;
2780                 }
2781         }
2782
2783         if(em->selectmode >= SCE_SELECT_VERTEX) {
2784                 for(eve= em->verts.first; eve; eve= eve->next) {
2785                         if(eve->f1==1) eve->h= 1;
2786                 }
2787         }
2788         
2789         em->totedgesel= em->totfacesel= em->totvertsel= 0;
2790 //      if(EM_texFaceCheck())
2791
2792         //      DAG_id_tag_update(obedit->data, 0);
2793 }
2794
2795 static int hide_mesh_exec(bContext *C, wmOperator *op)
2796 {
2797         Object *obedit= CTX_data_edit_object(C);
2798         EditMesh *em= BKE_mesh_get_editmesh(((Mesh *)obedit->data));
2799         
2800         EM_hide_mesh(em, RNA_boolean_get(op->ptr, "unselected"));
2801                 
2802         WM_event_add_notifier(C, NC_GEOM|ND_SELECT, obedit->data);
2803
2804         BKE_mesh_end_editmesh(obedit->data, em);
2805         return OPERATOR_FINISHED;       
2806 }
2807
2808 void MESH_OT_hide(wmOperatorType *ot)
2809 {
2810         /* identifiers */
2811         ot->name= "Hide Selection";
2812         ot->description= "Hide (un)selected vertices, edges or faces";
2813         ot->idname= "MESH_OT_hide";
2814         
2815         /* api callbacks */
2816         ot->exec= hide_mesh_exec;
2817         ot->poll= ED_operator_editmesh;
2818         
2819         /* flags */
2820         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
2821         
2822         /* props */
2823         RNA_def_boolean(ot->srna, "unselected", 0, "Unselected", "Hide unselected rather than selected");
2824 }
2825
2826 void EM_reveal_mesh(EditMesh *em)
2827 {
2828         EditVert *eve;
2829         EditEdge *eed;
2830         EditFace *efa;
2831         
2832         if(em==NULL) return;
2833
2834         for(eve= em->verts.first; eve; eve= eve->next) {
2835                 if(eve->h) {
2836                         eve->h= 0;
2837                         eve->f |= SELECT;
2838                 }
2839         }
2840         for(eed= em->edges.first; eed; eed= eed->next) {
2841                 if(eed->h & 1) {
2842                         eed->h &= ~1;
2843                         if(em->selectmode & SCE_SELECT_VERTEX); 
2844                         else EM_select_edge(eed, 1);
2845                 }
2846         }
2847         for(efa= em->faces.first; efa; efa= efa->next) {
2848                 if(efa->h) {
2849                         efa->h= 0;
2850                         if(em->selectmode & (SCE_SELECT_EDGE|SCE_SELECT_VERTEX)); 
2851                         else EM_select_face(efa, 1);
2852                 }
2853         }
2854
2855         EM_fgon_flags(em);      /* redo flags and indices for fgons */
2856         EM_selectmode_flush(em);
2857
2858 //      if (EM_texFaceCheck())
2859 //      DAG_id_tag_update(obedit->data, 0);
2860 }
2861
2862 static int reveal_mesh_exec(bContext *C, wmOperator *UNUSED(op))
2863 {
2864         Object *obedit= CTX_data_edit_object(C);
2865         EditMesh *em= BKE_mesh_get_editmesh(((Mesh *)obedit->data));
2866         
2867         EM_reveal_mesh(em);
2868
2869         WM_event_add_notifier(C, NC_GEOM|ND_SELECT, obedit->data);
2870
2871         BKE_mesh_end_editmesh(obedit->data, em);
2872         return OPERATOR_FINISHED;       
2873 }
2874
2875 void MESH_OT_reveal(wmOperatorType *ot)
2876 {
2877         /* identifiers */
2878         ot->name= "Reveal Hidden";
2879         ot->description= "Reveal all hidden vertices, edges and faces";
2880         ot->idname= "MESH_OT_reveal";
2881         
2882         /* api callbacks */
2883         ot->exec= reveal_mesh_exec;
2884         ot->poll= ED_operator_editmesh;
2885         
2886         /* flags */
2887         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
2888 }
2889
2890 static int select_by_number_vertices_exec(bContext *C, wmOperator *op)
2891 {
2892         Object *obedit= CTX_data_edit_object(C);
2893         EditMesh *em= BKE_mesh_get_editmesh(((Mesh *)obedit->data));
2894         EditFace *efa;
2895         int numverts= RNA_enum_get(op->ptr, "type");
2896
2897         /* Selects trias/qiads or isolated verts, and edges that do not have 2 neighboring
2898          * faces
2899          */
2900
2901         /* for loose vertices/edges, we first select all, loop below will deselect */
2902         if(numverts==5) {
2903                 EM_set_flag_all(em, SELECT);
2904         }
2905         else if(em->selectmode!=SCE_SELECT_FACE) {
2906                 BKE_report(op->reports, RPT_WARNING, "Only works in face selection mode");
2907                 return OPERATOR_CANCELLED;
2908         }
2909         
2910         for(efa= em->faces.first; efa; efa= efa->next) {
2911   &n