Skip to content

Instantly share code, notes, and snippets.

@JTRNS
Created April 7, 2022 08:52
Show Gist options
  • Save JTRNS/e45a40573e689dd94e0cc4078c1de1d0 to your computer and use it in GitHub Desktop.
Save JTRNS/e45a40573e689dd94e0cc4078c1de1d0 to your computer and use it in GitHub Desktop.
Create vertex groups for each mesh before joining objects in Blender
bl_info = {
"name": "Smart Join",
"author": "Jeroen Trines",
"version": (1, 0),
"blender": (3, 1, 0),
"location": "View3D > Object > Smart Join",
"description": "Create vertex groups for each mesh before joining objects in Blender",
"warning": "",
"doc_url": "",
"category": "Object",
}
import bpy
def isMesh(data):
return hasattr(data, 'type') and data.type == 'MESH'
def getSelectedMeshes(context):
return list(filter(isMesh, context.selected_objects))
def prependObjectNameToVertexGroups(mesh):
for vg in mesh.vertex_groups:
if vg.name.startswith(mesh.name.lower()):
continue
vg.name = f"{mesh.name.lower()}_{vg.name}"
def lockAllVertexGroups(mesh):
for vg in mesh.vertex_groups:
vg.lock_weight = True
def addObjectNameAsVertexGroup(mesh):
# https://docs.blender.org/api/current/bpy.path.html?highlight=case#bpy.path.clean_name
cleaned = bpy.path.clean_name(name=mesh.name)
vg = mesh.vertex_groups.new(name=cleaned)
vg.add(range(len(mesh.data.vertices)), 1.0, 'REPLACE')
def main(context):
for m in getSelectedMeshes(context):
prependObjectNameToVertexGroups(m)
addObjectNameAsVertexGroup(m)
lockAllVertexGroups(m)
bpy.ops.object.join()
class SmartJoinOperator(bpy.types.Operator):
"""Tooltip"""
bl_idname = "object.smart_join"
bl_label = "Smart Join"
@classmethod
def poll(cls, context):
return len([o for o in context.selected_objects if o.type == 'MESH']) > 1
def execute(self, context):
main(context)
return {'FINISHED'}
def menu_func(self, context):
self.layout.operator(SmartJoinOperator.bl_idname, text=SmartJoinOperator.bl_label)
# Register and add to the "object" menu (required to also use F3 search "Simple Object Operator" for quick access)
def register():
bpy.utils.register_class(SmartJoinOperator)
bpy.types.VIEW3D_MT_object.append(menu_func)
def unregister():
bpy.utils.unregister_class(SmartJoinOperator)
bpy.types.VIEW3D_MT_object.remove(menu_func)
if __name__ == "__main__":
register()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment