Fix T39806: Koro rig (Caminandes) wrong in master, worked in 270(a).

Edit existing animsys_refactor module to make able to execute more complex conversions
('to' can now be a callback, instead of a simple prop name), and add a new
Update Animated Transform Constraints operator that uses it to handle complex
conversion for this constraint (drived or animated properties).

Note this operator has to be called manually (from 'space' menu), will make this clear
in release notes.

Also, similar changes made in 2.70 are *not* addressed by this script (would rather wrote
new operators as/if need arise, but Transform constraint looks much more sensible that the others).

This op should not remain in more than two or three releases anyway, imho.
This commit is contained in:
Bastien Montagne 2014-04-28 13:26:01 +02:00
parent 912151763d
commit c089150426
Notes: blender-bot 2023-12-22 20:14:11 +01:00
Referenced by issue #39806, Koro rig (Caminandes) wrong in master, worked in 270(a)
2 changed files with 166 additions and 79 deletions

View File

@ -25,6 +25,10 @@ rna values in fcurves and drivers.
Currently unused, but might become useful later again.
"""
import sys
import bpy
IS_TESTING = False
@ -34,9 +38,21 @@ def drepr(string):
return '"%s"' % repr(string)[1:-1].replace("\"", "\\\"").replace("\\'", "'")
def classes_recursive(base_type, clss=None):
if clss is None:
clss = [base_type]
else:
clss.append(base_type)
for base_type_iter in base_type.__bases__:
if base_type_iter is not object:
classes_recursive(base_type_iter, clss)
return clss
class DataPathBuilder(object):
""" Dummy class used to parse fcurve and driver data paths.
"""
"""Dummy class used to parse fcurve and driver data paths."""
__slots__ = ("data_path", )
def __init__(self, attrs):
@ -55,38 +71,54 @@ class DataPathBuilder(object):
raise Exception("unsupported accessor %r of type %r (internal error)" % (key, type(key)))
return DataPathBuilder(self.data_path + (str_value, ))
def resolve(self, real_base, rna_update_from_map=None):
""" Return (attribute, value) pairs.
"""
def resolve(self, real_base, rna_update_from_map, fcurve, log):
"""Return (attribute, value) pairs."""
pairs = []
base = real_base
for item in self.data_path:
if base is not Ellipsis:
try:
# this only works when running with an old blender
# where the old path will resolve
base = eval("base" + item)
except:
base_new = Ellipsis
# guess the new name
if item.startswith("."):
for item_new in rna_update_from_map.get(item[1:], ()):
try:
print("base." + item_new)
base_new = eval("base." + item_new)
base_new = Ellipsis
# find the new name
if item.startswith("."):
for class_name, item_new, options in rna_update_from_map.get(item[1:], []) + [(None, item[1:], None)]:
if callable(item_new):
# No type check here, callback is assumed to know what it's doing.
base_new, item_new = item_new(base, class_name, item[1:], fcurve, options)
if base_new is not Ellipsis:
break # found, don't keep looking
except:
pass
else:
# Type check!
type_ok = True
if class_name is not None:
type_ok = False
for base_type in classes_recursive(type(base)):
if base_type.__name__ == class_name:
type_ok = True
break
if type_ok:
try:
#print("base." + item_new)
base_new = eval("base." + item_new)
break # found, don't keep looking
except:
pass
item_new = "." + item_new
else:
item_new = item
try:
base_new = eval("base" + item_new)
except:
pass
if base_new is Ellipsis:
print("Failed to resolve data path:", self.data_path)
base = base_new
if base_new is Ellipsis:
print("Failed to resolve data path:", self.data_path, file=log)
base = base_new
else:
item_new = item
pairs.append((item, base))
pairs.append((item_new, base))
return pairs
import bpy
def id_iter():
type_iter = type(bpy.data.objects)
@ -110,20 +142,7 @@ def anim_data_actions(anim_data):
return [act for act in actions if act]
def classes_recursive(base_type, clss=None):
if clss is None:
clss = [base_type]
else:
clss.append(base_type)
for base_type_iter in base_type.__bases__:
if base_type_iter is not object:
classes_recursive(base_type_iter, clss)
return clss
def find_path_new(id_data, data_path, rna_update_dict, rna_update_from_map):
def find_path_new(id_data, data_path, rna_update_from_map, fcurve, log):
# note!, id_data can be ID type or a node tree
# ignore ID props for now
if data_path.startswith("["):
@ -131,46 +150,28 @@ def find_path_new(id_data, data_path, rna_update_dict, rna_update_from_map):
# recursive path fixing, likely will be one in most cases.
data_path_builder = eval("DataPathBuilder(tuple())." + data_path)
data_resolve = data_path_builder.resolve(id_data, rna_update_from_map)
data_resolve = data_path_builder.resolve(id_data, rna_update_from_map, fcurve, log)
path_new = [pair[0] for pair in data_resolve]
# print(data_resolve)
data_base = id_data
for i, (attr, data) in enumerate(data_resolve):
if data is Ellipsis:
break
if attr.startswith("."):
# try all classes
for data_base_type in classes_recursive(type(data_base)):
attr_new = rna_update_dict.get(data_base_type.__name__, {}).get(attr[1:])
if attr_new:
path_new[i] = "." + attr_new
# set this as the base for further properties
data_base = data
data_path_new = "".join(path_new)[1:] # skip the first "."
return data_path_new
return "".join(path_new)[1:] # skip the first "."
def update_data_paths(rna_update):
""" rna_update triple [(class_name, from, to), ...]
def update_data_paths(rna_update, log=sys.stdout):
"""
rna_update triple [(class_name, from, to or to_callback, callback options), ...]
to_callback is a function with this signature: update_cb(base, class_name, old_path, fcurve, options)
where base is current object, class_name is the expected type name of base (callback has to handle
this), old_path it the org name of base's property, fcurve is the affected fcurve (!),
and options is an opaque data.
class_name, fcurve and options may be None!
"""
# make a faster lookup dict
rna_update_dict = {}
for ren_class, ren_from, ren_to in rna_update:
rna_update_dict.setdefault(ren_class, {})[ren_from] = ren_to
rna_update_from_map = {}
for ren_class, ren_from, ren_to in rna_update:
rna_update_from_map.setdefault(ren_from, []).append(ren_to)
for ren_class, ren_from, ren_to, options in rna_update:
rna_update_from_map.setdefault(ren_from, []).append((ren_class, ren_to, options))
for id_data in id_iter():
# check node-trees too
anim_data_ls = [(id_data, getattr(id_data, "animation_data", None))]
node_tree = getattr(id_data, "node_tree", None)
@ -183,13 +184,13 @@ def update_data_paths(rna_update):
for fcurve in anim_data.drivers:
data_path = fcurve.data_path
data_path_new = find_path_new(anim_data_base, data_path, rna_update_dict, rna_update_from_map)
data_path_new = find_path_new(anim_data_base, data_path, rna_update_from_map, fcurve, log)
# print(data_path_new)
if data_path_new != data_path:
if not IS_TESTING:
fcurve.data_path = data_path_new
fcurve.driver.is_valid = True # reset to allow this to work again
print("driver-fcurve (%s): %s -> %s" % (id_data.name, data_path, data_path_new))
print("driver-fcurve (%s): %s -> %s" % (id_data.name, data_path, data_path_new), file=log)
for var in fcurve.driver.variables:
if var.type == 'SINGLE_PROP':
@ -198,32 +199,33 @@ def update_data_paths(rna_update):
data_path = tar.data_path
if id_data_other and data_path:
data_path_new = find_path_new(id_data_other, data_path, rna_update_dict, rna_update_from_map)
data_path_new = find_path_new(id_data_other, data_path, rna_update_from_map, None, log)
# print(data_path_new)
if data_path_new != data_path:
if not IS_TESTING:
tar.data_path = data_path_new
print("driver (%s): %s -> %s" % (id_data_other.name, data_path, data_path_new))
print("driver (%s): %s -> %s" % (id_data_other.name, data_path, data_path_new),
file=log)
for action in anim_data_actions(anim_data):
for fcu in action.fcurves:
data_path = fcu.data_path
data_path_new = find_path_new(anim_data_base, data_path, rna_update_dict, rna_update_from_map)
data_path_new = find_path_new(anim_data_base, data_path, rna_update_from_map, fcu, log)
# print(data_path_new)
if data_path_new != data_path:
if not IS_TESTING:
fcu.data_path = data_path_new
print("fcurve (%s): %s -> %s" % (id_data.name, data_path, data_path_new))
print("fcurve (%s): %s -> %s" % (id_data.name, data_path, data_path_new), file=log)
if __name__ == "__main__":
# Example, should be called externally
# (class, from, to)
# (class, from, to or to_callback, callback_options)
replace_ls = [
("AnimVizMotionPaths", "frame_after", "frame_after"),
("AnimVizMotionPaths", "frame_before", "frame_before"),
("AnimVizOnionSkinning", "frame_after", "frame_after"),
("AnimVizMotionPaths", "frame_after", "frame_after", None),
("AnimVizMotionPaths", "frame_before", "frame_before", None),
("AnimVizOnionSkinning", "frame_after", "frame_after", None),
]
update_data_paths(replace_ls)

View File

@ -23,6 +23,7 @@ if "bpy" in locals():
if "anim_utils" in locals():
imp.reload(anim_utils)
import bpy
from bpy.types import Operator
from bpy.props import (IntProperty,
@ -281,3 +282,87 @@ class ClearUselessActions(Operator):
self.report({'INFO'}, "Removed %d empty and/or fake-user only Actions"
% removed)
return {'FINISHED'}
class UpdateAnimatedTransformConstraint(Operator):
"""
Update fcurves/drivers affecting Transform constraints (use it with files from 2.70 and earlier)
"""
bl_idname = "anim.update_animated_transform_constraints"
bl_label = "Update Animated Transform Constraints"
bl_options = {'REGISTER', 'UNDO'}
use_convert_to_radians = BoolProperty(
name="Convert To Radians",
description="Convert fcurves/drivers affecting rotations to radians (Warning: use this only once!)",
default=True,
)
def execute(self, context):
import animsys_refactor
from math import radians
import io
from_paths = {"from_max_x", "from_max_y", "from_max_z", "from_min_x", "from_min_y", "from_min_z"}
to_paths = {"to_max_x", "to_max_y", "to_max_z", "to_min_x", "to_min_y", "to_min_z"}
paths = from_paths | to_paths
def update_cb(base, class_name, old_path, fcurve, options):
print(options)
def handle_deg2rad(fcurve):
if fcurve is not None:
if hasattr(fcurve, "keyframes"):
for k in fcurve.keyframes:
k.co.y = radians(k.co.y)
for mod in fcurve.modifiers:
if mod.type == 'GENERATOR':
if mod.mode == 'POLYNOMIAL':
mod.coefficients[:] = [radians(c) for c in mod.coefficients]
else: # if mod.type == 'POLYNOMIAL_FACTORISED':
mod.coefficients[:2] = [radians(c) for c in mod.coefficients[:2]]
elif mod.type == 'FNGENERATOR':
mod.amplitude = radians(mod.amplitude)
fcurve.update()
data = ...
try:
data = eval("base." + old_path)
except:
pass
ret = (data, old_path)
if isinstance(base, bpy.types.TransformConstraint) and data is not ...:
new_path = None
map_info = base.map_from if old_path in from_paths else base.map_to
if map_info == 'ROTATION':
new_path = old_path + "_rot"
if options is not None and options["use_convert_to_radians"]:
handle_deg2rad(fcurve)
elif map_info == 'SCALE':
new_path = old_path + "_scale"
if new_path is not None:
data = ...
try:
data = eval("base." + new_path)
except:
pass
ret = (data, new_path)
#print(ret)
return ret
options = {"use_convert_to_radians": self.use_convert_to_radians}
replace_ls = [("TransformConstraint", p, update_cb, options) for p in paths]
log = io.StringIO()
animsys_refactor.update_data_paths(replace_ls, log)
context.scene.frame_set(context.scene.frame_current)
log = log.getvalue()
if log:
print(log)
text = bpy.data.texts.new("UpdateAnimatedTransformConstraint Report")
text.from_string(log)
self.report({'INFO'}, "Complete report available on '{}' text datablock".format(text.name))
return {'FINISHED'}