練習maya python API jointChain中文標註

Andrew-Woo發表於2013-09-28
# jointChain.py

import sys
import maya.OpenMaya as OpenMaya
import maya.OpenMayaMPx as OpenMayaMPx
import maya.OpenMayaAnim as OpenMayaAnim

kPluginCmdName = 'myJointChain'

# The length of the chain.
kLengthFlag = '-l'
kLengthLongFlag = '-length'
defaultLength = 3

jointDistance = 5     # the distance between two joints
jointOrientation = 20 # degrees.

##########################################################
# Plug-in 
##########################################################
class JointChainCommand(OpenMayaMPx.MPxCommand):
    
    
    def __init__(self):
        ''' Constructor. '''
        OpenMayaMPx.MPxCommand.__init__(self)
    
    
    def parseArgs(self, pArguments):
        ''' Parses the command's arguments. '''#解析命令的引數
        
        # Set the default chain length in case there are no arguments.如果沒有設定引數則設定為預設值
        global defaultLength
        self.length = defaultLength
        
        # Obtain the flag value, if the flag is set.如果標示被設定則獲得標示的數值
        argData = OpenMaya.MArgParser( self.syntax(), pArguments )
        if argData.isFlagSet( kLengthFlag ):
            
            # Get the value associated with the flag as an integer.得到的值與標示作為一個整型的關聯
            flagValue = argData.flagArgumentInt( kLengthFlag, 0 )
            
            # Make sure this value is larger than the default length.確保該數值大於預設數值
            if flagValue > defaultLength:
                self.length = flagValue
    
    
    def doIt(self, pArguments):
        ''' Command Execution. '''#執行命令
        
        # Parse the passed arguments.解析傳遞引數。
        self.parseArgs( pArguments )
        
        # Create an instance of an MDagModifier to keep track of the created objects,建立一個MDagModifier的例項來對建立的物體進行跟蹤
        # and to undo their creation in our undoIt() function.至於撤銷操作是在undoIt()的功能下
        self.dagModifier = OpenMaya.MDagModifier()
        
        # Create the joint MObjects we will be manipulating.我們建立將要操作joint MObjects
        self.jointObjects = []
        for i in range(0, self.length):
            if i == 0:
                # The first joint has no parent.第一個骨節沒有上層骨節
                newJointObj = self.dagModifier.createNode( 'joint' )
            else:
                # Assign the new joint as a child to the previous joint.分配新的骨節作為子骨子給之前的骨節
                newJointObj = self.dagModifier.createNode( 'joint', self.jointObjects[i-1] )
            # Keep track of all the joints created.繼續建立所有的骨節
            self.jointObjects.append( newJointObj )
        
        # Create the inverse kinematic effector MObject. The effector is a child of the last joint object.建立IKMobject,IK是最後骨節的子物體
        # The [-1] index is a Python-specific way of referring to the last item in a list.
        self.effectorObj = self.dagModifier.createNode( 'ikEffector', self.jointObjects[-1] )
        
        # Invoke the command's redoIt() function to actually create and manipulate these objects.呼叫命令的redoIt()函式建立和操縱這些物件。
        self.redoIt()
        
    
    def redoIt(self):
        ''' Create and manipulate the nodes to form the joint chain. '''#建立和形成骨節鏈
        
        # Perform the operations enqueued within our reference to MDagModifier.在MDagModifier內執行排列操作
        self.dagModifier.doIt()
        
        #=======================================
        # JOINT MANIPULATION#骨節控制
        #=======================================
        # We can now use the function sets on the newly created DAG objects.現在我們可以使用新建立的DAG物件的功能集
        jointFn = OpenMayaAnim.MFnIkJoint()
        
        for i in range( 1, len( self.jointObjects ) ):

            jointFn.setObject( self.jointObjects[i] )
            # We set the orientation for our joint to be 'jointOrientation' degrees, to form an arc. 我們為骨節設定方向(定義的變數jointOrientation這麼多)度,形成弧形
            # We use MFnIkJoint.setOrientation() instead of MFnTransform.setRotation() to let the
            # inverse-kinematic handle maintain the curvature.我們使用MFnIkJoint.setOrientation()來取代MFnTransform.setRotation()來讓IK手柄保持曲率
            global jointOrientation
            rotationAngle = OpenMaya.MAngle( jointOrientation, OpenMaya.MAngle.kDegrees )
            jointFn.setOrientation( OpenMaya.MEulerRotation( rotationAngle.asRadians(), 0 , 0, OpenMaya.MEulerRotation.kXYZ ) )
            
            # We translate the joint by 'jointDistance' units along its parent's y axis.我們沿著父骨節的Y軸移動jointDistance(這麼多)數值
            global jointDistance
            translationVector = OpenMaya.MVector( 0, jointDistance, 0 )
            jointFn.setTranslation( translationVector, OpenMaya.MSpace.kTransform )

        #=======================================
        # IK HANDLE MANIPULATION#IK手柄的控制
        #=======================================
        # We will use the MEL command 'ikHandle' to create the handle which will move our joint chain. This command
        # will be enqueued in our reference to the MDagModifier so that it can be undone in our call to MDagModifier.undoIt().
        #我要使用mel中的 'ikHandle' 命令來建立可以控制骨節鏈的手柄,該命令將被排入我們參考MDagModifier,以便它可以在我們的呼叫後對MDagModifier.undoIt()被撤消。
        
        # Obtain the DAG path of the first joint.設定第一個骨節的DAG路徑
        startJointDagPath = OpenMaya.MDagPath()
        jointFn.setObject( self.jointObjects[0] )
        jointFn.getPath( startJointDagPath )
             
        # Obtain the DAG path of the effector.設定操縱器的DAG路徑
        effectorDagPath = OpenMaya.MDagPath()
        effectorFn = OpenMayaAnim.MFnIkEffector( self.effectorObj )
        effectorFn.getPath( effectorDagPath )
        
        # Enqueue the following MEL command with the DAG paths of the start joint and the end effector.
        self.dagModifier.commandToExecute( 'ikHandle -sj ' + startJointDagPath.fullPathName() + ' -ee ' + effectorDagPath.fullPathName() )
        
        # We call MDagModifier.doIt() to effectively execute the MEL command and create the ikHandle. 我們呼叫MDagModifier.doIt()有效地執行MEL命令建立ikHandle
        self.dagModifier.doIt()#《《《《《《《《《《《《《《《《《《《《《事實上是 OpenMaya.MDagModifier.doIt()
        
    
    def undoIt(self):
        ''' Undo the command. '''
        # This call to MDagModifier.undoIt() undoes all the operations within the MDagModifier.這個呼叫MDagModifier.undoIt()撤消所有在MDagModifier內的操作
        # Observe that the number of calls to MDagModifier.undoIt() does not need to match the number of calls to MDagModifier.doIt().
        #觀察呼叫MDagModifier.undoIt()的數目不需要匹配MDagModifier.doIt()的呼叫數目
        self.dagModifier.undoIt()#《《《《《《《《《《《《《《《《《《《《《事實上是 OpenMaya.MDagModifier.undoIt()
        
        
    def isUndoable(self):
        ''' This function must return True to indicate that it is undoable. ''' #這個函式必須返回true以指示它是不可撤銷的 
        return True
        

##########################################################
# Plug-in initialization.#外掛的安裝
##########################################################
def cmdCreator():
    ''' Creates an instance of the command. '''#註冊這個命令
    return OpenMayaMPx.asMPxPtr( JointChainCommand() )

def syntaxCreator():
    ''' Defines the argument and flag syntax for this command. '''#註冊這個命令的引數以及標示
    syntax = OpenMaya.MSyntax()
    syntax.addFlag( kLengthFlag, kLengthLongFlag, OpenMaya.MSyntax.kDouble )
    return syntax

def initializePlugin( mobject ):
    ''' Initializes the plug-in. '''#安裝外掛
    mplugin = OpenMayaMPx.MFnPlugin( mobject )
    try:
        mplugin.registerCommand( kPluginCmdName, cmdCreator, syntaxCreator )
    except:
        sys.stderr.write( 'Failed to register command: ' + kPluginCmdName )
        raise
    
def uninitializePlugin( mobject ):
    ''' Uninitializes the plug-in. '''#解除安裝外掛
    mplugin = OpenMayaMPx.MFnPlugin( mobject )
    try:
        mplugin.deregisterCommand( kPluginCmdName )
    except:
        sys.stderr.write( 'Failed to unregister command: ' + kPluginCmdName )
        raise


##########################################################
# Sample usage.
##########################################################
''' 
# Copy the following lines and run them in Maya's Python Script Editor:

import maya.cmds as cmds
cmds.loadPlugin( 'jointChain.py' )
cmds.myJointChain( length=4 )

'''

相關文章