svn merge ^/trunk/blender -r40367:40368 --- raddish weight paint merge
authorCampbell Barton <ideasman42@gmail.com>
Thu, 22 Sep 2011 16:09:27 +0000 (16:09 +0000)
committerCampbell Barton <ideasman42@gmail.com>
Thu, 22 Sep 2011 16:09:27 +0000 (16:09 +0000)
25 files changed:
1  2 
release/scripts/startup/bl_ui/space_view3d.py
source/blender/blenkernel/BKE_paint.h
source/blender/blenkernel/intern/DerivedMesh.c
source/blender/editors/armature/editarmature.c
source/blender/editors/armature/meshlaplacian.c
source/blender/editors/include/ED_mesh.h
source/blender/editors/include/ED_view3d.h
source/blender/editors/mesh/bmesh_select.c
source/blender/editors/mesh/editface.c
source/blender/editors/object/object_intern.h
source/blender/editors/object/object_ops.c
source/blender/editors/object/object_vgroup.c
source/blender/editors/sculpt_paint/paint_image.c
source/blender/editors/sculpt_paint/paint_utils.c
source/blender/editors/sculpt_paint/paint_vertex.c
source/blender/editors/space_view3d/drawmesh.c
source/blender/editors/space_view3d/drawobject.c
source/blender/editors/space_view3d/space_view3d.c
source/blender/editors/space_view3d/view3d_header.c
source/blender/editors/space_view3d/view3d_select.c
source/blender/makesdna/DNA_mesh_types.h
source/blender/makesdna/DNA_object_types.h
source/blender/makesrna/intern/rna_mesh.c
source/blender/makesrna/intern/rna_object.c
source/blender/makesrna/intern/rna_scene.c

Simple merge
index d579bc0d3c73e5b3e1798e0cc88e166cd54efd93,1660ac29217bc19c9be5284b7b8b0d77e0e6da8f..dea40b70a4927cc5763925f465f9aaf702ad1896
  #include "BKE_paint.h"
  #include "BKE_texture.h"
  #include "BKE_multires.h"
+ #include "BKE_armature.h"
 +#include "BKE_particle.h"
 +#include "BKE_tessmesh.h"
 +#include "BKE_bvhutils.h"
  
  #include "BLO_sys_types.h" // for intptr_t support
  
@@@ -890,134 -1751,33 +936,139 @@@ void vDM_ColorBand_store(ColorBand *cob
        stored_cb= coba;
  }
  
- static void add_weight_mcol_dm(Object *ob, DerivedMesh *dm)
+ static void add_weight_mcol_dm(Object *ob, DerivedMesh *dm, int const draw_flag)
  {
 -      Mesh *me = ob->data;
 -      MFace *mf = me->mface;
 +      // Mesh *me = ob->data; // UNUSED
 +      MFace *mf = dm->getTessFaceArray(dm);
 +      MLoop *mloop = dm->getLoopArray(dm), *ml;
 +      MPoly *mp = dm->getPolyArray(dm);
        ColorBand *coba= stored_cb;     /* warning, not a local var */
        unsigned char *wtcol;
 -      int i;
 -      
 +      unsigned char(*wlcol)[4] = NULL;
 +      BLI_array_declare(wlcol);
 +      int i, j, totface=dm->getNumTessFaces(dm), totloop;
 +      int *origIndex = dm->getVertDataArray(dm, CD_ORIGINDEX);
-       
++
+       int defbase_len = BLI_countlist(&ob->defbase);
+       char *defbase_sel = MEM_mallocN(defbase_len * sizeof(char), __func__);
+       int selected = get_selected_defgroups(ob, defbase_sel, defbase_len);
+       int unselected = defbase_len - selected;
 -      wtcol = MEM_callocN (sizeof (unsigned char) * me->totface*4*4, "weightmap");
 +      wtcol = MEM_callocN (sizeof (unsigned char) * totface*4*4, "weightmap");
        
 -      memset(wtcol, 0x55, sizeof (unsigned char) * me->totface*4*4);
 -      for (i=0; i<me->totface; i++, mf++) {
 +      /*first add colors to the tesselation faces*/
 +      memset(wtcol, 0x55, sizeof (unsigned char) * totface*4*4);
 +      for (i=0; i<totface; i++, mf++) {
 +              /*origindex being NULL means we're operating on original mesh data*/
-               calc_weightpaint_vert_color(ob, coba, origIndex ? origIndex[mf->v1] : mf->v1, &wtcol[(i*4 + 0)*4]); 
-               calc_weightpaint_vert_color(ob, coba, origIndex ? origIndex[mf->v2] : mf->v2, &wtcol[(i*4 + 1)*4]); 
-               calc_weightpaint_vert_color(ob, coba, origIndex ? origIndex[mf->v3] : mf->v3, &wtcol[(i*4 + 2)*4]); 
+               calc_weightpaint_vert_color(ob, coba, mf->v1, &wtcol[(i*4 + 0)*4], defbase_sel, selected, unselected, draw_flag);
+               calc_weightpaint_vert_color(ob, coba, mf->v2, &wtcol[(i*4 + 1)*4], defbase_sel, selected, unselected, draw_flag);
+               calc_weightpaint_vert_color(ob, coba, mf->v3, &wtcol[(i*4 + 2)*4], defbase_sel, selected, unselected, draw_flag);
                if (mf->v4)
-                       calc_weightpaint_vert_color(ob, coba, origIndex ? origIndex[mf->v4] : mf->v4, &wtcol[(i*4 + 3)*4]); 
+                       calc_weightpaint_vert_color(ob, coba, mf->v4, &wtcol[(i*4 + 3)*4], defbase_sel, selected, unselected, draw_flag);
        }
        
 -      MEM_freeN(defbase_sel);
 +      CustomData_add_layer(&dm->faceData, CD_WEIGHT_MCOL, CD_ASSIGN, wtcol, totface);
 +
 +      /*now add to loops, so the data can be passed through the modifier stack*/
 +      totloop = 0;
 +      for (i=0; i<dm->numPolyData; i++, mp++) {
 +              ml = mloop + mp->loopstart;
 +
 +              for (j=0; j<mp->totloop; j++, ml++, totloop++) {
 +                      BLI_array_growone(wlcol);
 +
 +                      calc_weightpaint_vert_color(ob, coba, origIndex ? origIndex[ml->v] : ml->v,
-                                                                               (unsigned char *)&wlcol[totloop]);
++                                                                              (unsigned char *)&wlcol[totloop], defbase_sel, selected, unselected, draw_flag);
 +              }
 +      }
 +
 +      CustomData_add_layer(&dm->loopData, CD_WEIGHT_MLOOPCOL, CD_ASSIGN, wlcol, totloop);
 +}
 +
 +
 +static void shapekey_layers_to_keyblocks(DerivedMesh *dm, Mesh *me, int actshape_uid)
 +{
 +      KeyBlock *kb;
 +      int i, j, tot;
 +      
 +      if (!me->key)
 +              return; 
 +      
 +      tot = CustomData_number_of_layers(&dm->vertData, CD_SHAPEKEY);
 +      for (i=0; i<tot; i++) {
 +              CustomDataLayer *layer = &dm->vertData.layers[CustomData_get_layer_index_n(&dm->vertData, CD_SHAPEKEY, i)];
 +              float (*cos)[3], (*kbcos)[3];
 +              
 +              for (kb=me->key->block.first; kb; kb=kb->next) {
 +                      if (kb->uid == layer->uid)
 +                              break;
 +              }
 +              
 +              if (!kb) {
 +                      kb = add_keyblock(me->key, layer->name);
 +                      kb->uid = layer->uid;
 +              }
 +              
 +              if (kb->data)
 +                      MEM_freeN(kb->data);
 +              
 +              cos = CustomData_get_layer_n(&dm->vertData, CD_SHAPEKEY, i);
 +              kb->totelem = dm->numVertData;
 +
 +              kb->data = kbcos = MEM_mallocN(sizeof(float)*3*kb->totelem, "kbcos DerivedMesh.c");
 +              if (kb->uid == actshape_uid) {
 +                      MVert *mvert = dm->getVertArray(dm);
 +                      
 +                      for (j=0; j<dm->numVertData; j++, kbcos++, mvert++) {
 +                              copy_v3_v3(*kbcos, mvert->co);
 +                      }
 +              } else {
 +                      for (j=0; j<kb->totelem; j++, cos++, kbcos++) {
 +                              copy_v3_v3(*kbcos, *cos);
 +                      }
 +              }
 +      }
 +      
 +      for (kb=me->key->block.first; kb; kb=kb->next) {
 +              if (kb->totelem != dm->numVertData) {
 +                      if (kb->data)
 +                              MEM_freeN(kb->data);
 +                      
 +                      kb->totelem = dm->numVertData;
 +                      kb->data = MEM_callocN(sizeof(float)*3*kb->totelem, "kb->data derivedmesh.c");
 +                      printf("eek! lost a shapekey layer!\n");
 +              }
 +      }
 +}
  
 -      CustomData_add_layer(&dm->faceData, CD_WEIGHT_MCOL, CD_ASSIGN, wtcol, dm->numFaceData);
 +static void add_shapekey_layers(DerivedMesh *dm, Mesh *me, Object *UNUSED(ob))
 +{
 +      KeyBlock *kb;
 +      Key *key = me->key;
 +      int a, b;
 +      
 +      if (!me->key)
 +              return;
 +      
 +      if (dm->numVertData != me->totvert) {
 +              printf("error in add_shapekey_layers: dm isn't the same size as me\n");
 +              return;
 +      }
 +              
 +      for (a=0, kb=key->block.first; kb; kb=kb->next, a++) {
 +              float (*cos)[3] = CustomData_add_layer_named(&dm->vertData, CD_SHAPEKEY, CD_CALLOC, NULL, dm->numVertData, kb->name);
 +              int ci = CustomData_get_layer_index_n(&dm->vertData, CD_SHAPEKEY, a);
 +              
 +              dm->vertData.layers[ci].uid = kb->uid;
 +              if (kb->totelem != dm->numVertData) {
 +                      printf("error in add_shapekey_layers: totelem and totvert don't match");
 +                      continue;
 +              }
 +              
 +              for (b=0; b<kb->totelem; b++, cos++) {
 +                      copy_v3_v3((float *)cos, ((float*)kb->data)+b*3);
 +              }
 +      }
  }
  
  /* new value for useDeform -1  (hack for the gameengine):
@@@ -1244,17 -2001,10 +1298,14 @@@ static void mesh_calc_modifiers(Scene *
                                        DM_add_edge_layer(dm, CD_ORIGINDEX, CD_CALLOC, NULL);
                                        DM_add_face_layer(dm, CD_ORIGINDEX, CD_CALLOC, NULL);
  
-                                       orig = DM_get_vert_data_layer(dm, CD_ORIGINDEX);
-                                       for(i=0; i<dm->numVertData; i++) *orig++= i;
-                                       orig = DM_get_edge_data_layer(dm, CD_ORIGINDEX);
-                                       for(i=0; i<dm->numEdgeData; i++) *orig++= i;
-                                       orig = DM_get_face_data_layer(dm, CD_ORIGINDEX);
-                                       for(i=0; i<dm->numPolyData; i++) *orig++= i;
+                                       range_vni(DM_get_vert_data_layer(dm, CD_ORIGINDEX), dm->numVertData, 0);
+                                       range_vni(DM_get_edge_data_layer(dm, CD_ORIGINDEX), dm->numEdgeData, 0);
 -                                      range_vni(DM_get_face_data_layer(dm, CD_ORIGINDEX), dm->numFaceData, 0);
++                                      range_vni(DM_get_face_data_layer(dm, CD_ORIGINDEX), dm->numPolyData, 0);
                                }
-                                       add_weight_mcol_dm(ob, dm);
 +
 +                              if((dataMask & CD_MASK_WEIGHT_MCOL) && (ob->mode & OB_MODE_WEIGHT_PAINT))
++                                      add_weight_mcol_dm(ob, dm, draw_flag);
 +
                        }
  
                        
        } else if(dm) {
                finaldm = dm;
        } else {
 -              finaldm = CDDM_from_mesh(me, ob);
 +              int recalc_normals= 0;
  
 +              finaldm = CDDM_from_mesh(me, ob);
 +              
 +              if(build_shapekey_layers) {
 +                      add_shapekey_layers(finaldm, me, ob);
 +                      recalc_normals= 1;
 +              }
 +              
                if(deformedVerts) {
                        CDDM_apply_vert_coords(finaldm, deformedVerts);
 -                      CDDM_calc_normals(finaldm);
 +                      recalc_normals= 1;
                }
  
 +              if(recalc_normals)
 +                      CDDM_calc_normals(finaldm);
 +              
                if((dataMask & CD_MASK_WEIGHT_MCOL) && (ob->mode & OB_MODE_WEIGHT_PAINT))
-                       add_weight_mcol_dm(ob, finaldm);
-               
+                       add_weight_mcol_dm(ob, finaldm, draw_flag);
        }
  
        /* add an orco layer if needed */
