How to store and then retreive parent-child dependency data (Maya MEL/Python script)

泄露秘密 提交于 2019-12-01 13:20:45

I would suggest using python if you aren't already - you can use pretty much any data types with each other to get what you need in a single data structure. It will make it much easier than creating a long string and breaking it back up again later.

to collect your hierarchy data:

import maya.cmds as mc

def hierarchyTree(parent, tree):
    children = mc.listRelatives(parent, c=True, type='transform')
    if children:
        tree[parent] = (children, {})
        for child in children:
            hierarchyTree(child, tree[parent][1])

top_node = 'name_of_node'  # could also use mc.ls(sl=True)[0] if you want...
hierarchy_tree = {}
hierarchyTree(top_node, hierarchy_tree)

this should basically start from your top node and recursively go down the hierarchy to create a data structure that's almost like nested dicts... each key is a parent node with it's key value being a tuple that stores a list of children and a dict of children data. Each child dict follows the same format - the child is a key with it's child data in a tuple, etc, etc, etc to the end of the hierarchy. I'm using the tuple with a list and a dict since dicts are unordered... the list will basically ensure you re-parent them in the same order they came from, but you could just store the dict if you don't really care about retaining the order...

To parent it all back, you'll do something like this:

def reparent(tree):
    for parent, data in tree.iteritems():
        children, child_tree = data
        mc.parent(children, parent)
        reparent(child_tree)

reparent(hierarchy_tree)

now... I haven't tested this code - kind of wrote it on the fly without bringing it into Maya. I'm more concerned about errors popping up in the re-parent function, so you may need a try/except in there, but hopefully it'll just skip any empty dict items and get you close to what you need for the in-parenting/re-parenting. This is also assuming all of your nodes have unique short names...

Oh, a note about recursive functions... make sure they'll terminate at some point or else you can get stuck in an infinite loop (this should be fine since we're tracing a hierarchy that has a definite end - ie: no more child nodes)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!