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