index e3725d00fd68c8bd8042d8a6bafdb62f1dc6fc4f,9709979ff6a912dd911021c74077f0be37897047..cc4ed12c41e0104b2404f6187dfbdcf4b1f10d20
@@@ -241,6 -198,6 +241,9 @@@ int paintface_minmax(struct Object *ob
  void paintface_hide(struct Object *ob, const int unselected);
  void paintface_reveal(struct Object *ob);
  
++void paintvert_deselect_all_visible(struct Object *ob, int action, short flush_flags);
++void          paintvert_flush_flags(struct Object *ob);
++
  /* object_vgroup.c */
  
  #define WEIGHT_REPLACE 1
index 2b060a70009923a5d82eadd95564b031f3f28372,0000000000000000000000000000000000000000..db9717958e88dbb7793cd8fd844b40217bbe7db0
mode 100644,000000..100644
--- /dev/null
@@@ -1,2768 -1,0 +1,2770 @@@
 +/**
 + * $Id: 
 + *
 + * ***** BEGIN GPL LICENSE BLOCK *****
 + *
 + * This program is free software; you can redistribute it and/or
 + * modify it under the terms of the GNU General Public License
 + * as published by the Free Software Foundation; either version 2
 + * of the License, or (at your option) any later version.
 + *
 + * This program is distributed in the hope that it will be useful,
 + * but WITHOUT ANY WARRANTY; without even the implied warranty of
 + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 + * GNU General Public License for more details.
 + *
 + * You should have received a copy of the GNU General Public License
 + * along with this program; if not, write to the Free Software Foundation,
 + * Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 + *
 + * The Original Code is Copyright (C) 2004 Blender Foundation.
 + * All rights reserved.
 + *
 + * The Original Code is: all of this file.
 + *
 + * Contributor(s): none yet.
 + *
 + * ***** END GPL LICENSE BLOCK *****
 + */
 +
 +/*
 +
 +BMEditMesh_mods.c, UI level access, no geometry changes 
 +
 +*/
 +
 +#include <stdlib.h>
 +#include <string.h>
 +#include <math.h>
 +
 +#include "MEM_guardedalloc.h"
 +
 +#include "DNA_mesh_types.h"
 +#include "DNA_material_types.h"
 +#include "DNA_meshdata_types.h"
 +#include "DNA_modifier_types.h"
 +#include "DNA_object_types.h"
 +#include "DNA_texture_types.h"
 +#include "DNA_scene_types.h"
 +#include "DNA_screen_types.h"
 +#include "DNA_space_types.h"
 +#include "DNA_view3d_types.h"
 +
 +#include "BLI_utildefines.h"
 +#include "BLI_blenlib.h"
 +#include "BLI_math.h"
 +#include "BLI_rand.h"
 +#include "BLI_array.h"
 +#include "BLI_smallhash.h"
 +#include "BLI_heap.h"
 +
 +#include "BKE_context.h"
 +#include "BKE_displist.h"
 +#include "BKE_depsgraph.h"
 +#include "BKE_DerivedMesh.h"
 +#include "BKE_customdata.h"
 +#include "BKE_global.h"
 +#include "BKE_mesh.h"
 +#include "BKE_material.h"
 +#include "BKE_texture.h"
 +#include "BKE_report.h"
 +#include "BKE_tessmesh.h"
 +#include "BKE_paint.h"
 +
 +#include "IMB_imbuf_types.h"
 +#include "IMB_imbuf.h"
 +
 +#include "RE_render_ext.h"  /* externtex */
 +
 +#include "WM_api.h"
 +#include "WM_types.h"
 +
 +#include "RNA_access.h"
 +#include "RNA_define.h"
 +
 +#include "ED_mesh.h"
 +#include "ED_screen.h"
 +#include "ED_view3d.h"
 +#include "bmesh.h"
 +
 +#include "BIF_gl.h"
 +#include "BIF_glutil.h"
 +
 +#include "UI_resources.h"
 +
 +#include "mesh_intern.h"
 +
 +#include "BLO_sys_types.h" // for intptr_t support
 +
 +/* ****************************** MIRROR **************** */
 +
 +static void EDBM_select_mirrored(Object *obedit, BMEditMesh *em)
 +{
 +      if(em->selectmode & SCE_SELECT_VERTEX) {
 +              BMVert *eve, *v1;
 +              BMIter iter;
 +              int i;
 +
 +              i= 0;
 +              BM_ITER(eve, &iter, em->bm, BM_VERTS_OF_MESH, NULL) {
 +                      if (BM_TestHFlag(eve, BM_SELECT) && !BM_TestHFlag(eve, BM_HIDDEN)) {
 +                              v1= editbmesh_get_x_mirror_vert(obedit, em, eve, eve->co, i);
 +                              if(v1) {
 +                                      BM_Select(em->bm, eve, 0);
 +                                      BM_Select(em->bm, v1, 1);
 +                              }
 +                      }
 +                      i++;
 +              }
 +      }
 +}
 +
 +void EDBM_automerge(Scene *scene, Object *obedit, int update)
 +{
 +      BMEditMesh *em;
 +      
 +      if ((scene->toolsettings->automerge) &&
 +          (obedit && obedit->type==OB_MESH))
 +      {
 +              em = ((Mesh*)obedit->data)->edit_btmesh;
 +              if (!em)
 +                      return;
 +
 +              BMO_CallOpf(em->bm, "automerge verts=%av dist=%f", scene->toolsettings->doublimit);
 +              if (update) {
 +                      DAG_id_tag_update(obedit->data, OB_RECALC_DATA);
 +              }
 +      }
 +}
 +
 +/* ****************************** SELECTION ROUTINES **************** */
 +
 +unsigned int bm_solidoffs=0, bm_wireoffs=0, bm_vertoffs=0;    /* set in drawobject.c ... for colorindices */
 +
 +/* facilities for border select and circle select */
 +static char *selbuf= NULL;
 +
 +/* opengl doesn't support concave... */
 +static void draw_triangulated(int mcords[][2], short tot)
 +{
 +      ListBase lb={NULL, NULL};
 +      DispList *dl;
 +      float *fp;
 +      int a;
 +      
 +      /* make displist */
 +      dl= MEM_callocN(sizeof(DispList), "poly disp");
 +      dl->type= DL_POLY;
 +      dl->parts= 1;
 +      dl->nr= tot;
 +      dl->verts= fp=  MEM_callocN(tot*3*sizeof(float), "poly verts");
 +      BLI_addtail(&lb, dl);
 +      
 +      for(a=0; a<tot; a++, fp+=3) {
 +              fp[0]= (float)mcords[a][0];
 +              fp[1]= (float)mcords[a][1];
 +      }
 +      
 +      /* do the fill */
 +      filldisplist(&lb, &lb, 0);
 +
 +      /* do the draw */
 +      dl= lb.first;   /* filldisplist adds in head of list */
 +      if(dl->type==DL_INDEX3) {
 +              int *index;
 +              
 +              a= dl->parts;
 +              fp= dl->verts;
 +              index= dl->index;
 +              glBegin(GL_TRIANGLES);
 +              while(a--) {
 +                      glVertex3fv(fp+3*index[0]);
 +                      glVertex3fv(fp+3*index[1]);
 +                      glVertex3fv(fp+3*index[2]);
 +                      index+= 3;
 +              }
 +              glEnd();
 +      }
 +      
 +      freedisplist(&lb);
 +}
 +
 +
 +/* reads rect, and builds selection array for quick lookup */
 +/* returns if all is OK */
 +int EDBM_init_backbuf_border(ViewContext *vc, short xmin, short ymin, short xmax, short ymax)
 +{
 +      struct ImBuf *buf;
 +      unsigned int *dr;
 +      int a;
 +      
 +      if(vc->obedit==NULL || vc->v3d->drawtype<OB_SOLID || (vc->v3d->flag & V3D_ZBUF_SELECT)==0) return 0;
 +      
 +      buf= view3d_read_backbuf(vc, xmin, ymin, xmax, ymax);
 +      if(buf==NULL) return 0;
 +      if(bm_vertoffs==0) return 0;
 +
 +      dr = buf->rect;
 +      
 +      /* build selection lookup */
 +      selbuf= MEM_callocN(bm_vertoffs+1, "selbuf");
 +      
 +      a= (xmax-xmin+1)*(ymax-ymin+1);
 +      while(a--) {
 +              if(*dr>0 && *dr<=bm_vertoffs) 
 +                      selbuf[*dr]= 1;
 +              dr++;
 +      }
 +      IMB_freeImBuf(buf);
 +      return 1;
 +}
 +
 +int EDBM_check_backbuf(unsigned int index)
 +{
 +      if(selbuf==NULL) return 1;
 +      if(index>0 && index<=bm_vertoffs)
 +              return selbuf[index];
 +      return 0;
 +}
 +
 +void EDBM_free_backbuf(void)
 +{
 +      if(selbuf) MEM_freeN(selbuf);
 +      selbuf= NULL;
 +}
 +
 +/* mcords is a polygon mask
 +   - grab backbuffer,
 +   - draw with black in backbuffer, 
 +   - grab again and compare
 +   returns 'OK' 
 +*/
 +int EDBM_mask_init_backbuf_border(ViewContext *vc, int mcords[][2], short tot, short xmin, short ymin, short xmax, short ymax)
 +{
 +      unsigned int *dr, *drm;
 +      struct ImBuf *buf, *bufmask;
 +      int a;
 +      
 +      /* method in use for face selecting too */
 +      if(vc->obedit==NULL) {
 +              if(paint_facesel_test(vc->obact));
++              else if(paint_vertsel_test(vc->obact));
 +              else return 0;
 +      }
 +      else if(vc->v3d->drawtype<OB_SOLID || (vc->v3d->flag & V3D_ZBUF_SELECT)==0) return 0;
 +
 +      buf= view3d_read_backbuf(vc, xmin, ymin, xmax, ymax);
 +      if(buf==NULL) return 0;
 +      if(bm_vertoffs==0) return 0;
 +
 +      dr = buf->rect;
 +
 +      /* draw the mask */
 +      glDisable(GL_DEPTH_TEST);
 +      
 +      glColor3ub(0, 0, 0);
 +      
 +      /* yah, opengl doesn't do concave... tsk! */
 +      ED_region_pixelspace(vc->ar);
 +      draw_triangulated(mcords, tot); 
 +      
 +      glBegin(GL_LINE_LOOP);  /* for zero sized masks, lines */
 +      for(a=0; a<tot; a++) glVertex2iv(mcords[a]);
 +      glEnd();
 +      
 +      glFinish();     /* to be sure readpixels sees mask */
 +      
 +      /* grab mask */
 +      bufmask= view3d_read_backbuf(vc, xmin, ymin, xmax, ymax);
 +      drm = bufmask->rect;
 +      if(bufmask==NULL) return 0; /* only when mem alloc fails, go crash somewhere else! */
 +      
 +      /* build selection lookup */
 +      selbuf= MEM_callocN(bm_vertoffs+1, "selbuf");
 +      
 +      a= (xmax-xmin+1)*(ymax-ymin+1);
 +      while(a--) {
 +              if(*dr>0 && *dr<=bm_vertoffs && *drm==0) selbuf[*dr]= 1;
 +              dr++; drm++;
 +      }
 +      IMB_freeImBuf(buf);
 +      IMB_freeImBuf(bufmask);
 +      return 1;
 +      
 +}
 +
 +/* circle shaped sample area */
 +int EDBM_init_backbuf_circle(ViewContext *vc, short xs, short ys, short rads)
 +{
 +      struct ImBuf *buf;
 +      unsigned int *dr;
 +      short xmin, ymin, xmax, ymax, xc, yc;
 +      int radsq;
 +      
 +      /* method in use for face selecting too */
 +      if(vc->obedit==NULL) {
 +              if(paint_facesel_test(vc->obact));
++              else if(paint_vertsel_test(vc->obact));
 +              else return 0;
 +      }
 +      else if(vc->v3d->drawtype<OB_SOLID || (vc->v3d->flag & V3D_ZBUF_SELECT)==0) return 0;
 +      
 +      xmin= xs-rads; xmax= xs+rads;
 +      ymin= ys-rads; ymax= ys+rads;
 +      buf= view3d_read_backbuf(vc, xmin, ymin, xmax, ymax);
 +      if(bm_vertoffs==0) return 0;
 +      if(buf==NULL) return 0;
 +
 +      dr = buf->rect;
 +      
 +      /* build selection lookup */
 +      selbuf= MEM_callocN(bm_vertoffs+1, "selbuf");
 +      radsq= rads*rads;
 +      for(yc= -rads; yc<=rads; yc++) {
 +              for(xc= -rads; xc<=rads; xc++, dr++) {
 +                      if(xc*xc + yc*yc < radsq) {
 +                              if(*dr>0 && *dr<=bm_vertoffs) selbuf[*dr]= 1;
 +                      }
 +              }
 +      }
 +
 +      IMB_freeImBuf(buf);
 +      return 1;
 +      
 +}
 +
 +static void findnearestvert__doClosest(void *userData, BMVert *eve, int x, int y, int index)
 +{
 +      struct { short mval[2], pass, select, strict; int dist, lastIndex, closestIndex; BMVert *closest; } *data = userData;
 +
 +      if (data->pass==0) {
 +              if (index<=data->lastIndex)
 +                      return;
 +      } else {
 +              if (index>data->lastIndex)
 +                      return;
 +      }
 +
 +      if (data->dist>3) {
 +              int temp = abs(data->mval[0] - x) + abs(data->mval[1]- y);
 +              if (BM_TestHFlag(eve, BM_SELECT) == data->select) {
 +                      if (data->strict == 1)
 +                              return;
 +                      else
 +                              temp += 5;
 +              }
 +
 +              if (temp<data->dist) {
 +                      data->dist = temp;
 +                      data->closest = eve;
 +                      data->closestIndex = index;
 +              }
 +      }
 +}
 +
 +
 +
 +
 +static unsigned int findnearestvert__backbufIndextest(void *handle, unsigned int index)
 +{
 +      BMEditMesh *em= (BMEditMesh *)handle;
 +      BMVert *eve = BMIter_AtIndex(em->bm, BM_VERTS_OF_MESH, NULL, index-1);
 +
 +      if(eve && BM_TestHFlag(eve, BM_SELECT)) return 0;
 +      return 1; 
 +}
 +/**
 + * findnearestvert
 + * 
 + * dist (in/out): minimal distance to the nearest and at the end, actual distance
 + * sel: selection bias
 + *            if SELECT, selected vertice are given a 5 pixel bias to make them farter than unselect verts
 + *            if 0, unselected vertice are given the bias
 + * strict: if 1, the vertice corresponding to the sel parameter are ignored and not just biased 
 + */
 +BMVert *EDBM_findnearestvert(ViewContext *vc, int *dist, short sel, short strict)
 +{
 +      if(vc->v3d->drawtype>OB_WIRE && (vc->v3d->flag & V3D_ZBUF_SELECT)){
 +              int distance;
 +              unsigned int index;
 +              BMVert *eve;
 +              
 +              if(strict) index = view3d_sample_backbuf_rect(vc, vc->mval, 50, bm_wireoffs, 0xFFFFFF, &distance, strict, vc->em, findnearestvert__backbufIndextest); 
 +              else index = view3d_sample_backbuf_rect(vc, vc->mval, 50, bm_wireoffs, 0xFFFFFF, &distance, 0, NULL, NULL); 
 +              
 +              eve = BMIter_AtIndex(vc->em->bm, BM_VERTS_OF_MESH, NULL, index-1);
 +              
 +              if(eve && distance < *dist) {
 +                      *dist = distance;
 +                      return eve;
 +              } else {
 +                      return NULL;
 +              }
 +                      
 +      }
 +      else {
 +              struct { short mval[2], pass, select, strict; int dist, lastIndex, closestIndex; BMVert *closest; } data;
 +              static int lastSelectedIndex=0;
 +              static BMVert *lastSelected=NULL;
 +              
 +              if (lastSelected && BMIter_AtIndex(vc->em->bm, BM_VERTS_OF_MESH, NULL, lastSelectedIndex)!=lastSelected) {
 +                      lastSelectedIndex = 0;
 +                      lastSelected = NULL;
 +              }
 +
 +              data.lastIndex = lastSelectedIndex;
 +              data.mval[0] = vc->mval[0];
 +              data.mval[1] = vc->mval[1];
 +              data.select = sel;
 +              data.dist = *dist;
 +              data.strict = strict;
 +              data.closest = NULL;
 +              data.closestIndex = 0;
 +
 +              data.pass = 0;
 +
 +              ED_view3d_init_mats_rv3d(vc->obedit, vc->rv3d);
 +
 +              mesh_foreachScreenVert(vc, findnearestvert__doClosest, &data, 1);
 +
 +              if (data.dist>3) {
 +                      data.pass = 1;
 +                      mesh_foreachScreenVert(vc, findnearestvert__doClosest, &data, 1);
 +              }
 +
 +              *dist = data.dist;
 +              lastSelected = data.closest;
 +              lastSelectedIndex = data.closestIndex;
 +
 +              return data.closest;
 +      }
 +}
 +
 +/* returns labda for closest distance v1 to line-piece v2-v3 */
 +float labda_PdistVL2Dfl(const float v1[3], const float v2[3], const float v3[3])
 +{
 +      float rc[2], len;
 +      
 +      rc[0]= v3[0]-v2[0];
 +      rc[1]= v3[1]-v2[1];
 +      len= rc[0]*rc[0]+ rc[1]*rc[1];
 +      if(len==0.0f)
 +              return 0.0f;
 +      
 +      return ( rc[0]*(v1[0]-v2[0]) + rc[1]*(v1[1]-v2[1]) )/len;
 +}
 +
 +/* note; uses v3d, so needs active 3d window */
 +static void findnearestedge__doClosest(void *userData, BMEdge *eed, int x0, int y0, int x1, int y1, int UNUSED(index))
 +{
 +      struct { ViewContext vc; float mval[2]; int dist; BMEdge *closest; } *data = userData;
 +      float v1[2], v2[2];
 +      int distance;
 +              
 +      v1[0] = x0;
 +      v1[1] = y0;
 +      v2[0] = x1;
 +      v2[1] = y1;
 +              
 +      distance= dist_to_line_segment_v2(data->mval, v1, v2);
 +              
 +      if(BM_TestHFlag(eed, BM_SELECT)) distance+=5;
 +      if(distance < data->dist) {
 +              if(data->vc.rv3d->rflag & RV3D_CLIPPING) {
 +                      float labda= labda_PdistVL2Dfl(data->mval, v1, v2);
 +                      float vec[3];
 +
 +                      vec[0]= eed->v1->co[0] + labda*(eed->v2->co[0] - eed->v1->co[0]);
 +                      vec[1]= eed->v1->co[1] + labda*(eed->v2->co[1] - eed->v1->co[1]);
 +                      vec[2]= eed->v1->co[2] + labda*(eed->v2->co[2] - eed->v1->co[2]);
 +                      mul_m4_v3(data->vc.obedit->obmat, vec);
 +
 +                      if(ED_view3d_test_clipping(data->vc.rv3d, vec, 1)==0) {
 +                              data->dist = distance;
 +                              data->closest = eed;
 +                      }
 +              }
 +              else {
 +                      data->dist = distance;
 +                      data->closest = eed;
 +              }
 +      }
 +}
 +BMEdge *EDBM_findnearestedge(ViewContext *vc, int *dist)
 +{
 +
 +      if(vc->v3d->drawtype>OB_WIRE && (vc->v3d->flag & V3D_ZBUF_SELECT)) {
 +              int distance;
 +              unsigned int index;
 +              BMEdge *eed;
 +              
 +              view3d_validate_backbuf(vc);
 +              
 +              index = view3d_sample_backbuf_rect(vc, vc->mval, 50, bm_solidoffs, bm_wireoffs, &distance,0, NULL, NULL);
 +              eed = BMIter_AtIndex(vc->em->bm, BM_EDGES_OF_MESH, NULL, index-1);
 +              
 +              if (eed && distance<*dist) {
 +                      *dist = distance;
 +                      return eed;
 +              } else {
 +                      return NULL;
 +              }
 +      }
 +      else {
 +              struct { ViewContext vc; float mval[2]; int dist; BMEdge *closest; } data;
 +
 +              data.vc= *vc;
 +              data.mval[0] = vc->mval[0];
 +              data.mval[1] = vc->mval[1];
 +              data.dist = *dist;
 +              data.closest = NULL;
 +              ED_view3d_init_mats_rv3d(vc->obedit, vc->rv3d);
 +
 +              mesh_foreachScreenEdge(vc, findnearestedge__doClosest, &data, 2);
 +
 +              *dist = data.dist;
 +              return data.closest;
 +      }
 +}
 +
 +static void findnearestface__getDistance(void *userData, BMFace *efa, int x, int y, int UNUSED(index))
 +{
 +      struct { short mval[2]; int dist; BMFace *toFace; } *data = userData;
 +
 +      if (efa==data->toFace) {
 +              int temp = abs(data->mval[0]-x) + abs(data->mval[1]-y);
 +
 +              if (temp<data->dist)
 +                      data->dist = temp;
 +      }
 +}
 +static void findnearestface__doClosest(void *userData, BMFace *efa, int x, int y, int index)
 +{
 +      struct { short mval[2], pass; int dist, lastIndex, closestIndex; BMFace *closest; } *data = userData;
 +
 +      if (data->pass==0) {
 +              if (index<=data->lastIndex)
 +                      return;
 +      } else {
 +              if (index>data->lastIndex)
 +                      return;
 +      }
 +
 +      if (data->dist>3) {
 +              int temp = abs(data->mval[0]-x) + abs(data->mval[1]-y);
 +
 +              if (temp<data->dist) {
 +                      data->dist = temp;
 +                      data->closest = efa;
 +                      data->closestIndex = index;
 +              }
 +      }
 +}
 +
 +BMFace *EDBM_findnearestface(ViewContext *vc, int *dist)
 +{
 +
 +      if(vc->v3d->drawtype>OB_WIRE && (vc->v3d->flag & V3D_ZBUF_SELECT)) {
 +              unsigned int index;
 +              BMFace *efa;
 +
 +              view3d_validate_backbuf(vc);
 +
 +              index = view3d_sample_backbuf(vc, vc->mval[0], vc->mval[1]);
 +              efa = BMIter_AtIndex(vc->em->bm, BM_FACES_OF_MESH, NULL, index-1);
 +              
 +              if (efa) {
 +                      struct { short mval[2]; int dist; BMFace *toFace; } data;
 +
 +                      data.mval[0] = vc->mval[0];
 +                      data.mval[1] = vc->mval[1];
 +                      data.dist = 0x7FFF;             /* largest short */
 +                      data.toFace = efa;
 +
 +                      mesh_foreachScreenFace(vc, findnearestface__getDistance, &data);
 +
 +                      if(vc->em->selectmode == SCE_SELECT_FACE || data.dist<*dist) {  /* only faces, no dist check */
 +                              *dist= data.dist;
 +                              return efa;
 +                      }
 +              }
 +              
 +              return NULL;
 +      }
 +      else {
 +              struct { short mval[2], pass; int dist, lastIndex, closestIndex; BMFace *closest; } data;
 +              static int lastSelectedIndex=0;
 +              static BMFace *lastSelected=NULL;
 +
 +              if (lastSelected && BMIter_AtIndex(vc->em->bm, BM_FACES_OF_MESH, NULL, lastSelectedIndex)!=lastSelected) {
 +                      lastSelectedIndex = 0;
 +                      lastSelected = NULL;
 +              }
 +
 +              data.lastIndex = lastSelectedIndex;
 +              data.mval[0] = vc->mval[0];
 +              data.mval[1] = vc->mval[1];
 +              data.dist = *dist;
 +              data.closest = NULL;
 +              data.closestIndex = 0;
 +              ED_view3d_init_mats_rv3d(vc->obedit, vc->rv3d);
 +
 +              data.pass = 0;
 +              mesh_foreachScreenFace(vc, findnearestface__doClosest, &data);
 +
 +              if (data.dist>3) {
 +                      data.pass = 1;
 +                      ED_view3d_init_mats_rv3d(vc->obedit, vc->rv3d);
 +                      mesh_foreachScreenFace(vc, findnearestface__doClosest, &data);
 +              }
 +
 +              *dist = data.dist;
 +              lastSelected = data.closest;
 +              lastSelectedIndex = data.closestIndex;
 +
 +              return data.closest;
 +      }
 +}
 +
 +/* best distance based on screen coords. 
 +   use em->selectmode to define how to use 
 +   selected vertices and edges get disadvantage
 +   return 1 if found one
 +*/
 +static int unified_findnearest(ViewContext *vc, BMVert **eve, BMEdge **eed, BMFace **efa) 
 +{
 +      BMEditMesh *em= vc->em;
 +      int dist= 75;
 +      
 +      *eve= NULL;
 +      *eed= NULL;
 +      *efa= NULL;
 +      
 +      /* no afterqueue (yet), so we check it now, otherwise the em_xxxofs indices are bad */
 +      view3d_validate_backbuf(vc);
 +      
 +      if(em->selectmode & SCE_SELECT_VERTEX)
 +              *eve= EDBM_findnearestvert(vc, &dist, BM_SELECT, 0);
 +      if(em->selectmode & SCE_SELECT_FACE)
 +              *efa= EDBM_findnearestface(vc, &dist);
 +
 +      dist-= 20;      /* since edges select lines, we give dots advantage of 20 pix */
 +      if(em->selectmode & SCE_SELECT_EDGE)
 +              *eed= EDBM_findnearestedge(vc, &dist);
 +
 +      /* return only one of 3 pointers, for frontbuffer redraws */
 +      if(*eed) {
 +              *efa= NULL; *eve= NULL;
 +      }
 +      else if(*efa) {
 +              *eve= NULL;
 +      }
 +      
 +      return (*eve || *eed || *efa);
 +}
 +
 +/* ****************  SIMILAR "group" SELECTS. FACE, EDGE AND VERTEX ************** */
 +
 +static EnumPropertyItem prop_similar_types[] = {
 +      {SIMVERT_NORMAL, "NORMAL", 0, "Normal", ""},
 +      {SIMVERT_FACE, "FACE", 0, "Amount of Adjacent Faces", ""},
 +      {SIMVERT_VGROUP, "VGROUP", 0, "Vertex Groups", ""},
 +
 +      {SIMEDGE_LENGTH, "LENGTH", 0, "Length", ""},
 +      {SIMEDGE_DIR, "DIR", 0, "Direction", ""},
 +      {SIMEDGE_FACE, "FACE", 0, "Amount of Faces Around an Edge", ""},
 +      {SIMEDGE_FACE_ANGLE, "FACE_ANGLE", 0, "Face Angles", ""},
 +      {SIMEDGE_CREASE, "CREASE", 0, "Crease", ""},
 +      {SIMEDGE_SEAM, "SEAM", 0, "Seam", ""},
 +      {SIMEDGE_SHARP, "SHARP", 0, "Sharpness", ""},
 +
 +      {SIMFACE_MATERIAL, "MATERIAL", 0, "Material", ""},
 +      {SIMFACE_IMAGE, "IMAGE", 0, "Image", ""},
 +      {SIMFACE_AREA, "AREA", 0, "Area", ""},
 +      {SIMFACE_PERIMETER, "PERIMETER", 0, "Perimeter", ""},
 +      {SIMFACE_NORMAL, "NORMAL", 0, "Normal", ""},
 +      {SIMFACE_COPLANAR, "COPLANAR", 0, "Co-planar", ""},
 +
 +      {0, NULL, 0, NULL, NULL}
 +};
 +
 +/* selects new faces/edges/verts based on the existing selection */
 +
 +static int similar_face_select_exec(bContext *C, wmOperator *op)
 +{
 +      Object *ob = CTX_data_edit_object(C);
 +      BMEditMesh *em = ((Mesh*)ob->data)->edit_btmesh;
 +      BMOperator bmop;
 +
 +      /* get the type from RNA */
 +      int type = RNA_enum_get(op->ptr, "type");
 +
 +      float thresh = CTX_data_tool_settings(C)->select_thresh;
 +
 +      /* initialize the bmop using EDBM api, which does various ui error reporting and other stuff */
 +      EDBM_InitOpf(em, &bmop, op, "similarfaces faces=%hf type=%d thresh=%f", BM_SELECT, type, thresh);
 +
 +      /* execute the operator */
 +      BMO_Exec_Op(em->bm, &bmop);
 +
 +      /* clear the existing selection */
 +      EDBM_clear_flag_all(em, BM_SELECT);
 +
 +      /* select the output */
 +      BMO_HeaderFlag_Buffer(em->bm, &bmop, "faceout", BM_SELECT, BM_ALL);
 +
 +      /* finish the operator */
 +      if( !EDBM_FinishOp(em, &bmop, op, 1) )
 +              return OPERATOR_CANCELLED;
 +
 +      /* dependencies graph and notification stuff */
 +      DAG_id_tag_update(ob->data, OB_RECALC_DATA);
 +      WM_event_add_notifier(C, NC_GEOM|ND_SELECT, ob->data);
 +
 +      /* we succeeded */
 +      return OPERATOR_FINISHED;
 +}     
 +
 +/* ***************************************************** */
 +
 +/* EDGE GROUP */
 +
 +/* wrap the above function but do selection flushing edge to face */
 +static int similar_edge_select_exec(bContext *C, wmOperator *op)
 +{
 +      Object *ob = CTX_data_edit_object(C);
 +      BMEditMesh *em = ((Mesh*)ob->data)->edit_btmesh;
 +      BMOperator bmop;
 +
 +      /* get the type from RNA */
 +      int type = RNA_enum_get(op->ptr, "type");
 +
 +      float thresh = CTX_data_tool_settings(C)->select_thresh;
 +
 +      /* initialize the bmop using EDBM api, which does various ui error reporting and other stuff */
 +      EDBM_InitOpf(em, &bmop, op, "similaredges edges=%he type=%d thresh=%f", BM_SELECT, type, thresh);
 +
 +      /* execute the operator */
 +      BMO_Exec_Op(em->bm, &bmop);
 +
 +      /* clear the existing selection */
 +      EDBM_clear_flag_all(em, BM_SELECT);
 +
 +      /* select the output */
 +      BMO_HeaderFlag_Buffer(em->bm, &bmop, "edgeout", BM_SELECT, BM_ALL);
 +      EDBM_selectmode_flush(em);
 +
 +      /* finish the operator */
 +      if( !EDBM_FinishOp(em, &bmop, op, 1) )
 +              return OPERATOR_CANCELLED;
 +
 +      /* dependencies graph and notification stuff */
 +      DAG_id_tag_update(ob->data, OB_RECALC_DATA);
 +      WM_event_add_notifier(C, NC_GEOM|ND_SELECT, ob->data);
 +
 +      /* we succeeded */
 +      return OPERATOR_FINISHED;
 +}
 +
 +/* ********************************* */
 +
 +/*
 +VERT GROUP
 + mode 1: same normal
 + mode 2: same number of face users
 + mode 3: same vertex groups
 +*/
 +
 +
 +static int similar_vert_select_exec(bContext *C, wmOperator *op)
 +{
 +      Object *ob = CTX_data_edit_object(C);
 +      BMEditMesh *em = ((Mesh*)ob->data)->edit_btmesh;
 +      BMOperator bmop;
 +      /* get the type from RNA */
 +      int type = RNA_enum_get(op->ptr, "type");
 +      float thresh = CTX_data_tool_settings(C)->select_thresh;
 +
 +      /* initialize the bmop using EDBM api, which does various ui error reporting and other stuff */
 +      EDBM_InitOpf(em, &bmop, op, "similarverts verts=%hv type=%d thresh=%f", BM_SELECT, type, thresh);
 +
 +      /* execute the operator */
 +      BMO_Exec_Op(em->bm, &bmop);
 +
 +      /* clear the existing selection */
 +      EDBM_clear_flag_all(em, BM_SELECT);
 +
 +      /* select the output */
 +      BMO_HeaderFlag_Buffer(em->bm, &bmop, "vertout", BM_SELECT, BM_ALL);
 +
 +      /* finish the operator */
 +      if( !EDBM_FinishOp(em, &bmop, op, 1) )
 +              return OPERATOR_CANCELLED;
 +
 +      EDBM_selectmode_flush(em);
 +
 +      /* dependencies graph and notification stuff */
 +      DAG_id_tag_update(ob->data, OB_RECALC_DATA);
 +      WM_event_add_notifier(C, NC_GEOM|ND_SELECT, ob->data);
 +
 +      /* we succeeded */
 +      return OPERATOR_FINISHED;
 +}
 +
 +static int select_similar_exec(bContext *C, wmOperator *op)
 +{
 +      int type= RNA_enum_get(op->ptr, "type");
 +
 +      if(type < 100)
 +              return similar_vert_select_exec(C, op);
 +      else if(type < 200)
 +              return similar_edge_select_exec(C, op);
 +      else
 +              return similar_face_select_exec(C, op);
 +}
 +
 +static EnumPropertyItem *select_similar_type_itemf(bContext *C, PointerRNA *UNUSED(ptr), PropertyRNA *UNUSED(prop), int *free)
 +{
 +      Object *obedit = CTX_data_edit_object(C);
 +
 +      if(obedit && obedit->type == OB_MESH) {
 +              EnumPropertyItem *item= NULL;
 +              int a, totitem= 0;
 +              BMEditMesh *em= ((Mesh*)obedit->data)->edit_btmesh; 
 +
 +              if(em->selectmode & SCE_SELECT_VERTEX) {
 +                      for (a=SIMVERT_NORMAL; a<SIMEDGE_LENGTH; a++) {
 +                              RNA_enum_items_add_value(&item, &totitem, prop_similar_types, a);
 +                      }
 +              } else if(em->selectmode & SCE_SELECT_EDGE) {
 +                      for (a=SIMEDGE_LENGTH; a<SIMFACE_MATERIAL; a++) {
 +                              RNA_enum_items_add_value(&item, &totitem, prop_similar_types, a);
 +                      }
 +              } else if(em->selectmode & SCE_SELECT_FACE) {
 +                      for (a=SIMFACE_MATERIAL; a<=SIMFACE_COPLANAR; a++) {
 +                              RNA_enum_items_add_value(&item, &totitem, prop_similar_types, a);
 +                      }
 +              }
 +              RNA_enum_item_end(&item, &totitem);
 +
 +              *free= 1;
 +
 +              return item;
 +      }
 +      
 +      return NULL;
 +}
 +
 +void MESH_OT_select_similar(wmOperatorType *ot)
 +{
 +      PropertyRNA *prop;
 +
 +      /* identifiers */
 +      ot->name= "Select Similar";
 +      ot->idname= "MESH_OT_select_similar";
 +      
 +      /* api callbacks */
 +      ot->invoke= WM_menu_invoke;
 +      ot->exec= select_similar_exec;
 +      ot->poll= ED_operator_editmesh;
 +      ot->description= "Select similar vertices, edges or faces by property types.";
 +      
 +      /* flags */
 +      ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
 +      
 +      /* properties */
 +      prop= ot->prop= RNA_def_enum(ot->srna, "type", prop_similar_types, SIMVERT_NORMAL, "Type", "");
 +      RNA_def_enum_funcs(prop, select_similar_type_itemf);
 +}
 +
 +/* ***************************************************** */
 +
 +/* ****************  LOOP SELECTS *************** */
 +
 +static void walker_select(BMEditMesh *em, int walkercode, void *start, int select)
 +{
 +      BMesh *bm = em->bm;
 +      BMHeader *h;
 +      BMWalker walker;
 +
 +      BMW_Init(&walker, bm, walkercode, 0, 0);
 +      h = BMW_Begin(&walker, start);
 +      for (; h; h=BMW_Step(&walker)) {
 +              if (!select) {
 +                      BM_remove_selection(bm, h);
 +              }
 +              BM_Select(bm, h, select);
 +      }
 +      BMW_End(&walker);
 +}
 +
 +static int loop_multiselect(bContext *C, wmOperator *op)
 +{
 +      Object *obedit= CTX_data_edit_object(C);
 +      BMEditMesh *em = ((Mesh*)obedit->data)->edit_btmesh;
 +      BMEdge *eed;
 +      BMEdge **edarray;
 +      int edindex;
 +      int looptype= RNA_boolean_get(op->ptr, "ring");
 +      
 +      BMIter iter;
 +      int totedgesel = 0;
 +
 +      for(eed = BMIter_New(&iter, em->bm, BM_EDGES_OF_MESH, NULL);
 +          eed; eed = BMIter_Step(&iter)){
 +
 +              if(BM_TestHFlag(eed, BM_SELECT)){
 +                      totedgesel++;
 +              }
 +      }
 +
 +      
 +      edarray = MEM_mallocN(sizeof(BMEdge*)*totedgesel,"edge array");
 +      edindex = 0;
 +      
 +      for(eed = BMIter_New(&iter, em->bm, BM_EDGES_OF_MESH, NULL);
 +          eed; eed = BMIter_Step(&iter)){
 +
 +              if(BM_TestHFlag(eed, BM_SELECT)){
 +                      edarray[edindex] = eed;
 +                      edindex++;
 +              }
 +      }
 +      
 +      if(looptype){
 +              for(edindex = 0; edindex < totedgesel; edindex +=1){
 +                      eed = edarray[edindex];
 +                      walker_select(em, BMW_EDGERING, eed, 1);
 +              }
 +              EDBM_selectmode_flush(em);
 +      }
 +      else{
 +              for(edindex = 0; edindex < totedgesel; edindex +=1){
 +                      eed = edarray[edindex];
 +                      walker_select(em, BMW_LOOP, eed, 1);
 +              }
 +              EDBM_selectmode_flush(em);
 +      }
 +      MEM_freeN(edarray);
 +//    if (EM_texFaceCheck())
 +      
 +      WM_event_add_notifier(C, NC_GEOM|ND_SELECT, obedit);
 +
 +      return OPERATOR_FINISHED;       
 +}
 +
 +void MESH_OT_loop_multi_select(wmOperatorType *ot)
 +{
 +      /* identifiers */
 +      ot->name= "Multi Select Loops";
 +      ot->idname= "MESH_OT_loop_multi_select";
 +      
 +      /* api callbacks */
 +      ot->exec= loop_multiselect;
 +      ot->poll= ED_operator_editmesh;
 +      ot->description= "Select a loop of connected edges by connection type.";
 +      
 +      /* flags */
 +      ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
 +      
 +      /* properties */
 +      RNA_def_boolean(ot->srna, "ring", 0, "Ring", "");
 +}
 +
 +              
 +/* ***************** MAIN MOUSE SELECTION ************** */
 +
 +
 +/* ***************** loop select (non modal) ************** */
 +
 +static void mouse_mesh_loop(bContext *C, int mval[2], short extend, short ring)
 +{
 +      ViewContext vc;
 +      BMEditMesh *em;
 +      BMEdge *eed;
 +      int select= 1;
 +      int dist= 50;
 +      
 +      em_setup_viewcontext(C, &vc);
 +      vc.mval[0]= mval[0];
 +      vc.mval[1]= mval[1];
 +      em= vc.em;
 +      
 +      /* no afterqueue (yet), so we check it now, otherwise the bm_xxxofs indices are bad */
 +      view3d_validate_backbuf(&vc);
 +
 +      eed= EDBM_findnearestedge(&vc, &dist);
 +      if(eed) {
 +              if(extend==0) EDBM_clear_flag_all(em, BM_SELECT);
 +      
 +              if(BM_TestHFlag(eed, BM_SELECT)==0) select=1;
 +              else if(extend) select=0;
 +
 +              if(em->selectmode & SCE_SELECT_FACE) {
 +                      walker_select(em, BMW_FACELOOP, eed, select);
 +              }
 +              else if(em->selectmode & SCE_SELECT_EDGE) {
 +                      if(ring)
 +                              walker_select(em, BMW_EDGERING, eed, select);
 +                      else
 +                              walker_select(em, BMW_LOOP, eed, select);
 +              }
 +              else if(em->selectmode & SCE_SELECT_VERTEX) {
 +                      if(ring)
 +                              walker_select(em, BMW_EDGERING, eed, select);
 +                      else
 +                              walker_select(em, BMW_LOOP, eed, select);
 +              }
 +
 +              EDBM_selectmode_flush(em);
 +//                    if (EM_texFaceCheck())
 +              
 +              /* sets as active, useful for other tools */
 +              if(select && em->selectmode & SCE_SELECT_EDGE) {
 +                      EDBM_store_selection(em, eed);
 +              }
 +
 +              WM_event_add_notifier(C, NC_GEOM|ND_SELECT, vc.obedit);
 +      }
 +}
 +
 +static int mesh_select_loop_invoke(bContext *C, wmOperator *op, wmEvent *event)
 +{
 +      
 +      view3d_operator_needs_opengl(C);
 +      
 +      mouse_mesh_loop(C, event->mval, RNA_boolean_get(op->ptr, "extend"),
 +                                      RNA_boolean_get(op->ptr, "ring"));
 +      
 +      /* cannot do tweaks for as long this keymap is after transform map */
 +      return OPERATOR_FINISHED;
 +}
 +
 +void MESH_OT_loop_select(wmOperatorType *ot)
 +{
 +      /* identifiers */
 +      ot->name= "Loop Select";
 +      ot->idname= "MESH_OT_loop_select";
 +      ot->description= "Select a loop";
 +      
 +      /* api callbacks */
 +      ot->invoke= mesh_select_loop_invoke;
 +      ot->poll= ED_operator_editmesh;
 +      ot->description= "Select a loop of connected edges.";
 +      
 +      /* flags */
 +      ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
 +      
 +      /* properties */
 +      RNA_def_boolean(ot->srna, "extend", 0, "Extend Select", "Extend the selection");
 +      RNA_def_boolean(ot->srna, "ring", 0, "Select Ring", "Select ring");
 +}
 +
 +void MESH_OT_edgering_select (wmOperatorType *ot)
 +{
 +      /* description */
 +      ot->name= "Edge Ring Select";
 +      ot->idname= "MESH_OT_edgering_select";
 +      ot->description= "Select an edge ring";
 +      
 +      /* callbacks */
 +      ot->invoke= mesh_select_loop_invoke;
 +      ot->poll= ED_operator_editmesh; 
 +      
 +      /* flags */
 +      ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
 +
 +      RNA_def_boolean(ot->srna, "extend", 0, "Extend", "Extend the selection");
 +      RNA_def_boolean(ot->srna, "ring", 1, "Select Ring", "Select ring");
 +}
 +
 +/* ******************* edgetag_shortest_path and helpers ****************** */
 +
 +static float edgetag_cut_cost(BMEditMesh *UNUSED(em), BMEdge *e1, BMEdge *e2, BMVert* v)
 +{
 +      BMVert *v1 = (e1->v1 == v) ? e1->v2 : e1->v1;
 +      BMVert *v2 = (e2->v1 == v) ? e2->v2 : e2->v1;
 +      float cost, d1[3], d2[3];
 +
 +      /*The cost is based on the simple sum of the length of the two edgees...*/
 +      sub_v3_v3v3(d1, v->co, v1->co);
 +      sub_v3_v3v3(d2, v2->co, v->co);
 +      cost = len_v3(d1);
 +      cost += len_v3(d2);
 +
 +      /*...but is biased to give higher values to sharp turns, so that it will take
 +        paths with fewer "turns" when selecting between equal-weighted paths between
 +        the two edges*/
 +      cost = cost + 0.5f*cost*(2.0f - sqrt(fabs(dot_v3v3(d1, d2))));
 +
 +      return cost;
 +}
 +
 +static void edgetag_add_adjacent(BMEditMesh *em, SmallHash *visithash, Heap *heap, int mednum, int vertnum, 
 +                                                               int *nedges, int *edges, int *prevedge, float *cost)
 +{
 +      BMEdge *e1 = EDBM_get_edge_for_index(em, mednum);
 +      BMVert *v = EDBM_get_vert_for_index(em, vertnum);
 +      int startadj, endadj = nedges[vertnum+1];
 +
 +      for (startadj = nedges[vertnum]; startadj < endadj; startadj++) {
 +              int adjnum = edges[startadj];
 +              BMEdge *e2 = EDBM_get_edge_for_index(em, adjnum);
 +              float newcost;
 +              float cutcost;
 +
 +              if (BLI_smallhash_haskey(visithash, (uintptr_t)e2))
 +                      continue;
 +
 +              cutcost = edgetag_cut_cost(em, e1, e2, v);
 +              newcost = cost[mednum] + cutcost;
 +
 +              if (cost[adjnum] > newcost) {
 +                      cost[adjnum] = newcost;
 +                      prevedge[adjnum] = mednum;
 +                      BLI_heap_insert(heap, newcost, SET_INT_IN_POINTER(adjnum));
 +              }
 +      }
 +}
 +
 +static void edgetag_context_set(BMEditMesh *em, Scene *scene, BMEdge *e, int val)
 +{
 +      
 +      switch (scene->toolsettings->edge_mode) {
 +      case EDGE_MODE_SELECT:
 +              BM_Select(em->bm, e, val);
 +              break;
 +      case EDGE_MODE_TAG_SEAM:
 +              if (val)                {BM_SetHFlag(e, BM_SEAM);}
 +              else                    {BM_ClearHFlag(e, BM_SEAM);}
 +              break;
 +      case EDGE_MODE_TAG_SHARP:
 +              if (val)                {BM_SetHFlag(e, BM_SEAM);}
 +              else                    {BM_ClearHFlag(e, BM_SEAM);}
 +              break;                          
 +      case EDGE_MODE_TAG_CREASE:
 +       {
 +              float *crease = CustomData_bmesh_get(&em->bm->edata, e->head.data, CD_CREASE);
 +              
 +              if (val)                {*crease = 1.0f;}
 +              else                    {*crease = 0.0f;}
 +              break;
 +       }
 +      case EDGE_MODE_TAG_BEVEL:
 +       {
 +              float *bweight = CustomData_bmesh_get(&em->bm->edata, e->head.data, CD_BWEIGHT);
 +
 +              if (val)                {*bweight = 1.0f;}
 +              else                    {*bweight = 0.0f;}
 +              break;
 +       }
 +      }
 +}
 +
 +static float bm_cdata_get_single_float(BMesh *UNUSED(bm), CustomData *cdata, void *element, int type)
 +{
 +      BMHeader *ele = element;
 +      float *f;
 +      
 +      if (!CustomData_has_layer(cdata, type))
 +              return 0.0f;
 +      
 +      f = CustomData_bmesh_get(cdata, ele->data, type);
 +      
 +      return *f;
 +}
 +
 +static int edgetag_context_check(Scene *scene, BMEditMesh *em, BMEdge *e)
 +{
 +      switch (scene->toolsettings->edge_mode) {
 +      case EDGE_MODE_SELECT:
 +              return BM_TestHFlag(e, BM_SELECT) ? 1 : 0;
 +      case EDGE_MODE_TAG_SEAM:
 +              return BM_TestHFlag(e, BM_SEAM);
 +      case EDGE_MODE_TAG_SHARP:
 +              return BM_TestHFlag(e, BM_SHARP);
 +      case EDGE_MODE_TAG_CREASE:      
 +              return bm_cdata_get_single_float(em->bm, &em->bm->edata, e, CD_CREASE) ? 1 : 0;
 +      case EDGE_MODE_TAG_BEVEL:
 +              return bm_cdata_get_single_float(em->bm, &em->bm->edata, e, CD_BWEIGHT) ? 1 : 0;
 +      }
 +      return 0;
 +}
 +
 +static int edgetag_shortest_path(Scene *scene, BMEditMesh *em, BMEdge *source, BMEdge *target)
 +{
 +      BMEdge *e;
 +      BMVert *v;
 +      BMIter iter;
 +      Heap *heap;
 +      SmallHash visithash;
 +      float *cost;
 +      int i, totvert=0, totedge=0, *nedges, *edges, *prevedge, mednum = -1, nedgeswap = 0;
 +      int targetnum;
 +
 +      BLI_smallhash_init(&visithash);
 +
 +      /* we need the vert */
 +      BM_ITER(v, &iter, em->bm, BM_VERTS_OF_MESH, NULL) {
 +              BM_SetIndex(v, totvert);
 +              totvert++;
 +      }
 +
 +      BM_ITER(e, &iter, em->bm, BM_EDGES_OF_MESH, NULL) {
 +              e->head.flags[0].f = 0;
 +              if (BM_TestHFlag(e, BM_HIDDEN)) {
 +                      BLI_smallhash_insert(&visithash, (uintptr_t)e, NULL);
 +              }
 +              BM_SetIndex(e, totedge);
 +              totedge++;
 +      }
 +
 +      /* alloc */
 +      nedges = MEM_callocN(sizeof(*nedges)*totvert+1, "SeamPathNEdges");
 +      edges = MEM_mallocN(sizeof(*edges)*totedge*2, "SeamPathEdges");
 +      prevedge = MEM_mallocN(sizeof(*prevedge)*totedge, "SeamPathPrevious");
 +      cost = MEM_mallocN(sizeof(*cost)*totedge, "SeamPathCost");
 +
 +      /* count edges, compute adjacent edges offsets and fill adjacent */
 +      BM_ITER(e, &iter, em->bm, BM_EDGES_OF_MESH, NULL) {
 +              nedges[BM_GetIndex(e->v1)+1]++;
 +              nedges[BM_GetIndex(e->v2)+1]++;
 +      }
 +
 +      for (i = 1; i < totvert; i++) {
 +              int newswap = nedges[i+1];
 +              nedges[i+1] = nedgeswap + nedges[i];
 +              nedgeswap = newswap;
 +      }
 +      nedges[0] = nedges[1] = 0;
 +
 +      i = 0;
 +      BM_ITER(e, &iter, em->bm, BM_EDGES_OF_MESH, NULL) {
 +              edges[nedges[BM_GetIndex(e->v1)+1]++] = i;
 +              edges[nedges[BM_GetIndex(e->v2)+1]++] = i;
 +
 +              cost[i] = 1e20f;
 +              prevedge[i] = -1;
 +              i++;
 +      }
 +
 +      /*
 +       * Arrays are now filled as follows:
 +       *
 +       *      nedges[n] = sum of the # of edges incident to all vertices numbered 0 thru n-1
 +       *      edges[edges[n]..edges[n-1]] = the indices of of the edges incident to vertex n
 +       *
 +       * As the search continues, prevedge[n] will be the previous edge on the shortest
 +       * path found so far to edge n. The visitedhash will of course contain entries
 +       * for edges that have been visited, cost[n] will contain the length of the shortest
 +       * path to edge n found so far, Finally, heap is a priority heap which is built on the
 +       * the same data as the cost arry, but inverted: it is a worklist of edges prioritized
 +       * by the shortest path found so far to the edge.
 +      */
 +
 +#if 0 /* UNUSED */ /* this block does nothing, not sure why its here? - campbell */
 +      for (i = 0; i < totvert; i++) {
 +              int start = nedges[i], end = nedges[i+1], cur;
 +              for (cur = start; cur < end; cur++) {
 +                      BMEdge* e = EDBM_get_edge_for_index(em, edges[cur]);
 +              }
 +      }
 +#endif
 +
 +      /* regular dijkstra shortest path, but over edges instead of vertices */
 +      heap = BLI_heap_new();
 +      BLI_heap_insert(heap, 0.0f, SET_INT_IN_POINTER(BM_GetIndex(source)));
 +      cost[BM_GetIndex(source)] = 0.0f;
 +      EDBM_init_index_arrays(em, 1, 1, 0);
 +      targetnum = BM_GetIndex(target);
 +
 +      while (!BLI_heap_empty(heap)) {
 +              mednum = GET_INT_FROM_POINTER(BLI_heap_popmin(heap));
 +              e = EDBM_get_edge_for_index(em, mednum);
 +
 +              if (mednum == targetnum)
 +                      break;
 +
 +              if (BLI_smallhash_haskey(&visithash, (uintptr_t)e))
 +                      continue;
 +
 +              BLI_smallhash_insert(&visithash, (uintptr_t)e, NULL);
 +
 +              edgetag_add_adjacent(em, &visithash, heap, mednum, BM_GetIndex(e->v1), nedges, edges, prevedge, cost);
 +              edgetag_add_adjacent(em, &visithash, heap, mednum, BM_GetIndex(e->v2), nedges, edges, prevedge, cost);
 +      }
 +      
 +      if (mednum == targetnum) {
 +              short allseams = 1;
 +
 +              /*Check whether the path is already completely tagged.
 +                if it is, the tags will be cleared instead of set.*/
 +              mednum = targetnum;
 +              do {
 +                      e = EDBM_get_edge_for_index(em, mednum);
 +                      if (!edgetag_context_check(scene, em, e)) {
 +                              allseams = 0;
 +                              break;
 +                      }
 +                      mednum = prevedge[mednum];
 +              } while (mednum != BM_GetIndex(source));
 +
 +              /*Follow path back and source and add or remove tags*/
 +              mednum = targetnum;
 +              do {
 +                      e = EDBM_get_edge_for_index(em, mednum);
 +                      if (allseams)
 +                              edgetag_context_set(em, scene, e, 0);
 +                      else
 +                              edgetag_context_set(em, scene, e, 1);
 +                      mednum = prevedge[mednum];
 +              } while (mednum != -1);
 +      }
 +
 +      EDBM_free_index_arrays(em);
 +      MEM_freeN(nedges);
 +      MEM_freeN(edges);
 +      MEM_freeN(prevedge);
 +      MEM_freeN(cost);
 +      BLI_heap_free(heap, NULL);
 +      BLI_smallhash_release(&visithash);
 +
 +      return 1;
 +}
 +
 +/* ******************* mesh shortest path select, uses prev-selected edge ****************** */
 +
 +/* since you want to create paths with multiple selects, it doesn't have extend option */
 +static void mouse_mesh_shortest_path(bContext *C, int mval[2])
 +{
 +      Object *ob = CTX_data_edit_object(C);
 +      ViewContext vc;
 +      BMEditMesh *em;
 +      BMEdge *e;
 +      int dist= 50;
 +      
 +      em_setup_viewcontext(C, &vc);
 +      vc.mval[0]= mval[0];
 +      vc.mval[1]= mval[1];
 +      em= vc.em;
 +      
 +      e= EDBM_findnearestedge(&vc, &dist);
 +      if(e) {
 +              Mesh *me= vc.obedit->data;
 +              int path = 0;
 +              
 +              if (em->bm->selected.last) {
 +                      EditSelection *ese = em->bm->selected.last;
 +                      
 +                      if(ese && ese->type == BM_EDGE) {
 +                              BMEdge *e_act;
 +                              e_act = (BMEdge*)ese->data;
 +                              if (e_act != e) {
 +                                      if (edgetag_shortest_path(vc.scene, em, e_act, e)) {
 +                                              EDBM_remove_selection(em, e_act);
 +                                              path = 1;
 +                                      }
 +                              }
 +                      }
 +              }
 +              if (path==0) {
 +                      int act = (edgetag_context_check(vc.scene, em, e)==0);
 +                      edgetag_context_set(em, vc.scene, e, act); /* switch the edge option */
 +              }
 +              
 +              EDBM_selectmode_flush(em);
 +
 +              /* even if this is selected it may not be in the selection list */
 +              if(edgetag_context_check(vc.scene, em, e)==0)
 +                      EDBM_remove_selection(em, e);
 +              else
 +                      EDBM_store_selection(em, e);
 +      
 +              /* force drawmode for mesh */
 +              switch (CTX_data_tool_settings(C)->edge_mode) {
 +                      
 +                      case EDGE_MODE_TAG_SEAM:
 +                              me->drawflag |= ME_DRAWSEAMS;
 +                              break;
 +                      case EDGE_MODE_TAG_SHARP:
 +                              me->drawflag |= ME_DRAWSHARP;
 +                              break;
 +                      case EDGE_MODE_TAG_CREASE:      
 +                              me->drawflag |= ME_DRAWCREASES;
 +                              break;
 +                      case EDGE_MODE_TAG_BEVEL:
 +                              me->drawflag |= ME_DRAWBWEIGHTS;
 +                              break;
 +              }
 +              
 +              DAG_id_tag_update(ob->data, OB_RECALC_DATA);
 +              WM_event_add_notifier(C, NC_GEOM|ND_SELECT, ob->data);
 +      }
 +}
 +
 +
 +static int mesh_shortest_path_select_invoke(bContext *C, wmOperator *UNUSED(op), wmEvent *event)
 +{
 +      
 +      view3d_operator_needs_opengl(C);
 +
 +      mouse_mesh_shortest_path(C, event->mval);
 +      
 +      return OPERATOR_FINISHED;
 +}
 +      
 +void MESH_OT_select_shortest_path(wmOperatorType *ot)
 +{
 +      /* identifiers */
 +      ot->name= "Shortest Path Select";
 +      ot->idname= "MESH_OT_select_shortest_path";
 +      
 +      /* api callbacks */
 +      ot->invoke= mesh_shortest_path_select_invoke;
 +      ot->poll= ED_operator_editmesh;
 +      ot->description= "Select shortest path between two selections.";
 +      
 +      /* flags */
 +      ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
 +      
 +      /* properties */
 +      RNA_def_boolean(ot->srna, "extend", 0, "Extend Select", "");
 +}
 +
 +/* ************************************************** */
 +/* here actual select happens */
 +/* gets called via generic mouse select operator */
 +int mouse_mesh(bContext *C, const int mval[2], short extend)
 +{
 +      ViewContext vc;
 +      BMVert *eve = NULL;
 +      BMEdge *eed = NULL;
 +      BMFace *efa = NULL;
 +      
 +      /* setup view context for argument to callbacks */
 +      em_setup_viewcontext(C, &vc);
 +      vc.mval[0]= mval[0];
 +      vc.mval[1]= mval[1];
 +      
 +      if(unified_findnearest(&vc, &eve, &eed, &efa)) {
 +              
 +              if(extend==0) EDBM_clear_flag_all(vc.em, BM_SELECT);
 +              
 +              if(efa) {
 +                      /* set the last selected face */
 +                      BM_set_actFace(vc.em->bm, efa);
 +                      
 +                      if(!BM_TestHFlag(efa, BM_SELECT)) {
 +                              EDBM_store_selection(vc.em, efa);
 +                              BM_Select(vc.em->bm, efa, 1);
 +                      }
 +                      else if(extend) {
 +                              EDBM_remove_selection(vc.em, efa);
 +                              BM_Select(vc.em->bm, efa, 0);
 +                      }
 +              }
 +              else if(eed) {
 +                      if(!BM_TestHFlag(eed, BM_SELECT)) {
 +                              EDBM_store_selection(vc.em, eed);
 +                              BM_Select(vc.em->bm, eed, 1);
 +                      }
 +                      else if(extend) {
 +                              EDBM_remove_selection(vc.em, eed);
 +                              BM_Select(vc.em->bm, eed, 0);
 +                      }
 +              }
 +              else if(eve) {
 +                      if(!BM_TestHFlag(eve, BM_SELECT)) {
 +                              EDBM_store_selection(vc.em, eve);
 +                              BM_Select(vc.em->bm, eve, 1);
 +                      }
 +                      else if(extend){ 
 +                              EDBM_remove_selection(vc.em, eve);
 +                              BM_Select(vc.em->bm, eve, 0);
 +                      }
 +              }
 +              
 +              EDBM_selectmode_flush(vc.em);
 +                
 +//            if (EM_texFaceCheck()) {
 +
 +              if (efa && efa->mat_nr != vc.obedit->actcol-1) {
 +                      vc.obedit->actcol= efa->mat_nr+1;
 +                      vc.em->mat_nr= efa->mat_nr;
 +//                    BIF_preview_changed(ID_MA);
 +              }
 +
 +              WM_event_add_notifier(C, NC_GEOM|ND_SELECT, vc.obedit);
 +              return 1;
 +      }
 +
 +      return 0;
 +}
 +
 +static void EDBM_strip_selections(BMEditMesh *em)
 +{
 +      BMEditSelection *ese, *nextese;
 +
 +      if(!(em->selectmode & SCE_SELECT_VERTEX)){
 +              ese = em->bm->selected.first;
 +              while(ese){
 +                      nextese = ese->next; 
 +                      if(ese->type == BM_VERT) BLI_freelinkN(&(em->bm->selected),ese);
 +                      ese = nextese;
 +              }
 +      }
 +      if(!(em->selectmode & SCE_SELECT_EDGE)){
 +              ese=em->bm->selected.first;
 +              while(ese){
 +                      nextese = ese->next;
 +                      if(ese->type == BM_EDGE) BLI_freelinkN(&(em->bm->selected), ese);
 +                      ese = nextese;
 +              }
 +      }
 +      if(!(em->selectmode & SCE_SELECT_FACE)){
 +              ese=em->bm->selected.first;
 +              while(ese){
 +                      nextese = ese->next;
 +                      if(ese->type == BM_FACE) BLI_freelinkN(&(em->bm->selected), ese);
 +                      ese = nextese;
 +              }
 +      }
 +}
 +
 +/* when switching select mode, makes sure selection is consistant for editing */
 +/* also for paranoia checks to make sure edge or face mode works */
 +void EDBM_selectmode_set(BMEditMesh *em)
 +{
 +      BMVert *eve;
 +      BMEdge *eed;
 +      BMFace *efa;
 +      BMIter iter;
 +      
 +      em->bm->selectmode = em->selectmode;
 +
 +      EDBM_strip_selections(em); /*strip BMEditSelections from em->selected that are not relevant to new mode*/
 +      
 +      if(em->selectmode & SCE_SELECT_VERTEX) {
 +              /*BMIter iter;
 +              
 +              eed = BMIter_New(&iter, em->bm, BM_EDGES_OF_MESH, NULL);
 +              for ( ; eed; eed=BMIter_Step(&iter)) BM_Select(em->bm, eed, 0);
 +              
 +              efa = BMIter_New(&iter, em->bm, BM_FACES_OF_MESH, NULL);
 +              for ( ; efa; efa=BMIter_Step(&iter)) BM_Select(em->bm, efa, 0);*/
 +
 +              EDBM_selectmode_flush(em);
 +      }
 +      else if(em->selectmode & SCE_SELECT_EDGE) {
 +              /* deselect vertices, and select again based on edge select */
 +              eve = BMIter_New(&iter, em->bm, BM_VERTS_OF_MESH, NULL);
 +              for ( ; eve; eve=BMIter_Step(&iter)) BM_Select(em->bm, eve, 0);
 +              
 +              eed = BMIter_New(&iter, em->bm, BM_EDGES_OF_MESH, NULL);
 +              for ( ; eed; eed=BMIter_Step(&iter)) {
 +                      if (BM_TestHFlag(eed, BM_SELECT))
 +                              BM_Select(em->bm, eed, 1);
 +              }
 +              
 +              /* selects faces based on edge status */
 +              EDBM_selectmode_flush(em);
 +      }
 +      else if(em->selectmode & SCE_SELECT_FACE) {
 +              /* deselect eges, and select again based on face select */
 +              eed = BMIter_New(&iter, em->bm, BM_EDGES_OF_MESH, NULL);
 +              for ( ; eed; eed=BMIter_Step(&iter)) BM_Select(em->bm, eed, 0);
 +              
 +              efa = BMIter_New(&iter, em->bm, BM_FACES_OF_MESH, NULL);
 +              for ( ; efa; efa=BMIter_Step(&iter)) {
 +                      if (BM_TestHFlag(efa, BM_SELECT))
 +                              BM_Select(em->bm, efa, 1);
 +              }
 +      }
 +}
 +
 +void EDBM_convertsel(BMEditMesh *em, short oldmode, short selectmode)
 +{
 +      BMEdge *eed;
 +      BMFace *efa;
 +      BMIter iter;
 +
 +      /*have to find out what the selectionmode was previously*/
 +      if(oldmode == SCE_SELECT_VERTEX) {
 +              if(selectmode == SCE_SELECT_EDGE) {
 +                      /*select all edges associated with every selected vertex*/
 +                      eed = BMIter_New(&iter, em->bm, BM_EDGES_OF_MESH, NULL);
 +                      for ( ; eed; eed=BMIter_Step(&iter)) {
 +                              if(BM_TestHFlag(eed->v1, BM_SELECT)) BM_Select(em->bm, eed, 1);
 +                              else if(BM_TestHFlag(eed->v2, BM_SELECT)) BM_Select(em->bm, eed, 1);
 +                      }
 +              }               
 +              else if(selectmode == SCE_SELECT_FACE) {
 +                      BMIter liter;
 +                      BMLoop *l;
 +
 +                      /*select all faces associated with every selected vertex*/
 +                      efa = BMIter_New(&iter, em->bm, BM_FACES_OF_MESH, NULL);
 +                      for ( ; efa; efa=BMIter_Step(&iter)) {
 +                              l = BMIter_New(&liter, em->bm, BM_LOOPS_OF_FACE, efa);
 +                              for (; l; l=BMIter_Step(&liter)) {
 +                                      if (BM_TestHFlag(l->v, BM_SELECT)) {
 +                                              BM_Select(em->bm, efa, 1);
 +                                              break;
 +                                      }
 +                              }
 +                      }
 +              }
 +      }
 +      
 +      if(oldmode == SCE_SELECT_EDGE){
 +              if(selectmode == SCE_SELECT_FACE) {
 +                      BMIter liter;
 +                      BMLoop *l;
 +
 +                      /*select all faces associated with every selected vertex*/
 +                      efa = BMIter_New(&iter, em->bm, BM_FACES_OF_MESH, NULL);
 +                      for ( ; efa; efa=BMIter_Step(&iter)) {
 +                              l = BMIter_New(&liter, em->bm, BM_LOOPS_OF_FACE, efa);
 +                              for (; l; l=BMIter_Step(&liter)) {
 +                                      if (BM_TestHFlag(l->v, BM_SELECT)) {
 +                                              BM_Select(em->bm, efa, 1);
 +                                              break;
 +                                      }
 +                              }
 +                      }
 +              }
 +      }
 +}
 +
 +
 +void EDBM_deselect_by_material(struct BMEditMesh *em, const short index, const short select)
 +{
 +      BMIter iter;
 +      BMFace *efa;
 +
 +      BM_ITER(efa, &iter, em->bm, BM_FACES_OF_MESH, NULL) {
 +              if (BM_TestHFlag(efa, BM_HIDDEN))
 +                      continue;
 +              if(efa->mat_nr == index) {
 +                      BM_Select(em->bm, efa, select);
 +              }
 +      }
 +}
 +
 +
 +void EDBM_select_swap(BMEditMesh *em) /* exported for UV */
 +{
 +      BMIter iter;
 +      BMVert *eve;
 +      BMEdge *eed;
 +      BMFace *efa;
 +      
 +      if(em->bm->selectmode & SCE_SELECT_VERTEX) {
 +              BM_ITER(eve, &iter, em->bm, BM_VERTS_OF_MESH, NULL) {
 +                      if (BM_TestHFlag(eve, BM_HIDDEN))
 +                              continue;
 +                      BM_Select(em->bm, eve, !BM_TestHFlag(eve, BM_SELECT));
 +              }
 +      }
 +      else if(em->selectmode & SCE_SELECT_EDGE) {
 +              BM_ITER(eed, &iter, em->bm, BM_EDGES_OF_MESH, NULL) {
 +                      if (BM_TestHFlag(eed, BM_HIDDEN))
 +                              continue;
 +                      BM_Select(em->bm, eed, !BM_TestHFlag(eed, BM_SELECT));
 +              }
 +      }
 +      else {
 +              BM_ITER(efa, &iter, em->bm, BM_FACES_OF_MESH, NULL) {
 +                      if (BM_TestHFlag(efa, BM_HIDDEN))
 +                              continue;
 +                      BM_Select(em->bm, efa, !BM_TestHFlag(efa, BM_SELECT));
 +              }
 +
 +      }
 +//    if (EM_texFaceCheck())
 +}
 +
 +static int select_inverse_mesh_exec(bContext *C, wmOperator *UNUSED(op))
 +{
 +      Object *obedit= CTX_data_edit_object(C);
 +      BMEditMesh *em= ((Mesh *)obedit->data)->edit_btmesh;
 +      
 +      EDBM_select_swap(em);
 +      
 +      WM_event_add_notifier(C, NC_GEOM|ND_SELECT, obedit);
 +
 +      return OPERATOR_FINISHED;       
 +}
 +
 +void MESH_OT_select_inverse(wmOperatorType *ot)
 +{
 +      /* identifiers */
 +      ot->name= "Select Inverse";
 +      ot->idname= "MESH_OT_select_inverse";
 +      ot->description= "Select inverse of (un)selected vertices, edges or faces.";
 +      
 +      /* api callbacks */
 +      ot->exec= select_inverse_mesh_exec;
 +      ot->poll= ED_operator_editmesh;
 +      
 +      /* flags */
 +      ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
 +}
 +
 +
 +static int select_linked_pick_invoke(bContext *C, wmOperator *op, wmEvent *event)
 +{
 +      Object *obedit= CTX_data_edit_object(C);
 +      ViewContext vc;
 +      BMWalker walker;
 +      BMEditMesh *em;
 +      BMVert *eve;
 +      BMEdge *e, *eed;
 +      BMFace *efa;
 +      int sel= !RNA_boolean_get(op->ptr, "deselect");
 +      
 +      /* unified_finednearest needs ogl */
 +      view3d_operator_needs_opengl(C);
 +      
 +      /* setup view context for argument to callbacks */
 +      em_setup_viewcontext(C, &vc);
 +      em = vc.em;
 +
 +      if(vc.em->bm->totedge==0)
 +              return OPERATOR_CANCELLED;
 +      
 +      vc.mval[0]= event->mval[0];
 +      vc.mval[1]= event->mval[1];
 +      
 +      /* return warning! */
 +
 +      /*if(limit) {
 +              int retval= select_linked_limited_invoke(&vc, 0, sel);
 +              WM_event_add_notifier(C, NC_GEOM|ND_SELECT, obedit);
 +              return retval;
 +      }*/
 +      
 +      if( unified_findnearest(&vc, &eve, &eed, &efa)==0 ) {
 +              WM_event_add_notifier(C, NC_GEOM|ND_SELECT, obedit);
 +      
 +              return OPERATOR_CANCELLED;
 +      }
 +      
 +      if (efa) {
 +              eed = bm_firstfaceloop(efa)->e;
 +      } else if (!eed) {
 +              if (!eve || !eve->e)
 +                      return OPERATOR_CANCELLED;
 +              
 +              eed = eve->e;
 +      }
 +
 +      BMW_Init(&walker, em->bm, BMW_SHELL, 0, 0);
 +      e = BMW_Begin(&walker, eed->v1);
 +      for (; e; e=BMW_Step(&walker)) {
 +                      BM_Select(em->bm, e->v1, sel);
 +                      BM_Select(em->bm, e->v2, sel);
 +      }
 +      BMW_End(&walker);
 +      EDBM_select_flush(em, SCE_SELECT_VERTEX);
 +
 +      WM_event_add_notifier(C, NC_GEOM|ND_SELECT, obedit);
 +      return OPERATOR_FINISHED;       
 +}
 +
 +void MESH_OT_select_linked_pick(wmOperatorType *ot)
 +{
 +      /* identifiers */
 +      ot->name= "Select Linked";
 +      ot->idname= "MESH_OT_select_linked_pick";
 +      
 +      /* api callbacks */
 +      ot->invoke= select_linked_pick_invoke;
 +      ot->poll= ED_operator_editmesh;
 +      ot->description= "select/deselect all vertices linked to the edge under the mouse cursor.";
 +      
 +      /* flags */
 +      ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
 +      
 +      RNA_def_boolean(ot->srna, "deselect", 0, "Deselect", "");
 +      RNA_def_boolean(ot->srna, "limit", 0, "Limit by Seams", "");
 +}
 +
 +
 +static int select_linked_exec(bContext *C, wmOperator *UNUSED(op))
 +{
 +      Object *obedit= CTX_data_edit_object(C);
 +      BMEditMesh *em= ((Mesh*)obedit->data)->edit_btmesh;
 +      BLI_array_declare(verts);
 +      BMVert **verts = NULL;
 +      BMIter iter;
 +      BMVert *v;
 +      BMEdge *e;
 +      BMWalker walker;
 +      int i, tot;
 +
 +      tot = 0;
 +      BM_ITER(v, &iter, em->bm, BM_VERTS_OF_MESH, NULL) {
 +              if (BM_TestHFlag(v, BM_SELECT) && !BM_TestHFlag(v, BM_HIDDEN)) {
 +                      BLI_array_growone(verts);
 +                      verts[tot++] = v;
 +              }
 +      }
 +
 +      BMW_Init(&walker, em->bm, BMW_SHELL, 0, 0);
 +      for (i=0; i<tot; i++) {
 +              e = BMW_Begin(&walker, verts[i]);
 +              for (; e; e=BMW_Step(&walker)) {
 +                      BM_Select(em->bm, e->v1, 1);
 +                      BM_Select(em->bm, e->v2, 1);
 +              }
 +      }
 +      BMW_End(&walker);
 +      EDBM_select_flush(em, SCE_SELECT_VERTEX);
 +
 +      BLI_array_free(verts);
 +      WM_event_add_notifier(C, NC_GEOM|ND_SELECT, obedit);
 +
 +      return OPERATOR_FINISHED;       
 +}
 +
 +void MESH_OT_select_linked(wmOperatorType *ot)
 +{
 +      /* identifiers */
 +      ot->name= "Select Linked All";
 +      ot->idname= "MESH_OT_select_linked";
 +      
 +      /* api callbacks */
 +      ot->exec= select_linked_exec;
 +      ot->poll= ED_operator_editmesh;
 +      ot->description= "Select all vertices linked to the active mesh.";
 +      
 +      /* flags */
 +      ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
 +      
 +      RNA_def_boolean(ot->srna, "limit", 0, "Limit by Seams", "");
 +}
 +
 +/* ******************** **************** */
 +
 +static int select_more(bContext *C, wmOperator *op)
 +{
 +      Object *obedit= CTX_data_edit_object(C);
 +      BMEditMesh *em= (((Mesh *)obedit->data))->edit_btmesh;
 +      BMOperator bmop;
 +      int usefaces = em->selectmode > SCE_SELECT_EDGE;
 +
 +      EDBM_InitOpf(em, &bmop, op, "regionextend geom=%hvef constrict=%d usefaces=%d", 
 +                   BM_SELECT, 0, usefaces);
 +
 +      BMO_Exec_Op(em->bm, &bmop);
 +      BMO_HeaderFlag_Buffer(em->bm, &bmop, "geomout", BM_SELECT, BM_ALL);
 +
 +      EDBM_selectmode_flush(em);
 +
 +      if (!EDBM_FinishOp(em, &bmop, op, 1))
 +              return OPERATOR_CANCELLED;
 +
 +      WM_event_add_notifier(C, NC_GEOM|ND_SELECT, obedit);
 +      return OPERATOR_FINISHED;
 +}
 +
 +void MESH_OT_select_more(wmOperatorType *ot)
 +{
 +      /* identifiers */
 +      ot->name= "Select More";
 +      ot->idname= "MESH_OT_select_more";
 +      ot->description= "Select more vertices, edges or faces connected to initial selection.";
 +
 +      /* api callbacks */
 +      ot->exec= select_more;
 +      ot->poll= ED_operator_editmesh;
 +      
 +      /* flags */
 +      ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
 +}
 +
 +static int select_less(bContext *C, wmOperator *op)
 +{
 +      Object *obedit= CTX_data_edit_object(C);
 +      BMEditMesh *em= (((Mesh *)obedit->data))->edit_btmesh;
 +      BMOperator bmop;
 +      int usefaces = em->selectmode > SCE_SELECT_EDGE;
 +
 +      EDBM_InitOpf(em, &bmop, op, "regionextend geom=%hvef constrict=%d usefaces=%d", 
 +                   BM_SELECT, 1, usefaces);
 +
 +      BMO_Exec_Op(em->bm, &bmop);
 +      BMO_UnHeaderFlag_Buffer(em->bm, &bmop, "geomout", BM_SELECT, BM_ALL);
 +
 +      EDBM_selectmode_flush(em);
 +
 +      if (!EDBM_FinishOp(em, &bmop, op, 1))
 +              return OPERATOR_CANCELLED;
 +
 +      WM_event_add_notifier(C, NC_GEOM|ND_SELECT, obedit);
 +      return OPERATOR_FINISHED;
 +}
 +
 +void MESH_OT_select_less(wmOperatorType *ot)
 +{
 +      /* identifiers */
 +      ot->name= "Select Less";
 +      ot->idname= "MESH_OT_select_less";
 +      ot->description= "Deselect vertices, edges or faces at the boundary of each selection region.";
 +
 +      /* api callbacks */
 +      ot->exec= select_less;
 +      ot->poll= ED_operator_editmesh;
 +      
 +      /* flags */
 +      ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
 +}
 +
 +/* not that optimal!, should be nicer with bmesh */
 +static void tag_face_edges(BMesh* bm, BMFace *f)
 +{
 +      BMLoop *l;
 +      BMIter iter;
 +
 +      BM_ITER(l, &iter, bm, BM_LOOPS_OF_FACE, f) {
 +              BM_SetIndex(l->e, 1);
 +      }
 +}
 +static int tag_face_edges_test(BMesh* bm, BMFace *f)
 +{
 +      BMLoop *l;
 +      BMIter iter;
 +
 +      BM_ITER(l, &iter, bm, BM_LOOPS_OF_FACE, f) {
 +              if(BM_GetIndex(l->e) != 0)
 +                      return 1;
 +      }
 +
 +      return 0;
 +}
 +
 +static void em_deselect_nth_face(BMEditMesh *em, int nth, BMFace *f_act)
 +{
 +      BMFace *f;
 +      BMEdge *e;
 +      BMIter iter;
 +      BMesh *bm = em->bm;
 +      int index;
 +      int ok= 1;
 +
 +      if(f_act==NULL) {
 +              return;
 +      }
 +
 +      /* to detect loose edges, we put f2 flag on 1 */
 +      BM_ITER(e, &iter, bm, BM_EDGES_OF_MESH, NULL) {
 +              BM_SetIndex(e, 0);
 +      }
 +
 +      BM_ITER(f, &iter, bm, BM_FACES_OF_MESH, NULL) {
 +              BM_SetIndex(f, 0);
 +      }
 +
 +      BM_SetIndex(f_act, 1);
 +
 +      while(ok) {
 +              ok = 0;
 +
 +              BM_ITER(f, &iter, bm, BM_FACES_OF_MESH, NULL) {
 +                      index= BM_GetIndex(f);
 +                      if(index==1) { /* initialize */
 +                              tag_face_edges(bm, f);
 +                      }
 +
 +                      if (index)
 +                              BM_SetIndex(f, index+1);
 +              }
 +
 +              BM_ITER(f, &iter, bm, BM_FACES_OF_MESH, NULL) {
 +                      if(BM_GetIndex(f)==0 && tag_face_edges_test(bm, f)) {
 +                              BM_SetIndex(f, 1);
 +                              ok= 1; /* keep looping */
 +                      }
 +              }
 +      }
 +
 +      BM_ITER(f, &iter, bm, BM_FACES_OF_MESH, NULL) {
 +              index= BM_GetIndex(f);
 +              if(index > 0 && index % nth) {
 +                      BM_Select(bm, f, 0);
 +              }
 +      }
 +
 +      EDBM_select_flush(em, SCE_SELECT_FACE);
 +}
 +
 +/* not that optimal!, should be nicer with bmesh */
 +static void tag_edge_verts(BMEdge *e)
 +{
 +      BM_SetIndex(e->v1, 1);
 +      BM_SetIndex(e->v2, 1);
 +}
 +static int tag_edge_verts_test(BMEdge *e)
 +{
 +      return (BM_GetIndex(e->v1) || BM_GetIndex(e->v2)) ? 1:0;
 +}
 +
 +static void em_deselect_nth_edge(BMEditMesh *em, int nth, BMEdge *e_act)
 +{
 +      BMEdge *e;
 +      BMVert *v;
 +      BMIter iter;
 +      BMesh *bm = em->bm;
 +      int index;
 +      int ok= 1;
 +
 +      if(e_act==NULL) {
 +              return;
 +      }
 +
 +      BM_ITER(v, &iter, bm, BM_VERTS_OF_MESH, NULL) {
 +              BM_SetIndex(v, 0);
 +      }
 +
 +      BM_ITER(e, &iter, bm, BM_EDGES_OF_MESH, NULL) {
 +              BM_SetIndex(e, 0);
 +      }
 +
 +      BM_SetIndex(e_act, 1);
 +
 +      while(ok) {
 +              ok = 0;
 +
 +              BM_ITER(e, &iter, bm, BM_EDGES_OF_MESH, NULL) {
 +                      index= BM_GetIndex(e);
 +                      if (index==1) { /* initialize */
 +                              tag_edge_verts(e);
 +                      }
 +
 +                      if (index)
 +                              BM_SetIndex(e, index+1);
 +              }
 +
 +              BM_ITER(e, &iter, bm, BM_EDGES_OF_MESH, NULL) {
 +                      if (BM_GetIndex(e)==0 && tag_edge_verts_test(e)) {
 +                              BM_SetIndex(e, 1);
 +                              ok = 1; /* keep looping */
 +                      }
 +              }
 +      }
 +
 +      BM_ITER(e, &iter, bm, BM_EDGES_OF_MESH, NULL) {
 +              index= BM_GetIndex(e);
 +              if (index > 0 && index % nth)
 +                      BM_Select(bm, e, 0);
 +      }
 +
 +      EDBM_select_flush(em, SCE_SELECT_EDGE);
 +}
 +
 +static void em_deselect_nth_vert(BMEditMesh *em, int nth, BMVert *v_act)
 +{
 +      BMEdge *e;
 +      BMVert *v;
 +      BMIter iter;
 +      BMesh *bm = em->bm;
 +      int ok= 1;
 +
 +      if(v_act==NULL) {
 +              return;
 +      }
 +
 +      BM_ITER(v, &iter, bm, BM_VERTS_OF_MESH, NULL) {
 +              BM_SetIndex(v, 0);
 +      }
 +      
 +      BM_SetIndex(v_act, 1);
 +
 +      while(ok) {
 +              ok = 0;
 +
 +              BM_ITER(v, &iter, bm, BM_VERTS_OF_MESH, NULL) {
 +                      int index = BM_GetIndex(v);
 +                      if (index != 0)
 +                              BM_SetIndex(v, index+1);
 +              }
 +
 +              BM_ITER(e, &iter, bm, BM_EDGES_OF_MESH, NULL) {
 +                      int indexv1= BM_GetIndex(e->v1);
 +                      int indexv2= BM_GetIndex(e->v2);
 +                      if (indexv1 == 2 && indexv2 == 0) {
 +                              BM_SetIndex(e->v2, 1);
 +                              ok = 1; /* keep looping */
 +                      }
 +                      else if (indexv2 == 2 && indexv1 == 0) {
 +                              BM_SetIndex(e->v1, 1);
 +                              ok = 1; /* keep looping */
 +                      }
 +              }
 +      }
 +
 +      BM_ITER(v, &iter, bm, BM_VERTS_OF_MESH, NULL) {
 +              int index= BM_GetIndex(v);
 +              if(index && index % nth) {
 +                      BM_Select(bm, v, 0);
 +              }
 +      }
 +
 +      EDBM_select_flush(em, SCE_SELECT_VERTEX);
 +}
 +
 +static void deselect_nth_active(BMEditMesh *em, BMVert **v_p, BMEdge **e_p, BMFace **f_p)
 +{
 +      BMVert *v;
 +      BMEdge *e;
 +      BMFace *f;
 +      BMIter iter;
 +      BMEditSelection *ese;
 +
 +      *v_p= NULL;
 +      *e_p= NULL;
 +      *f_p= NULL;
 +
 +      EDBM_selectmode_flush(em);
 +      ese= (BMEditSelection*)em->bm->selected.last;
 +
 +      if(ese) {
 +              switch(ese->type) {
 +              case BM_VERT:
 +                      *v_p= (BMVert *)ese->data;
 +                      return;
 +              case BM_EDGE:
 +                      *e_p= (BMEdge *)ese->data;
 +                      return;
 +              case BM_FACE:
 +                      *f_p= (BMFace *)ese->data;
 +                      return;
 +              }
 +      }
 +
 +      if(em->selectmode & SCE_SELECT_VERTEX) {
 +              BM_ITER(v, &iter, em->bm, BM_VERTS_OF_MESH, NULL) {
 +                      if (BM_TestHFlag(v, BM_SELECT)) {
 +                              *v_p = v;
 +                              return;
 +                      }
 +              }
 +      }
 +      else if(em->selectmode & SCE_SELECT_EDGE) {
 +              BM_ITER(e, &iter, em->bm, BM_EDGES_OF_MESH, NULL) {
 +                      if (BM_TestHFlag(e, BM_SELECT)) {
 +                              *e_p = e;
 +                              return;
 +                      }
 +              }
 +      }
 +      else if(em->selectmode & SCE_SELECT_FACE) {
 +              f= BM_get_actFace(em->bm, 1);
 +              if(f) {
 +                      *f_p= f;
 +                      return;
 +              }
 +      }
 +}
 +
 +static int EM_deselect_nth(BMEditMesh *em, int nth)
 +{
 +      BMVert *v;
 +      BMEdge *e;
 +      BMFace *f;
 +
 +      deselect_nth_active(em, &v, &e, &f);
 +
 +      if(v) {
 +              em_deselect_nth_vert(em, nth, v);
 +              return 1;
 +      }
 +      else if(e) {
 +              em_deselect_nth_edge(em, nth, e);
 +              return 1;
 +      }
 +      else if(f) {
 +              em_deselect_nth_face(em, nth, f);
 +              return 1;
 +      }
 +
 +      return 0;
 +}
 +
 +static int mesh_select_nth_exec(bContext *C, wmOperator *op)
 +{
 +      Object *obedit= CTX_data_edit_object(C);
 +      BMEditMesh *em= ((Mesh *)obedit->data)->edit_btmesh;
 +      int nth= RNA_int_get(op->ptr, "nth");
 +
 +      if(EM_deselect_nth(em, nth) == 0) {
 +              BKE_report(op->reports, RPT_ERROR, "Mesh has no active vert/edge/face.");
 +              return OPERATOR_CANCELLED;
 +      }
 +
 +      DAG_id_tag_update(obedit->data, OB_RECALC_DATA);
 +      WM_event_add_notifier(C, NC_GEOM|ND_DATA, obedit->data);
 +
 +      return OPERATOR_FINISHED;
 +}
 +
 +
 +void MESH_OT_select_nth(wmOperatorType *ot)
 +{
 +      /* identifiers */
 +      ot->name= "Select Nth";
 +      ot->description= "";
 +      ot->idname= "MESH_OT_select_nth";
 +
 +      /* api callbacks */
 +      ot->exec= mesh_select_nth_exec;
 +      ot->poll= ED_operator_editmesh;
 +
 +      /* flags */
 +      ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
 +
 +      RNA_def_int(ot->srna, "nth", 2, 2, 100, "Nth Selection", "", 1, INT_MAX);
 +}
 +
 +void em_setup_viewcontext(bContext *C, ViewContext *vc)
 +{
 +      view3d_set_viewcontext(C, vc);
 +      
 +      if(vc->obedit) {
 +              Mesh *me= vc->obedit->data;
 +              vc->em= me->edit_btmesh;
 +      }
 +}
 +
 +/* poll call for mesh operators requiring a view3d context */
 +int EM_view3d_poll(bContext *C)
 +{
 +      if(ED_operator_editmesh(C) && ED_operator_view3d_active(C))
 +              return 1;
 +      return 0;
 +}
 +
 +
 +static int select_sharp_edges_exec(bContext *C, wmOperator *op)
 +{
 +      /* Find edges that have exactly two neighboring faces,
 +      * check the angle between those faces, and if angle is
 +      * small enough, select the edge
 +      */
 +      Object *obedit= CTX_data_edit_object(C);
 +      BMEditMesh *em= ((Mesh *)obedit->data)->edit_btmesh;
 +      BMIter iter;
 +      BMEdge *e;
 +      BMLoop *l1, *l2;
 +      float sharp = RNA_float_get(op->ptr, "sharpness"), angle;
 +
 +      sharp = DEG2RADF(sharp);
 +
 +      BM_ITER(e, &iter, em->bm, BM_EDGES_OF_MESH, NULL) {
 +              if (BM_TestHFlag(e, BM_HIDDEN) || !e->l)
 +                      continue;
 +
 +              l1 = e->l;
 +              l2 = l1->radial_next;
 +
 +              if (l1 == l2)
 +                      continue;
 +
 +              /* edge has exactly two neighboring faces, check angle */
 +              angle = saacos(l1->f->no[0]*l2->f->no[0]+l1->f->no[1]*l2->f->no[1]+l1->f->no[2]*l2->f->no[2]);
 +
 +              if (fabsf(angle) < sharp) {
 +                      BM_Select(em->bm, e, 1);
 +              }
 +
 +      }
 +
 +      WM_event_add_notifier(C, NC_GEOM|ND_SELECT, obedit->data);
 +
 +      return OPERATOR_FINISHED;
 +}
 +
 +void MESH_OT_edges_select_sharp(wmOperatorType *ot)
 +{
 +      /* identifiers */
 +      ot->name= "Select Sharp Edges";
 +      ot->description= "Marked selected edges as sharp.";
 +      ot->idname= "MESH_OT_edges_select_sharp";
 +      
 +      /* api callbacks */
 +      ot->exec= select_sharp_edges_exec;
 +      ot->poll= ED_operator_editmesh;
 +      
 +      /* flags */
 +      ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
 +      
 +      /* props */
 +      RNA_def_float(ot->srna, "sharpness", 1.0f, 0.01f, FLT_MAX, "sharpness", "", 1.0f, 180.0f);
 +}
 +
 +static int select_linked_flat_faces_exec(bContext *C, wmOperator *op)
 +{
 +      Object *obedit= CTX_data_edit_object(C);
 +      BMEditMesh *em= ((Mesh *)obedit->data)->edit_btmesh;
 +      BMIter iter, liter, liter2;
 +      BMFace *f, **stack = NULL;
 +      BLI_array_declare(stack);
 +      BMLoop *l, *l2;
 +      float sharp = RNA_float_get(op->ptr, "sharpness");
 +      int i;
 +
 +      sharp = (sharp * M_PI) / 180.0;
 +
 +      BM_ITER(f, &iter, em->bm, BM_FACES_OF_MESH, NULL) {
 +              BM_SetIndex(f, 0);
 +      }
 +
 +      BM_ITER(f, &iter, em->bm, BM_FACES_OF_MESH, NULL) {
 +              if (BM_TestHFlag(f, BM_HIDDEN) || !BM_TestHFlag(f, BM_SELECT) || BM_GetIndex(f))
 +                      continue;
 +
 +              BLI_array_empty(stack);
 +              i = 1;
 +
 +              BLI_array_growone(stack);
 +              stack[i-1] = f;
 +
 +              while (i) {
 +                      f = stack[i-1];
 +                      i--;
 +
 +                      BM_Select(em->bm, f, 1);
 +
 +                      BM_SetIndex(f, 1);
 +
 +                      BM_ITER(l, &liter, em->bm, BM_LOOPS_OF_FACE, f) {
 +                              BM_ITER(l2, &liter2, em->bm, BM_LOOPS_OF_LOOP, l) {
 +                                      float angle;
 +
 +                                      if (BM_GetIndex(l2->f) || BM_TestHFlag(l2->f, BM_HIDDEN))
 +                                              continue;
 +
 +                                      /* edge has exactly two neighboring faces, check angle */
 +                                      angle = saacos(f->no[0]*l2->f->no[0]+f->no[1]*l2->f->no[1]+f->no[2]*l2->f->no[2]);
 +
 +                                      /* invalidate: edge too sharp */
 +                                      if (fabs(angle) < sharp) {
 +                                              BLI_array_growone(stack);
 +                                              stack[i] = l2->f;
 +                                              i++;
 +                                      }
 +                              }
 +                      }
 +              }
 +      }
 +
 +      BLI_array_free(stack);
 +
 +      WM_event_add_notifier(C, NC_GEOM|ND_SELECT, obedit->data);
 +
 +      return OPERATOR_FINISHED;
 +}
 +
 +void MESH_OT_faces_select_linked_flat(wmOperatorType *ot)
 +{
 +      /* identifiers */
 +      ot->name= "Select Linked Flat Faces";
 +      ot->description= "Select linked faces by angle.";
 +      ot->idname= "MESH_OT_faces_select_linked_flat";
 +      
 +      /* api callbacks */
 +      ot->exec= select_linked_flat_faces_exec;
 +      ot->poll= ED_operator_editmesh;
 +      
 +      /* flags */
 +      ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
 +      
 +      /* props */
 +      RNA_def_float(ot->srna, "sharpness", 1.0f, 0.01f, FLT_MAX, "sharpness", "", 1.0f, 180.0f);
 +}
 +
 +static int select_non_manifold_exec(bContext *C, wmOperator *op)
 +{
 +      Object *obedit= CTX_data_edit_object(C);
 +      BMEditMesh *em= ((Mesh *)obedit->data)->edit_btmesh;
 +      BMVert *v;
 +      BMEdge *e;
 +      BMIter iter;
 +
 +      /* Selects isolated verts, and edges that do not have 2 neighboring
 +       * faces
 +       */
 +      
 +      if(em->selectmode==SCE_SELECT_FACE) {
 +              BKE_report(op->reports, RPT_ERROR, "Doesn't work in face selection mode");
 +              return OPERATOR_CANCELLED;
 +      }
 +      
 +      BM_ITER(v, &iter, em->bm, BM_VERTS_OF_MESH, NULL) {
 +              if (!BM_TestHFlag(em->bm, BM_HIDDEN) && BM_Nonmanifold_Vert(em->bm, v))
 +                      BM_Select(em->bm, v, 1);
 +      }
 +      
 +      BM_ITER(e, &iter, em->bm, BM_EDGES_OF_MESH, NULL) {
 +              if (!BM_TestHFlag(em->bm, BM_HIDDEN) && BM_Edge_FaceCount(e) != 2)
 +                      BM_Select(em->bm, e, 1);
 +      }
 +
 +      WM_event_add_notifier(C, NC_GEOM|ND_SELECT, obedit->data);
 +
 +      return OPERATOR_FINISHED;       
 +}
 +
 +void MESH_OT_select_non_manifold(wmOperatorType *ot)
 +{
 +      /* identifiers */
 +      ot->name= "Select Non Manifold";
 +      ot->description= "Select all non-manifold vertices or edges.";
 +      ot->idname= "MESH_OT_select_non_manifold";
 +      
 +      /* api callbacks */
 +      ot->exec= select_non_manifold_exec;
 +      ot->poll= ED_operator_editmesh;
 +      
 +      /* flags */
 +      ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
 +}
 +
 +static int mesh_select_random_exec(bContext *C, wmOperator *op)
 +{
 +      Object *obedit= CTX_data_edit_object(C);
 +      BMEditMesh *em= ((Mesh *)obedit->data)->edit_btmesh;
 +      BMVert *eve;
 +      BMEdge *eed;
 +      BMFace *efa;
 +      BMIter iter;
 +      float randfac =  RNA_float_get(op->ptr, "percent")/100.0f;
 +
 +      BLI_srand( BLI_rand() ); /* random seed */
 +      
 +      if(!RNA_boolean_get(op->ptr, "extend"))
 +              EDBM_clear_flag_all(em, BM_SELECT);
 +
 +      if(em->selectmode & SCE_SELECT_VERTEX) {
 +              BM_ITER(eve, &iter, em->bm, BM_VERTS_OF_MESH, NULL) {
 +                      if (!BM_TestHFlag(eve, BM_HIDDEN) && BLI_frand() < randfac)
 +                              BM_Select(em->bm, eve, 1);
 +              }
 +              EDBM_selectmode_flush(em);
 +      }
 +      else if(em->selectmode & SCE_SELECT_EDGE) {
 +              BM_ITER(eed, &iter, em->bm, BM_EDGES_OF_MESH, NULL) {
 +                      if (!BM_TestHFlag(eed, BM_HIDDEN) && BLI_frand() < randfac)
 +                              BM_Select(em->bm, eed, 1);
 +              }
 +              EDBM_selectmode_flush(em);
 +      }
 +      else {
 +              BM_ITER(efa, &iter, em->bm, BM_FACES_OF_MESH, NULL) {
 +                      if (!BM_TestHFlag(efa, BM_HIDDEN) && BLI_frand() < randfac)
 +                              BM_Select(em->bm, efa, 1);
 +              }
 +              EDBM_selectmode_flush(em);
 +      }
 +      
 +      WM_event_add_notifier(C, NC_GEOM|ND_SELECT, obedit->data);
 +      
 +      return OPERATOR_FINISHED;       
 +}
 +
 +void MESH_OT_select_random(wmOperatorType *ot)
 +{
 +      /* identifiers */
 +      ot->name= "Select Random";
 +      ot->description= "Randomly select vertices.";
 +      ot->idname= "MESH_OT_select_random";
 +
 +      /* api callbacks */
 +      ot->exec= mesh_select_random_exec;
 +      ot->poll= ED_operator_editmesh;
 +
 +      /* flags */
 +      ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
 +      
 +      /* props */
 +      RNA_def_float_percentage(ot->srna, "percent", 50.f, 0.0f, 100.0f, "Percent", "Percentage of elements to select randomly.", 0.f, 100.0f);
 +      RNA_def_boolean(ot->srna, "extend", 0, "Extend Selection", "Extend selection instead of deselecting everything first.");
 +}
 +
 +static int select_next_loop(bContext *C, wmOperator *UNUSED(op))
 +{
 +      Object *obedit= CTX_data_edit_object(C);
 +      BMEditMesh *em= (((Mesh *)obedit->data))->edit_btmesh;
 +      BMFace *f;
 +      BMVert *v;
 +      BMIter iter;
 +      
 +      BM_ITER(v, &iter, em->bm, BM_VERTS_OF_MESH, NULL) {
 +              BM_SetIndex(v, 0);
 +      }
 +      
 +      BM_ITER(f, &iter, em->bm, BM_FACES_OF_MESH, NULL) {
 +              BMLoop *l;
 +              BMIter liter;
 +              
 +              BM_ITER(l, &liter, em->bm, BM_LOOPS_OF_FACE, f) {
 +                      if (BM_TestHFlag(l->v, BM_SELECT) && !BM_TestHFlag(l->v, BM_HIDDEN)) {
 +                              BM_SetIndex(l->next->v, 1);
 +                              BM_Select(em->bm, l->v, 0);
 +                      }
 +              }
 +      }
 +
 +      BM_ITER(v, &iter, em->bm, BM_VERTS_OF_MESH, NULL) {
 +              if (BM_GetIndex(v)) {
 +                      BM_Select(em->bm, v, 1);
 +              }
 +      }
 +
 +      WM_event_add_notifier(C, NC_GEOM|ND_SELECT, obedit);
 +      return OPERATOR_FINISHED;
 +}
 +
 +void MESH_OT_select_next_loop(wmOperatorType *ot)
 +{
 +      /* identifiers */
 +      ot->name= "Select Next Loop";
 +      ot->idname= "MESH_OT_select_next_loop";
 +      ot->description= "";
 +
 +      /* api callbacks */
 +      ot->exec= select_next_loop;
 +      ot->poll= ED_operator_editmesh;
 +      
 +      /* flags */
 +      ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
 +}
 +
 +
 +static int region_to_loop(bContext *C, wmOperator *UNUSED(op))
 +{
 +      Object *obedit = CTX_data_edit_object(C);
 +      BMEditMesh *em = ((Mesh*)obedit->data)->edit_btmesh;
 +      BMFace *f;
 +      BMEdge *e;
 +      BMIter iter;
 +      
 +      BM_ITER(e, &iter, em->bm, BM_EDGES_OF_MESH, NULL) {
 +              BM_SetIndex(e, 0);
 +      }
 +
 +      BM_ITER(f, &iter, em->bm, BM_FACES_OF_MESH, NULL) {
 +              BMLoop *l1, *l2;
 +              BMIter liter1, liter2;
 +              
 +              BM_ITER(l1, &liter1, em->bm, BM_LOOPS_OF_FACE, f) {
 +                      int tot=0, totsel=0;
 +                      
 +                      BM_ITER(l2, &liter2, em->bm, BM_LOOPS_OF_EDGE, l1->e) {
 +                              tot++;
 +                              totsel += BM_TestHFlag(l2->f, BM_SELECT) != 0;
 +                      }
 +                      
 +                      if ((tot != totsel && totsel > 0) || (totsel == 1 && tot == 1))
 +                              BM_SetIndex(l1->e, 1);
 +              }
 +      }
 +
 +      EDBM_clear_flag_all(em, BM_SELECT);
 +      
 +      BM_ITER(e, &iter, em->bm, BM_EDGES_OF_MESH, NULL) {
 +              if (BM_GetIndex(e) && !BM_TestHFlag(e, BM_HIDDEN))
 +                      BM_Select_Edge(em->bm, e, 1);
 +      }
 +      
 +      WM_event_add_notifier(C, NC_GEOM|ND_SELECT, obedit->data);
 +      return OPERATOR_FINISHED;
 +}
 +
 +void MESH_OT_region_to_loop(wmOperatorType *ot)
 +{
 +      /* identifiers */
 +      ot->name= "Select Boundary Loop";
 +      ot->idname= "MESH_OT_region_to_loop";
 +
 +      /* api callbacks */
 +      ot->exec= region_to_loop;
 +      ot->poll= ED_operator_editmesh;
 +
 +      /* flags */
 +      ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
 +}
 +
 +static int loop_find_region(BMEditMesh *em, BMLoop *l, int flag, 
 +      SmallHash *fhash, BMFace ***region_out)
 +{
 +      BLI_array_declare(region);
 +      BLI_array_declare(stack);
 +      BMFace **region = NULL, *f;
 +      BMFace **stack = NULL;
 +      
 +      BLI_array_append(stack, l->f);
 +      BLI_smallhash_insert(fhash, (uintptr_t)l->f, NULL);
 +      
 +      while (BLI_array_count(stack) > 0) {
 +              BMIter liter1, liter2;
 +              BMLoop *l1, *l2;
 +              
 +              f = BLI_array_pop(stack);
 +              BLI_array_append(region, f);
 +              
 +              BM_ITER(l1, &liter1, em->bm, BM_LOOPS_OF_FACE, f) {
 +                      if (BM_TestHFlag(l1->e, flag))
 +                              continue;
 +                      
 +                      BM_ITER(l2, &liter2, em->bm, BM_LOOPS_OF_EDGE, l1->e) {
 +                              if (BLI_smallhash_haskey(fhash, (uintptr_t)l2->f))
 +                                      continue;
 +                              
 +                              BLI_array_append(stack, l2->f);
 +                              BLI_smallhash_insert(fhash, (uintptr_t)l2->f, NULL);
 +                      }
 +              }
 +      }
 +      
 +      BLI_array_free(stack);
 +      
 +      *region_out = region;
 +      return BLI_array_count(region);
 +}
 +
 +static int verg_radial(const void *va, const void *vb)
 +{
 +      BMEdge *e1 = *((void**)va);
 +      BMEdge *e2 = *((void**)vb);
 +      int a, b;
 +      
 +      a = BM_Edge_FaceCount(e1);
 +      b = BM_Edge_FaceCount(e2);
 +      
 +      if (a > b) return -1;
 +      if (a == b) return 0;
 +      if (a < b) return 1;
 +      
 +      return -1;
 +}
 +
 +static int loop_find_regions(BMEditMesh *em, int selbigger)
 +{
 +      SmallHash visithash;
 +      BMIter iter;
 +      BMEdge *e, **edges=NULL;
 +      BLI_array_declare(edges);
 +      BMFace *f;
 +      int count = 0, i;
 +      
 +      BLI_smallhash_init(&visithash);
 +      
 +      BM_ITER(f, &iter, em->bm, BM_FACES_OF_MESH, NULL) {
 +              BM_SetIndex(f, 0);
 +      }
 +
 +      BM_ITER(e, &iter, em->bm, BM_EDGES_OF_MESH, NULL) {
 +              if (BM_TestHFlag(e, BM_SELECT)) {
 +                      BLI_array_append(edges, e);
 +                      BM_SetIndex(e, 1);
 +              } else {
 +                      BM_SetIndex(e, 0);
 +              }
 +      }
 +      
 +      /*sort edges by radial cycle length*/
 +      qsort(edges,  BLI_array_count(edges), sizeof(void*), verg_radial);
 +      
 +      for (i=0; i<BLI_array_count(edges); i++) {
 +              BMIter liter;
 +              BMLoop *l;
 +              BMFace **region=NULL, **r;
 +              int c, tot=0;
 +              
 +              e = edges[i];
 +              
 +              if (!BM_GetIndex(e))
 +                      continue;
 +              
 +              BM_ITER(l, &liter, em->bm, BM_LOOPS_OF_EDGE, e) {
 +                      if (BLI_smallhash_haskey(&visithash, (uintptr_t)l->f))
 +                              continue;
 +                                              
 +                      c = loop_find_region(em, l, BM_SELECT, &visithash, &r);
 +                      
 +                      if (!region || (selbigger ? c >= tot : c < tot)) {
 +                              tot = c;
 +                              if (region) 
 +                                      MEM_freeN(region);
 +                              region = r;
 +                      }
 +              }
 +              
 +              if (region) {
 +                      int j;
 +                      
 +                      for (j=0; j<tot; j++) {
 +                              BM_SetIndex(region[j], 1);
 +                              BM_ITER(l, &liter, em->bm, BM_LOOPS_OF_FACE, region[j]) {
 +                                      BM_SetIndex(l->e, 0);
 +                              }
 +                      }
 +                      
 +                      count += tot;
 +                      
 +                      MEM_freeN(region);
 +              }
 +      }
 +      
 +      BLI_array_free(edges);
 +      BLI_smallhash_release(&visithash);
 +      
 +      return count;
 +}
 +
 +static int loop_to_region(bContext *C, wmOperator *op)
 +{
 +      Object *obedit = CTX_data_edit_object(C);
 +      BMEditMesh *em = ((Mesh*)obedit->data)->edit_btmesh;
 +      BMIter iter;
 +      BMFace *f;
 +      int selbigger = RNA_boolean_get(op->ptr, "select_bigger");
 +      int a, b;
 +      
 +      /*find the set of regions with smallest number of total faces*/
 +      a = loop_find_regions(em, selbigger);
 +      b = loop_find_regions(em, !selbigger);
 +      
 +      if ((a <= b) ^ selbigger) {
 +              loop_find_regions(em, selbigger);
 +      }
 +      
 +      EDBM_clear_flag_all(em, BM_SELECT);
 +      
 +      BM_ITER(f, &iter, em->bm, BM_FACES_OF_MESH, NULL) {
 +              if (BM_GetIndex(f) && !BM_TestHFlag(f, BM_HIDDEN)) {
 +                      BM_Select_Face(em->bm, f, 1);
 +              }
 +      }
 +      
 +      WM_event_add_notifier(C, NC_GEOM|ND_SELECT, obedit->data);
 +      return OPERATOR_FINISHED;
 +}
 +
 +void MESH_OT_loop_to_region(wmOperatorType *ot)
 +{
 +      /* identifiers */
 +      ot->name= "Select Loop Inner-Region";
 +      ot->idname= "MESH_OT_loop_to_region";
 +
 +      /* api callbacks */
 +      ot->exec= loop_to_region;
 +      ot->poll= ED_operator_editmesh;
 +
 +      /* flags */
 +      ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
 +      
 +      RNA_def_boolean(ot->srna, "select_bigger", 0, "Select Bigger", "Select bigger regions instead of smaller ones");
 +}
index 53cc8409c39d0c37d446124968f68f168381f73d,ab62c88deaa17d4d267873aff5dece258abcefe6..d7734867bbb237e80c1fc0f4f3852effc1923bd6
@@@ -624,3 -818,3 +624,101 @@@ int do_paintface_box_select(ViewContex
  
        return OPERATOR_FINISHED;
  }
++
++
++/*  (similar to void paintface_flush_flags(Object *ob))
++ * copy the vertex flags, most importantly selection from the mesh to the final derived mesh,
++ * use in object mode when selecting vertices (while painting) */
++void paintvert_flush_flags(Object *ob)
++{
++      Mesh *me= get_mesh(ob);
++      DerivedMesh *dm= ob->derivedFinal;
++      MVert *dm_mvert, *dm_mv;
++      int *index_array = NULL;
++      int totvert;
++      int i;
++
++      if(me==NULL || dm==NULL)
++              return;
++
++      index_array = dm->getVertDataArray(dm, CD_ORIGINDEX);
++
++      dm_mvert = dm->getVertArray(dm);
++      totvert = dm->getNumVerts(dm);
++
++      dm_mv= dm_mvert;
++
++      if(index_array) {
++              int orig_index;
++              for (i= 0; i<totvert; i++, dm_mv++) {
++                      orig_index= index_array[i];
++                      if(orig_index != ORIGINDEX_NONE) {
++                              dm_mv->flag= me->mvert[index_array[i]].flag;
++                      }
++              }
++      }
++      else {
++              for (i= 0; i<totvert; i++, dm_mv++) {
++                      dm_mv->flag= me->mvert[i].flag;
++              }
++      }
++}
++/*  note: if the caller passes FALSE to flush_flags, then they will need to run paintvert_flush_flags(ob) themselves */
++void paintvert_deselect_all_visible(Object *ob, int action, short flush_flags)
++{
++      Mesh *me;
++      MVert *mvert;
++      int a;
++
++      me= get_mesh(ob);
++      if(me==NULL) return;
++      
++      if(action == SEL_INVERT) {
++              mvert= me->mvert;
++              a= me->totvert;
++              while(a--) {
++                      if((mvert->flag & ME_HIDE) == 0) {
++                              mvert->flag ^= SELECT;
++                      }
++                      mvert++;
++              }
++      }
++      else {
++              if (action == SEL_TOGGLE) {
++                      action = SEL_SELECT;
++
++                      mvert= me->mvert;
++                      a= me->totvert;
++                      while(a--) {
++                              if((mvert->flag & ME_HIDE) == 0 && mvert->flag & SELECT) {
++                                      action = SEL_DESELECT;
++                                      break;
++                              }
++                              mvert++;
++                      }
++              }
++
++              mvert= me->mvert;
++              a= me->totvert;
++              while(a--) {
++                      if((mvert->flag & ME_HIDE) == 0) {
++                              switch (action) {
++                              case SEL_SELECT:
++                                      mvert->flag |= SELECT;
++                                      break;
++                              case SEL_DESELECT:
++                                      mvert->flag &= ~SELECT;
++                                      break;
++                              case SEL_INVERT:
++                                      mvert->flag ^= SELECT;
++                                      break;
++                              }
++                      }
++                      mvert++;
++              }
++      }
++
++      if(flush_flags) {
++              paintvert_flush_flags(ob);
++      }
++}
index 5d3951f6c1d8c1e5c93949a5ddf4c74962e7d2e1,797cf4289694bc96fb2c89bc0b2a2e75bada6f0e..8c7ffb33984e2bffe6c1d0994b11136d9e9f4c4c
@@@ -50,8 -49,9 +50,9 @@@
  #include "DNA_scene_types.h"
  #include "DNA_particle_types.h"
  
+ #include "BLI_math.h"
  #include "BLI_blenlib.h"
 -#include "BLI_editVert.h"
 +#include "BLI_cellalloc.h"
  #include "BLI_utildefines.h"
  
  #include "BKE_context.h"
@@@ -60,8 -60,8 +61,9 @@@
  #include "BKE_depsgraph.h"
  #include "BKE_global.h"
  #include "BKE_mesh.h"
 +#include "BKE_tessmesh.h"
  #include "BKE_report.h"
+ #include "BKE_DerivedMesh.h"
  
  #include "RNA_access.h"
  #include "RNA_define.h"
index 38ad0b320d9a7663dcae0976c5f7bc73f04ec71a,1eb92e24c8db391c03317f9f8792435ab1add5bf..48c53dcef0ce4ce83f42827ba34a57a1eb8e15c2
@@@ -1178,15 -1112,457 +1193,457 @@@ static void do_weight_paint_auto_normal
                }
        }
  }
 -#endif
  
- static void do_weight_paint_vertex(VPaint *wp, Object *ob, int index, 
-                                  float alpha, float paintweight, int flip, 
-                                  int vgroup_mirror, char *validmap)
+ /* the active group should be involved in auto normalize */
+ static void do_weight_paint_auto_normalize_all_groups(MDeformVert *dvert, char *map, char do_auto_normalize)
+ {
+ //    MDeformWeight *dw = dvert->dw;
+       float sum=0.0f, fac=0.0f;
+       int i, tot=0;
+       if (do_auto_normalize == FALSE)
+               return;
+       for (i=0; i<dvert->totweight; i++) {
+               if (map[dvert->dw[i].def_nr]) {
+                       tot += 1;
+                       sum += dvert->dw[i].weight;
+               }
+       }
+       
+       if (!tot || sum == 1.0f)
+               return;
+       fac = sum;
+       fac = fac==0.0f ? 1.0f : 1.0f / fac;
+       for (i=0; i<dvert->totweight; i++) {
+               if (map[dvert->dw[i].def_nr]) {
+                       dvert->dw[i].weight *= fac;
+               }
+       }
+ }
+ /*
+ See if the current deform vertex has a locked group
+ */
+ static char has_locked_group(MDeformVert *dvert, const char *lock_flags)
+ {
+       int i;
+       for(i = 0; i < dvert->totweight; i++) {
+               if(lock_flags[dvert->dw[i].def_nr] && dvert->dw[i].weight > 0.0f) {
+                       return TRUE;
+               }
+       }
+       return FALSE;
+ }
+ /* 
+  * gen_lck_flags gets the status of "flag" for each bDeformGroup
+  *in ob->defbase and returns an array containing them
+  */
+ static char *gen_lock_flags(Object* ob, int defbase_tot)
+ {
+       char is_locked = FALSE;
+       int i;
+       //int defbase_tot = BLI_countlist(&ob->defbase);
+       char *lock_flags = MEM_mallocN(defbase_tot*sizeof(char), "defflags");
+       bDeformGroup *defgroup;
+       for(i = 0, defgroup = ob->defbase.first; i < defbase_tot && defgroup; defgroup = defgroup->next, i++) {
+               lock_flags[i] = ((defgroup->flag & DG_LOCK_WEIGHT) != 0);
+               is_locked |= lock_flags[i];
+       }
+       if(is_locked){
+               return lock_flags;
+       }
+       // don't forget to free it if it is unneeded
+       MEM_freeN(lock_flags);
+       return NULL;
+ }
+ static int has_locked_group_selected(int defbase_tot, char *defbase_sel, char *lock_flags) {
+       int i;
+       for(i = 0; i < defbase_tot; i++) {
+               if(defbase_sel[i] && lock_flags[i]) {
+                       return TRUE;
+               }
+       }
+       return FALSE;
+ }
+ #if 0 /* UNUSED */
+ static int has_unselected_unlocked_bone_group(int defbase_tot, char *defbase_sel, int selected, char *lock_flags, char *vgroup_validmap) {
+       int i;
+       if(defbase_tot == selected) {
+               return FALSE;
+       }
+       for(i = 0; i < defbase_tot; i++) {
+               if(vgroup_validmap[i] && !defbase_sel[i] && !lock_flags[i]) {
+                       return TRUE;
+               }
+       }
+       return FALSE;
+ }
+ #endif
+ static void multipaint_selection(MDeformVert *dvert, float change, char *defbase_sel, int defbase_tot) {
+       int i;
+       MDeformWeight *dw;
+       float val;
+       // make sure they are all at most 1 after the change
+       for(i = 0; i < defbase_tot; i++) {
+               if(defbase_sel[i]) {
+                       dw = defvert_find_index(dvert, i);
+                       if(dw && dw->weight) {
+                               val = dw->weight * change;
+                               if(val > 1) {
+                                       /*  TODO: when the change is reduced, you need to recheck the earlier values to make sure they are not 0 (precision error) */
+                                       change = 1.0f/dw->weight;
+                               }
+                               // the value should never reach zero while multi-painting if it was nonzero beforehand
+                               if(val <= 0) {
+                                       return;
+                               }
+                       }
+               }
+       }
+       // apply the valid change
+       for(i = 0; i < defbase_tot; i++) {
+               if(defbase_sel[i]) {
+                       dw = defvert_find_index(dvert, i);
+                       if(dw && dw->weight) {
+                               dw->weight = dw->weight * change;
+                       }
+               }
+       }
+ }
+ // move all change onto valid, unchanged groups.  If there is change left over, then return it.
+ // assumes there are valid groups to shift weight onto
+ static float redistribute_change(MDeformVert *ndv, char *change_status, int changeme, int changeto, const char *vgroup_validmap, float totchange, float total_valid, char do_auto_normalize) {
+       float was_change;
+       float change;
+       float oldval;
+       MDeformWeight *ndw;
+       int i;
+       do {
+               // assume there is no change until you see one
+               was_change = FALSE;
+               // change each group by the same amount each time
+               change = totchange/total_valid;
+               for(i = 0; i < ndv->totweight && total_valid && totchange; i++) {
+                       ndw = (ndv->dw+i);
+                       // change only the groups with a valid status
+                       if(change_status[ndw->def_nr] == changeme) {
+                               oldval = ndw->weight;
+                               // if auto normalize is active, don't worry about upper bounds
+                               if(do_auto_normalize == FALSE && ndw->weight + change > 1) {
+                                       totchange -= 1-ndw->weight;
+                                       ndw->weight = 1;
+                                       // stop the changes to this group
+                                       change_status[ndw->def_nr] = changeto;
+                                       total_valid--;
+                               } else if(ndw->weight + change < 0) { // check the lower bound
+                                       totchange -= ndw->weight;
+                                       ndw->weight = 0;
+                                       change_status[ndw->def_nr] = changeto;
+                                       total_valid--;
+                               } else {// a perfectly valid change occurred to ndw->weight
+                                       totchange -= change;
+                                       ndw->weight += change;
+                               }
+                               // see if there was a change
+                               if(oldval != ndw->weight) {
+                                       was_change = TRUE;
+                               }
+                       }
+               }
+       // don't go again if there was no change, if there is no valid group, or there is no change left
+       }while(was_change && total_valid && totchange);
+       // left overs
++      (void)vgroup_validmap;
+       return totchange;
+ }
+ // observe the changes made to the weights of groups.
+ // make sure all locked groups on the vertex have the same deformation
+ // by moving the changes made to groups onto other unlocked groups
+ static void enforce_locks(MDeformVert *odv, MDeformVert *ndv, int defbase_tot,
+                           const char *lock_flags, const char *vgroup_validmap, char do_auto_normalize)
+ {
+       float totchange = 0.0f;
+       float totchange_allowed = 0.0f;
+       float left_over;
+       int total_valid = 0;
+       int total_changed = 0;
+       int i;
+       MDeformWeight *ndw;
+       MDeformWeight *odw;
+       MDeformWeight *ndw2;
+       MDeformWeight *odw2;
+       int designatedw = -1;
+       int designatedw_changed = FALSE;
+       float storedw;
+       char *change_status;
+       char new_weight_has_zero = FALSE;
+       if(!lock_flags || !has_locked_group(ndv, lock_flags)) {
+               return;
+       }
+       // record if a group was changed, unlocked and not changed, or locked
+       change_status = MEM_callocN(sizeof(char)*defbase_tot, "unlocked_unchanged");
+       for(i = 0; i < defbase_tot; i++) {
+               ndw = defvert_find_index(ndv, i);
+               odw = defvert_find_index(odv, i);
+               // the weights are zero, so we can assume a lot
+               if(!ndw || !odw) {
+                       if (!lock_flags[i] && vgroup_validmap[i]){
+                               defvert_verify_index(odv, i);
+                               defvert_verify_index(ndv, i);
+                               total_valid++;
+                               change_status[i] = 1; // can be altered while redistributing
+                       }
+                       continue;
+               }
+               // locked groups should not be changed
+               if(lock_flags[i]) {
+                       ndw->weight = odw->weight;
+               }
+               else if(ndw->weight != odw->weight) { // changed groups are handled here
+                       totchange += ndw->weight - odw->weight;
+                       change_status[i] = 2; // was altered already
+                       total_changed++;
+                       if(ndw->weight == 0) {
+                               new_weight_has_zero = TRUE;
+                       }
+                       else if(designatedw == -1){
+                               designatedw = i;
+                       }
+               } // unchanged, unlocked bone groups are handled here
+               else if (vgroup_validmap[i]){
+                       totchange_allowed += ndw->weight;
+                       total_valid++;
+                       change_status[i] = 1; // can be altered while redistributing
+               }
+       }
+       // if there was any change, redistribute it
+       if(total_changed) {
+               // auto normalize will allow weights to temporarily go above 1 in redistribution
+               if(vgroup_validmap && total_changed < 0 && total_valid) {
+                       totchange_allowed = total_valid;
+               }
+               // there needs to be change allowed, or you should not bother
+               if(totchange_allowed) {
+                       // the way you modify the unlocked+unchanged groups is different depending
+                       // on whether or not you are painting the weight(s) up or down
+                       if(totchange < 0) {
+                               totchange_allowed = total_valid - totchange_allowed;
+                       }
+                       else {
+                               totchange_allowed *= -1;
+                       }
+                       left_over = 0;
+                       if(fabsf(totchange_allowed) < fabsf(totchange)) {
+                               // this amount goes back onto the changed, unlocked weights
+                               left_over = fabsf(fabsf(totchange) - fabsf(totchange_allowed));
+                               if(totchange > 0) {
+                                       left_over *= -1;
+                               }
+                       }
+                       else {
+                               // all of the change will be permitted
+                               totchange_allowed = -totchange;
+                       }
+                       // move the weight evenly between the allowed groups, move excess back onto the used groups based on the change
+                       totchange_allowed = redistribute_change(ndv, change_status, 1, -1, vgroup_validmap, totchange_allowed, total_valid, do_auto_normalize);
+                       left_over += totchange_allowed;
+                       if(left_over) {
+                               // more than one nonzero weights were changed with the same ratio, so keep them changed that way!
+                               if(total_changed > 1 && !new_weight_has_zero && designatedw >= 0) {
+                                       // this dw is special, it is used as a base to determine how to change the others
+                                       ndw = defvert_find_index(ndv, designatedw);
+                                       odw = defvert_find_index(odv, designatedw);
+                                       storedw = ndw->weight;
+                                       for(i = 0; i < ndv->totweight; i++) {
+                                               if(change_status[ndw->def_nr] == 2) {
+                                                       odw2 = (odv->dw+i);
+                                                       ndw2 = (ndv->dw+i);
+                                                       if(!designatedw_changed) {
+                                                               ndw->weight = (totchange_allowed + odw->weight + odw2->weight)/(1 + ndw2->weight/ndw->weight);
+                                                               designatedw_changed = TRUE;
+                                                       }
+                                                       ndw2->weight = ndw->weight * ndw2->weight / storedw;
+                                               }
+                                       }
+                               }
+                               // a weight was changed to zero, only one weight was changed, or designatedw is still -1
+                               // put weight back as evenly as possible
+                               else {
+                                       redistribute_change(ndv, change_status, 2, -2, vgroup_validmap, left_over, total_changed, do_auto_normalize);
+                               }
+                       }
+               }
+               else {
+                       // reset the weights
+                       for(i = 0; i < ndv->totweight; i++) {
+                               ndv->dw[i].weight = odv->dw[i].weight;
+                       }
+               }
+       }
+       MEM_freeN(change_status);
+ }
+ // multi-paint's initial, potential change is computed here based on the user's stroke
+ static float get_mp_change(MDeformVert *odv, char *defbase_sel, float brush_change) {
+       float selwsum = 0.0f;
+       int i;
+       MDeformWeight *dw;
+       for(i=0; i < odv->totweight; i++) {
+               if(defbase_sel[(dw= &odv->dw[i])->def_nr]) {
+                       selwsum += dw->weight;
+               }
+       }
+       if(selwsum && selwsum+brush_change > 0) {
+               return (selwsum+brush_change)/selwsum;
+       }
+       return 0.0f;
+ }
+ // change the weights back to the wv's weights
+ // it assumes you already have the correct pointer index
+ static void reset_to_prev(MDeformVert *wv, MDeformVert *dv) {
+       int i;
+       MDeformWeight *d;
+       MDeformWeight *w;
+       for(i = 0; i < dv->totweight; i++) {
+               d= &dv->dw[i];
+               w= defvert_find_index(wv, d->def_nr);
+               /* if there was no w when there is a d, then the old weight was 0 */
+               d->weight = w ? w->weight : 0.0f;
+       }
+ }
+ static void clamp_weights(MDeformVert *dvert) {
+       int i;
+       for (i = 0; i < dvert->totweight; i++) {
+               CLAMP((dvert->dw+i)->weight, 0.0f, 1.0f);
+       }
+ }
+ /* struct to avoid passing many args each call to do_weight_paint_vertex()
+  * this _could_ be made a part of the operators 'WPaintData' struct, or at
+  * least a member, but for now keep its own struct, initialized on every
+  * paint stroke update - campbell */
+ typedef struct WeightPaintInfo {
+       int defbase_tot;
+       /* both must add up to 'defbase_tot' */
+       int defbase_tot_sel;
+       int defbase_tot_unsel;
+       int vgroup_mirror; /* mirror group or -1 */
+       char *lock_flags;  /* boolean array for locked bones,
+                                               * length of defbase_tot */
+       char *defbase_sel; /* boolean array for selected bones,
+                                               * length of defbase_tot */
+       char *vgroup_validmap; /* same as WeightPaintData.vgroup_validmap,
+                               * only added here for convenience */
+       char do_flip;
+       char do_multipaint;
+       char do_auto_normalize;
+ } WeightPaintInfo;
+ /* fresh start to make multi-paint and locking modular */
+ /* returns TRUE if it thinks you need to reset the weights due to
+  * normalizing while multi-painting */
+ static int apply_mp_locks_normalize(Mesh *me, const WeightPaintInfo *wpi,
+                                     const int index,
+                                     MDeformWeight *dw, MDeformWeight *tdw,
+                                     float change, float oldChange,
+                                     float oldw, float neww)
+ {
+       MDeformVert *dv= me->dvert+index;
+       MDeformVert dv_test= {NULL};
+       dv_test.dw= MEM_dupallocN(dv->dw);
+       dv_test.flag = dv->flag;
+       dv_test.totweight = dv->totweight;
+       /* do not multi-paint if a locked group is selected or the active group is locked
+        * !lock_flags[dw->def_nr] helps if nothing is selected, but active group is locked */
+       if((wpi->lock_flags == NULL) || (wpi->lock_flags[dw->def_nr] == FALSE && has_locked_group_selected(wpi->defbase_tot, wpi->defbase_sel, wpi->lock_flags) == FALSE)) {
+               if(wpi->do_multipaint && wpi->defbase_tot_sel > 1) {
+                       if(change && change!=1) {
+                               multipaint_selection(dv, change, wpi->defbase_sel, wpi->defbase_tot);
+                       }
+               }
+               else { /* this lets users paint normally, but don't let them paint locked groups */
+                       dw->weight = neww;
+               }
+       }
+       clamp_weights(dv);
+       enforce_locks(&dv_test, dv, wpi->defbase_tot, wpi->lock_flags, wpi->vgroup_validmap, wpi->do_auto_normalize);
+       do_weight_paint_auto_normalize_all_groups(dv, wpi->vgroup_validmap, wpi->do_auto_normalize);
+       if(oldChange && wpi->do_multipaint && wpi->defbase_tot_sel > 1) {
+               if(tdw->weight != oldw) {
+                       if(neww > oldw) {
+                               if(tdw->weight <= oldw) {
+                                       MEM_freeN(dv_test.dw);
+                                       return TRUE;
+                               }
+                       }
+                       else {
+                               if(tdw->weight >= oldw) {
+                                       MEM_freeN(dv_test.dw);
+                                       return TRUE;
+                               }
+                       }
+               }
+       }
+       MEM_freeN(dv_test.dw);
+       return FALSE;
+ }
+ /* within the current dvert index, get the dw that is selected and has a weight
+  * above 0, this helps multi-paint */
+ static int get_first_selected_nonzero_weight(MDeformVert *dvert, char *defbase_sel) {
+       int i;
+       MDeformWeight *dw;
+       for(i=0; i< dvert->totweight; i++) {
+               dw = &dvert->dw[i];
+               if(defbase_sel[dw->def_nr] && dw->weight > 0) {
+                       return i;
+               }
+       }
+       return -1;
+ }
+ static char *wpaint_make_validmap(Object *ob);
+ static void do_weight_paint_vertex( /* vars which remain the same for every vert */
+                                    VPaint *wp, Object *ob, const WeightPaintInfo *wpi,
+                                     /* vars which change on each stroke */
+                                    int index, float alpha, float paintweight
+                                    )
  {
        Mesh *me= ob->data;
+       
        MDeformWeight *dw, *uw;
        int vgroup= ob->actdef-1;
-       
        if(wp->flag & VP_ONLYVGROUP) {
                dw= defvert_find_index(me->dvert+index, vgroup);
                uw= defvert_find_index(wp->wpaint_prev+index, vgroup);
@@@ -1547,13 -2037,20 +2125,20 @@@ static void wpaint_stroke_update_step(b
                paintweight= ts->vgroup_weight;
                        
        for(index=0; index<totindex; index++) {
 -              if(indexar[index] && indexar[index]<=me->totface) {
 -                      MFace *mface= me->mface + (indexar[index]-1);
 +              if(indexar[index] && indexar[index]<=me->totpoly) {
 +                      MPoly *mpoly= me->mpoly + (indexar[index]-1);
 +                      MLoop *ml = me->mloop + mpoly->loopstart;
 +                      int i;
  
-                       for (i=0; i<mpoly->totloop; i++, ml++) {
-                               (me->dvert+ml->v)->flag = 1;
+                       if(use_vert_sel) {
 -                              me->dvert[mface->v1].flag = (me->mvert[mface->v1].flag & SELECT);
 -                              me->dvert[mface->v2].flag = (me->mvert[mface->v2].flag & SELECT);
 -                              me->dvert[mface->v3].flag = (me->mvert[mface->v3].flag & SELECT);
 -                              if(mface->v4) me->dvert[mface->v4].flag = (me->mvert[mface->v4].flag & SELECT);
++                              for (i=0; i<mpoly->totloop; i++, ml++) {
++                                      me->dvert[ml->v].flag = (me->mvert[ml->v].flag & SELECT);
++                              }
+                       }
+                       else {
 -                              me->dvert[mface->v1].flag= 1;
 -                              me->dvert[mface->v2].flag= 1;
 -                              me->dvert[mface->v3].flag= 1;
 -                              if(mface->v4) me->dvert[mface->v4].flag= 1;
++                              for (i=0; i<mpoly->totloop; i++, ml++) {
++                                      me->dvert[ml->v].flag = 1;
++                              }
                        }
                                        
                        if(brush->vertexpaint_tool==VP_BLUR) {
                                else
                                        dw_func= defvert_verify_index;
                                                
 -                              dw= dw_func(me->dvert+mface->v1, ob->actdef-1);
 -                              if(dw) {paintweight+= dw->weight; totw++;}
 -                              dw= dw_func(me->dvert+mface->v2, ob->actdef-1);
 -                              if(dw) {paintweight+= dw->weight; totw++;}
 -                              dw= dw_func(me->dvert+mface->v3, ob->actdef-1);
 -                              if(dw) {paintweight+= dw->weight; totw++;}
 -                              if(mface->v4) {
 -                                      dw= dw_func(me->dvert+mface->v4, ob->actdef-1);
 -                                      if(dw) {paintweight+= dw->weight; totw++;}
 +                              ml = me->mloop + mpoly->loopstart;
 +                              for (i=0; i<mpoly->totloop; i++, ml++) {
 +                                      dw = dw_func(me->dvert+ml->v, ob->actdef-1);
 +                                      if (dw) {
 +                                              paintweight += dw->weight;
 +                                              totw++;
-                                       }                                       
++                                      }
                                }
                        }
                }
                paintweight/= (float)totw;
                        
        for(index=0; index<totindex; index++) {
 -                              
 -              if(indexar[index] && indexar[index]<=me->totface) {
 -                      MFace *mf= me->mface + (indexar[index]-1);
 -                      unsigned int fidx= mf->v4 ? 3:2;;
 -                      do {
 -                              int vidx= *(&mf->v1 + fidx);
 -
 -                              if(me->dvert[vidx].flag) {
 +              if(indexar[index] && indexar[index]<=me->totpoly) {
 +                      MPoly *mpoly= me->mpoly + (indexar[index]-1);
 +                      MLoop *ml=me->mloop+mpoly->loopstart;
 +                      int i;
 +
 +                      for (i=0; i<mpoly->totloop; i++, ml++) {
-                               if ((me->dvert+ml->v)->flag) {
-                                       alpha= calc_vp_alpha_dl(wp, vc, wpd->wpimat, wpd->vertexcosnos+6*ml->v, mval, pressure);
++                              unsigned int vidx= ml->v;
++                              if (me->dvert[vidx].flag) {
+                                       alpha= calc_vp_alpha_dl(wp, vc, wpd->wpimat, wpd->vertexcosnos+6*vidx, mval, pressure);
 -                                      if(alpha) {
 +                                      if(alpha != 0.0f) {
-                                               do_weight_paint_vertex(wp, ob, ml->v, 
-                                                       alpha, paintweight, flip, wpd->vgroup_mirror, 
-                                                       wpd->vgroup_validmap);
+                                               do_weight_paint_vertex(wp, ob, &wpi, vidx, alpha, paintweight);
                                        }
-                                       (me->dvert+ml->v)->flag= 0;
+                                       me->dvert[vidx].flag= 0;
                                }
 -                      } while (fidx--);
 +                      }
                }
        }
-                       
+       /* *** free wpi members */
+       MEM_freeN(wpi.defbase_sel);
+       /* *** dont freeing wpi members */
        swap_m4m4(vc->rv3d->persmat, mat);
                        
        DAG_id_tag_update(ob->data, 0);
index 4e185d6603aa183823aca0d3c2ff812703c5781a,ecdac083aed15d19408e0753e556f3ec0bc9d32a..cbdfc312f09a7e6062407f0540fece6febcb43bb
@@@ -1745,14 -1740,38 +1745,39 @@@ void mesh_foreachScreenVert(ViewContex
        dm->release(dm);
  }
  
+ /*  draw callback */
+ static void drawSelectedVertices__mapFunc(void *userData, int index, float *co, float *UNUSED(no_f), short *UNUSED(no_s))
+ {
+       MVert *mv = &((MVert *)userData)[index];
+       if(!(mv->flag & ME_HIDE)) {
+               const char sel= mv->flag & SELECT;
+               // TODO define selected color
+               if(sel) {
+                       glColor3f(1.0f, 1.0f, 0.0f);
+               }
+               else {
+                       glColor3f(0.0f, 0.0f, 0.0f);
+               }
+               glVertex3fv(co);
+       }
+ }
+ static void drawSelectedVertices(DerivedMesh *dm, Mesh *me) {
+       glBegin(GL_POINTS);
+       dm->foreachMappedVert(dm, drawSelectedVertices__mapFunc, me->mvert);
+       glEnd();
+ }
  static void mesh_foreachScreenEdge__mapFunc(void *userData, int index, float *v0co, float *v1co)
  {
 -      struct { void (*func)(void *userData, EditEdge *eed, int x0, int y0, int x1, int y1, int index); void *userData; ViewContext vc; int clipVerts; } *data = userData;
 -      EditEdge *eed = EM_get_edge_for_index(index);
 -      short s[2][2];
 +      struct { void (*func)(void *userData, BMEdge *eed, int x0, int y0, int x1, int y1, int index); void *userData; ViewContext vc; int clipVerts; float pmat[4][4], vmat[4][4]; } *data = userData;
 +      BMEdge *eed = EDBM_get_edge_for_index(data->vc.em, index);
 +
 +      if (!BM_TestHFlag(eed, BM_HIDDEN)) {
 +              short s[2][2];
  
 -      if (eed->h==0) {
                if (data->clipVerts==1) {
                        view3d_project_short_clip(data->vc.ar, v0co, s[0], 1);
                        view3d_project_short_clip(data->vc.ar, v1co, s[1], 1);
@@@ -6604,13 -6550,38 +6638,39 @@@ void draw_object(Scene *scene, ARegion 
  
  /* ***************** BACKBUF SEL (BBS) ********* */
  
+ static void bbs_obmode_mesh_verts__mapFunc(void *userData, int index, float *co, float *UNUSED(no_f), short *UNUSED(no_s))
+ {
+       struct {void* offset; MVert *mvert;} *data = userData;
+       MVert *mv = &data->mvert[index];
+       int offset = (intptr_t) data->offset;
+       if (!(mv->flag & ME_HIDE)) {
+               WM_set_framebuffer_index_color(offset+index);
+               bglVertex3fv(co);
+       }
+ }
+ static void bbs_obmode_mesh_verts(Object *ob, DerivedMesh *dm, int offset)
+ {
+       struct {void* offset; struct MVert *mvert;} data;
+       Mesh *me = ob->data;
+       MVert *mvert = me->mvert;
+       data.mvert = mvert;
+       data.offset = (void*)(intptr_t) offset;
+       glPointSize( UI_GetThemeValuef(TH_VERTEX_SIZE) );
+       bglBegin(GL_POINTS);
+       dm->foreachMappedVert(dm, bbs_obmode_mesh_verts__mapFunc, &data);
+       bglEnd();
+       glPointSize(1.0);
+ }
  static void bbs_mesh_verts__mapFunc(void *userData, int index, float *co, float *UNUSED(no_f), short *UNUSED(no_s))
  {
 -      int offset = (intptr_t) userData;
 -      EditVert *eve = EM_get_vert_for_index(index);
 +      void **ptrs = userData;
 +      int offset = (intptr_t) ptrs[0];
 +      BMVert *eve = EDBM_get_vert_for_index(ptrs[1], index);
  
 -      if (eve->h==0) {
 +      if (!BM_TestHFlag(eve, BM_HIDDEN)) {
                WM_set_framebuffer_index_color(offset+index);
                bglVertex3fv(co);
        }
@@@ -6767,10 -6740,24 +6838,24 @@@ void draw_object_backbufsel(Scene *scen
  
                        dm->release(dm);
  
 -                      EM_free_index_arrays();
 +                      EDBM_free_index_arrays(em);
                }
                else {
-                       bbs_mesh_solid(scene, ob);
+                       Mesh *me= ob->data;
+                       if(me->editflag & ME_EDIT_VERT_SEL) {
+                               DerivedMesh *dm = mesh_get_derived_final(scene, ob, scene->customdata_mask);
+                               glColor3ub(0, 0, 0);
+                               dm->drawMappedFaces(dm, bbs_mesh_solid_hide2__setDrawOpts, me, 0, GPU_enable_material, NULL);
+                               
+                               bbs_obmode_mesh_verts(ob, dm, 1);
 -                              em_vertoffs = me->totvert+1;
++                              bm_vertoffs = me->totvert+1;
+                               dm->release(dm);
+                       }
+                       else {
+                               bbs_mesh_solid(scene, ob);
+                       }
                }
                break;
        case OB_CURVE:
index 990df969d68e0e87c81dca0b61e4036ca0fc4ee3,aa3166a7a65cce8047f734db69ef31df5a33b57d..7dc4112d7296bc3c3d338e03dd55598598ba90ab
@@@ -204,15 -203,33 +209,34 @@@ static void EDBM_backbuf_checkAndSelect
        }
  }
  
 -static void EM_backbuf_checkAndSelectVerts_obmode(Mesh *me, int select)
+ /* object mode, EM_ prefix is confusing here, rename? */
 -                      if(EM_check_backbuf(a)) {
++static void EDBM_backbuf_checkAndSelectVerts_obmode(Mesh *me, int select)
+ {
+       MVert *mv = me->mvert;
+       int a;
+       if (mv) {
+               for(a=1; a<=me->totvert; a++, mv++) {
 -static void EM_backbuf_checkAndSelectTFaces(Mesh *me, int select)
++                      if(EDBM_check_backbuf(a)) {
+                               if(!(mv->flag & ME_HIDE)) {
+                                       mv->flag = select?(mv->flag|SELECT):(mv->flag&~SELECT);
+                               }
+                       }
+               }
+       }
+ }
+ /* object mode, EM_ prefix is confusing here, rename? */
++
 +static void EDBM_backbuf_checkAndSelectTFaces(Mesh *me, int select)
  {
 -      MFace *mface = me->mface;
 +      MPoly *mpoly = me->mpoly;
        int a;
  
 -      if (mface) {
 -              for(a=1; a<=me->totface; a++, mface++) {
 -                      if(EM_check_backbuf(a)) {
 -                              mface->flag = select?(mface->flag|ME_FACE_SEL):(mface->flag&~ME_FACE_SEL);
 +      if (mpoly) {
 +              for(a=1; a<=me->totpoly; a++, mpoly++) {
 +                      if(EDBM_check_backbuf(a)) {
 +                              mpoly->flag = select?(mpoly->flag|ME_FACE_SEL):(mpoly->flag&~ME_FACE_SEL);
                        }
                }
        }
@@@ -733,6 -750,88 +757,88 @@@ static void do_lasso_select_meta(ViewCo
        }
  }
  
 -      em_vertoffs= me->totvert+1;     /* max index array */
+ int do_paintvert_box_select(ViewContext *vc, rcti *rect, int select, int extend)
+ {
+       Mesh *me;
+       MVert *mvert;
+       struct ImBuf *ibuf;
+       unsigned int *rt;
+       int a, index;
+       char *selar;
+       int sx= rect->xmax-rect->xmin+1;
+       int sy= rect->ymax-rect->ymin+1;
+       me= vc->obact->data;
+       if(me==NULL || me->totvert==0 || sx*sy <= 0)
+               return OPERATOR_CANCELLED;
+       selar= MEM_callocN(me->totvert+1, "selar");
+       if (extend == 0 && select)
+               paintvert_deselect_all_visible(vc->obact, SEL_DESELECT, FALSE);
+       view3d_validate_backbuf(vc);
+       ibuf = IMB_allocImBuf(sx,sy,32,IB_rect);
+       rt = ibuf->rect;
+       glReadPixels(rect->xmin+vc->ar->winrct.xmin,  rect->ymin+vc->ar->winrct.ymin, sx, sy, GL_RGBA, GL_UNSIGNED_BYTE,  ibuf->rect);
+       if(ENDIAN_ORDER==B_ENDIAN) IMB_convert_rgba_to_abgr(ibuf);
+       a= sx*sy;
+       while(a--) {
+               if(*rt) {
+                       index= WM_framebuffer_to_index(*rt);
+                       if(index<=me->totvert) selar[index]= 1;
+               }
+               rt++;
+       }
+       mvert= me->mvert;
+       for(a=1; a<=me->totvert; a++, mvert++) {
+               if(selar[a]) {
+                       if(mvert->flag & ME_HIDE);
+                       else {
+                               if(select) mvert->flag |= SELECT;
+                               else mvert->flag &= ~SELECT;
+                       }
+               }
+       }
+       IMB_freeImBuf(ibuf);
+       MEM_freeN(selar);
+ #ifdef __APPLE__      
+       glReadBuffer(GL_BACK);
+ #endif
+       paintvert_flush_flags(vc->obact);
+       return OPERATOR_FINISHED;
+ }
+ static void do_lasso_select_paintvert(ViewContext *vc, int mcords[][2], short moves, short extend, short select)
+ {
+       Object *ob= vc->obact;
+       Mesh *me= ob?ob->data:NULL;
+       rcti rect;
+       if(me==NULL || me->totvert==0)
+               return;
+       if(extend==0 && select)
+               paintvert_deselect_all_visible(ob, SEL_DESELECT, FALSE); /* flush selection at the end */
 -      EM_mask_init_backbuf_border(vc, mcords, moves, rect.xmin, rect.ymin, rect.xmax, rect.ymax);
++      bm_vertoffs= me->totvert+1;     /* max index array */
+       lasso_select_boundbox(&rect, mcords, moves);
 -      EM_backbuf_checkAndSelectVerts_obmode(me, select);
++      EDBM_mask_init_backbuf_border(vc, mcords, moves, rect.xmin, rect.ymin, rect.xmax, rect.ymax);
 -      EM_free_backbuf();
++      EDBM_backbuf_checkAndSelectVerts_obmode(me, select);
++      EDBM_free_backbuf();
+       paintvert_flush_flags(ob);
+ }
  static void do_lasso_select_paintface(ViewContext *vc, int mcords[][2], short moves, short extend, short select)
  {
        Object *ob= vc->obact;
@@@ -2010,6 -2169,24 +2176,24 @@@ static void paint_facesel_circle_select
  }
  
  
 -              em_vertoffs= me->totvert+1;     /* max index array */
+ static void paint_vertsel_circle_select(ViewContext *vc, int select, const int mval[2], float rad)
+ {
+       Object *ob= vc->obact;
+       Mesh *me = ob?ob->data:NULL;
+       int bbsel;
+       /* struct {ViewContext *vc; short select; int mval[2]; float radius; } data = {NULL}; */ /* UNUSED */
+       if (me) {
 -              bbsel= EM_init_backbuf_circle(vc, mval[0], mval[1], (short)(rad+1.0f));
 -              EM_backbuf_checkAndSelectVerts_obmode(me, select==LEFTMOUSE);
 -              EM_free_backbuf();
++              bm_vertoffs= me->totvert+1;     /* max index array */
++              bbsel= EDBM_init_backbuf_circle(vc, mval[0], mval[1], (short)(rad+1.0f));
++              EDBM_backbuf_checkAndSelectVerts_obmode(me, select==LEFTMOUSE);
++              EDBM_free_backbuf();
+               paintvert_flush_flags(ob);
+       }
+ }
  static void nurbscurve_circle_doSelect(void *userData, Nurb *UNUSED(nu), BPoint *bp, BezTriple *bezt, int beztindex, int x, int y)
  {
        struct {ViewContext *vc; short select; int mval[2]; float radius; } *data = userData;