Add to vertex group
24 Ⅷ 2013
To work with Vertex groups and BMesh combined, you must be aware that the actual group is always part of the Object, not the vertex… So… to add a vertex group, you need to use the old bpy.data way. What we need to work with is the index of the actual vertex group… so lets say you want a group called “cluster”.. lets see if it exists, and if it doesn’t… make one… then get the index.
import bpy, bmesh groupName = 'cluster' ob = bpy.context.active_object me = ob.data # Try to retrieve the vertex group, and if we can't make a new one try: group_index = ob.vertex_groups[groupName].index except: group = ob.vertex_groups.new(groupName) group_index = group.index #Let's get the bmesh data bm = bmesh.new() bm.from_mesh(me) # Now here's something new... we have to get the custom data layer # The vertex groups are all in the deform layer (there is always just one, which we retrieve as the active one) deform_layer = bm.verts.layers.deform.active if deform_layer is None: deform_layer = bm.verts.layers.deform.new() # Let's loop through all faces and if they are selected put the verts in the group! for f in bm.faces: if f.select: for v in f.verts: v[deform_layer][group_index] = 1.0 # Now here's a quick way to see if a vertex is in a vertex group for v in bm.verts: if group_index in v[deform_layer]: print('vert',v.index,'is in the group') # That's it... we're done... so we put the bmesh back in the object bm.to_mesh(me) bm.free()