In order to completely select or deselect the entire mesh, it is not enough to change the selection only for its vertices, we also need to change the selection for the edges and polygons of the mesh.
However, in some cases we do not have the ability to control the selection of the edges and faces of the mesh, and we can select and deselect only its vertices.
When we have changed the selection for the mesh vertices, we can “recalculate” the selection, extending it from the vertices to the edges and faces.
For example, let’s deselect the existing selection from the currently active mesh.
Create a bmesh object and transfer the active geometry to it. Also recalculate the indices of the mesh vertices so that they correspond to the original ones.
1 2 3 4 |
import bmesh bm = bmesh.from_edit_mesh(bpy.context.object.data) bm.verts.ensure_lookup_table() |
We can get a list of currently selected vertices very simply.
1 2 3 |
selected_vertiecs = [vert for vert in bm.verts if vert.select] # [<BMVert(0x00000221FB10F7C8), index=73>, <BMVert(0x00000221FB10F800), index=74>, ...] |
If we try to walk through the list and change each vertex’s “select” property to False,
1 2 |
for vert in selected_vertiecs: vert.select = False |
we will see that the vertices are deselected, but the edges and faces of the mesh are still selected.
To remove the selection completely, we can find linked edges and polygons for our list of vertices in a loop and remove the selection in them, but there is an easier way.
First, switch the selection mode to the vertex selection mode – “VERTS”. And after removing the selection from the vertices, call the selection recalculation function select_flush_mode() so that it changes for the entire mesh geometry without exceptions.
1 2 3 4 5 6 |
bm.select_mode = {'VERT'} for vert in selected_vertiecs: vert.select = False bm.select_flush_mode() |
Now we see that the selection has been completely removed from our mesh.
We can do the same when setting the desired selection. Select the desired vertices, and then recalculate the selection.
For example, let’s select the first hundred vertices along with the edges and polygons adjacent to them.
1 2 3 4 |
for i in range(100): bm.verts[i].select = True bm.select_flush_mode() |
As with deselecting, using the select_flush_mode() function frees us from having to separately search for and select the edges and polygons of the mesh that are intended for selection.
Don’t forget to return the changes from the bmesh to the original mesh and clear the memory bmesh occupies.
1 2 |
bmesh.update_edit_mesh(bpy.context.object.data) bm.free() |