Skip to content

Instantly share code, notes, and snippets.

@usagi
Forked from p2or/blender-merge-vertex-groups.py
Last active April 13, 2020 16:15
Show Gist options
  • Save usagi/dfb7a0ca6de32c08f277b51d2c9de867 to your computer and use it in GitHub Desktop.
Save usagi/dfb7a0ca6de32c08f277b51d2c9de867 to your computer and use it in GitHub Desktop.
import bpy
from re import compile
print('')
# Target(s) REGEX
regex = compile( '^Edit(KamiARoot|MaeKamiA(_00[1,2])?)$' )
# Replace Mode := Remove a target(s) -> new a merged
replace = True
# Merged name; "+".join if None
to = 'EditKamiARoot'
# Dry run
dry = True
ob = bpy.context.active_object
group_lookup = {g.index: g.name for g in ob.vertex_groups}
group_candidates = {n for n in group_lookup.values() if regex.match(n)}
# test whether all candidates components of group_lookup
if all(n in group_lookup.values() for n in group_candidates):
pass
# general tests
if (len(group_candidates) and ob.type == 'MESH' and
bpy.context.mode == 'OBJECT'):
# iterate through the vertices and sum the weights per group
vertex_weights = {}
for vert in ob.data.vertices:
if len(vert.groups):
for item in vert.groups:
vg = ob.vertex_groups[item.group]
if vg.name in group_candidates:
if vert.index in vertex_weights:
vertex_weights[vert.index] += vg.weight(vert.index)
else:
vertex_weights[vert.index] = vg.weight(vert.index)
# clamp/slice values above 1.0
for key in vertex_weights.keys():
if (vertex_weights[key] > 1.0): vertex_weights[key] = 1.0
# remove sources
if replace:
for g in group_candidates:
if dry:
print('be remove(dry-run): ', g)
else:
ob.vertex_groups.remove(ob.vertex_groups.get(g))
print('removed:', g)
# create new vertex group
new_name = to if to != None else "+".join(group_candidates)
if dry:
print('be merge(dry-run):', new_name)
else:
vgroup = ob.vertex_groups.new(name=new_name)
print('merged: ', vgroup.name)
# add the values to the group
for key, value in vertex_weights.items():
vgroup.add([key], value ,'REPLACE') #'ADD','SUBTRACT'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment