diff options
Diffstat (limited to 'release/scripts/modules')
14 files changed, 908 insertions, 585 deletions
diff --git a/release/scripts/modules/bpy/utils.py b/release/scripts/modules/bpy/utils.py index 76e8b011628..ad0fa4e8ba5 100644 --- a/release/scripts/modules/bpy/utils.py +++ b/release/scripts/modules/bpy/utils.py @@ -53,6 +53,23 @@ def clean_name(name, replace="_"): name = name.replace(ch, replace) return name +def display_name(name): + ''' + Only capitalize all lowercase names, mixed case use them as is. + should work with filenames and module names. + ''' + name_base = os.path.splitext(name)[0] + + # string replacements + name_base = name_base.replace("_colon_", ":") + + name_base = name_base.replace("_", " ") + + if name_base.lower() == name_base: + return ' '.join([w[0].upper() + w[1:] for w in name_base.split()]) + else: + return name_base + # base scripts _scripts = os.path.join(os.path.dirname(__file__), os.path.pardir, os.path.pardir) diff --git a/release/scripts/modules/bpy_types.py b/release/scripts/modules/bpy_types.py index 28ea2d71be8..239990e2bd5 100644 --- a/release/scripts/modules/bpy_types.py +++ b/release/scripts/modules/bpy_types.py @@ -288,21 +288,7 @@ class Menu(StructRNA): # hard coded to set the operators 'path' to the filename. import os - - def path_to_name(f): - ''' Only capitalize all lowercase names, mixed case use them as is. - ''' - f_base = os.path.splitext(f)[0] - - # string replacements - f_base = f_base.replace("_colon_", ":") - - f_base = f_base.replace("_", " ") - - if f_base.lower() == f_base: - return ' '.join([w[0].upper() + w[1:] for w in f_base.split()]) - else: - return f_base + import bpy.utils layout = self.layout @@ -318,7 +304,7 @@ class Menu(StructRNA): if f.startswith("."): continue - layout.operator(operator, text=path_to_name(f)).path = path + layout.operator(operator, text=bpy.utils.display_name(f)).path = path def draw_preset(self, context): '''Define these on the subclass diff --git a/release/scripts/modules/graphviz_export.py b/release/scripts/modules/graphviz_export.py index 92eb427f8d2..f39095b9eba 100644 --- a/release/scripts/modules/graphviz_export.py +++ b/release/scripts/modules/graphviz_export.py @@ -48,7 +48,7 @@ def compat_str(text, line_length=0): #text = text.replace(']', ']\n') text = text.replace("\n", "\\n") text = text.replace('"', '\\"') - return "* " + text + return text def graph_armature(obj, path, FAKE_PARENT=True, CONSTRAINTS=True, DRIVERS=True, XTRA_INFO=True): @@ -150,16 +150,16 @@ def graph_armature(obj, path, FAKE_PARENT=True, CONSTRAINTS=True, DRIVERS=True, if animation_data: fcurve_drivers = [fcurve_driver for fcurve_driver in animation_data.drivers] - fcurve_drivers.sort(key=lambda fcurve_driver: fcurve_driver.rna_path) + fcurve_drivers.sort(key=lambda fcurve_driver: fcurve_driver.data_path) for fcurve_driver in fcurve_drivers: - rna_path = fcurve_driver.rna_path + rna_path = fcurve_driver.data_path pbone = rna_path_as_pbone(rna_path) if pbone: for target in fcurve_driver.driver.targets: - pbone_target = rna_path_as_pbone(target.rna_path) - rna_path_target = target.rna_path + pbone_target = rna_path_as_pbone(target.data_path) + rna_path_target = target.data_path if pbone_target: opts = ['dir=forward', "weight=1", "arrowhead=normal", "arrowtail=none", "constraint=false", 'color="blue"', "labelfontsize=4"] # , display_source = rna_path.replace("pose.bones", "") diff --git a/release/scripts/modules/rigify/__init__.py b/release/scripts/modules/rigify/__init__.py index af345b5e546..33a2f4c007e 100644 --- a/release/scripts/modules/rigify/__init__.py +++ b/release/scripts/modules/rigify/__init__.py @@ -23,376 +23,96 @@ from Mathutils import Vector # TODO, have these in a more general module from rna_prop_ui import rna_idprop_ui_prop_get - -empty_layer = [False] * 32 - - -def auto_class(slots, name="ContainerClass", class_dict=None): - - if class_dict: - class_dict = class_dict.copy() - else: - class_dict = {} - - class_dict["__slots__"] = tuple(slots) - - return type(name, (object,), class_dict) - - -def auto_class_instance(slots, name="ContainerClass", class_dict=None): - return auto_class(slots, name, class_dict)() - - -def _bone_class_instance_update(self): - ''' Re-Assigns bones from the blender data - ''' - arm = self.obj.data - bbones = arm.bones - pbones = self.obj.pose.bones - ebones = arm.edit_bones - - for member in self.attr_names: - name = getattr(self, member, None) - if name is not None: - setattr(self, member + "_b", bbones.get(name, None)) - setattr(self, member + "_p", pbones.get(name, None)) - setattr(self, member + "_e", ebones.get(name, None)) - - -def _bone_class_instance_rename(self, attr, new_name): - ''' Rename bones, editmode only - ''' - - if self.obj.mode != 'EDIT': - raise Exception("Only rename in editmode supported") - - ebone = getattr(self, attr + "_e") - ebone.name = new_name - - # we may not get what is asked for so get the name from the editbone - setattr(self, attr, ebone.name) - - -def _bone_class_instance_copy(self, from_fmt="%s", to_fmt="%s", exclude_attrs=(), base_names=None): - from_name_ls = [] - new_name_ls = [] - new_slot_ls = [] - - for attr in self.attr_names: - - if attr in exclude_attrs: - continue +SPECIAL_TYPES = "root", + +class RigifyError(Exception): + """Exception raised for errors in the metarig. + """ + def __init__(self, message): + self.message = message + def __str__(self): + return repr(self.message) + +def submodule_func_from_type(bone_type): + type_pair = bone_type.split(".") + + # 'leg.ik' will look for an ik function in the leg module + # 'leg' will look up leg.main + if len(type_pair) == 1: + type_pair = type_pair[0], "main" + + submod_name, func_name = type_pair + + # from rigify import leg + try: + submod = __import__(name="%s.%s" % (__package__, submod_name), fromlist=[submod_name]) + except ImportError: + raise RigifyError("python module for type '%s' not found" % submod_name) - bone_name_orig = getattr(self, attr) - ebone = getattr(self, attr + "_e") - # orig_names[attr] = bone_name_orig - - # insert formatting - if from_fmt != "%s": - bone_name = from_fmt % bone_name_orig - ebone.name = bone_name - bone_name = ebone.name # cant be sure we get what we ask for - else: - bone_name = bone_name_orig - - setattr(self, attr, bone_name) - - new_slot_ls.append(attr) - from_name_ls.append(bone_name) - if base_names: - bone_name_orig = base_names[bone_name_orig] - new_name_ls.append(to_fmt % bone_name_orig) - - new_bones = copy_bone_simple_list(self.obj.data, from_name_ls, new_name_ls, True) - new_bc = bone_class_instance(self.obj, new_slot_ls) - - for i, attr in enumerate(new_slot_ls): - ebone = new_bones[i] - setattr(new_bc, attr + "_e", ebone) - setattr(new_bc, attr, ebone.name) - - return new_bc - - -def _bone_class_instance_names(self): - return [getattr(self, attr) for attr in self.attr_names] - - -def _bone_class_instance_blend(self, from_bc, to_bc, target_bone=None, target_prop="blend"): - ''' - Use for blending bone chains. + reload(submod) + return submod, getattr(submod, func_name) - blend_target = (bone_name, bone_property) - default to the last bone, blend prop - XXX - toggles editmode, need to re-validate all editbones :( - ''' - - if self.attr_names != from_bc.attr_names or self.attr_names != to_bc.attr_names: - raise Exception("can only blend between matching chains") - - apply_bones = [getattr(self, attr) for attr in self.attr_names] - from_bones = [getattr(from_bc, attr) for attr in from_bc.attr_names] - to_bones = [getattr(to_bc, attr) for attr in to_bc.attr_names] - - blend_bone_list(self.obj, apply_bones, from_bones, to_bones, target_bone, target_prop) - - -def bone_class_instance(obj, slots, name="BoneContainer"): +def submodule_types(): + import os + submodules = [] + files = os.listdir(os.path.dirname(__file__)) + for f in files: + if not f.startswith("_") and f.endswith(".py"): + submodules.append(f[:-3]) - if len(slots) != len(set(slots)): - raise Exception("duplicate entries found %s" % attr_names) - - attr_names = tuple(slots) # dont modify the original - slots = list(slots) # dont modify the original - for i in range(len(slots)): - member = slots[i] - slots.append(member + "_b") # bone bone - slots.append(member + "_p") # pose bone - slots.append(member + "_e") # edit bone - - class_dict = { \ - "obj": obj, \ - "attr_names": attr_names, \ - "update": _bone_class_instance_update, \ - "rename": _bone_class_instance_rename, \ - "names": _bone_class_instance_names, \ - "copy": _bone_class_instance_copy, \ - "blend": _bone_class_instance_blend, \ - } - - instance = auto_class_instance(slots, name, class_dict) - return instance - - -def get_bone_data(obj, bone_name): - arm = obj.data - pbone = obj.pose.bones[bone_name] - if obj.mode == 'EDIT': - bone = arm.edit_bones[bone_name] - else: - bone = arm.bones[bone_name] - - return arm, pbone, bone + return sorted(submodules) -def copy_bone_simple(arm, from_bone, name, parent=False): - ebone = arm.edit_bones[from_bone] - ebone_new = arm.edit_bones.new(name) - - if parent: - ebone_new.connected = ebone.connected - ebone_new.parent = ebone.parent - - ebone_new.head = ebone.head - ebone_new.tail = ebone.tail - ebone_new.roll = ebone.roll - return ebone_new - - -def copy_bone_simple_list(arm, from_bones, to_bones, parent=False): - - if len(from_bones) != len(to_bones): - raise Exception("bone list sizes must match") - - copy_bones = [copy_bone_simple(arm, bone_name, to_bones[i], True) for i, bone_name in enumerate(from_bones)] - - # now we need to re-parent - for ebone in copy_bones: - parent = ebone.parent - if parent: - try: - i = from_bones.index(parent.name) - except: - i = -1 - - if i == -1: - ebone.parent = None - else: - ebone.parent = copy_bones[i] - - return copy_bones - - -def blend_bone_list(obj, apply_bones, from_bones, to_bones, target_bone=None, target_prop="blend"): - - if obj.mode == 'EDIT': - raise Exception("blending cant be called in editmode") - - if len(apply_bones) != len(from_bones): - raise Exception("lists differ in length (from -> apply): \n\t%s\n\t%s" % (from_bones, apply_bones)) - if len(apply_bones) != len(to_bones): - raise Exception("lists differ in length (to -> apply): \n\t%s\n\t%s" % (to_bones, apply_bones)) - - # setup the blend property - if target_bone is None: - target_bone = apply_bones[-1] # default to the last bone - - prop_pbone = obj.pose.bones[target_bone] - if prop_pbone.get(target_bone, None) is None: - prop = rna_idprop_ui_prop_get(prop_pbone, target_prop, create=True) - prop_pbone[target_prop] = 0.5 - prop["soft_min"] = 0.0 - prop["soft_max"] = 1.0 - - driver_path = prop_pbone.path_to_id() + ('["%s"]' % target_prop) - - def blend_target(driver): - tar = driver.targets.new() - tar.name = target_bone - tar.id_type = 'OBJECT' - tar.id = obj - tar.rna_path = driver_path - - def blend_location(new_pbone, from_bone_name, to_bone_name): - con = new_pbone.constraints.new('COPY_LOCATION') - con.target = obj - con.subtarget = from_bone_name - - con = new_pbone.constraints.new('COPY_LOCATION') - con.target = obj - con.subtarget = to_bone_name - - fcurve = con.driver_add("influence", 0) - driver = fcurve.driver - driver.type = 'AVERAGE' - fcurve.modifiers.remove(0) # grr dont need a modifier - - blend_target(driver) - - def blend_rotation(new_pbone, from_bone_name, to_bone_name): - con = new_pbone.constraints.new('COPY_ROTATION') - con.target = obj - con.subtarget = from_bone_name - - con = new_pbone.constraints.new('COPY_ROTATION') - con.target = obj - con.subtarget = to_bone_name - - fcurve = con.driver_add("influence", 0) - driver = fcurve.driver - driver.type = 'AVERAGE' - fcurve.modifiers.remove(0) # grr dont need a modifier - - blend_target(driver) - - for i, new_bone_name in enumerate(apply_bones): - from_bone_name = from_bones[i] - to_bone_name = to_bones[i] - - # allow skipping some bones by having None in the list - if None in (new_bone_name, from_bone_name, to_bone_name): - continue - - new_pbone = obj.pose.bones[new_bone_name] - - # if the bone is connected or its location is totally locked then dont add location blending. - if not (new_pbone.bone.connected or (False not in new_pbone.lock_location)): - blend_location(new_pbone, from_bone_name, to_bone_name) - - if not (False not in new_pbone.lock_rotation): # TODO. 4D chech? - blend_rotation(new_pbone, from_bone_name, to_bone_name) - - -def add_stretch_to(obj, from_name, to_name, name): +def validate_rig(context, obj): ''' - Adds a bone that stretches from one to another + Makes no changes + only runs the metarig definitions and reports errors ''' - - mode_orig = obj.mode - bpy.ops.object.mode_set(mode='EDIT') - - arm = obj.data - stretch_ebone = arm.edit_bones.new(name) - stretch_name = stretch_ebone.name - del name - - head = stretch_ebone.head = arm.edit_bones[from_name].head.copy() - #tail = stretch_ebone.tail = arm.edit_bones[to_name].head.copy() - - # annoying exception for zero length bones, since its using stretch_to the rest pose doesnt really matter - #if (head - tail).length < 0.1: - if 1: - tail = stretch_ebone.tail = arm.edit_bones[from_name].tail.copy() - - - # Now for the constraint - bpy.ops.object.mode_set(mode='OBJECT') - - stretch_pbone = obj.pose.bones[stretch_name] - - con = stretch_pbone.constraints.new('COPY_LOCATION') - con.target = obj - con.subtarget = from_name - - con = stretch_pbone.constraints.new('STRETCH_TO') - con.target = obj - con.subtarget = to_name - con.original_length = (head - tail).length - con.keep_axis = 'PLANE_X' - con.volume = 'NO_VOLUME' - - bpy.ops.object.mode_set(mode=mode_orig) + type_found = False - return stretch_name - -def add_pole_target_bone(obj, base_name, name, mode='CROSS'): - ''' - Does not actually create a poll target, just the bone to use as a poll target - ''' - mode_orig = obj.mode - bpy.ops.object.mode_set(mode='EDIT') - - arm = obj.data - - poll_ebone = arm.edit_bones.new(base_name + "_poll") - base_ebone = arm.edit_bones[base_name] - poll_name = poll_ebone.name - parent_ebone = base_ebone.parent - - base_head = base_ebone.head.copy() - base_tail = base_ebone.tail.copy() - base_dir = base_head - base_tail - - parent_head = parent_ebone.head.copy() - parent_tail = parent_ebone.tail.copy() - parent_dir = parent_head - parent_tail + for pbone in obj.pose.bones: + bone_name = pbone.name + bone_type = pbone.get("type", "") - distance = (base_dir.length + parent_dir.length) - - if mode == 'CROSS': - # direction from the angle of the joint - offset = base_dir.copy().normalize() - parent_dir.copy().normalize() - offset.length = distance - elif mode == 'ZAVERAGE': - # between both bones Z axis - z_axis_a = base_ebone.matrix.copy().rotationPart() * Vector(0.0, 0.0, -1.0) - z_axis_b = parent_ebone.matrix.copy().rotationPart() * Vector(0.0, 0.0, -1.0) - offset = (z_axis_a + z_axis_b).normalize() * distance - else: - # preset axis - offset = Vector(0, 0, 0) - if mode[0] == "+": - val = distance + if bone_type: + bone_type_list = [bt for bt in bone_type.replace(",", " ").split()] else: - val = - distance - - setattr(offset, mode[1].lower(), val) - - poll_ebone.head = base_head + offset - poll_ebone.tail = base_head + (offset * (1.0 - (1.0 / 4.0))) + bone_type_list = [] - bpy.ops.object.mode_set(mode=mode_orig) + for bone_type in bone_type_list: + if bone_type.split(".")[0] in SPECIAL_TYPES: + continue - return poll_name + submod, type_func = submodule_func_from_type(bone_type) + reload(submod) + submod.metarig_definition(obj, bone_name) + type_found = True + + # missing, - check for duplicate root bone. + + if not type_found: + raise RigifyError("This rig has no 'type' properties defined on any pose bones, nothing to do") def generate_rig(context, obj_orig, prefix="ORG-", META_DEF=True): + ''' + Main function for generating + ''' from collections import OrderedDict + import rigify_utils + reload(rigify_utils) + + # Not needed but catches any errors before duplicating + validate_rig(context, obj_orig) global_undo = context.user_preferences.edit.global_undo context.user_preferences.edit.global_undo = False - + mode_orig = context.mode + rest_backup = obj_orig.data.pose_position + obj_orig.data.pose_position = 'REST' + + bpy.ops.object.mode_set(mode='OBJECT') scene = context.scene @@ -404,7 +124,7 @@ def generate_rig(context, obj_orig, prefix="ORG-", META_DEF=True): scene.objects.link(obj) scene.objects.active = obj obj.selected = True - + if META_DEF: obj_def = obj_orig.copy() obj_def.data = obj_orig.data.copy() @@ -435,6 +155,12 @@ def generate_rig(context, obj_orig, prefix="ORG-", META_DEF=True): # value: [functions, ...] # each function is from the module. eg leg.ik, arm.main bone_typeinfos = {} + + # key: bone name + # value: [new_bone_name, ...] + # where each bone with a 'type' stores a list of bones that it created + # ...needed so we can override the root parent + bone_genesis = {} # inspect all bones and assign their definitions before modifying for pbone in obj.pose.bones: @@ -455,31 +181,17 @@ def generate_rig(context, obj_orig, prefix="ORG-", META_DEF=True): bone_type_list[:] = [] for bone_type in bone_type_list: - - type_pair = bone_type.split(".") - - # 'leg.ik' will look for an ik function in the leg module - # 'leg' will look up leg.main - if len(type_pair) == 1: - type_pair = type_pair[0], "main" - - submod_name, func_name = type_pair - - # from rigify import leg - submod = __import__(name="%s.%s" % (__package__, submod_name), fromlist=[submod_name]) + submod, type_func = submodule_func_from_type(bone_type) reload(submod) - + submod_name = submod.__name__ + bone_def_dict = bone_definitions.setdefault(bone_name, {}) # Only calculate bone definitions once if submod_name not in bone_def_dict: - metarig_definition_func = getattr(submod, "metarig_definition") - bone_def_dict[submod_name] = metarig_definition_func(obj, bone_name) - + bone_def_dict[submod_name] = submod.metarig_definition(obj, bone_name) bone_typeinfo = bone_typeinfos.setdefault(bone_name, []) - - type_func = getattr(submod, func_name) bone_typeinfo.append((submod_name, type_func)) @@ -501,6 +213,8 @@ def generate_rig(context, obj_orig, prefix="ORG-", META_DEF=True): # Only blend results from the same submodule, eg. # leg.ik and arm.fk could not be blended. results = OrderedDict() + + bone_names_pre = set([bone.name for bone in arm.bones]) for submod_name, type_func in bone_typeinfos[bone_name]: # this bones definition of the current typeinfo @@ -525,15 +239,41 @@ def generate_rig(context, obj_orig, prefix="ORG-", META_DEF=True): if len(result_submod) == 2: blend_bone_list(obj, definition, result_submod[0], result_submod[1], target_bone=bone_name) + + bone_names_post = set([bone.name for bone in arm.bones]) + + # Store which bones were created from this one + bone_genesis[bone_name] = list(bone_names_post - bone_names_pre) + + # need a reverse lookup on bone_genesis so as to know immediately + # where a bone comes from + bone_genesis_reverse = {} + for bone_name, bone_children in bone_genesis.items(): + for bone_child_name in bone_children: + bone_genesis_reverse[bone_child_name] = bone_name + + if root_bone: # assign all new parentless bones to this bpy.ops.object.mode_set(mode='EDIT') root_ebone = arm.edit_bones[root_bone] for ebone in arm.edit_bones: - if ebone.parent is None and ebone.name not in base_names: + bone_name = ebone.name + if ebone.parent is None and bone_name not in base_names: + # check for override + bone_creator = bone_genesis_reverse[bone_name] + pbone_creator = obj.pose.bones[bone_creator] + root_bone_override = pbone_creator.get("root", "") + + if root_bone_override: + root_ebone_tmp = arm.edit_bones[root_bone_override] + else: + root_ebone_tmp = root_ebone + ebone.connected = False - ebone.parent = root_ebone + ebone.parent = root_ebone_tmp + bpy.ops.object.mode_set(mode='OBJECT') @@ -552,75 +292,24 @@ def generate_rig(context, obj_orig, prefix="ORG-", META_DEF=True): con.target = obj con.subtarget = bone_name + # would be 'REST' from when copied + obj_def.data.pose_position = 'POSE' + # Only for demo'ing # obj.restrict_view = True obj.data.draw_axes = False + bpy.ops.object.mode_set(mode=mode_orig) + obj_orig.data.pose_position = rest_backup + obj.data.pose_position = 'POSE' context.user_preferences.edit.global_undo = global_undo - + + return obj -def write_meta_rig(obj, func_name="metarig_template"): - ''' Must be in editmode - ''' - code = [] - - code.append("def %s():" % func_name) - code.append(" # generated by rigify.write_meta_rig") - bpy.ops.object.mode_set(mode='EDIT') - code.append(" bpy.ops.object.mode_set(mode='EDIT')") - - code.append(" obj = bpy.context.object") - code.append(" arm = obj.data") - - arm = obj.data - # write parents first - bones = [(len(bone.parent_recursive), bone.name) for bone in arm.edit_bones] - bones.sort(key=lambda item: item[0]) - bones = [item[1] for item in bones] - - - for bone_name in bones: - bone = arm.edit_bones[bone_name] - code.append(" bone = arm.edit_bones.new('%s')" % bone.name) - code.append(" bone.head[:] = %.4f, %.4f, %.4f" % bone.head.toTuple(4)) - code.append(" bone.tail[:] = %.4f, %.4f, %.4f" % bone.tail.toTuple(4)) - code.append(" bone.roll = %.4f" % bone.roll) - code.append(" bone.connected = %s" % str(bone.connected)) - if bone.parent: - code.append(" bone.parent = arm.edit_bones['%s']" % bone.parent.name) - - bpy.ops.object.mode_set(mode='OBJECT') - code.append("") - code.append(" bpy.ops.object.mode_set(mode='OBJECT')") - - for bone_name in bones: - pbone = obj.pose.bones[bone_name] - pbone_written = False - - # Only 1 level of props, simple types supported - for key, value in pbone.items(): - if key.startswith("_"): - continue - - if type(value) not in (float, str, int): - print("Unsupported ID Prop:", str((key, value))) - continue - - if type(value) == str: - value = "'" + value + "'" - - if not pbone_written: # only write bones we need - code.append(" pbone = obj.pose.bones['%s']" % bone_name) - - code.append(" pbone['%s'] = %s" % (key, value)) - - return "\n".join(code) - - -def generate_test(context): +def generate_test(context, metarig_type="", GENERATE_FINAL=True): import os new_objects = [] @@ -632,53 +321,58 @@ def generate_test(context): obj_new.data = armature scene.objects.link(obj_new) scene.objects.active = obj_new + for obj in scene.objects: + obj.selected = False + obj_new.selected = True - files = os.listdir(os.path.dirname(__file__)) - for f in files: - if f.startswith("_"): - continue - - if not f.endswith(".py"): + for module_name in submodule_types(): + if (metarig_type and module_name != metarig_type): continue - - module_name = f[:-3] - submodule = __import__(name="%s.%s" % (__package__, module_name), fromlist=[module_name]) + + submodule, func = submodule_func_from_type(module_name) metarig_template = getattr(submodule, "metarig_template", None) if metarig_template: create_empty_armature("meta_" + module_name) # sets active metarig_template() - obj = context.object - obj_new = generate_rig(context, obj) - - new_objects.append((obj, obj_new)) + obj = context.active_object + obj.location = scene.cursor_location + + if GENERATE_FINAL: + obj_new = generate_rig(context, obj) + new_objects.append((obj, obj_new)) + else: + new_objects.append((obj, None)) else: print("note: rig type '%s' has no metarig_template(), can't test this", module_name) return new_objects -def generate_test_all(context): +def generate_test_all(context, GRAPH=False): import rigify + import rigify_utils import graphviz_export import os reload(rigify) + reload(rigify_utils) reload(graphviz_export) new_objects = rigify.generate_test(context) + + if GRAPH: + base_name = os.path.splitext(bpy.data.filename)[0] + for obj, obj_new in new_objects: + for obj in (obj, obj_new): + fn = base_name + "-" + bpy.utils.clean_name(obj.name) - base_name = os.path.splitext(bpy.data.filename)[0] - for obj, obj_new in new_objects: - for obj in (obj, obj_new): - fn = base_name + "-" + bpy.utils.clean_name(obj.name) - - path_dot = fn + ".dot" - path_png = fn + ".png" - saved = graphviz_export.graph_armature(obj, path_dot, CONSTRAINTS=True, DRIVERS=True) + path_dot = fn + ".dot" + path_png = fn + ".png" + saved = graphviz_export.graph_armature(obj, path_dot, CONSTRAINTS=True, DRIVERS=True) - #if saved: - # os.system("dot -Tpng %s > %s; eog %s" % (path_dot, path_png, path_png)) + #if saved: + # os.system("dot -Tpng %s > %s; eog %s" % (path_dot, path_png, path_png)) i = 0 for obj, obj_new in new_objects: @@ -691,4 +385,4 @@ def generate_test_all(context): if __name__ == "__main__": - generate_rig(bpy.context, bpy.context.object) + generate_rig(bpy.context, bpy.context.active_object) diff --git a/release/scripts/modules/rigify/arm.py b/release/scripts/modules/rigify/arm_biped_generic.py index 6ed564ac070..e22857852ee 100644 --- a/release/scripts/modules/rigify/arm.py +++ b/release/scripts/modules/rigify/arm_biped_generic.py @@ -19,7 +19,8 @@ # <pep8 compliant> import bpy -from rigify import bone_class_instance, copy_bone_simple, add_pole_target_bone, add_stretch_to, blend_bone_list +from rigify import RigifyError +from rigify_utils import bone_class_instance, copy_bone_simple, add_pole_target_bone, add_stretch_to, blend_bone_list, get_side_name, get_base_name from rna_prop_ui import rna_idprop_ui_prop_get from Mathutils import Vector @@ -29,7 +30,7 @@ METARIG_NAMES = "shoulder", "arm", "forearm", "hand" def metarig_template(): # generated by rigify.write_meta_rig bpy.ops.object.mode_set(mode='EDIT') - obj = bpy.context.object + obj = bpy.context.active_object arm = obj.data bone = arm.edit_bones.new('shoulder') bone.head[:] = 0.0000, -0.4515, 0.0000 @@ -57,7 +58,7 @@ def metarig_template(): bpy.ops.object.mode_set(mode='OBJECT') pbone = obj.pose.bones['upper_arm'] - pbone['type'] = 'arm' + pbone['type'] = 'arm_biped_generic' def metarig_definition(obj, orig_bone_name): @@ -68,10 +69,7 @@ def metarig_definition(obj, orig_bone_name): mt.shoulder_p = mt.arm_p.parent if not mt.shoulder_p: - raise Exception("could not find '%s' parent, skipping:" % orig_bone_name) - - if mt.arm_p.parent.bone.connected: - raise Exception("expected '%s' to be disconnected from its parent" % orig_bone_name) + raise RigifyError("could not find '%s' parent, skipping:" % orig_bone_name) mt.shoulder = mt.shoulder_p.name @@ -79,11 +77,11 @@ def metarig_definition(obj, orig_bone_name): hands = [] for pbone in obj.pose.bones: index = pbone.parent_index(mt.arm_p) - if index == 2: + if index == 2 and pbone.bone.connected and pbone.bone.parent.connected: hands.append(pbone) if len(hands) != 1: - raise Exception("Expected more then 1 hand found on:", orig_bone_name) + raise RigifyError("Found %s possible hands attached to this arm, expected 1 from bone: %s" % ([pbone.name for pbone in hands], orig_bone_name)) # first add the 2 new bones mt.hand_p = hands[0] @@ -106,12 +104,18 @@ def ik(obj, definitions, base_names): # IK needs no parent_index ik_chain.hand_e.connected = False ik_chain.hand_e.parent = None + ik_chain.hand_e.local_location = False + ik_chain.rename("hand", get_base_name(base_names[mt.hand]) + "_ik" + get_side_name(mt.hand)) ik_chain.arm_e.connected = False ik_chain.arm_e.parent = mt.shoulder_e # Add the bone used for the arms poll target - ik.pole = add_pole_target_bone(obj, mt.forearm, "elbow_poll", mode='ZAVERAGE') + #ik.pole = add_pole_target_bone(obj, mt.forearm, get_base_name(base_names[mt.forearm]) + "_target" + get_side_name(mt.forearm), mode='ZAVERAGE') + ik.pole = add_pole_target_bone(obj, mt.forearm, "elbow_target" + get_side_name(mt.forearm), mode='ZAVERAGE') + + ik.update() + ik.pole_e.local_location = False # update bones after this! ik.hand_vis = add_stretch_to(obj, mt.hand, ik_chain.hand, "VIS-%s_ik" % base_names[mt.hand]) @@ -178,7 +182,7 @@ def fk(obj, definitions, base_names): ex.socket = ex.socket_e.name ex.socket_e.connected = False ex.socket_e.parent = mt.shoulder_e - ex.socket_e.tail = mt.shoulder_e.tail + ex.socket_e.length *= 0.5 # insert the 'DLT-hand', between the forearm and the hand # copies forarm rotation @@ -236,7 +240,7 @@ def fk(obj, definitions, base_names): tar.name = "hinge" tar.id_type = 'OBJECT' tar.id = obj - tar.rna_path = controller_path + '["hinge"]' + tar.data_path = controller_path + '["hinge"]' mod = driver_fcurve.modifiers[0] mod.poly_order = 1 diff --git a/release/scripts/modules/rigify/copy.py b/release/scripts/modules/rigify/copy.py new file mode 100644 index 00000000000..21d0970234b --- /dev/null +++ b/release/scripts/modules/rigify/copy.py @@ -0,0 +1,66 @@ +# ##### BEGIN GPL LICENSE BLOCK ##### +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; either version 2 +# of the License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software Foundation, +# Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +# +# ##### END GPL LICENSE BLOCK ##### + +# <pep8 compliant> + +import bpy +from rigify_utils import copy_bone_simple, get_side_name, bone_class_instance +from rna_prop_ui import rna_idprop_ui_prop_get + +METARIG_NAMES = ("cpy",) + +# note, this example is just a bone with copy property. +def metarig_template(): + # generated by rigify.write_meta_rig + bpy.ops.object.mode_set(mode='EDIT') + obj = bpy.context.active_object + arm = obj.data + bone = arm.edit_bones.new('Bone') + bone.head[:] = 0.0000, 0.0000, 0.0000 + bone.tail[:] = 0.0000, 0.0000, 1.0000 + bone.roll = 0.0000 + bone.connected = False + + bpy.ops.object.mode_set(mode='OBJECT') + pbone = obj.pose.bones['Bone'] + pbone['type'] = 'copy' + +def metarig_definition(obj, orig_bone_name): + return [orig_bone_name] + + +def main(obj, bone_definition, base_names): + arm = obj.data + mt = bone_class_instance(obj, METARIG_NAMES) + mt.cpy = bone_definition[0] + mt.update() + cp = mt.copy(to_fmt="%s_cpy") + bpy.ops.object.mode_set(mode='OBJECT') + + cp.update() + mt.update() + + con = cp.cpy_p.constraints.new('COPY_ROTATION') + con.target = obj + con.subtarget = mt.cpy + + con = cp.cpy_p.constraints.new('COPY_LOCATION') + con.target = obj + con.subtarget = mt.cpy + + return [mt.cpy] diff --git a/release/scripts/modules/rigify/delta.py b/release/scripts/modules/rigify/delta.py index 00d79ed33df..261e2b22479 100644 --- a/release/scripts/modules/rigify/delta.py +++ b/release/scripts/modules/rigify/delta.py @@ -19,12 +19,40 @@ # <pep8 compliant> import bpy -from rigify import get_bone_data +from rigify import RigifyError # not used, defined for completeness METARIG_NAMES = tuple() +def metarig_template(): + # generated by rigify.write_meta_rig + bpy.ops.object.mode_set(mode='EDIT') + obj = bpy.context.active_object + arm = obj.data + bone = arm.edit_bones.new('bonesker') + bone.head[:] = 0.0000, 0.0000, 0.0000 + bone.tail[:] = -0.0000, 0.7382, 0.1895 + bone.roll = -0.0000 + bone.connected = False + bone = arm.edit_bones.new('delta') + bone.head[:] = -0.0497, 0.8414, 0.3530 + bone.tail[:] = -0.2511, 1.1588, 0.9653 + bone.roll = 2.6044 + bone.connected = False + bone.parent = arm.edit_bones['bonesker'] + bone = arm.edit_bones.new('boney') + bone.head[:] = 0.7940, 2.5592, 0.4134 + bone.tail[:] = 0.7940, 3.3975, 0.4890 + bone.roll = 3.1416 + bone.connected = False + bone.parent = arm.edit_bones['delta'] + + bpy.ops.object.mode_set(mode='OBJECT') + pbone = obj.pose.bones['delta'] + pbone['type'] = 'delta' + + def metarig_definition(obj, orig_bone_name): ''' The bone given is the head, its parent is the body, @@ -37,7 +65,10 @@ def metarig_definition(obj, orig_bone_name): children = delta.children if len(children) != 1: - print("only 1 child supported for delta") + raise RigifyError("only 1 child supported for delta on bone '%s'" % delta.name) + + if delta.connected: + raise RigifyError("bone cannot be connected to its parent '%s'" % delta.name) bone_definition = [delta.name, children[0].name] @@ -48,7 +79,6 @@ def main(obj, bone_definition, base_names): ''' Use this bone to define a delta thats applied to its child in pose mode. ''' - mode_orig = obj.mode bpy.ops.object.mode_set(mode='OBJECT') @@ -56,7 +86,8 @@ def main(obj, bone_definition, base_names): delta_pbone = obj.pose.bones[delta_name] - arm, child_pbone, child_bone = get_bone_data(obj, child_name) + arm = obj.data + child_pbone = obj.pose.bones[child_name] delta_phead = delta_pbone.head.copy() delta_ptail = delta_pbone.tail.copy() @@ -77,7 +108,6 @@ def main(obj, bone_definition, base_names): delta_head = delta_ebone.head.copy() delta_tail = delta_ebone.tail.copy() - # arm, parent_pbone, parent_bone = get_bone_data(obj, delta_name) child_head = child_ebone.head.copy() child_tail = child_ebone.tail.copy() @@ -125,7 +155,6 @@ def main(obj, bone_definition, base_names): mod.coefficients[1] = 0.0 - # arm, parent_pbone, parent_bone = get_bone_data(obj, delta_name) bpy.ops.object.mode_set(mode='EDIT') bpy.ops.object.mode_set(mode=mode_orig) diff --git a/release/scripts/modules/rigify/finger.py b/release/scripts/modules/rigify/finger_curl.py index baa9ed49041..7f21eecd7d3 100644 --- a/release/scripts/modules/rigify/finger.py +++ b/release/scripts/modules/rigify/finger_curl.py @@ -19,7 +19,8 @@ # <pep8 compliant> import bpy -from rigify import get_bone_data, empty_layer, copy_bone_simple +from rigify import RigifyError +from rigify_utils import copy_bone_simple, get_side_name, get_base_name, EMPTY_LAYER from rna_prop_ui import rna_idprop_ui_prop_get from functools import reduce @@ -28,7 +29,7 @@ METARIG_NAMES = "finger_01", "finger_02", "finger_03" def metarig_template(): bpy.ops.object.mode_set(mode='EDIT') - obj = bpy.context.object + obj = bpy.context.active_object arm = obj.data bone = arm.edit_bones.new('finger.01') bone.head[:] = 0.0000, 0.0000, 0.0000 @@ -50,7 +51,7 @@ def metarig_template(): bpy.ops.object.mode_set(mode='OBJECT') pbone = obj.pose.bones['finger.01'] - pbone['type'] = 'finger' + pbone['type'] = 'finger_curl' def metarig_definition(obj, orig_bone_name): @@ -73,13 +74,13 @@ def metarig_definition(obj, orig_bone_name): children = bone.children if len(children) != 1: - raise Exception("expected the chain to have 2 children without a fork") + raise RigifyError("expected the chain to have 2 children from bone '%s' without a fork" % orig_bone_name) bone = children[0] bone_definition.append(bone.name) # finger_02, finger_03 chain += 1 if len(bone_definition) != len(METARIG_NAMES): - raise Exception("internal problem, expected %d bones" % len(METARIG_NAMES)) + raise RigifyError("internal problem, expected %d bones" % len(METARIG_NAMES)) return bone_definition @@ -89,7 +90,9 @@ def main(obj, bone_definition, base_names): # *** EDITMODE # get assosiated data - arm, orig_pbone, orig_ebone = get_bone_data(obj, bone_definition[0]) + arm = obj.data + orig_pbone = obj.pose.bones[bone_definition[0]] + orig_ebone = arm.edit_bones[bone_definition[0]] obj.animation_data_create() # needed if its a new armature with no keys @@ -98,11 +101,12 @@ def main(obj, bone_definition, base_names): children = orig_pbone.children_recursive tot_len = reduce(lambda f, pbone: f + pbone.bone.length, children, orig_pbone.bone.length) - base_name = base_names[bone_definition[0]].rsplit(".", 1)[0] + # FIXME, the line below is far too arbitrary + base_name = base_names[bone_definition[0]].rsplit(".", 2)[0] # first make a new bone at the location of the finger #control_ebone = arm.edit_bones.new(base_name) - control_ebone = copy_bone_simple(arm, bone_definition[0], base_name) + control_ebone = copy_bone_simple(arm, bone_definition[0], base_name + get_side_name(base_names[bone_definition[0]]), parent=True) control_bone_name = control_ebone.name # we dont know if we get the name requested control_ebone.connected = orig_ebone.connected @@ -115,7 +119,7 @@ def main(obj, bone_definition, base_names): children = [pbone.name for pbone in children] # set an alternate layer for driver bones - other_layer = empty_layer[:] + other_layer = EMPTY_LAYER[:] other_layer[8] = True @@ -197,14 +201,14 @@ def main(obj, bone_definition, base_names): tar.name = "scale" tar.id_type = 'OBJECT' tar.id = obj - tar.rna_path = controller_path + '.scale[1]' + tar.data_path = controller_path + '.scale[1]' # bend target tar = driver.targets.new() tar.name = "br" tar.id_type = 'OBJECT' tar.id = obj - tar.rna_path = controller_path + '["bend_ratio"]' + tar.data_path = controller_path + '["bend_ratio"]' # XXX - todo, any number if i == 0: diff --git a/release/scripts/modules/rigify/leg.py b/release/scripts/modules/rigify/leg_biped_generic.py index ed28c21fd32..65fde79da6e 100644 --- a/release/scripts/modules/rigify/leg.py +++ b/release/scripts/modules/rigify/leg_biped_generic.py @@ -19,7 +19,8 @@ # <pep8 compliant> import bpy -from rigify import bone_class_instance, copy_bone_simple, blend_bone_list +from rigify import RigifyError +from rigify_utils import bone_class_instance, copy_bone_simple, blend_bone_list, get_side_name, get_base_name from rna_prop_ui import rna_idprop_ui_prop_get METARIG_NAMES = "hips", "thigh", "shin", "foot", "toe", "heel" @@ -28,7 +29,7 @@ METARIG_NAMES = "hips", "thigh", "shin", "foot", "toe", "heel" def metarig_template(): # generated by rigify.write_meta_rig bpy.ops.object.mode_set(mode='EDIT') - obj = bpy.context.object + obj = bpy.context.active_object arm = obj.data bone = arm.edit_bones.new('hips') bone.head[:] = 0.0000, 0.0000, 0.0000 @@ -68,7 +69,7 @@ def metarig_template(): bpy.ops.object.mode_set(mode='OBJECT') pbone = obj.pose.bones['thigh'] - pbone['type'] = 'leg' + pbone['type'] = 'leg_biped_generic' def metarig_definition(obj, orig_bone_name): @@ -85,7 +86,7 @@ def metarig_definition(obj, orig_bone_name): orig_bone_parent = orig_bone.parent if orig_bone_parent is None: - raise Exception("expected the thigh bone to have a parent hip bone") + raise RigifyError("expected the thigh bone to have a parent hip bone") bone_definition.append(orig_bone_parent.name) bone_definition.append(orig_bone.name) @@ -97,7 +98,7 @@ def metarig_definition(obj, orig_bone_name): children = bone.children if len(children) != 1: - raise Exception("expected the thigh bone to have 3 children without a fork") + raise RigifyError("expected the thigh bone to have 3 children without a fork") bone = children[0] bone_definition.append(bone.name) # shin, foot chain += 1 @@ -105,10 +106,10 @@ def metarig_definition(obj, orig_bone_name): children = bone.children # Now there must be 2 children, only one connected if len(children) != 2: - raise Exception("expected the foot bone:'%s' to have 2 children" % bone.name ) + raise RigifyError("expected the foot bone:'%s' to have 2 children" % bone.name ) if children[0].connected == children[1].connected: - raise Exception("expected one bone to be connected") + raise RigifyError("expected one bone to be connected") toe, heel = children if heel.connected: @@ -119,7 +120,7 @@ def metarig_definition(obj, orig_bone_name): bone_definition.append(heel.name) if len(bone_definition) != len(METARIG_NAMES): - raise Exception("internal problem, expected %d bones" % len(METARIG_NAMES)) + raise RigifyError("internal problem, expected %d bones" % len(METARIG_NAMES)) return bone_definition @@ -145,22 +146,26 @@ def ik(obj, bone_definition, base_names): # XXX - end dupe - # Make a new chain, ORG are the original bones renamed. - ik_chain = mt_chain.copy(to_fmt="MCH-%s") + # Make a new chain + ik_chain = mt_chain.copy(to_fmt="MCH-%s", base_names=base_names) # simple rename ik_chain.rename("thigh", ik_chain.thigh + "_ik") ik_chain.rename("shin", ik_chain.shin + "_ik") - # ik foot, no parents - base_foot_name = base_names[mt_chain.foot] # whatever the foot is called, use that!, XXX - ORG! - ik.foot_e = copy_bone_simple(arm, mt_chain.foot, "%s_ik" % base_foot_name) + # make sure leg is child of hips + ik_chain.thigh_e.parent = mt.hips_e + + # ik foot: no parents + base_foot_name = get_base_name(base_names[mt_chain.foot]) + ik.foot_e = copy_bone_simple(arm, mt_chain.foot, base_foot_name + "_ik" + get_side_name(base_names[mt_chain.foot])) ik.foot = ik.foot_e.name ik.foot_e.tail.z = ik.foot_e.head.z ik.foot_e.roll = 0.0 + ik.foot_e.local_location = False - # heel pointing backwards, half length - ik.foot_roll_e = copy_bone_simple(arm, mt.heel, "%s_roll" % base_foot_name) + # foot roll: heel pointing backwards, half length + ik.foot_roll_e = copy_bone_simple(arm, mt.heel, base_foot_name + "_roll" + get_side_name(base_names[mt_chain.foot])) ik.foot_roll = ik.foot_roll_e.name ik.foot_roll_e.tail = ik.foot_roll_e.head + (ik.foot_roll_e.head - ik.foot_roll_e.tail) / 2.0 ik.foot_roll_e.parent = ik.foot_e # heel is disconnected @@ -182,7 +187,7 @@ def ik(obj, bone_definition, base_names): # rename 'MCH-toe' --> to 'toe_ik' and make the child of ik.foot_roll_01 # ------------------ FK or IK? - ik_chain.rename("toe", base_names[mt_chain.toe] + "_ik") + ik_chain.rename("toe", get_base_name(base_names[mt_chain.toe]) + "_ik" + get_side_name(base_names[mt_chain.toe])) ik_chain.toe_e.connected = False ik_chain.toe_e.parent = ik.foot_roll_01_e @@ -201,6 +206,7 @@ def ik(obj, bone_definition, base_names): ik.knee_target_e.translate(offset) ik.knee_target_e.length *= 0.5 ik.knee_target_e.parent = ik.foot_e + ik.knee_target_e.local_location = False # roll the bone to point up... could also point in the same direction as ik.foot_roll # ik.foot_roll_02_e.matrix * Vector(0.0, 0.0, 1.0) # ACK!, no rest matrix in editmode @@ -218,6 +224,12 @@ def ik(obj, bone_definition, base_names): ik_chain.shin_p.ik_dof_y = False ik_chain.shin_p.ik_dof_z = False + # Set rotation modes and axis locks + ik.foot_roll_p.rotation_mode = 'XYZ' + ik.foot_roll_p.lock_rotation = False, True, True + ik_chain.toe_p.rotation_mode = 'YXZ' + ik_chain.toe_p.lock_rotation = False, True, True + # IK con = ik_chain.shin_p.constraints.new('IK') con.chain_length = 2 @@ -284,13 +296,10 @@ def fk(obj, bone_definition, base_names): ex.thigh_socket = ex.thigh_socket_e.name ex.thigh_socket_e.tail = ex.thigh_socket_e.head + Vector(0.0, 0.0, ex.thigh_socket_e.length / 4.0) - ex.thigh_hinge_e = copy_bone_simple(arm, mt_chain.thigh, "MCH-%s_hinge" % base_names[mt_chain.thigh]) + ex.thigh_hinge_e = copy_bone_simple(arm, mt.hips, "MCH-%s_hinge" % base_names[mt_chain.thigh], parent=False) ex.thigh_hinge = ex.thigh_hinge_e.name - ex.thigh_hinge_e.tail = ex.thigh_hinge_e.head + Vector(0.0, 0.0, mt_chain.thigh_e.head.length) - ex.thigh_hinge_e.translate(Vector( - (mt.hips_e.head.x - mt_chain.thigh_e.head.x), 0.0, 0.0)) - ex.thigh_hinge_e.length = mt.hips_e.length - fk_chain = mt_chain.copy() # fk has no prefix! + fk_chain = mt_chain.copy(base_names=base_names) # fk has no prefix! fk_chain.thigh_e.connected = False fk_chain.thigh_e.parent = ex.thigh_hinge_e @@ -301,6 +310,13 @@ def fk(obj, bone_definition, base_names): mt_chain.update() fk_chain.update() + # Set rotation modes and axis locks + fk_chain.shin_p.rotation_mode = 'XYZ' + fk_chain.shin_p.lock_rotation = False, True, True + fk_chain.foot_p.rotation_mode = 'YXZ' + fk_chain.toe_p.rotation_mode = 'YXZ' + fk_chain.toe_p.lock_rotation = False, True, True + con = fk_chain.thigh_p.constraints.new('COPY_LOCATION') con.target = obj con.subtarget = ex.thigh_socket @@ -325,7 +341,7 @@ def fk(obj, bone_definition, base_names): tar.name = "var" tar.id_type = 'OBJECT' tar.id = obj - tar.rna_path = hinge_driver_path + tar.data_path = hinge_driver_path mod = fcurve.modifiers[0] mod.poly_order = 1 diff --git a/release/scripts/modules/rigify/neck.py b/release/scripts/modules/rigify/neck_flex.py index 887b0b091fc..9bb852b25b5 100644 --- a/release/scripts/modules/rigify/neck.py +++ b/release/scripts/modules/rigify/neck_flex.py @@ -19,7 +19,8 @@ # <pep8 compliant> import bpy -from rigify import bone_class_instance, copy_bone_simple +from rigify import RigifyError +from rigify_utils import bone_class_instance, copy_bone_simple from rna_prop_ui import rna_idprop_ui_prop_get # not used, defined for completeness @@ -29,7 +30,7 @@ METARIG_NAMES = ("body", "head") def metarig_template(): # generated by rigify.write_meta_rig bpy.ops.object.mode_set(mode='EDIT') - obj = bpy.context.object + obj = bpy.context.active_object arm = obj.data bone = arm.edit_bones.new('body') bone.head[:] = -0.0000, -0.2771, -1.3345 @@ -75,7 +76,7 @@ def metarig_template(): bpy.ops.object.mode_set(mode='OBJECT') pbone = obj.pose.bones['head'] - pbone['type'] = 'neck' + pbone['type'] = 'neck_flex' def metarig_definition(obj, orig_bone_name): @@ -91,7 +92,7 @@ def metarig_definition(obj, orig_bone_name): children = head.children if len(children) != 1: - print("expected the head to have only 1 child.") + raise RigifyError("expected the head bone '%s' to have only 1 child." % orig_bone_name) child = children[0] bone_definition = [body.name, head.name, child.name] @@ -120,10 +121,14 @@ def main(obj, bone_definition, base_names): neck_chain_basename = base_names[mt_chain.neck_01_e.name].split(".")[0] neck_chain_segment_length = mt_chain.neck_01_e.length - ex = bone_class_instance(obj, ["body", "head", "head_hinge", "neck_socket"]) # hinge & extras + ex = bone_class_instance(obj, ["body", "head", "head_hinge", "neck_socket", "head_ctrl"]) # hinge & extras # Add the head hinge at the bodys location, becomes the parent of the original head + # apply everything to this copy of the chain + ex_chain = mt_chain.copy(base_names=base_names) + ex_chain.neck_01_e.parent = mt_chain.neck_01_e.parent + # Copy the head bone and offset ex.head_e = copy_bone_simple(arm, mt.head, "MCH_%s" % base_names[mt.head], parent=True) @@ -135,16 +140,12 @@ def main(obj, bone_definition, base_names): ex.head_e.tail.y += head_length / 2.0 # Yes, use the body bone but call it a head hinge - ex.head_hinge_e = copy_bone_simple(arm, mt.body, "MCH_%s_hinge" % base_names[mt.head], parent=True) + ex.head_hinge_e = copy_bone_simple(arm, mt.body, "MCH_%s_hinge" % base_names[mt.head], parent=False) ex.head_hinge_e.connected = False ex.head_hinge = ex.head_hinge_e.name ex.head_hinge_e.head.y += head_length / 4.0 ex.head_hinge_e.tail.y += head_length / 4.0 - # reparent the head, assume its not connected - mt.head_e.connected = False - mt.head_e.parent = ex.head_hinge_e - # Insert the neck socket, the head copys this loation ex.neck_socket_e = arm.edit_bones.new("MCH-%s_socked" % neck_chain_basename) ex.neck_socket = ex.neck_socket_e.name @@ -153,20 +154,21 @@ def main(obj, bone_definition, base_names): ex.neck_socket_e.head = mt.head_e.head ex.neck_socket_e.tail = mt.head_e.head - Vector(0.0, neck_chain_segment_length / 2.0, 0.0) ex.neck_socket_e.roll = 0.0 + + + # copy of the head for controling + ex.head_ctrl_e = copy_bone_simple(arm, mt.head, base_names[mt.head]) + ex.head_ctrl = ex.head_ctrl_e.name + ex.head_ctrl_e.parent = ex.head_hinge_e - # offset the head, not really needed since it has a copyloc constraint - mt.head_e.head.y += head_length / 4.0 - mt.head_e.tail.y += head_length / 4.0 - - for i, attr in enumerate(mt_chain.attr_names): - neck_e = getattr(mt_chain, attr + "_e") + for i, attr in enumerate(ex_chain.attr_names): + neck_e = getattr(ex_chain, attr + "_e") # dont store parent names, re-reference as each chain bones parent. - neck_e_parent = arm.edit_bones.new("MCH-rot_%s" % base_names[neck_e.name]) + neck_e_parent = arm.edit_bones.new("MCH-rot_%s" % base_names[getattr(mt_chain, attr)]) neck_e_parent.head = neck_e.head neck_e_parent.tail = neck_e.head + ((mt.head_e.tail - mt.head_e.head).normalize() * neck_chain_segment_length / 2.0) neck_e_parent.roll = mt.head_e.roll - orig_parent = neck_e.parent neck_e.connected = False @@ -183,20 +185,21 @@ def main(obj, bone_definition, base_names): mt.update() mt_chain.update() + ex_chain.update() ex.update() # Simple one off constraints, no drivers - con = mt.head_p.constraints.new('COPY_LOCATION') + con = ex.head_ctrl_p.constraints.new('COPY_LOCATION') con.target = obj con.subtarget = ex.neck_socket con = ex.head_p.constraints.new('COPY_ROTATION') con.target = obj - con.subtarget = mt.head + con.subtarget = ex.head_ctrl # driven hinge - prop = rna_idprop_ui_prop_get(mt.head_p, "hinge", create=True) - mt.head_p["hinge"] = 0.0 + prop = rna_idprop_ui_prop_get(ex.head_ctrl_p, "hinge", create=True) + ex.head_ctrl_p["hinge"] = 0.0 prop["soft_min"] = 0.0 prop["soft_max"] = 1.0 @@ -206,7 +209,7 @@ def main(obj, bone_definition, base_names): con.subtarget = mt.body # add driver - hinge_driver_path = mt.head_p.path_to_id() + '["hinge"]' + hinge_driver_path = ex.head_ctrl_p.path_to_id() + '["hinge"]' fcurve = con.driver_add("influence", 0) driver = fcurve.driver @@ -215,7 +218,7 @@ def main(obj, bone_definition, base_names): tar.name = "var" tar.id_type = 'OBJECT' tar.id = obj - tar.rna_path = hinge_driver_path + tar.data_path = hinge_driver_path #mod = fcurve_driver.modifiers.new('GENERATOR') mod = fcurve.modifiers[0] @@ -223,12 +226,12 @@ def main(obj, bone_definition, base_names): mod.coefficients[0] = 1.0 mod.coefficients[1] = -1.0 - head_driver_path = mt.head_p.path_to_id() + head_driver_path = ex.head_ctrl_p.path_to_id() target_names = [("b%.2d" % (i + 1)) for i in range(len(neck_chain))] - mt.head_p["bend_tot"] = 0.0 - fcurve = mt.head_p.driver_add('["bend_tot"]', 0) + ex.head_ctrl_p["bend_tot"] = 0.0 + fcurve = ex.head_ctrl_p.driver_add('["bend_tot"]', 0) driver = fcurve.driver driver.type = 'SUM' fcurve.modifiers.remove(0) # grr dont need a modifier @@ -238,19 +241,19 @@ def main(obj, bone_definition, base_names): tar.name = target_names[i] tar.id_type = 'OBJECT' tar.id = obj - tar.rna_path = head_driver_path + ('["bend_%.2d"]' % (i + 1)) + tar.data_path = head_driver_path + ('["bend_%.2d"]' % (i + 1)) - for i, attr in enumerate(mt_chain.attr_names): - neck_p = getattr(mt_chain, attr + "_p") + for i, attr in enumerate(ex_chain.attr_names): + neck_p = getattr(ex_chain, attr + "_p") neck_p.lock_location = True, True, True neck_p.lock_location = True, True, True neck_p.lock_rotations_4d = True # Add bend prop prop_name = "bend_%.2d" % (i + 1) - prop = rna_idprop_ui_prop_get(mt.head_p, prop_name, create=True) - mt.head_p[prop_name] = 1.0 + prop = rna_idprop_ui_prop_get(ex.head_ctrl_p, prop_name, create=True) + ex.head_ctrl_p[prop_name] = 1.0 prop["soft_min"] = 0.0 prop["soft_max"] = 1.0 @@ -278,13 +281,20 @@ def main(obj, bone_definition, base_names): tar.name = "bend_tot" tar.id_type = 'OBJECT' tar.id = obj - tar.rna_path = head_driver_path + ('["bend_tot"]') + tar.data_path = head_driver_path + ('["bend_tot"]') tar = driver.targets.new() tar.name = "bend" tar.id_type = 'OBJECT' tar.id = obj - tar.rna_path = head_driver_path + ('["%s"]' % prop_name) + tar.data_path = head_driver_path + ('["%s"]' % prop_name) + + + # finally constrain the original bone to this one + orig_neck_p = getattr(mt_chain, attr + "_p") + con = orig_neck_p.constraints.new('COPY_ROTATION') + con.target = obj + con.subtarget = neck_p.name # no blending the result of this return None diff --git a/release/scripts/modules/rigify/palm.py b/release/scripts/modules/rigify/palm_curl.py index 5f4ada6128d..867889b0084 100644 --- a/release/scripts/modules/rigify/palm.py +++ b/release/scripts/modules/rigify/palm_curl.py @@ -19,7 +19,7 @@ # <pep8 compliant> import bpy -from rigify import get_bone_data, copy_bone_simple +from rigify_utils import copy_bone_simple, get_side_name from rna_prop_ui import rna_idprop_ui_prop_get # not used, defined for completeness @@ -28,7 +28,7 @@ METARIG_NAMES = tuple() def metarig_template(): # generated by rigify.write_meta_rig bpy.ops.object.mode_set(mode='EDIT') - obj = bpy.context.object + obj = bpy.context.active_object arm = obj.data bone = arm.edit_bones.new('hand') bone.head[:] = 0.0082, -1.2492, 0.0000 @@ -74,7 +74,7 @@ def metarig_template(): bpy.ops.object.mode_set(mode='OBJECT') pbone = obj.pose.bones['palm.01'] - pbone['type'] = 'palm' + pbone['type'] = 'palm_curl' def metarig_definition(obj, orig_bone_name): @@ -97,7 +97,8 @@ def metarig_definition(obj, orig_bone_name): def main(obj, bone_definition, base_names): - arm, palm_pbone, palm_ebone = get_bone_data(obj, bone_definition[0]) + arm = obj.data + children = bone_definition[1:] # Make a copy of the pinky @@ -105,7 +106,10 @@ def main(obj, bone_definition, base_names): pinky_ebone = arm.edit_bones[children[0]] ring_ebone = arm.edit_bones[children[1]] - control_ebone = copy_bone_simple(arm, pinky_ebone.name, "palm_control", parent=True) + # FIXME, why split the second one? + base_name = base_names[pinky_ebone.name].rsplit('.', 2)[0] + + control_ebone = copy_bone_simple(arm, pinky_ebone.name, base_name + get_side_name(base_names[pinky_ebone.name]), parent=True) control_name = control_ebone.name offset = (pinky_ebone.head - ring_ebone.head) @@ -114,9 +118,9 @@ def main(obj, bone_definition, base_names): bpy.ops.object.mode_set(mode='OBJECT') - - arm, control_pbone, control_ebone = get_bone_data(obj, control_name) - arm, pinky_pbone, pinky_ebone = get_bone_data(obj, children[0]) + arm = obj.data + control_pbone = obj.pose.bones[control_name] + pinky_pbone = obj.pose.bones[children[0]] control_pbone.rotation_mode = 'YZX' control_pbone.lock_rotation = False, True, True @@ -141,7 +145,7 @@ def main(obj, bone_definition, base_names): tar.name = "x" tar.id_type = 'OBJECT' tar.id = obj - tar.rna_path = controller_path + ".rotation_euler[0]" + tar.data_path = controller_path + ".rotation_euler[0]" # ***** @@ -152,23 +156,43 @@ def main(obj, bone_definition, base_names): tar.name = "x" tar.id_type = 'OBJECT' tar.id = obj - tar.rna_path = controller_path + ".rotation_euler[0]" + tar.data_path = controller_path + ".rotation_euler[0]" # ***** driver = driver_fcurves[2].driver driver.expression = "(1.0-cos(x))-s" + + def x_direction(): + # NOTE: the direction of the Z rotation depends on which side the palm is on. + # we could do a simple side-of-x test but better to work out the direction + # the hand is facing. + from Mathutils import Vector, AngleBetweenVecs + from math import degrees + child_pbone_01 = obj.pose.bones[children[0]] + child_pbone_02 = obj.pose.bones[children[1]] + + rel_vec = child_pbone_01.head - child_pbone_02.head + x_vec = child_pbone_01.matrix.rotationPart() * Vector(1.0, 0.0, 0.0) + return degrees(AngleBetweenVecs(rel_vec, x_vec)) > 90.0 + + if x_direction(): # flip + driver.expression = "-(%s)" % driver.expression + + for fcurve in driver_fcurves: + fcurve.modifiers.remove(0) # grr dont need a modifier + tar = driver.targets.new() tar.name = "x" tar.id_type = 'OBJECT' tar.id = obj - tar.rna_path = controller_path + ".rotation_euler[0]" + tar.data_path = controller_path + ".rotation_euler[0]" tar = driver.targets.new() tar.name = "s" tar.id_type = 'OBJECT' tar.id = obj - tar.rna_path = controller_path + '["spread"]' + tar.data_path = controller_path + '["spread"]' for i, child_name in enumerate(children): diff --git a/release/scripts/modules/rigify/spine.py b/release/scripts/modules/rigify/spine_pivot_flex.py index 2ccc10350b1..beeb5c68b7c 100644 --- a/release/scripts/modules/rigify/spine.py +++ b/release/scripts/modules/rigify/spine_pivot_flex.py @@ -19,7 +19,7 @@ # <pep8 compliant> import bpy -from rigify import bone_class_instance, copy_bone_simple +from rigify_utils import bone_class_instance, copy_bone_simple from rna_prop_ui import rna_idprop_ui_prop_get # not used, defined for completeness @@ -29,7 +29,7 @@ METARIG_NAMES = ("pelvis", "ribcage") def metarig_template(): # generated by rigify.write_meta_rig bpy.ops.object.mode_set(mode='EDIT') - obj = bpy.context.object + obj = bpy.context.active_object arm = obj.data bone = arm.edit_bones.new('pelvis') bone.head[:] = -0.0000, -0.2559, 0.8673 @@ -87,7 +87,7 @@ def metarig_template(): bpy.ops.object.mode_set(mode='OBJECT') pbone = obj.pose.bones['rib_cage'] - pbone['type'] = 'spine.fk' + pbone['type'] = 'spine_pivot_flex' def metarig_definition(obj, orig_bone_name): @@ -104,11 +104,11 @@ def metarig_definition(obj, orig_bone_name): pelvis = ribcage.parent if pelvis is None: - raise Exception("expected the ribcage bone:'%s' to have a parent (ribcage)." % ribcage.name) + raise RigifyError("expected the ribcage bone:'%s' to have a parent (ribcage)." % ribcage.name) children = ribcage.children if len(children) != 1: - raise Exception("expected the ribcage to have only 1 child.") + raise RigifyError("expected the ribcage to have only 1 child.") child = children[0] @@ -148,6 +148,7 @@ def main(obj, bone_definition, base_names): ex.pelvis_copy_e = copy_bone_simple(arm, mt.pelvis, base_names[mt.pelvis]) # no parent ex.pelvis_copy = ex.pelvis_copy_e.name + ex.pelvis_copy_e.local_location = False # copy the pelvis, offset to make MCH-spine_rotate and MCH-ribcage_hinge ex.ribcage_hinge_e = copy_bone_simple(arm, mt.pelvis, "MCH-%s_hinge" % base_names[mt.ribcage]) @@ -321,7 +322,7 @@ def main(obj, bone_definition, base_names): tar.name = "var" tar.id_type = 'OBJECT' tar.id = obj - tar.rna_path = ex.ribcage_copy_p.path_to_id() + '["hinge"]' + tar.data_path = ex.ribcage_copy_p.path_to_id() + '["hinge"]' mod = fcurve.modifiers[0] mod.poly_order = 1 @@ -405,7 +406,7 @@ def main(obj, bone_definition, base_names): tar.name = target_names[i] tar.id_type = 'OBJECT' tar.id = obj - tar.rna_path = rib_driver_path + ('["bend_%.2d"]' % (i + 1)) + tar.data_path = rib_driver_path + ('["bend_%.2d"]' % (i + 1)) for i in range(1, spine_chain_len): @@ -440,13 +441,13 @@ def main(obj, bone_definition, base_names): tar.name = "bend_tot" tar.id_type = 'OBJECT' tar.id = obj - tar.rna_path = rib_driver_path + ('["bend_tot"]') + tar.data_path = rib_driver_path + ('["bend_tot"]') tar = driver.targets.new() tar.name = "bend" tar.id_type = 'OBJECT' tar.id = obj - tar.rna_path = rib_driver_path + ('["%s"]' % prop_name) + tar.data_path = rib_driver_path + ('["%s"]' % prop_name) @@ -489,7 +490,7 @@ def main(obj, bone_definition, base_names): tar.name = "var" tar.id_type = 'OBJECT' tar.id = obj - tar.rna_path = rib_driver_path + '["pivot_slide"]' + tar.data_path = rib_driver_path + '["pivot_slide"]' mod = fcurve.modifiers[0] mod.poly_order = 1 diff --git a/release/scripts/modules/rigify_utils.py b/release/scripts/modules/rigify_utils.py new file mode 100644 index 00000000000..a1fc54cb5bb --- /dev/null +++ b/release/scripts/modules/rigify_utils.py @@ -0,0 +1,472 @@ +# ##### BEGIN GPL LICENSE BLOCK ##### +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; either version 2 +# of the License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software Foundation, +# Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +# +# ##### END GPL LICENSE BLOCK ##### + +# <pep8 compliant> + +# rigify its self does not depend on this module, however some of the +# rigify templates use these utility functions. +# +# So even though this can be for general purpose use, this module was created +# for rigify so in some cases seemingly generic functions make assumptions +# that a generic function would need to check for. + +import bpy +from Mathutils import Vector +from rna_prop_ui import rna_idprop_ui_prop_get + +DELIMITER = '-._' +EMPTY_LAYER = [False] * 32 + +def add_stretch_to(obj, from_name, to_name, name): + ''' + Adds a bone that stretches from one to another + ''' + + mode_orig = obj.mode + bpy.ops.object.mode_set(mode='EDIT') + + arm = obj.data + stretch_ebone = arm.edit_bones.new(name) + stretch_name = stretch_ebone.name + del name + + head = stretch_ebone.head = arm.edit_bones[from_name].head.copy() + #tail = stretch_ebone.tail = arm.edit_bones[to_name].head.copy() + + # annoying exception for zero length bones, since its using stretch_to the rest pose doesnt really matter + #if (head - tail).length < 0.1: + if 1: + tail = stretch_ebone.tail = arm.edit_bones[from_name].tail.copy() + + + # Now for the constraint + bpy.ops.object.mode_set(mode='OBJECT') + + stretch_pbone = obj.pose.bones[stretch_name] + + con = stretch_pbone.constraints.new('COPY_LOCATION') + con.target = obj + con.subtarget = from_name + + con = stretch_pbone.constraints.new('STRETCH_TO') + con.target = obj + con.subtarget = to_name + con.original_length = (head - tail).length + con.keep_axis = 'PLANE_X' + con.volume = 'NO_VOLUME' + + bpy.ops.object.mode_set(mode=mode_orig) + + return stretch_name + + +def copy_bone_simple(arm, from_bone, name, parent=False): + ebone = arm.edit_bones[from_bone] + ebone_new = arm.edit_bones.new(name) + + if parent: + ebone_new.connected = ebone.connected + ebone_new.parent = ebone.parent + + ebone_new.head = ebone.head + ebone_new.tail = ebone.tail + ebone_new.roll = ebone.roll + return ebone_new + + +def copy_bone_simple_list(arm, from_bones, to_bones, parent=False): + + if len(from_bones) != len(to_bones): + raise Exception("bone list sizes must match") + + copy_bones = [copy_bone_simple(arm, bone_name, to_bones[i], True) for i, bone_name in enumerate(from_bones)] + + # now we need to re-parent + for ebone in copy_bones: + parent = ebone.parent + if parent: + try: + i = from_bones.index(parent.name) + except: + i = -1 + + if i == -1: + ebone.parent = None + else: + ebone.parent = copy_bones[i] + + return copy_bones + + +def blend_bone_list(obj, apply_bones, from_bones, to_bones, target_bone=None, target_prop="blend"): + + if obj.mode == 'EDIT': + raise Exception("blending cant be called in editmode") + + if len(apply_bones) != len(from_bones): + raise Exception("lists differ in length (from -> apply): \n\t%s\n\t%s" % (from_bones, apply_bones)) + if len(apply_bones) != len(to_bones): + raise Exception("lists differ in length (to -> apply): \n\t%s\n\t%s" % (to_bones, apply_bones)) + + # setup the blend property + if target_bone is None: + target_bone = apply_bones[-1] # default to the last bone + + prop_pbone = obj.pose.bones[target_bone] + if prop_pbone.get(target_bone, None) is None: + prop = rna_idprop_ui_prop_get(prop_pbone, target_prop, create=True) + prop_pbone[target_prop] = 0.5 + prop["soft_min"] = 0.0 + prop["soft_max"] = 1.0 + + driver_path = prop_pbone.path_to_id() + ('["%s"]' % target_prop) + + def blend_target(driver): + tar = driver.targets.new() + tar.name = target_bone + tar.id_type = 'OBJECT' + tar.id = obj + tar.data_path = driver_path + + def blend_location(new_pbone, from_bone_name, to_bone_name): + con = new_pbone.constraints.new('COPY_LOCATION') + con.target = obj + con.subtarget = from_bone_name + + con = new_pbone.constraints.new('COPY_LOCATION') + con.target = obj + con.subtarget = to_bone_name + + fcurve = con.driver_add("influence", 0) + driver = fcurve.driver + driver.type = 'AVERAGE' + fcurve.modifiers.remove(0) # grr dont need a modifier + + blend_target(driver) + + def blend_rotation(new_pbone, from_bone_name, to_bone_name): + con = new_pbone.constraints.new('COPY_ROTATION') + con.target = obj + con.subtarget = from_bone_name + + con = new_pbone.constraints.new('COPY_ROTATION') + con.target = obj + con.subtarget = to_bone_name + + fcurve = con.driver_add("influence", 0) + driver = fcurve.driver + driver.type = 'AVERAGE' + fcurve.modifiers.remove(0) # grr dont need a modifier + + blend_target(driver) + + for i, new_bone_name in enumerate(apply_bones): + from_bone_name = from_bones[i] + to_bone_name = to_bones[i] + + # allow skipping some bones by having None in the list + if None in (new_bone_name, from_bone_name, to_bone_name): + continue + + new_pbone = obj.pose.bones[new_bone_name] + + # if the bone is connected or its location is totally locked then dont add location blending. + if not (new_pbone.bone.connected or (False not in new_pbone.lock_location)): + blend_location(new_pbone, from_bone_name, to_bone_name) + + if not (False not in new_pbone.lock_rotation): # TODO. 4D chech? + blend_rotation(new_pbone, from_bone_name, to_bone_name) + + +def add_pole_target_bone(obj, base_bone_name, name, mode='CROSS'): + ''' + Does not actually create a poll target, just the bone to use as a poll target + ''' + mode_orig = obj.mode + bpy.ops.object.mode_set(mode='EDIT') + + arm = obj.data + + poll_ebone = arm.edit_bones.new(name) + base_ebone = arm.edit_bones[base_bone_name] + poll_name = poll_ebone.name + parent_ebone = base_ebone.parent + + base_head = base_ebone.head.copy() + base_tail = base_ebone.tail.copy() + base_dir = base_head - base_tail + + parent_head = parent_ebone.head.copy() + parent_tail = parent_ebone.tail.copy() + parent_dir = parent_head - parent_tail + + distance = (base_dir.length + parent_dir.length) + + if mode == 'CROSS': + # direction from the angle of the joint + offset = base_dir.copy().normalize() - parent_dir.copy().normalize() + offset.length = distance + elif mode == 'ZAVERAGE': + # between both bones Z axis + z_axis_a = base_ebone.matrix.copy().rotationPart() * Vector(0.0, 0.0, -1.0) + z_axis_b = parent_ebone.matrix.copy().rotationPart() * Vector(0.0, 0.0, -1.0) + offset = (z_axis_a + z_axis_b).normalize() * distance + else: + # preset axis + offset = Vector(0, 0, 0) + if mode[0] == "+": + val = distance + else: + val = - distance + + setattr(offset, mode[1].lower(), val) + + poll_ebone.head = base_head + offset + poll_ebone.tail = base_head + (offset * (1.0 - (1.0 / 4.0))) + + bpy.ops.object.mode_set(mode=mode_orig) + + return poll_name + + + +def get_side_name(name): + ''' + Returns the last part of a string (typically a bone's name) indicating + whether it is a a left or right (or center, or whatever) bone. + Returns an empty string if nothing is found. + ''' + if name[-2] in DELIMITER: + return name[-2:] + else: + return "" + +def get_base_name(name): + ''' + Returns the part of a string (typically a bone's name) corresponding to it's + base name (no sidedness, no ORG prefix). + ''' + if name[-2] in DELIMITER: + return name[:-2] + else: + return name + + +def write_meta_rig(obj, func_name="metarig_template"): + ''' + Write a metarig as a python script, this rig is to have all info needed for + generating the real rig with rigify. + ''' + code = [] + + code.append("def %s():" % func_name) + code.append(" # generated by rigify.write_meta_rig") + bpy.ops.object.mode_set(mode='EDIT') + code.append(" bpy.ops.object.mode_set(mode='EDIT')") + + code.append(" obj = bpy.context.active_object") + code.append(" arm = obj.data") + + arm = obj.data + # write parents first + bones = [(len(bone.parent_recursive), bone.name) for bone in arm.edit_bones] + bones.sort(key=lambda item: item[0]) + bones = [item[1] for item in bones] + + + for bone_name in bones: + bone = arm.edit_bones[bone_name] + code.append(" bone = arm.edit_bones.new('%s')" % bone.name) + code.append(" bone.head[:] = %.4f, %.4f, %.4f" % bone.head.toTuple(4)) + code.append(" bone.tail[:] = %.4f, %.4f, %.4f" % bone.tail.toTuple(4)) + code.append(" bone.roll = %.4f" % bone.roll) + code.append(" bone.connected = %s" % str(bone.connected)) + if bone.parent: + code.append(" bone.parent = arm.edit_bones['%s']" % bone.parent.name) + + bpy.ops.object.mode_set(mode='OBJECT') + code.append("") + code.append(" bpy.ops.object.mode_set(mode='OBJECT')") + + for bone_name in bones: + pbone = obj.pose.bones[bone_name] + pbone_written = False + + # Only 1 level of props, simple types supported + for key, value in pbone.items(): + if key.startswith("_"): + continue + + if type(value) not in (float, str, int): + print("Unsupported ID Prop:", str((key, value))) + continue + + if type(value) == str: + value = "'" + value + "'" + + if not pbone_written: # only write bones we need + code.append(" pbone = obj.pose.bones['%s']" % bone_name) + + code.append(" pbone['%s'] = %s" % (key, value)) + + return "\n".join(code) + + + +# *** bone class collection *** +def bone_class_instance(obj, slots, name="BoneContainer"): + ''' + bone collection utility class to help manage cases with + edit/pose/bone bones where switching modes can invalidate some of the members. + + there are also utility functions for manipulating all members. + ''' + + if len(slots) != len(set(slots)): + raise Exception("duplicate entries found %s" % attr_names) + + attr_names = tuple(slots) # dont modify the original + slots = list(slots) # dont modify the original + for i in range(len(slots)): + member = slots[i] + slots.append(member + "_b") # bone bone + slots.append(member + "_p") # pose bone + slots.append(member + "_e") # edit bone + + class_dict = { \ + "obj": obj, \ + "attr_names": attr_names, \ + "update": _bone_class_instance_update, \ + "rename": _bone_class_instance_rename, \ + "names": _bone_class_instance_names, \ + "copy": _bone_class_instance_copy, \ + "blend": _bone_class_instance_blend, \ + } + + instance = auto_class_instance(slots, name, class_dict) + return instance + +def auto_class(slots, name="ContainerClass", class_dict=None): + + if class_dict: + class_dict = class_dict.copy() + else: + class_dict = {} + + class_dict["__slots__"] = tuple(slots) + + return type(name, (object,), class_dict) + + +def auto_class_instance(slots, name="ContainerClass", class_dict=None): + return auto_class(slots, name, class_dict)() + + +def _bone_class_instance_update(self): + ''' Re-Assigns bones from the blender data + ''' + arm = self.obj.data + bbones = arm.bones + pbones = self.obj.pose.bones + ebones = arm.edit_bones + + for member in self.attr_names: + name = getattr(self, member, None) + if name is not None: + setattr(self, member + "_b", bbones.get(name, None)) + setattr(self, member + "_p", pbones.get(name, None)) + setattr(self, member + "_e", ebones.get(name, None)) + + +def _bone_class_instance_rename(self, attr, new_name): + ''' Rename bones, editmode only + ''' + + if self.obj.mode != 'EDIT': + raise Exception("Only rename in editmode supported") + + ebone = getattr(self, attr + "_e") + ebone.name = new_name + + # we may not get what is asked for so get the name from the editbone + setattr(self, attr, ebone.name) + + +def _bone_class_instance_copy(self, from_fmt="%s", to_fmt="%s", exclude_attrs=(), base_names=None): + from_name_ls = [] + new_name_ls = [] + new_slot_ls = [] + + for attr in self.attr_names: + + if attr in exclude_attrs: + continue + + bone_name_orig = getattr(self, attr) + ebone = getattr(self, attr + "_e") + # orig_names[attr] = bone_name_orig + + # insert formatting + if from_fmt != "%s": + bone_name = from_fmt % bone_name_orig + ebone.name = bone_name + bone_name = ebone.name # cant be sure we get what we ask for + else: + bone_name = bone_name_orig + + setattr(self, attr, bone_name) + + new_slot_ls.append(attr) + from_name_ls.append(bone_name) + if base_names: + bone_name_orig = base_names[bone_name_orig] + new_name_ls.append(to_fmt % bone_name_orig) + + new_bones = copy_bone_simple_list(self.obj.data, from_name_ls, new_name_ls, True) + new_bc = bone_class_instance(self.obj, new_slot_ls) + + for i, attr in enumerate(new_slot_ls): + ebone = new_bones[i] + setattr(new_bc, attr + "_e", ebone) + setattr(new_bc, attr, ebone.name) + + return new_bc + + +def _bone_class_instance_names(self): + return [getattr(self, attr) for attr in self.attr_names] + + +def _bone_class_instance_blend(self, from_bc, to_bc, target_bone=None, target_prop="blend"): + ''' + Use for blending bone chains. + + blend_target = (bone_name, bone_property) + default to the last bone, blend prop + + XXX - toggles editmode, need to re-validate all editbones :( + ''' + + if self.attr_names != from_bc.attr_names or self.attr_names != to_bc.attr_names: + raise Exception("can only blend between matching chains") + + apply_bones = [getattr(self, attr) for attr in self.attr_names] + from_bones = [getattr(from_bc, attr) for attr in from_bc.attr_names] + to_bones = [getattr(to_bc, attr) for attr in to_bc.attr_names] + + blend_bone_list(self.obj, apply_bones, from_bones, to_bones, target_bone, target_prop) diff --git a/release/scripts/modules/rna_prop_ui.py b/release/scripts/modules/rna_prop_ui.py index dd71da74d35..07b3a7c1c42 100644 --- a/release/scripts/modules/rna_prop_ui.py +++ b/release/scripts/modules/rna_prop_ui.py @@ -120,7 +120,7 @@ def draw(layout, context, context_member, use_edit=True): prop = row.operator("wm.properties_edit", text="edit") assign_props(prop, val_draw, key) - prop = row.operator("wm.properties_remove", text="", icon='ICON_ZOOMOUT') + prop = row.operator("wm.properties_remove", text="", icon='ZOOMOUT') assign_props(prop, val_draw, key) |