## Description
The “Blender Script to Remove Duplicate Shape Keys and Empty Vertex Groups” is a Python script for Blender that automates the process of cleaning up shape keys and vertex groups in selected mesh objects. Specifically, the script performs the following actions:
1. Identifies and removes any shape keys (excluding the first one) that have the same vertex coordinates as the first shape key (basis shape key).
2. Deletes any vertex groups that have no assigned vertices (empty vertex groups).
3. If the first shape key is the only shape key remaining after the cleanup, it will also be removed.
## Directions
1. Open Blender and select the mesh objects you want to process.
2. Open the Scripting workspace in Blender.
3. Create a new script by clicking on the “New” button in the Text Editor.
4. Copy and paste the provided script into the Text Editor.
5. Click the “Run Script” button (or press the Alt+P key combination) to execute the script.
Before running the script, it is strongly recommended to save your Blender project and create a backup copy of the data you are working on. The script modifies shape keys and vertex groups, so it’s essential to have a backup in case of any unintended results.
## Source
```python
import bpy
import math
# Define a tolerance for comparing vertex positions
tolerance = 1e-5
def are_vertices_equal(verts_a, verts_b):
for i in range(len(verts_a)):
if math.sqrt((verts_a[i].co - verts_b[i].co).length_squared) > tolerance:
return False
return True
def is_vertex_group_empty(obj, group_index):
for v in obj.data.vertices:
for g in v.groups:
if g.group == group_index:
return False
return True
# Iterate over all selected objects
for obj in bpy.context.selected_objects:
# Check if the object is a mesh and has shape keys
if obj.type == 'MESH':
if obj.data.shape_keys:
# Get the vertex coordinates of the first shape key (basis shape key)
basis_shape_key = obj.data.shape_keys.key_blocks[0]
basis_verts = basis_shape_key.data
# Iterate over the rest of the shape keys (ignoring the first one)
i = 1
while i < len(obj.data.shape_keys.key_blocks):
shape_key = obj.data.shape_keys.key_blocks[i]
# Compare the vertex coordinates to the basis shape key's coordinates
if are_vertices_equal(basis_verts, shape_key.data):
# If the vertex coordinates match, delete the shape key
bpy.context.object.active_shape_key_index = i
bpy.ops.object.shape_key_remove(all=False)
else:
i += 1
# Delete the first shape key if it's the only one left
if len(obj.data.shape_keys.key_blocks) == 1:
bpy.context.object.active_shape_key_index = 0
bpy.ops.object.shape_key_remove(all=False)
# Check the object's vertex groups and delete any vertex group that has no assigned vertices
i = 0
while i < len(obj.vertex_groups):
if is_vertex_group_empty(obj, i):
obj.vertex_groups.remove(obj.vertex_groups[i])
else:
i += 1
```