如何获取在场景中创建的根目录 parents - Autodesk Maya / Python?

How to get the list of root parents created in a scene - Autodesk Maya / Python?

我对 python 有点陌生,我正在尝试获取一个包含类型 joint 场景中所有根 parent 的列表。 例如,我的场景大纲是这样的:

group1>>group2>>joint1>>joint2>>joint3

group3>>joint4>>joint5

joint16>>joint17>>joint18

我想要一个遍历大纲的脚本和 returns 一个列表,在我的示例中:

[joint1, joint4, joint16]

如有任何提示,我们将不胜感激。非常感谢。

我建议列出所有关节,对于每个关节,您可以检查它的父关节是否不是关节。在您的定义中,这些关节应该是您的根关节。

我不确定它是否有用 Haggi Krey 解决方案工作正常但是 您也可以使用标志:-long from cmds.ls

# list all the joints from the scene
mjoints = cmds.ls(type='joint', l=True)
# list of the top joints from chain
output = []
# list to optimise the loop counter
exclusion = []
# lets iterate joints
for jnt in mjoints:
    # convert all hierarchy into a list
    pars = jnt.split('|')[1:]
    # lets see if our hierarchy is in the exclusion list
    # we put [1:] because maya root is represented by ''
    if not set(pars) & set(exclusion):
        # we parse the hierarchy until we reach the top joint
        # then we add it to the output
        # we add everything else to the exclusion list to avoid 
        for p in pars:
            if cmds.nodeType(p) == 'joint':
                output.append(p)
                exclusion+=pars
                break
print(output)

我之所以这么说,是因为没有一条路可走。我希望这段代码的构建可以帮助你的 python 技能。完全一样,只是查找父节点的方式不同!

我之前使用过 DrWeeny 的想法,您可以通过对象的长名称遍历层次结构。这个答案的不同之处在于,如果场景中存在重名的对象,脚本不会崩溃。我的意思是假设您有 2 个层次结构:

group1>>joint1>>joint2>>group2>>joint3

group3>>joint1>>joint2>>group2>>joint3

Maya 很容易允许这种情况,例如在复制顶部节点时,因此我们需要防止脚本在这种情况下崩溃。当存在多个具有重复名称的对象时,如果您尝试访问对象的短名称(它不知道您指的是什么!),Maya 将会崩溃,因此我们必须始终使用其长名称:

import maya.cmds as cmds


jnts = cmds.ls(type="joint", l=True)  # Collect all joints in the scene by their long names.
output = set()  # Use a set to avoid adding the same joint.

for jnt in jnts:
    pars = jnt.split("|")  # Split long name so we can traverse its hierarchy.

    root_jnt = None

    while pars:
        obj = "|".join(pars)
        del pars[-1]  # Remove last word to "traverse" up hierarchy on next loop.

        # If this is a joint, mark it as the new root joint.
        if obj and cmds.nodeType(obj) == "joint":
            root_jnt = obj

    # If a root joint was found, append it to our final list.
    if root_jnt is not None:
        output.add(root_jnt)

print(list(output))

在上面的层次结构中使用此脚本会 return

[u'|group1|joint1', u'|group3|joint1']

我用这个方法得到一个联合层次结构。我已经放弃尝试找出一种更性感的方式来做到这一点。

myItems = cmds.ls(selection = True, type='joint') 
theParentJnt = cmds.listRelatives(myItems, parent = True)
jntRel = cmds.listRelatives(myItems, allDescendents = True)
allJnt = jntRel + myItems

@绿细胞

你的方法用过一次,就再也没有用过。重新启动 maya 2020 超过 5 次,只显示顶部节点关节,再也不会 return 一个列表中的所有关节。