Exemplo n.º 1
0
def markingMenuSet( rigInstance ):
    ctls = cmds.ls( '*_CTL' )
    
    rObj = cmds.createNode( 'multDoubleLinear', n='RightClickObj_Rigs' )
    attrEdit = rigbase.AttrEdit( rObj )
    attrEdit.addAttr( ln='originalName', dt='string' )
    cmds.setAttr( rObj+'.originalName', rObj, type='string' )
    
    attrEdit = rigbase.AttrEdit( rObj )
    
    for ctl in ctls:
        attrEdit.addAttr( ln=ctl, at='message' )
        cmds.connectAttr( ctl+'.message', rObj+'.'+ctl )
    rigbase.AttrEdit( 'World_CTL' ).addAttr( ln=rObj, at='message' )
    cmds.connectAttr( rObj+'.message', 'World_CTL.'+rObj )
    
    bjts = cmds.ls( '*_BJT' )
    bjts.append( 'BJT_World' )
    
    rObj = cmds.createNode( 'multDoubleLinear', n='RightClickObj_Bjts' )
    attrEdit = rigbase.AttrEdit( rObj )
    attrEdit.addAttr( ln='originalName', dt='string' )
    cmds.setAttr( rObj+'.originalName', rObj, type='string' )
    
    attrEdit = rigbase.AttrEdit( rObj )
    
    for bjt in bjts:
        attrEdit.addAttr( ln=bjt, at='message' )
        cmds.connectAttr( bjt+'.message', rObj+'.'+bjt )
    rigbase.AttrEdit( 'BJT_World' ).addAttr( ln=rObj, at='message' )
    cmds.connectAttr( rObj+'.message', 'BJT_World.'+rObj )
Exemplo n.º 2
0
def switch(node,attr,value=0,inputNames=list(),inputValues=list()):
    '''
    :param node:
    :param attr:
    :param value:
    :param inputName:
    :param inputValues:
    :return:
    '''

    attrName = "{0}.{1}".format(node,attr)
    choiceName = "{0}_{1}_switch".format(node,attr)
    cmds.createNode("choice",name=choiceName)
    cmds.addAttr(node,ln=attr,at="enum",en=":".join(inputNames),dv=value,keyable=True)

    for i in range(len(inputValues)):
        choiceAttr = "output{0}".format(i)
        cmds.addAttr(choiceName,ln=choiceAttr,at="double3")
        cmds.addAttr(choiceName,ln="{0}x".format(choiceAttr),at="double",p=choiceAttr,dv=inputValues[i][0])
        cmds.addAttr(choiceName,ln="{0}y".format(choiceAttr),at="double",p=choiceAttr,dv=inputValues[i][1])
        cmds.addAttr(choiceName,ln="{0}z".format(choiceAttr),at="double",p=choiceAttr,dv=inputValues[i][2])

        cmds.connectAttr("{0}.{1}".format(choiceName,choiceAttr),"{0}.input[{1}]".format(choiceName,i))

    cmds.connectAttr(attrName,"{0}.selector".format(choiceName),f=True)

    return "{0}.output".format(choiceName)
Exemplo n.º 3
0
    def add_target(self, name):
        cmds.select(self.main_jnt)
        jnt = cmds.joint(name=self.name + "_" + name + "_target_jnt")
        cmds.setAttr(jnt + ".t" + self.axis, 1.0)
        cmds.addAttr(jnt, ln="cone_angle", at="double", keyable=1, maxValue=360, minValue=0)
        cmds.addAttr(jnt, ln="pose_weight", at="double")

        norm_vp = cmds.createNode("vectorProduct", name=self.name + "_" + name + "normalize_vp")
        cmds.connectAttr(jnt + ".t", norm_vp + ".input1")
        cmds.setAttr(norm_vp + ".normalizeOutput", 1)
        cmds.setAttr(norm_vp + ".operation", 0)

        dot_vp = cmds.createNode("vectorProduct", name=self.name + "_" + name + "dot_vp")
        cmds.connectAttr(norm_vp + ".output", dot_vp + ".input1")
        cmds.connectAttr(self.reader_jnt + ".t", dot_vp + ".input2")
        cmds.setAttr(dot_vp + ".normalizeOutput", 1)

        angle_rv = cmds.createNode("remapValue", name=self.name + "_" + name + "_angle_rv")
        cmds.connectAttr(jnt + ".cone_angle", angle_rv + ".inputValue")
        cmds.setAttr(angle_rv + ".value[0].value_FloatValue", 1)
        cmds.setAttr(angle_rv + ".value[1].value_FloatValue", -1)
        cmds.setAttr(angle_rv + ".inputMax", 360.0)

        rv = cmds.createNode("remapValue", name=self.name + "_" + name + "_rv")
        # cmds.connectAttr(jnt + '.cone_angle', rv + '.value[0].value_Position')
        cmds.connectAttr(angle_rv + ".outValue", rv + ".value[0].value_Position")
        cmds.connectAttr(dot_vp + ".outputX", rv + ".inputValue")
        cmds.connectAttr(rv + ".outValue", jnt + ".pose_weight")
Exemplo n.º 4
0
def aimObjectConnect( targets ):
    
    for i in range( len( targets ) -1 ):
        
        first  = targets[i]
        second = targets[i+1]
        
        grp = cmds.createNode( 'transform', n=second+'_aimObj_GRP' )
        trg = cmds.createNode( 'transform', n=second+'_aimObj' )
        cmds.parent( trg, grp )
        constraint( first, grp )
        
        localMtx = cmds.createNode( 'multMatrixDecompose', n=second+'_localMtx' )
        fbfMtx   = cmds.createNode( 'fourByFourMatrix',    n=second+'_fbfMtx' )
        shdOrt   = cmds.createNode( 'shoulderOrient',      n=second+'_shdOrt' )
        
        cmds.connectAttr( second+'.wm', localMtx+'.i[0]' )
        cmds.connectAttr( first+'.wim', localMtx+'.i[1]' )
        cmds.connectAttr( localMtx+'.otx', fbfMtx+'.i00' )
        cmds.connectAttr( localMtx+'.oty', fbfMtx+'.i01' )
        cmds.connectAttr( localMtx+'.otz', fbfMtx+'.i02' )
        cmds.connectAttr( fbfMtx+'.output', shdOrt+'.inputMatrix' )
        cmds.connectAttr( shdOrt+'.outAngleX', trg+'.rx' )
        cmds.connectAttr( shdOrt+'.outAngleY', trg+'.ry' )
        cmds.connectAttr( shdOrt+'.outAngleZ', trg+'.rz' )
Exemplo n.º 5
0
    def create_line_from_2_obj(self, obja, objb, crv_name='_curve_CRV'):
        '''
        Desc:
        Make a line between 2 objects

        Parameter:
        crv_name = name of curve
        pta = first object
        ptb = second object

        Return: Curve name
        '''

        # Define generic curve
        curve=cmds.curve(d=1, p=[(0,0,0),(0,0,0)], k=[0,1], n=crv_name)
        cmds.setAttr(curve+'.overrideEnabled',1)
        cmds.setAttr(curve+'.overrideColor', 13)

        # Making connection in worldSpace using decomposeMatrix
        dMa=cmds.createNode('decomposeMatrix', n='_DMAT')
        dMb=cmds.createNode('decomposeMatrix', n='_DMAT')

        # Connect control worldMatrix to decomposeMatrix.inputMatrix
        KstMaya.node_op(obja+'.worldMatrix','>>', dMa+'.inputMatrix')
        KstMaya.node_op(dMa+'.outputTranslate','>>',curve+'.controlPoints[0]')
        KstMaya.node_op(objb+'.worldMatrix','>>', dMb+'.inputMatrix')
        KstMaya.node_op(dMb+'.outputTranslate','>>',curve+'.controlPoints[1]')
        return curve
Exemplo n.º 6
0
def blendAttrs(targ1=None, targ2=None, driven=None, blendAttr=None, translate=1, rotate=1):
    '''
    sets up blending of translation / rotation values from targs 1 & 2 on the driven node.
    If a blendAttr is supplied, this is connected to the blender value
    
    '''
    if not targ1 and not targ2 and not driven:
        if len(cmds.ls(sl=1)) == 3:
            targ1 = cmds.ls(sl=1)[0]
            targ2 = cmds.ls(sl=1)[1]
            driven = cmds.ls(sl=1)[2]
        else:
            return showDialog( 'Argument Error', 'Please supply or select targ1, targ2 and driven nodes' )
    
    if translate:
        t_bc = cmds.createNode('blendColors', name='%s_translate_bc' % driven)
        cmds.connectAttr('%s.t' % targ2, '%s.color1' % t_bc)
        cmds.connectAttr('%s.t' % targ1, '%s.color2' % t_bc)
        if blendAttr:
            cmds.connectAttr(blendAttr, '%s.blender' % t_bc)
        cmds.connectAttr('%s.output' % t_bc, '%s.t' % driven)
            
    if rotate:
        r_bc = cmds.createNode('blendColors', name='%s_rotate_bc' % driven)
        cmds.connectAttr('%s.rotate' % targ2, '%s.color1' % r_bc)
        cmds.connectAttr('%s.rotate' % targ1, '%s.color2' % r_bc)
        if blendAttr:
            cmds.connectAttr(blendAttr, '%s.blender' % r_bc)
        cmds.connectAttr('%s.output' % r_bc, '%s.rotate' % driven)
Exemplo n.º 7
0
def createSplineCurveInfo( curve, number, **options ):
    
    crvShape = cmds.listRelatives( curve, s=1 )
    if not crvShape: return None
    crvShape = crvShape[0]
    
    splineNode = cmds.createNode( 'splineCurveInfo', n=curve+'_spline' )
    cmds.connectAttr( crvShape+'.local', splineNode+'.inputCurve' )
    
    if number <= 1:
        return None
    elif number > 1:
        eachRate = 1.0/(number-1)
        for i in range( number ):
            cmds.setAttr( splineNode+'.parameter[%d]' % i, eachRate*i+0.001 )
            
    for i in range( number-1 ):
        trNode = cmds.createNode( 'transform' )
        cmds.connectAttr( splineNode+'.output[%d].position' % i, trNode+'.t' )
        cmds.connectAttr( splineNode+'.output[%d].rotate' % i, trNode+'.r' )
        cmds.parent( trNode, curve )
        cmds.setAttr( trNode+'.dh', 1 )
        cmds.setAttr( trNode+'.dla', 1 )
    
    return splineNode
Exemplo n.º 8
0
        def reverseObj(self , name , one , another):
                #--------------------------------------------------------------------------------------#
                #note : this two object's axial must be consistent and matched for world !
                #--------------------------------------------------------------------------------------#
                if name=='':
                        pass
                else:
                        name = name+'_'
                #--------------------------------------------------------------------------------------#

                tranNode = mc.createNode( 'multiplyDivide' , n = name+one+'to'+another+'_reverseTran_md')
                rotaNode = mc.createNode( 'multiplyDivide' , n = name+one+'to'+another+'_reverseRota_md')
                unlock=[ '.tx' , '.ty' , '.tz' , '.rx' , '.ry' , '.rz' ]
                for x in unlock:
                        mc.setAttr(another+x , lock=False)

                #reverse tanslate value.
                mc.setAttr( '%s.input2X'%(tranNode) , -1 )
                mc.connectAttr( '%s.tx'%(one) , '%s.input1X'%(tranNode) )
                mc.connectAttr( '%s.ty'%(one) , '%s.input1Y'%(tranNode) )
                mc.connectAttr( '%s.tz'%(one) , '%s.input1Z'%(tranNode) )
                mc.connectAttr( '%s.outputX'%(tranNode) ,  '%s.tx'%(another) )
                mc.connectAttr( '%s.outputY'%(tranNode) ,  '%s.ty'%(another) )
                mc.connectAttr( '%s.outputZ'%(tranNode) ,  '%s.tz'%(another) )
                #reverse rotate value.
                mc.setAttr( '%s.input2Y'%(rotaNode) , -1 )
                mc.setAttr( '%s.input2Z'%(rotaNode) , -1 )
                mc.connectAttr( '%s.rx'%(one) , '%s.input1X'%(rotaNode) )
                mc.connectAttr( '%s.ry'%(one) , '%s.input1Y'%(rotaNode) )
                mc.connectAttr( '%s.rz'%(one) , '%s.input1Z'%(rotaNode) )
                mc.connectAttr( '%s.outputX'%(rotaNode) ,  '%s.rx'%(another) )
                mc.connectAttr( '%s.outputY'%(rotaNode) ,  '%s.ry'%(another) )
                mc.connectAttr( '%s.outputZ'%(rotaNode) ,  '%s.rz'%(another) )
Exemplo n.º 9
0
def perform(**kwargs):
	sel = cmds.ls(sl=True)
	sel3=[]
	for s in sel:
	    sel3+=cmds.xform(s,q=True, ws=True, t=True)
	pointset=[]
	for i in xrange(len(sel3)/3):
	    pointset+=[Vector(sel3[i*3],sel3[i*3+1],sel3[i*3+2])]
	bbox = BBox()
	bbox.obbFromPointSet(pointset)
	t = Transform(bbox.axis[0],bbox.axis[1],bbox.axis[2])
	t = t.transpose()
	z = t.getEuler()
	cube = cmds.createNode("polyCube")
	cubeShape = cmds.createNode("mesh")
	cubeTrans = cmds.listRelatives(cubeShape,p=True)[0]
	cmds.connectAttr(cube+".output",cubeShape+".inMesh")
	cmds.setAttr(cubeTrans+".tx",bbox.center[0])
	cmds.setAttr(cubeTrans+".ty",bbox.center[1])
	cmds.setAttr(cubeTrans+".tz",bbox.center[2])
	cmds.setAttr(cubeTrans+".rz",degrees(z[2]))
	cmds.setAttr(cubeTrans+".ry",degrees(z[1]))
	cmds.setAttr(cubeTrans+".rx",degrees(z[0]))
	cmds.setAttr(cube+".width",bbox.max[0]-bbox.min[0])
	cmds.setAttr(cube+".height",bbox.max[1]-bbox.min[1])
	cmds.setAttr(cube+".depth",bbox.max[2]-bbox.min[2])
	cmds.sets(e=True,forceElement="initialShadingGroup")
	cmds.select(sel)
Exemplo n.º 10
0
 def connectInit(self, inits ):
     rigbase.connectSameAttr( inits[0], self.neckCtl.transformGrp ).doIt( 't', 'r' )
     neckMiddleMtxDcmp = self.getMtxDcmpInNeckSet()
     cmds.connectAttr( neckMiddleMtxDcmp+'.ot', self.neckMiddleCtl.transformGrp+'.t' )
     cmds.connectAttr( neckMiddleMtxDcmp+'.or', self.neckMiddleCtl.transformGrp+'.r' )
     headPosMtxDcmp = rigbase.getChildMtxDcmp( inits[2], inits[0] )
     cmds.connectAttr( headPosMtxDcmp+'.ot', self.headCtl.transformGrp+'.t' )
     cmds.connectAttr( headPosMtxDcmp+'.or', self.headCtl.transformGrp+'.r' )
     
     eyeCenterMtx = cmds.createNode( 'blendTwoMatrixDecompose', n='EyeCenterMtx' )
     eyeLMtxDcmp =  cmds.createNode( 'multMatrixDecompose', n='Eye_L_MtxDcmp' )
     eyeRMtxDcmp =  cmds.createNode( 'multMatrixDecompose', n='Eye_R_MtxDcmp' )
     
     eyeCenterObj = rigbase.Transform( n='EyeCenterObj' )
     eyeCenterObj.setParent( self.headCtl )
     
     eyeLInitTarget = rigbase.Transform( n='Eye_L_InitTarget' )
     eyeRInitTarget = rigbase.Transform( n='Eye_R_InitTarget' )
     eyeLInitTarget.setParent( self.headCtl )
     eyeRInitTarget.setParent( self.headCtl )
     rigbase.connectSameAttr( inits[3], eyeLInitTarget.name ).doIt( 't', 'r' )
     rigbase.connectSameAttr( inits[4], eyeRInitTarget.name ).doIt( 't', 'r' )
     
     cmds.connectAttr( eyeLInitTarget+'.m', eyeCenterMtx+'.inMatrix1' )
     cmds.connectAttr( eyeRInitTarget+'.m', eyeCenterMtx+'.inMatrix2' )
     cmds.connectAttr( eyeCenterMtx+'.ot', eyeCenterObj+'.t' )
     
     cmds.connectAttr( eyeLInitTarget+'.wm', eyeLMtxDcmp+'.i[0]' )
     cmds.connectAttr( eyeRInitTarget+'.wm', eyeRMtxDcmp+'.i[0]' )
     cmds.connectAttr( eyeCenterObj+'.wim', eyeLMtxDcmp+'.i[1]' )
     cmds.connectAttr( eyeCenterObj+'.wim', eyeRMtxDcmp+'.i[1]' )
     
     cmds.connectAttr( eyeLMtxDcmp+'.ot', self.eyeLCtl.transformGrp+'.t' )
     cmds.connectAttr( eyeRMtxDcmp+'.ot', self.eyeRCtl.transformGrp+'.t' )
     cmds.connectAttr( inits[-1]+'.t', self.eyeCtl.transformGrp+'.t' )
Exemplo n.º 11
0
 def neckMiddleCtlSet(self):
     self.neckMiddleCtl = rigbase.Controler( n='NeckMiddle_CTL' )
     self.neckMiddleCtl.setShape( normal=[0,1,0], radius = .5 )
     self.neckMiddleCtl.setColor( 29 )
     
     self.middlePoint1 = rigbase.Transform( n='NeckMiddle_spline_Point1' )
     self.middlePoint2 = rigbase.Transform( n='NeckMiddle_spline_Point2' )
     
     self.middlePoint1.setParent( self.neckMiddleCtl )
     self.middlePoint2.setParent( self.neckMiddleCtl )
     rigbase.transformDefault( self.middlePoint1, self.middlePoint2 )
     
     midPnt1Dist= cmds.createNode( 'distanceBetween', n='NeckMiddle_spPnt1_dist' )
     midPnt2Dist = cmds.createNode( 'distanceBetween', n='NeckMiddle_spPnt2_dist' )
     midMult1Dist = cmds.createNode( 'multDoubleLinear', n='NeckMiddle_md1' )
     midMult2Dist = cmds.createNode( 'multDoubleLinear', n='NeckMiddle_md2' )
     
     cmds.setAttr( midMult1Dist+'.input2', -.4 )
     cmds.setAttr( midMult2Dist+'.input2', .4 )
     
     cmds.connectAttr( self.neckMiddleInit+'.m', midPnt1Dist+'.inMatrix1' )
     cmds.connectAttr( self.headInit+'.m',       midPnt2Dist+'.inMatrix2' )
     cmds.connectAttr( midPnt1Dist+'.distance', midMult1Dist+'.input1' )
     cmds.connectAttr( midPnt2Dist+'.distance', midMult2Dist+'.input1' )
     cmds.connectAttr( midMult1Dist+'.output', self.middlePoint1+'.ty' )
     cmds.connectAttr( midMult2Dist+'.output', self.middlePoint2+'.ty' )
     
     attrEdit = rigbase.AttrEdit( self.neckMiddleCtl.name )
     attrEdit.lockAndHideAttrs( 'sx','sy','sz','v' )
     
     self.rigInstance.neckMiddleCtl = self.neckMiddleCtl.name
Exemplo n.º 12
0
def connection(vks, jt, jgroup):
    """
    Establishes a connection between the vks control and one of the joints in the chain
    """
    ucn_p = setup.onetenthNode(vks, 'position')

    linstepA = cmds.createNode('setRange', n='setRangeA_%s' % jt)
    cmds.setAttr('%s.minX' % linstepA, 1)
    cmds.connectAttr('%s.parameter' % jt, '%s.valueX' % linstepA)
    cmds.connectAttr('%s.maxPos' % vks, '%s.oldMaxX' % linstepA)
    cmds.connectAttr('%s.output' % ucn_p, '%s.oldMinX' % linstepA)

    linstepB = cmds.createNode('setRange', n='setRangeB_%s' % jt)
    cmds.setAttr('%s.maxX' % linstepB, 1)
    cmds.connectAttr('%s.parameter' % jt, '%s.valueX' % linstepB)
    cmds.connectAttr('%s.minPos' % vks, '%s.oldMinX' % linstepB)
    cmds.connectAttr('%s.output' % ucn_p, '%s.oldMaxX' % linstepB)

    cond = cmds.createNode('condition', n='condition_%s' % jt)
    cmds.setAttr('%s.operation' % cond, 2)
    cmds.connectAttr('%s.parameter' % jt, '%s.firstTerm' % cond)
    cmds.connectAttr('%s.output' % ucn_p, '%s.secondTerm' % cond)
    cmds.connectAttr('%s.outValueX' % linstepA, '%s.colorIfTrueR' % cond)
    cmds.connectAttr('%s.outValueX' % linstepB, '%s.colorIfFalseR' % cond)

    mtp_r = cmds.createNode('multiplyDivide', n='multiplyRotate_%s' % jt)
    cmds.connectAttr('%s.rotate' % vks, '%s.input1' % mtp_r)
    cmds.connectAttr('%s.outColorR' % cond, '%s.input2X' % mtp_r)
    cmds.connectAttr('%s.outColorR' % cond, '%s.input2Y' % mtp_r)
    cmds.connectAttr('%s.outColorR' % cond, '%s.input2Z' % mtp_r)
    cmds.connectAttr('%s.output' % mtp_r, '%s.rotate' % jgroup)
Exemplo n.º 13
0
def ik_stretch(ikhnd):
    '''

    '''
    jts = cmds.ikHandle(ikhnd, q=True, jl=True)
    cu_s = cmds.ikHandle(ikhnd, q=True, c=True)
    cu = cmds.listRelatives(cu_s, p=1)[0]
    cmds.addAttr(ikhnd, longName='ik_stretch', k=1, defaultValue=1.0, minValue=0.0, maxValue=1.)

    dcu = cmds.duplicate(cu, n=cu + '_base_scale')[0]
    dcu_s = cmds.listRelatives(dcu, c=1)[0]

    cf = cmds.createNode('curveInfo')
    dcf = cmds.createNode('curveInfo')
    bl = cmds.createNode('blendTwoAttr')
    md = cmds.createNode('multiplyDivide')

    cmds.connectAttr(cu_s + '.worldSpace', cf + '.inputCurve')
    cmds.connectAttr(dcu_s + '.worldSpace', dcf + '.inputCurve')
    cmds.connectAttr(dcf + '.arcLength', bl + '.input[0]')
    cmds.connectAttr(cf + '.arcLength', bl + '.input[1]')
    cmds.connectAttr(ikhnd + '.ik_stretch', bl + '.attributesBlender')
    cmds.connectAttr(bl + '.output', md + '.input1X')

    cmds.setAttr(md + '.input2X', cmds.getAttr(cf + '.arcLength'), l=1)
    cmds.setAttr(md + '.operation', 2)
    cmds.setAttr(dcu + '.v', 0)

    for j in jts:
        cmds.connectAttr(md + '.outputX', j + '.sx')

    return dcu
Exemplo n.º 14
0
 def __init__(self):
     
     TopInfo.__init__(self)
     
     node = self.getRetargetNode_for( self._target )
     
     self.originRate = node+'.originalRate'
     self.source = node+'.sourceMatrix'
     self.sourceOrig = node+'.sourceOrigMatrix'
     self.sourceParent = node+'.sourceParentMatrix'
     self.targetOrig = node+'.targetOrigMatrix'
     self.targetParent = node+'.targetParentMatrix'
     self.distRate = node+'.distanceRate'
     self.localData = [ node+'.localData[0].localMatrix', node+'.localData[0].localOffset' ]
     
     
     if self._transDirect:
         transDirect = cmds.createNode( "multMatrixDecompose", n= self._target+'_transDirect' )
         invNode = cmds.createNode( 'inverseMatrix', n= self._target+'_transDirect_origInv' )
         multNode = cmds.createNode( 'multiplyDivide', n=self._target+'_transDirect_mult' )
         cmds.connectAttr( self.source, transDirect+'.i[0]' )
         cmds.connectAttr( self.sourceOrig, invNode+'.inputMatrix' )
         cmds.connectAttr( invNode+'.outputMatrix', transDirect+'.i[1]' )
         cmds.connectAttr( transDirect+'.ot', multNode+'.input1' )
         cmds.connectAttr( self.distRate, multNode+'.input2X' )
         cmds.connectAttr( self.distRate, multNode+'.input2Y' )
         cmds.connectAttr( self.distRate, multNode+'.input2Z' )
         cmds.connectAttr( multNode+'.outputX', self._target+'.tx', f=1 )
         cmds.connectAttr( multNode+'.outputY', self._target+'.ty', f=1 )
         cmds.connectAttr( multNode+'.outputZ', self._target+'.tz', f=1 )
Exemplo n.º 15
0
 def getRetargetNode_for( self, target ):
     
     retargetBlenderCons = cmds.listConnections( target, s=1, d=0, type='retargetBlender' )
     
     if not retargetBlenderCons:
         retargetBlender = cmds.createNode( 'retargetBlender', n= target+'_retargetBlender' )
         
         sourceName = target.replace( self._targetNS, self._sourceNS )
         retargetNode = cmds.createNode( 'retargetTransNode', n= sourceName+'_RTTrans' )
         
         self.blenderToControl( retargetBlender, target )
         
         if cmds.nodeType( target ) == 'joint':
             fnc.tryConnect( target+'.jo', retargetBlender+'.orient' )
         
         cmds.connectAttr( retargetNode+'.transMatrix', retargetBlender+'.input[0].transMatrix' )
     
     else:
         retargetBlender = retargetBlenderCons[0]
         fnc.clearArrayElement( retargetBlender+'.input' )
         cuIndex = fnc.getLastIndex( retargetBlender+'.input' )
         
         if cuIndex == -1: cuIndex = 0
         retargetTransCons = cmds.listConnections( retargetBlender+'.input[%d].transMatrix ' % cuIndex )
         
         if retargetTransCons: cuIndex += 1
         
         sourceName = target.replace( self._targetNS, self._sourceNS )
         retargetNode = cmds.createNode( 'retargetTransNode', n= sourceName+'_RTTrans' )
         
         cmds.connectAttr( retargetNode+'.transMatrix', retargetBlender+'.input[%d].transMatrix' % cuIndex )
     
     return retargetNode
Exemplo n.º 16
0
def importCache( mesh, xmlFilePath ):
    
    mesh = sgModelDag.getShape( mesh )
    
    xmlFileSplits = xmlFilePath.split( '/' )
    cachePath = '/'.join( xmlFileSplits[:-1] )
    cacheName = xmlFileSplits[-1].split( '.' )[0]
    
    deformer = cmds.createNode( 'historySwitch' )
    cacheNode = cmds.createNode( 'cacheFile' )
    
    cmds.connectAttr( cacheNode+'.outCacheData[0]', deformer+'.inPositions[0]')
    cmds.connectAttr( cacheNode+'.inRange',         deformer+'.playFromCache' )
    cmds.connectAttr( 'time1.outTime', cacheNode+'.time' )
    
    cmds.setAttr( cacheNode+'.cachePath', cachePath, type='string' )
    cmds.setAttr( cacheNode+'.cacheName', cacheName, type='string' )
    
    #print "xml filePath : ", xmlFilePath
    startFrame, endFrame = sgModelData.getStartAndEndFrameFromXmlFile( xmlFilePath )
    cmds.playbackOptions( animationStartTime = startFrame, animationEndTime= endFrame,
                          minTime = startFrame+5, maxTime= endFrame-5 )
    
    cmds.setAttr( cacheNode+'.startFrame',    startFrame )
    cmds.setAttr( cacheNode+'.sourceStart',   startFrame )
    cmds.setAttr( cacheNode+'.sourceEnd',     endFrame )
    cmds.setAttr( cacheNode+'.originalStart', startFrame )
    cmds.setAttr( cacheNode+'.originalEnd',   endFrame )

    origMesh = sgModelDag.getOrigShape( mesh )
    if not origMesh: return None
    
    cmds.connectAttr( origMesh+'.worldMesh', deformer+'.undeformedGeometry[0]' )
    cmds.connectAttr( deformer+'.outputGeometry[0]', mesh+'.inMesh', f=1 )
Exemplo n.º 17
0
def pfxHairScaleConnect( ctl, hairSystemGrp ):
    
    hairSystems = cmds.listRelatives( hairSystemGrp, c=1, ad=1, type='hairSystem' )
    
    def getMultDoubleLinear( attr ):
        multNodes = cmds.listConnections( attr, type='multDoubleLinear', s=1, d=0 )
        if not multNodes:
            multNode = cmds.createNode( 'multDoubleLinear' )
            sgRigAttribute.addAttr( multNode, ln='clumpWidthMult', at='message' )
            attrValue = cmds.getAttr( attr )
            cmds.setAttr( multNode+'.input1', attrValue )
            cmds.connectAttr( multNode+'.output', attr )
            return multNode
        else:
            if not cmds.attributeQuery( 'clumpWidthMult', node=multNodes[0], ex=1 ):
                multNode = cmds.createNode( 'multDoubleLinear' )
                sgRigAttribute.addAttr( multNode, ln='clumpWidthMult', at='message' )
                attrValue = cmds.getAttr( attr )
                cmds.setAttr( multNode+'.input1', attrValue )
                cmds.connectAttr( multNode+'.output', attr )
                return multNode
            else:
                return multNodes[0]
                
    
    for hairSystem in hairSystems:
        dcmp = cmds.createNode( 'decomposeMatrix' )
        multNode = cmds.createNode( 'multDoubleLinear' )
        cmds.connectAttr( ctl+'.wm', dcmp+'.imat' )
        cmds.connectAttr( dcmp+'.osx', multNode+'.input1' )
        cmds.setAttr( multNode+'.input2', cmds.getAttr( hairSystem+'.clumpWidth' ) )
        cmds.connectAttr( multNode+'.output', hairSystem+'.clumpWidth' )
        
        
Exemplo n.º 18
0
        def closestPointOnModel(self , modelShape , obj):

                closest_Point = []
                modelShapeType = self.getObjType(modelShape)

                temp = mc.createNode('transform',name=obj+'_point_temp')
                mc.parentConstraint(obj,temp,mo = False)

                #model type data
                if modelShapeType == 'kNurbsSurface':
                        closest_Point = ['closestPointOnSurface' , temp+'_cpos' , 'local' , 'inputSurface']
                elif modelShapeType == 'kMesh':
                        closest_Point = ['closestPointOnMesh' , temp+'_cpom' , 'outMesh' , 'inMesh']

                #create getUV Node
                closest_PointNode = mc.createNode( closest_Point[0] , name = closest_Point[1] )
                mc.connectAttr( temp+'.translate' , closest_PointNode+'.inPosition' )
                mc.connectAttr( modelShape + '.' + closest_Point[2]  ,  closest_PointNode +'.' + closest_Point[3] )

                #get UV
                U = mc.getAttr(closest_PointNode + '.result.parameterU')
                V = mc.getAttr(closest_PointNode + '.result.parameterV')
                mc.delete(closest_PointNode,temp)

                return {'u':U , 'v':V}
Exemplo n.º 19
0
def create(baseCrv,curveList,inMeshList,prefix):
	'''
	Create standard copyMeshToCurve setup based on the input arguments
	@param baseCrv: Base curve
	@type baseCrv: str
	@param curveList: List of curves to copy mesh to
	@type curveList: list
	@param inMeshList: List of meshes to copy to curves
	@type inMeshList: list
	@param prefix: Naming prefix
	@type prefix: str
	'''
	# Create copyMeshToCurve node
	copyMeshToCurve = mc.createNode('copyMeshToCurve',n=prefix+'_copyMeshToCurve')
	
	# Connect base curve
	mc.connectAttr(baseCrv+'.worldSpace[0]',copyMeshToCurve+'.baseCurve',f=True)
	
	# Connect input curves
	connectInputCurves(copyMeshToCurve,curveList)
	
	# Connect input mesh
	connectInputMesh(copyMeshToCurve,inMeshList)
	
	# Create output mesh
	outMeshShape = mc.createNode('mesh',n=prefix+'_outMeshShape')
	outMesh = mc.listRelatives(outMeshShape,p=True)[0]
	mc.rename(outMesh,prefix+'_outMesh')
	
	# Connect out mesh
	mc.connectAttr(copyMeshToCurve+'.outputMesh',outMeshShape+'.inMesh',f=True)
	
	# Return Reult
	return copyMeshToCurve
Exemplo n.º 20
0
def	postProcessControl	(	_control,	_function,	_controlled	):	# <<< string, string, list
	lockHideAttributes	(	_control	)

	if (cmds.objExists('anim_control_set') == False):	cmds.createNode('objectSet',name='anim_control_set',skipSelect=True)

	cmds.sets	(	_control,	addElement	=	'anim_control_set'	)
	cmds.toggle	(	localAxis				=	1	)

	if	len	(	_controlled	)	==	0:
		_control	=	cmds.rename	(	'_'	+	_function	+	'_control'	)
		_control	=	cmds.group	( 	world	=	1,	name	=	'_'	+	_function	+	'_control_offSet'	)
		cmds.move					(	0,	0,	0,	_control	+	'.rotatePivot',	_control	+	'.scalePivot'	)

		lockHideAttributes	(	_control	)

	else:
		_k				=	_controlled[0].rfind	(	'|'	)
		_control		=	_controlled[0][_k+1:]
		cmds.rename		(	_control	+	'_'	+	_function	+	'_control'	)
		_control		=	cmds.group	(	world	=	1,	name	=	_control	+	'_'	+ _function	+	'_control_offSet'	)
		cmds.move			(	0, 0, 0, _control + '.rotatePivot', _control + '.scalePivot' )

		lockHideAttributes	(	_control	)

		cmds.select		(	_controlled[0],	toggle	=	True	)
		cmds.parent		()
		cmds.xform		(	translation	=	(	0,	0,	0	),	rotation	=	(	0,	0,	0	)	)
		cmds.parent		(	world		= 	1	)
	
	cmds.pickWalk	(	direction	=	"down"	)
Exemplo n.º 21
0
def	setupStrechy	():
	# >>>	get IK from selection, get start/end joints & IK curve, determine strechy joints
	_IK				=	cmds.ls					(selection	=	True)[0]
	_IKcurve		=	cmds.listConnections	(_IK	+	'.inCurve',				destination	=	True)[0]
	_startJoint		=	cmds.listConnections	(_IK	+	'.startJoint',			destination	=	True)[0]
	_endEffector	=	cmds.listConnections	(_IK	+	'.endEffector',			destination	=	True)[0]
	_endJoint		=	cmds.listConnections	(_endEffector	+	'.translateX',	destination	=	True)[0]
	cmds.select									(_endJoint,	hierarchy	=	True)
	_jointsTrash	=	cmds.ls					(selection	=	True)
	cmds.select									(_startJoint,	hierarchy	=	True)
	_strachyJoints_	=	cmds.ls					(selection	=	True)
	_strachyJoints_	=	_strachyJoints_[:len	(_strachyJoints_)	-	len	(_jointsTrash)-1]
	
	# >>>	setup utility nodes
	_curveInfo		=	cmds.arclen			(_IKcurve,	constructionHistory	=	True)
	_condtition		=	cmds.createNode		('condition')
	_startLength	=	cmds.getAttr		(_curveInfo	+	'.arcLength')
	_currentLength	=	cmds.createNode		('multiplyDivide')
	cmds.setAttr							(_currentLength	+	'.operation',	2)
	cmds.setAttr							(_currentLength	+	'.input2X',	_startLength)
	cmds.setAttr							(_condtition	+	'.firstTerm',	_startLength)
	cmds.setAttr							(_condtition	+	'.operation',	4)
	cmds.connectAttr						(_curveInfo		+	'.arcLength',	_currentLength	+	'.input1X',	force	=	True)
	cmds.connectAttr						(_curveInfo		+	'.arcLength',	_condtition	+	'.secondTerm',	force	=	True)
	cmds.connectAttr						(_currentLength	+	'.outputX',	_condtition	+	'.colorIfTrueR',	force	=	True)

	# >>>	connect calculated scale to joints
	for	_j	in	_strachyJoints_:
		cmds.connectAttr					(_condtition	+	'.outColorR',	_j	+	'.scaleX',	force	=	True)
Exemplo n.º 22
0
def createWristAngleJoints( orientObject ):

    import sgBFunction_dag

    orientObjP = sgBFunction_dag.getParent( orientObject )
    orientObjectName = orientObject.split( '|' )[-1]
    
    if cmds.nodeType( orientObject ) == 'joint':
        baseJointRad = cmds.getAttr( orientObject+'.radius' )
    else:
        baseJointRad = 1
    
    cmds.select( orientObjP )
    zJoint = cmds.joint( n = orientObjectName+'_waZ', radius = baseJointRad * 1.5 )
    yJoint = cmds.joint( n = orientObjectName+'_waY', radius = baseJointRad * 2.0 )
    xJoint = cmds.joint( n = orientObjectName+'_waX', radius = baseJointRad * 2.5 )
    
    waz = cmds.createNode( 'wristAngle', n='WA_Z_' + orientObjectName )
    way = cmds.createNode( 'wristAngle', n='WA_Y_' + orientObjectName )
    wax = cmds.createNode( 'wristAngle', n='WA_X_' + orientObjectName )
    
    cmds.connectAttr( orientObject+'.m', waz+'.inputMatrix' )
    cmds.setAttr( waz+'.axis', 2 )
    cmds.connectAttr( waz+'.outAngle', zJoint+'.rotateZ' )
    
    mm = getMultMatrixAsParenting( orientObject, zJoint )
    cmds.connectAttr( mm+'.o', way+'.inputMatrix' )
    cmds.setAttr( way+'.axis', 1 )
    cmds.connectAttr( way+'.outAngle', yJoint+'.rotateY' )
    
    mm = getMultMatrixAsParenting( orientObject, yJoint )
    cmds.connectAttr( mm+'.o', wax+'.inputMatrix' )
    cmds.setAttr( wax+'.axis', 0 )
    cmds.connectAttr( wax+'.outAngle', xJoint+'.rotateX' )
Exemplo n.º 23
0
def addAngleDriverAttribute( sel ):
    
    import sgBFunction_attribute
    
    sgBFunction_attribute.addAttr( sel, ln='angleRate0', cb=1 )
    sgBFunction_attribute.addAttr( sel, ln='angleRate1', cb=1 )
    sgBFunction_attribute.addAttr( sel, ln='angleRate2', cb=1 )
    
    if cmds.listConnections( sel, s=1, d=0, type='angleDriver' ): return None
    
    selP = cmds.listRelatives( sel, p=1, f=1 )[0]
    selName = sel.split( '|' )[-1]
    targetDriver = cmds.createNode( 'angleDriver', n= 'angleDriver_' + selName )
    mm = cmds.createNode( 'multMatrix', n='mm_' + selName )
    base = cmds.createNode( 'transform', n= 'angleBase_' + selName )

    base = cmds.parent( base, selP )[0]

    cmds.xform( base, ws=1, matrix= cmds.getAttr( sel+'.wm' ) )
    
    cmds.connectAttr( sel+'.wm', mm+'.i[0]' )
    cmds.connectAttr( base+'.wim', mm+'.i[1]' )
    cmds.connectAttr( mm+'.matrixSum', targetDriver+'.angleMatrix' )
        
    
    sgBFunction_attribute.addAttr( sel, ln='angleRate0', cb=1 )
    sgBFunction_attribute.addAttr( sel, ln='angleRate1', cb=1 )
    sgBFunction_attribute.addAttr( sel, ln='angleRate2', cb=1 )
    if not cmds.isConnected( targetDriver+'.outDriver0', sel+'.angleRate0' ):
        cmds.connectAttr( targetDriver+'.outDriver0', sel+'.angleRate0' )
    if not cmds.isConnected( targetDriver+'.outDriver1', sel+'.angleRate1' ):
        cmds.connectAttr( targetDriver+'.outDriver1', sel+'.angleRate1' )
    if not cmds.isConnected( targetDriver+'.outDriver2', sel+'.angleRate2' ):
        cmds.connectAttr( targetDriver+'.outDriver2', sel+'.angleRate2' )
Exemplo n.º 24
0
 def createAimObjectCmd( first, second, third, worldPosition=False ):
 
     aimObjectMatrix = cmds.createNode( 'aimObjectMatrix' )
     cmds.connectAttr( first+'.wm', aimObjectMatrix+'.targetMatrix' )
     cmds.connectAttr( second+'.wm', aimObjectMatrix+'.baseMatrix' )
     
     if third:
         aimObject = third
     else:
         aimObject = cmds.createNode( 'transform' )
     
     if cmds.nodeType( aimObject ) == 'joint':
         try: cmds.setAttr( aimObject+'.jo', 0,0,0 )
         except:pass
     cmds.connectAttr( aimObjectMatrix+'.outRotate', aimObject+'.r' )
     
     if not third: cmds.parent( aimObject, second )
     cmds.setAttr( aimObject+'.t', 0,0,0 )
     
     if worldPosition:
         cmds.setAttr( aimObjectMatrix+'.worldSpaceOutput', 1 )
         cmds.connectAttr( aimObject+'.pim', aimObjectMatrix+'.parentInverseMatrix' )
         cmds.connectAttr( aimObjectMatrix+'.outTranslate', aimObject+'.t' )
         cmds.parent( aimObject, w=1 )
     
     return aimObject, aimObjectMatrix
Exemplo n.º 25
0
def getWristAngleNode( target, targetBase=None ):
    wristAngleCons = cmds.listConnections( target+'.m', s=0, d=1, type='wristAngle' )
    wristAngleNode = ''
    
    if not wristAngleCons:
        mmCons = cmds.listConnections( target+'.wm', s=0, d=1, type='multMatrix' )
        if mmCons:
            wristAngleCons = cmds.listConnections( mmCons[0]+'.o', s=0, d=1, type='wristAngle' )
            if wristAngleCons: wristAngleNode = wristAngleCons[0]
    else:
        wristAngleNode = wristAngleCons[0]
    
    if wristAngleNode: return wristAngleNode
    
    wa = cmds.createNode( 'wristAngle' )
    if not targetBase: 
        targetBase = cmds.listRelatives( target, p=1, f=1 )[0]
        cmds.connectAttr( target+'.m', wa+'.inputMatrix' )
    else:
        mm = cmds.createNode( 'multMatrix' )
        cmds.connectAttr( target+'.wm', mm+'.i[0]' )
        cmds.connectAttr( targetBase+'.wim', mm+'.i[1]' )
        cmds.connectAttr( mm+'.o', wa+'.inputMatrix' )
    
    cmds.select( wa )
    return wa
Exemplo n.º 26
0
def createWorldBlendTwoMatrixObject( first, second, target = None ):
    
    import sgBFunction_attribute
    
    blMtx = cmds.createNode( 'blendTwoMatrix' )
    mmdc  = cmds.createNode( 'multMatrixDecompose' )
    cmds.connectAttr( first+'.wm', blMtx+'.inMatrix1' )
    cmds.connectAttr( second+'.wm', blMtx+'.inMatrix2' )
    cmds.connectAttr( blMtx+'.outMatrix', mmdc+'.i[0]' )
    
    if not target: target = cmds.createNode( 'transform' )
    cmds.connectAttr( target+'.pim', mmdc+'.i[1]' )
    
    sgBFunction_attribute.addAttr( target, ln='blend', min=0, max=1, dv=0.5, k=1 )
    cmds.connectAttr( target+'.blend', blMtx+'.attributeBlender' )
    
    if not cmds.isConnected( mmdc+'.ot', target+'.t' ):
        cmds.connectAttr( mmdc+'.ot', target+'.t', f=1 )
    if not cmds.isConnected( mmdc+'.or', target+'.r' ):
        cmds.connectAttr( mmdc+'.or', target+'.r', f=1 )
    if not cmds.isConnected( mmdc+'.os', target+'.s' ):
        cmds.connectAttr( mmdc+'.os', target+'.s', f=1 )
    if not cmds.isConnected( mmdc+'.osh', target+'.sh' ):
        cmds.connectAttr( mmdc+'.osh', target+'.sh', f=1 )
    
    cmds.select( blMtx, target )
    return blMtx, target
Exemplo n.º 27
0
def followMatrixConnection( ctl, others ):
    
    import sgBFunction_attribute
    ctlP = cmds.listRelatives( ctl, p=1 )[0]
    
    followMatrix = cmds.createNode( 'followMatrix' )
    mmdc = cmds.createNode( 'multMatrixDecompose' )
    
    cmds.connectAttr( others[0]+'.wm', followMatrix+'.originalMatrix' )
    
    sgBFunction_attribute.addAttr( ctl, ln='_______', at='enum', en='Parent:', cb=1 )
    
    for other in others[1:]:
        i = others.index( other ) - 1
        cmds.connectAttr( other+'.wm', followMatrix+'.inputMatrix[%d]' % i )
        
        attrName = 'parent' + other.split( '_' )[-1]
        print other, attrName
        sgBFunction_attribute.addAttr( ctl, ln= attrName, min=0, max=10, k=1 )
        cmds.connectAttr( ctl+'.'+attrName, followMatrix+'.inputWeight[%d]' % i )
    
    cmds.connectAttr( followMatrix+'.outputMatrix', mmdc+'.i[0]' )
    cmds.connectAttr( ctlP+'.pim', mmdc+'.i[1]' )
    cmds.connectAttr( mmdc+'.ot', ctlP+'.t' )
    cmds.connectAttr( mmdc+'.or', ctlP+'.r' )
Exemplo n.º 28
0
def addModification( meshObjs ):
    
    import sgBFunction_attribute
    import sgBFunction_dag
    
    meshObjs = sgBFunction_dag.getChildrenMeshExists( meshObjs )
    softMod = cmds.deformer( meshObjs, type='softMod' )[0]
    
    ctlGrp = cmds.createNode( 'transform' )
    cmds.setAttr( ctlGrp+'.dh', 1 )
    dcmp   = cmds.createNode( 'decomposeMatrix' )
    ctl = cmds.sphere()[0]
    ctl = cmds.parent( ctl, ctlGrp )[0]
    sgBFunction_attribute.addAttr( ctl, ln='__________', at='enum', enumName = ':Modify Attr', cb=1 )
    sgBFunction_attribute.addAttr( ctl, ln='falloffRadius', min=0, dv=1, k=1 )
    sgBFunction_attribute.addAttr( ctl, ln='envelope', min=0, max=1, dv=1, k=1 )
    
    cmds.connectAttr( ctlGrp+'.wim', softMod+'.bindPreMatrix' )
    cmds.connectAttr( ctlGrp+'.wm', softMod+'.preMatrix' )
    cmds.connectAttr( ctl+'.wm', softMod+'.matrix' )
    cmds.connectAttr( ctl+'.m',  softMod+'.weightedMatrix' )
    
    cmds.connectAttr( ctlGrp+'.wm', dcmp+'.imat' )
    
    cmds.connectAttr( dcmp+'.ot', softMod+'.falloffCenter' )
    for i in range( len( meshObjs ) ):
        cmds.connectAttr( meshObjs[i]+'.wm', softMod+'.geomMatrix[%d]' % i )
    
    cmds.connectAttr( ctl+'.envelope', softMod+'.envelope' )
    cmds.connectAttr( ctl+'.falloffRadius', softMod+'.falloffRadius' )
    
    cmds.xform( ctlGrp, ws=1, t=cmds.getAttr( meshObjs[0]+'.wm' )[-4:-1] )
    cmds.select( ctlGrp )
Exemplo n.º 29
0
def chimaAddWingBsh() :
	# Add wing blend shapes to bird character
	cmd = 'file -import -type "mayaAscii" -rpr "geo_1" -options "v=0"  -pr -loadReferenceDepth "all" "Y:/USERS/Peck/projs/chimaWingFold/geo_1.ma";'
	mm.eval( cmd )

	mc.select( 'wingFoldLFT_bsh' , r=True )
	mc.select( 'wingFoldLFT_bsh' , add=True )
	cmd = 'blendShape -e  -t Eggbert_wings_geo 2 wingFoldLFT_bsh 1 -t Eggbert_wings_geo 3 wingFoldRGT_bsh 1 wings_bls;'
	mm.eval( cmd )


	rootCtrl = 'Pelvis_Ctrl'
	mc.addAttr( rootCtrl , ln='L_wingFoldB' , k=True , min=0 , max=10 )
	mc.addAttr( rootCtrl , ln='R_wingFoldB' , k=True , min=0 , max=10 )


	lMdv = mc.createNode( 'multDoubleLinear' , n='wingFoldBBshLFT_mdv' )

	mc.connectAttr( '%s.L_wingFoldB' % rootCtrl , '%s.i1' % lMdv )
	mc.setAttr( '%s.i2' % lMdv , 0.1 )
	mc.connectAttr( '%s.o' % lMdv , 'wings_bls.wingFoldLFT_bsh' )

	rMdv = mc.createNode( 'multDoubleLinear' , n='wingFoldBBshRGT_mdv' )

	mc.connectAttr( '%s.R_wingFoldB' % rootCtrl , '%s.i1' % rMdv )
	mc.setAttr( '%s.i2' % rMdv , 0.1 )
	mc.connectAttr( '%s.o' % rMdv , 'wings_bls.wingFoldRGT_bsh' )

	mc.delete( 'wingFold_bsh' )
	mc.delete( 'wingOrig_bsh' )
	mc.delete( 'wingFoldLFT_bsh' )
	mc.delete( 'wingFoldRGT_bsh' )
Exemplo n.º 30
0
def createLocalBlendTwoMatrixObject( first, second, target = None ):
    
    import sgBFunction_attribute
    
    blMtx = cmds.createNode( 'blendTwoMatrixDecompose' )
    cmds.connectAttr( first+'.m', blMtx+'.inMatrix1' )
    cmds.connectAttr( second+'.m', blMtx+'.inMatrix2' )
    
    if not target: target = cmds.createNode( 'transform' )
    
    sgBFunction_attribute.addAttr( target, ln='blend', min=0, max=1, dv=0.5, k=1 )
    cmds.connectAttr( target+'.blend', blMtx+'.attributeBlender' )
    
    if cmds.nodeType( target ) == 'joint':
        try:cmds.setAttr( target+'.jo', 0,0,0 )
        except:pass
    
    if not cmds.isConnected( blMtx+'.ot', target+'.t' ):
        cmds.connectAttr( blMtx+'.ot', target+'.t', f=1 )
    if not cmds.isConnected( blMtx+'.or', target+'.r' ):
        cmds.connectAttr( blMtx+'.or', target+'.r', f=1 )
    if not cmds.isConnected( blMtx+'.os', target+'.s' ):
        cmds.connectAttr( blMtx+'.os', target+'.s', f=1 )
    if not cmds.isConnected( blMtx+'.osh', target+'.sh' ):
        cmds.connectAttr( blMtx+'.osh', target+'.sh', f=1 )
    
    cmds.select( blMtx, target )
    return blMtx, target
Exemplo n.º 31
0
def patch():

    facialDrv = 'facialDrivers'

    eyeMaskOrig = 'eyeMask_ctrl_orig'

    JawClenchLOrig = 'Jaw_Clench_l_ctrl_orig'
    JawClenchROrig = 'Jaw_Clench_r_ctrl_orig'

    UpHeadGuide = 'UpHead_ctrl_GUIDE_01'
    UpHeadOrig = 'UpHead_ctrl_01_orig'
    UpHeadCtrl = 'UpHead_ctrl_01'
    LowerHeadGuide = 'LowerHead_ctrl_GUIDE_01'
    LowerHeadOrig = 'LowerHead_ctrl_01_orig'
    LowerHeadCtrl = 'LowerHead_ctrl_01'
    mouthSquashOrig = 'mouthSquash_jnt_orig'
    foreheadGrp = 'forehead_grp'
    headSKN = 'head_SKN'
    jawctrl = 'jaw_ctrl'
    noseGrp = 'nose_grp'
    noseUp = 'nose_up_ctrl'
    sneerTip = 'sneer_tip_ctrl'

    CUpperLip = 'C_upper_lip_ctrl'
    CUpperLipSideDkey = 'C_lipFlap_ctrl_01_dKeyAll_side'

    sides = ['L', 'R', 'C']
    lipFlapOrig = 'lipFlap_ctrl_01_orig'
    lipflapAll = 'lipFlap_all_ctrl'
    lipflapTip = 'lipFlap_tip_ctrl'
    lipflapCup = 'lipFlap_cup_ctrl'
    lipFlapList = [lipflapAll, lipflapTip, lipflapCup]

    allFlapsWeigts = [
        'lipFlap_all_inOut', 'lipFlap_all_UpDn', 'lipFlap_all_bwFw',
        'lipFlap_all_rotX', 'lipFlap_all_rotY', 'lipFlap_all_rotZ'
    ]
    tipFlapsWeigts = [
        'lipFlap_tip_inOut', 'lipFlap_tip_UpDn', 'lipFlap_tip_bwFw',
        'lipFlap_tip_rotX', 'lipFlap_tip_rotY', 'lipFlap_tip_rotZ'
    ]
    flapWeightsList = [allFlapsWeigts, tipFlapsWeigts]
    transformListBcs = [
        'translateX', 'translateY', 'translateZ', 'outValueX', 'outValueY',
        'outValueZ'
    ]

    bcsNode = mc.ls('*_bcs', type='DPK_bcs')[0]

    #reparent cups inside flaps All
    for side in sides:
        mc.parent('%s_%s_orig' % (side, lipflapCup),
                  '%s_%s' % (side, lipflapAll))

    # create drivenKeys on all dKeys nodes
    dKeyTrVals = [-2, 0, 2]
    dKeyRoVals = [-180, 0, 180]
    dKeyValsList = [dKeyTrVals, dKeyRoVals]

    axisList = ['X', 'Y', 'Z']
    transformList = ['translate', 'rotate']

    if mc.objExists('tempSaveGrp'):
        dKeyAllNodesList = eval(mc.getAttr('tempSaveGrp.dKeyAllNodesList'))
        dKeyTipNodesList = eval(mc.getAttr('tempSaveGrp.dKeyTipNodesList'))

        ## create dKeys on dKeyAll nodes
        for s, side in enumerate(sides):
            slaveNum = len(dKeyAllNodesList[s])
            ctrlName = '%s_%s' % (side, lipflapAll)
            targetList = dKeyAllNodesList[s]

            for t, transform in enumerate(transformList):
                for a, axis in enumerate(axisList):
                    for r, target in enumerate(targetList):
                        valuesDivider = len(targetList)

                        if transform == 'rotate':
                            mc.setAttr('%s.%s%s' % (ctrlName, transform, axis),
                                       0)
                            for value in dKeyValsList[t]:
                                mc.setAttr(
                                    '%s.%s%s' % (ctrlName, transform, axis),
                                    value)
                                mc.setAttr(
                                    '%s.%s%s' % (target, transform, axis),
                                    value / (valuesDivider / 2))
                                mc.setDrivenKeyframe(
                                    target,
                                    at='%s%s' % (transform, axis),
                                    cd='%s.%s%s' % (ctrlName, transform, axis))
                            mc.setAttr('%s.%s' % (ctrlName, transform), 0, 0,
                                       0)
                        elif transform == 'translate':
                            trFactor = mc.getAttr('%s_orig.scale' %
                                                  ctrlName)[0]

                            if not axis == 'Y':
                                if r > 0:
                                    pass
                                else:
                                    mc.setAttr(
                                        '%s.%s%s' %
                                        (ctrlName, transform, axis), 0)
                                    for value in dKeyValsList[t]:
                                        mc.setAttr(
                                            '%s.%s%s' %
                                            (ctrlName, transform, axis), value)
                                        mc.setAttr(
                                            '%s.%s%s' %
                                            (target, transform, axis),
                                            value * abs(trFactor[a]))
                                        mc.setDrivenKeyframe(
                                            target,
                                            at='%s%s' % (transform, axis),
                                            cd='%s.%s%s' %
                                            (ctrlName, transform, axis))
                                    mc.setAttr('%s.%s' % (ctrlName, transform),
                                               0, 0, 0)
                            else:
                                mc.setAttr(
                                    '%s.%s%s' % (ctrlName, transform, axis), 0)
                                for value in dKeyValsList[t]:
                                    mc.setAttr(
                                        '%s.%s%s' %
                                        (ctrlName, transform, axis), value)
                                    mc.setAttr(
                                        '%s.%s%s' % (target, transform, axis),
                                        value * abs(trFactor[a]))
                                    mc.setDrivenKeyframe(
                                        target,
                                        at='%s%s' % (transform, axis),
                                        cd='%s.%s%s' %
                                        (ctrlName, transform, axis))
                                mc.setAttr('%s.%s' % (ctrlName, transform), 0,
                                           0, 0)

                        mc.keyTangent(target, itt='linear', ott='linear')

        ## create dKeys on dKeytip nodes
        for s, side in enumerate(sides):
            slaveNum = len(dKeyAllNodesList[s])
            ctrlName = '%s_%s' % (side, lipflapTip)
            targetList = dKeyTipNodesList[s]

            for t, transform in enumerate(transformList):
                for a, axis in enumerate(axisList):
                    for r, target in enumerate(targetList):
                        valuesDivider = len(targetList)

                        if transform == 'rotate':
                            mc.setAttr('%s.%s%s' % (ctrlName, transform, axis),
                                       0)
                            for value in dKeyValsList[t]:
                                mc.setAttr(
                                    '%s.%s%s' % (ctrlName, transform, axis),
                                    value)
                                mc.setAttr(
                                    '%s.%s%s' % (target, transform, axis),
                                    value / (valuesDivider / 2))
                                mc.setDrivenKeyframe(
                                    target,
                                    at='%s%s' % (transform, axis),
                                    cd='%s.%s%s' % (ctrlName, transform, axis))
                            mc.setAttr('%s.%s' % (ctrlName, transform), 0, 0,
                                       0)
                        elif transform == 'translate':
                            trFactor = mc.getAttr('%s_orig.scale' %
                                                  ctrlName)[0]

                            if not axis == 'Y':
                                if r > 0:
                                    pass
                                else:
                                    mc.setAttr(
                                        '%s.%s%s' %
                                        (ctrlName, transform, axis), 0)
                                    for value in dKeyValsList[t]:
                                        mc.setAttr(
                                            '%s.%s%s' %
                                            (ctrlName, transform, axis), value)
                                        mc.setAttr(
                                            '%s.%s%s' %
                                            (target, transform, axis),
                                            value * abs(trFactor[a]))
                                        mc.setDrivenKeyframe(
                                            target,
                                            at='%s%s' % (transform, axis),
                                            cd='%s.%s%s' %
                                            (ctrlName, transform, axis))
                                    mc.setAttr('%s.%s' % (ctrlName, transform),
                                               0, 0, 0)
                            else:
                                mc.setAttr(
                                    '%s.%s%s' % (ctrlName, transform, axis), 0)
                                for value in dKeyValsList[t]:
                                    mc.setAttr(
                                        '%s.%s%s' %
                                        (ctrlName, transform, axis), value)
                                    mc.setAttr(
                                        '%s.%s%s' % (target, transform, axis),
                                        value * abs(trFactor[a]))
                                    mc.setDrivenKeyframe(
                                        target,
                                        at='%s%s' % (transform, axis),
                                        cd='%s.%s%s' %
                                        (ctrlName, transform, axis))
                                mc.setAttr('%s.%s' % (ctrlName, transform), 0,
                                           0, 0)

                        mc.keyTangent(target, itt='linear', ott='linear')

        ## create additionnal Dkeys
        ### create nose up dKeyAllNodesList
        noseDkeyVals = [-2, 0, 2]
        mc.setAttr('{}_dKey.rotateY'.format(noseUp), 0)
        mc.setAttr('{}.translateX'.format(sneerTip), 0)
        for val in noseDkeyVals:
            mc.setAttr('{}.translateX'.format(sneerTip), val)
            mc.setAttr('{}_dKey.rotateY'.format(noseUp), val * 1.5)
            mc.setDrivenKeyframe('{}_dKey'.format(noseUp),
                                 at='rotateY',
                                 cd='{}.translateX'.format(sneerTip))
        mc.setAttr('{}.translateX'.format(sneerTip), 0)
        ### create C_upperLip_side_dkey
        lipDkeyVals = [-1.5, 0, 1.5]
        axisList = ['X', 'Z']
        for axis in axisList:
            mc.setAttr('{}.translate{}'.format(CUpperLip, axis), 0)
            mc.setAttr('{}.translate{}'.format(CUpperLipSideDkey, axis), 0)
            for val in lipDkeyVals:
                mc.setAttr('{}.translate{}'.format(CUpperLip, axis), val)
                mc.setAttr('{}.translate{}'.format(CUpperLipSideDkey, axis),
                           val * 0.1)
                mc.setDrivenKeyframe(CUpperLipSideDkey,
                                     at='translate{}'.format(axis),
                                     cd='{}.translate{}'.format(
                                         CUpperLip, axis))
            mc.setAttr('{}.translate{}'.format(CUpperLip, axis), 0)

        mc.delete('tempSaveGrp')

        # add locks and translate limits to controls
        for side in sides:
            for lipFlap in (lipFlapList[0], lipFlapList[1]):
                patchLib.locksSwitch('%s_%s' % (side, lipFlap),
                                     T=False,
                                     R=False,
                                     S=True,
                                     V=False,
                                     lockdo='lock',
                                     keydo=False)
                mc.transformLimits('%s_%s' % (side, lipFlap),
                                   tx=(-1, 1),
                                   ty=(-1, 1),
                                   tz=(-1, 1))
                mc.transformLimits('%s_%s' % (side, lipFlap),
                                   rx=(-180, 180),
                                   ry=(-180, 180),
                                   rz=(-180, 180))
                mc.transformLimits('%s_%s' % (side, lipFlap),
                                   etx=(True, True),
                                   ety=(True, True),
                                   etz=(True, True))
                mc.transformLimits('%s_%s' % (side, lipFlap),
                                   erx=(True, True),
                                   ery=(True, True),
                                   erz=(True, True))
                createOvershootAttrLimit(['%s_%s' % (side, lipFlap)],
                                         ['tx', 'ty', 'tz'])

        #connect flaps controls to bcs weights
        if bcsNode:
            for side in sides:
                for f, flap in enumerate(lipFlapList[0:2]):
                    flapCtrl = '%s_%s' % (side, flap)

                    flapSR = mc.createNode('setRange', n='%s_sr' % flapCtrl)
                    mc.connectAttr('%s.rotate' % flapCtrl, '%s.value' % flapSR)
                    mc.setAttr('%s.min' % flapSR, -2, -2, -2)
                    mc.setAttr('%s.max' % flapSR, 2, 2, 2)
                    mc.setAttr('%s.oldMin' % flapSR, -180, -180, -180)
                    mc.setAttr('%s.oldMax' % flapSR, 180, 180, 180)

                    for w, weight in enumerate(flapWeightsList[f]):
                        if w < 3:
                            mc.connectAttr(
                                '%s.%s' % (flapCtrl, transformListBcs[w]),
                                '%s.%s_%s' % (bcsNode, weight, side))
                        else:
                            mc.connectAttr(
                                '%s.%s' % (flapSR, transformListBcs[w]),
                                '%s.%s_%s' % (bcsNode, weight, side))

    else:
        print 'saveGrp missing, do jawGen dog befor creating dKeys'
Exemplo n.º 32
0
 def test_childPathAtIndex(self):
     nodeParent = nodes.asMObject(cmds.group(self.node))
     child1 = nodes.asMObject(cmds.createNode("transform"))
     nodes.setParent(child1, nodeParent)
     dagPath = om.MFnDagNode(nodeParent).getPath()
     self.assertEquals(nodes.childPathAtIndex(dagPath, 0).partialPathName(), self.node)
Exemplo n.º 33
0
 def test_setParent(self):
     obj = nodes.asMObject(self.node)
     self.assertFalse(nodes.hasParent(obj))
     transform = nodes.asMObject(cmds.createNode("transform"))
     nodes.setParent(transform, obj)
     self.assertTrue(nodes.hasParent(transform))
Exemplo n.º 34
0
 def test_toApiObjectReturnsDependNode(self):
     node = cmds.createNode("multiplyDivide")
     self.assertIsInstance(nodes.toApiMFnSet(node), om.MFnDependencyNode)
Exemplo n.º 35
0
 def setUp(self):
     self.node = cmds.createNode("transform")
Exemplo n.º 36
0
    cmds.parentConstraint(sel, targetA)
    cmds.delete(targetA + '_parentConstraint1')
    cmds.parent(sel, targetA)
    up = cmds.listRelatives(sel, p=True)
    cmds.parentConstraint(sel, targetB)
    cmds.delete(targetB + '_parentConstraint1')
    cmds.parent(targetA, targetB)
    cmds.select(cl=1)
    return targetB


name_ = 'ankle_ribbon'
sel = orderls()
num_ = len(sel)
posList_, crvShape_ = pointCrv(sel, name_)
crv_ = crv(sel, name_, posList_)

for i in range(num_):
    padding = '2'
    pad = ("%%0%si" % padding) % int(i)
    #cmds.getAttr('{}.{}[{}]'.format(shape_, 'controlPoints', i))
    poci_ = cmds.createNode('pointOnCurveInfo',
                            n='{}_{}_{}'.format(name_, pad, 'POCI'))
    ctl_, ctl_os = ctl('{}_{}'.format(name_, pad), 'sphere', 2)
    jnt_ = jnt(ctl_, '{}_{}'.format(name_, pad))
    jnt_os = OSCS(jnt_)
    cmds.parent(jnt_os, ctl_)
    cmds.setAttr('{}.{}'.format(poci_, 'parameter'), i)
    cmds.connectAttr('{}.{}'.format(crv_, 'ws'), '{}.{}'.format(poci_, 'ic'))
    cmds.connectAttr('{}.{}'.format(poci_, 'p'), '{}.{}'.format(ctl_os, 't'))
Exemplo n.º 37
0
    def createSpace(self):
        if cmds.objExists(
                self.firstSpace.replace(
                    self.firstSpace.split('_')[-1], 'space_SPC')):
            self.firstSpaceNul = self.firstSpace.replace(
                self.firstSpace.split('_')[-1], 'space_SPC')

            fLocatorName = self.target.replace(
                self.firstSpace.split('_')[-1], 'LOC')
            self.firstSpaceLOC = cmds.spaceLocator(n=fLocatorName.replace(
                fLocatorName.split('_')[-2], '%sIn%s' %
                (self.target.split('_')[-2],
                 self.firstSpace.split('_')[-2].capitalize())))
            POsnap(self.firstSpaceLOC, self.target)

            cmds.parent(self.firstSpaceLOC, self.firstSpaceNul)

        else:
            self.firstSpaceNul = cmds.createNode(
                'transform',
                n=self.firstSpace.replace(
                    self.firstSpace.split('_')[-1], 'space_SPC'))
            POsnap(self.firstSpaceNul, self.firstSpace)

            fLocatorName = self.target.replace(
                self.firstSpace.split('_')[-1], 'LOC')
            self.firstSpaceLOC = cmds.spaceLocator(n=fLocatorName.replace(
                fLocatorName.split('_')[-2], '%sIn%s' %
                (self.target.split('_')[-2],
                 self.firstSpace.split('_')[-2].capitalize())))
            POsnap(self.firstSpaceLOC, self.target)

            cmds.parent(self.firstSpaceLOC, self.firstSpaceNul)

        if cmds.objExists(
                self.secondSpace.replace(
                    self.secondSpace.split('_')[-1], 'space_SPC')):
            self.secondSpaceNul = self.secondSpace.replace(
                self.secondSpace.split('_')[-1], 'space_SPC')
            sLocatorName = self.target.replace(
                self.secondSpace.split('_')[-1], 'LOC')
            self.secondSpaceLOC = cmds.spaceLocator(n=sLocatorName.replace(
                sLocatorName.split('_')[-2], '%sIn%s' %
                (self.target.split('_')[-2],
                 self.secondSpace.split('_')[-2].capitalize())))

            POsnap(self.secondSpaceLOC[0], self.target)

            cmds.parent(self.secondSpaceLOC, self.secondSpaceNul)

        else:
            self.secondSpaceNul = cmds.createNode(
                'transform',
                n=self.secondSpace.replace(
                    self.secondSpace.split('_')[-1], 'space_SPC'))
            POsnap(self.secondSpaceNul, self.secondSpace)

            sLocatorName = self.target.replace(
                self.secondSpace.split('_')[-1], 'LOC')
            self.secondSpaceLOC = cmds.spaceLocator(n=sLocatorName.replace(
                sLocatorName.split('_')[-2], '%sIn%s' %
                (self.target.split('_')[-2],
                 self.secondSpace.split('_')[-2].capitalize())))

            POsnap(self.secondSpaceLOC[0], self.target)

            cmds.parent(self.secondSpaceLOC, self.secondSpaceNul)
        return [self.firstSpaceNul, self.secondSpaceNul]
        """
Exemplo n.º 38
0
 def meshAlphaMapCreateNew(node, attr):
     logger.debug("Alpha Map create new: %s.%s" % (node, attr))
     alphaMap = mc.createNode("appleseedAlphaMap")
     mc.connectAttr(alphaMap + ".shape", node + '.' + attr)
Exemplo n.º 39
0
def remapValue(inputAttr,
               targetAttr='',
               inputMin=0,
               inputMax=1,
               outputMin=0,
               outputMax=1,
               interpType='linear',
               rampValues=[],
               prefix=''):
    '''
	Create a remapValue node based on the incoming arguments
	@param inputAttr: Input attribute plug to connect to the remapValue node input.
	@type inputAttr: str
	@param targetAttr: Optional target attribute to receive the output value of the remapValue node.
	@type targetAttr: str
	@param inputMin: Input minimum value for the remapValue node.
	@type inputMin: float
	@param inputMax: Input maximum value for the remapValue node.
	@type inputMax: float
	@param outputMin: Output minimum value for the remapValue node.
	@type outputMin: float
	@param outputMax: Output maximum value for the remapValue node.
	@type outputMax: float
	@param interpType: Ramp interpolation method.
	@type interpType: str
	@param rampValues: List of ramp position and value pairs. [(pos1,val1),(pos2,val2),(pos3,val3)]
	@type rampValues: list
	@param prefix: Naming prefix string for remapValue node
	@type prefix: str
	'''
    # ==========
    # - Checks -
    # ==========

    # Input Attributes
    if not mc.objExists(inputAttr):
        raise Exception('Input attribute "' + inputAttr + '" does not exist!')
    try:
        mc.getAttr(inputAttr, l=True)
    except:
        raise Exception('Input attribute argument "' + inputAttr +
                        '" is not a valid attribute!')

    # Target
    if targetAttr:
        if not mc.objExists(targetAttr):
            raise Exception('Target attribute "' + targetAttr +
                            '" does not exist!')
        try:
            mc.getAttr(targetAttr, l=True)
        except:
            raise Exception('Target attribute argument "' + targetAttr +
                            '" is not a valid attribute!')

    # Interp Type
    interpTypeList = ['none', 'linear', 'smooth', 'spline']
    if not interpTypeList.count(interpType):
        raise Exception('Invalid interpolation type specified! ("' +
                        interpType + '")')

    # Prefix
    if not prefix: prefix = inputAttr.replace('.', '_')

    # ==========================
    # - Create RemapValue Node -
    # ==========================

    remapValueNode = mc.createNode('remapValue', n=prefix + '_remapValue')

    # Connect Input
    mc.connectAttr(inputAttr, remapValueNode + '.inputValue', f=True)

    # Set Input/Output Min/Max
    mc.setAttr(remapValueNode + '.inputMin', inputMin)
    mc.setAttr(remapValueNode + '.inputMax', inputMax)
    mc.setAttr(remapValueNode + '.outputMin', outputMin)
    mc.setAttr(remapValueNode + '.outputMax', outputMax)

    # Interp Type
    interpTypeInd = interpTypeList.index(interpType)
    mc.setAttr(remapValueNode + '.value[0].value_Interp', interpTypeInd)
    mc.setAttr(remapValueNode + '.value[1].value_Interp', interpTypeInd)

    # ====================
    # - Plot Ramp Values -
    # ====================

    for i in range(len(rampValues)):

        mc.setAttr(remapValueNode + '.value[' + str(i) + '].value_Position',
                   rampValues[i][0])
        mc.setAttr(remapValueNode + '.value[' + str(i) + '].value_FloatValue',
                   rampValues[i][1])
        mc.setAttr(remapValueNode + '.value[' + str(i) + '].value_Interp',
                   interpTypeInd)

    # ===============================
    # - Connect to Target Attribute -
    # ===============================

    if targetAttr:
        mc.connectAttr(remapValueNode + '.outValue', targetAttr, f=True)

    # =================
    # - Return Result -
    # =================

    return remapValueNode
Exemplo n.º 40
0
    def fromType(nodeType):
        n = cmds.createNode(nodeType)

        return Node(n)
Exemplo n.º 41
0
def create(path,
           objectType,
           num=0,
           parent=False,
           useDist=False,
           min=0.0,
           max=1.0,
           prefix=''):
    """
    Create objects along a curve

    # INPUTS:
    @input path: Input nurbs curve path
    @inputType path: str
    @input objectType: Type of objects to create and place along path
    @inputType objectType: str
    @input num: Number of objects to create along path. If num=0, number of edit points will be used.
    @inputType num: int
    @input parent: Parent each new object to the previously created object. eg. Joint chain
    @inputType parent: bool
    @input useDist: Use distance along curve instead of parametric length for sample distribution
    @inputType useDist: bool
    @input min: Percent along the path to start placing objects
    @inputType min: float
    @input max: Percent along the path to stop placing objects
    @inputType max: float
    @input prefix: Name prefix for builder created nodes. If left at default ("") prefix will be derived from path name.
    @inputType prefix: str

    # OUTPUTS:
    @output outObjectList: List of objects placed along path
    @outputType outObjectList: list
    """

    # Check Path
    if not glTools.utils.curve.isCurve(path):
        raise Exception('Path object ' + path + ' is not a valid nurbs curve!')

    # Check prefix
    if not prefix: prefix = glTools.utils.stringUtils.stripSuffix(path)

    # Check object count
    if not num: num = cmds.getAttr(path + '.spans') + 1

    # Get curve sample points
    paramList = glTools.utils.curve.sampleParam(path, num, useDist, min, max)

    # Create object along path
    objList = []
    for i in range(num):

        # Get string index
        ind = glTools.utils.stringUtils.stringIndex(i + 1)

        # Create object
        obj = cmds.createNode(objectType, n=prefix + ind + '_' + objectType)
        if not glTools.utils.base.isTransform(obj):
            obj = cmds.listRelatives(obj, p=True, pa=True)[0]

        # Position
        pos = cmds.pointOnCurve(path, pr=paramList[i])
        cmds.xform(obj, t=pos, ws=True)

        # Parent
        if parent and i: obj = cmds.parent(obj, objList[-1])[0]

        # Orient Joint
        if objectType == 'joint' and i:
            cmds.joint(objList[-1], e=True, zso=True, oj='xyz', sao='yup')

        # Append result
        objList.append(str(obj))

    # Return result
    return objList
Exemplo n.º 42
0
    def build(
            self,
            spineJoints = [],
            rootJoint = '',
            rigScale = 1.0,
            createFKSystem = True,
            createCircleFkControl = True,
            createCircleIkControl = False,
            surroundingMeshes = []
            ):

        # Create upper body control.
        upperBodyCtrl = SERigControl.RigArrowCrossControl(
                                rigSide = SERigEnum.eRigSide.RS_Center,
                                rigType = SERigEnum.eRigType.RT_SpineUpperBody,
                                prefix = self.Prefix + 'UpperBody', 
                                translateTo = spineJoints[0],
                                scale = rigScale*20,
                                scaleX = 5,
                                scaleZ = 5,
                                parent = self.ControlsGrp,
                                fitToSurroundingMeshes = True,
                                surroundingMeshes = surroundingMeshes,
                                postFitScale = 1.75,
                                overrideFitRayDirection = True, 
                                fitRayDirection = (-1, 0, 0)
                                )
        SERigObjectTypeHelper.linkRigObjects(self.TopGrp, upperBodyCtrl.ControlGroup, 'UpperBodyCtrl', 'ControlOwner')
        self.UpperBodyCtrl = upperBodyCtrl

        # Create pelvis and chest proxy joints.
        pelvisProxyJoint = cmds.duplicate(spineJoints[0], n = spineJoints[0] + SERigNaming.s_Proxy, parentOnly = True)[0]
        chestBeginProxyJoint = cmds.duplicate(spineJoints[-1], n = spineJoints[-1] + SERigNaming.s_Proxy, parentOnly = True)[0]
        cmds.hide(pelvisProxyJoint, chestBeginProxyJoint)

        # Create IK controls.
        chestBeginCtrl = None
        if createCircleIkControl:
            chestBeginCtrl = SERigControl.RigCircleControl(
                                        rigSide = SERigEnum.eRigSide.RS_Center,
                                        rigType = SERigEnum.eRigType.RT_SpineChest,
                                        prefix = self.Prefix + 'Chest', 
                                        translateTo = chestBeginProxyJoint,
                                        rotateTo = chestBeginProxyJoint,
                                        scale = rigScale*22,
                                        parent = upperBodyCtrl.ControlObject,
                                        fitToSurroundingMeshes = True,
                                        surroundingMeshes = surroundingMeshes,
                                        postFitScale = 1.6
                                        )
        else:
            chestBeginCtrl = SERigControl.RigCubeControl(
                                    rigSide = SERigEnum.eRigSide.RS_Center,
                                    rigType = SERigEnum.eRigType.RT_SpineChest,
                                    prefix = self.Prefix + 'Chest', 
                                    translateTo = chestBeginProxyJoint,
                                    rotateTo = chestBeginProxyJoint,
                                    scale = rigScale*22,
                                    parent = upperBodyCtrl.ControlObject,
                                    cubeScaleX = 4.0,
                                    cubeScaleY = 35.0,
                                    cubeScaleZ = 35.0,
                                    transparency = 0.75,
                                    fitToSurroundingMeshes = True,
                                    surroundingMeshes = surroundingMeshes,
                                    postFitScale = 1.25
                                    )
        SERigObjectTypeHelper.linkRigObjects(self.TopGrp, chestBeginCtrl.ControlGroup, 'ChestBeginCtrl', 'ControlOwner')
        self.ChestBeginCtrl = chestBeginCtrl

        pelvisCtrl = None
        if createCircleIkControl:
            pelvisCtrl = SERigControl.RigCircleControl(
                                    rigSide = SERigEnum.eRigSide.RS_Center,
                                    rigType = SERigEnum.eRigType.RT_SpinePelvis,
                                    prefix = self.Prefix + 'Pelvis', 
                                    translateTo = pelvisProxyJoint,
                                    rotateTo = pelvisProxyJoint,
                                    scale = rigScale*26,
                                    parent = upperBodyCtrl.ControlObject,
                                    fitToSurroundingMeshes = True,
                                    surroundingMeshes = surroundingMeshes,
                                    postFitScale = 1.3
                                    )
        else:
            pelvisCtrl = SERigControl.RigCubeControl(
                                    rigSide = SERigEnum.eRigSide.RS_Center,
                                    rigType = SERigEnum.eRigType.RT_SpinePelvis,
                                    prefix = self.Prefix + 'Pelvis', 
                                    translateTo = pelvisProxyJoint,
                                    rotateTo = pelvisProxyJoint,
                                    scale = rigScale*26,
                                    parent = upperBodyCtrl.ControlObject,
                                    cubeScaleX = 4.0,
                                    cubeScaleY = 35.0,
                                    cubeScaleZ = 35.0,
                                    transparency = 0.75,
                                    fitToSurroundingMeshes = True,
                                    surroundingMeshes = surroundingMeshes,
                                    postFitScale = 1.2
                                    )
        SERigObjectTypeHelper.linkRigObjects(self.TopGrp, pelvisCtrl.ControlGroup, 'PelvisCtrl', 'ControlOwner')
        self.PelvisCtrl = pelvisCtrl

        pelvisLocalCtrl = SERigControl.RigCircleControl(
                                rigSide = SERigEnum.eRigSide.RS_Center,
                                rigType = SERigEnum.eRigType.RT_SpinePelvisLocal,
                                prefix = self.Prefix + 'PelvisLocal', 
                                translateTo = pelvisProxyJoint,
                                rotateTo = pelvisProxyJoint,
                                scale = rigScale*22,
                                parent = upperBodyCtrl.ControlObject,
                                lockChannels = ['s', 't', 'v'],
                                fitToSurroundingMeshes = True,
                                surroundingMeshes = surroundingMeshes,
                                postFitScale = 1.35
                                )
        SERigObjectTypeHelper.linkRigObjects(self.TopGrp, pelvisLocalCtrl.ControlGroup, 'PelvisLocalCtrl', 'ControlOwner')
        self.PelvisLocalCtrl = pelvisLocalCtrl

        chestBeginLocalCtrl = SERigControl.RigCircleControl(
                                rigSide = SERigEnum.eRigSide.RS_Center,
                                rigType = SERigEnum.eRigType.RT_SpineChestLocal,
                                prefix = self.Prefix + 'ChestLocal', 
                                translateTo = chestBeginProxyJoint,
                                rotateTo = chestBeginProxyJoint,
                                scale = rigScale*22,
                                parent = upperBodyCtrl.ControlObject,
                                lockChannels = ['s', 't', 'v'],
                                fitToSurroundingMeshes = True,
                                surroundingMeshes = surroundingMeshes,
                                postFitScale = 1.35
                                )
        SERigObjectTypeHelper.linkRigObjects(self.TopGrp, chestBeginLocalCtrl.ControlGroup, 'ChestBeginLocalCtrl', 'ControlOwner')
        self.ChestBeginLocalCtrl = chestBeginLocalCtrl

        cmds.parent(pelvisProxyJoint, chestBeginProxyJoint, self.JointsGrp)

        cmds.parentConstraint(chestBeginCtrl.ControlObject, chestBeginProxyJoint)
        cmds.parentConstraint(chestBeginCtrl.ControlObject, chestBeginLocalCtrl.ControlGroup)
        cmds.parentConstraint(pelvisCtrl.ControlObject, pelvisProxyJoint)
        cmds.parentConstraint(pelvisCtrl.ControlObject, pelvisLocalCtrl.ControlGroup)

        # Insert two new parents for the spine end joints.
        chestBeginNewParent = SEJointHelper.createNewParentJoint(spineJoints[-1])
        spine0NewParent = SEJointHelper.createNewParentJoint(spineJoints[1], True)

        # Get spine joints on which IK joints shall be created.
        cmds.parent(spineJoints[-1], w = 1)
        newSpineJoints = SEJointHelper.listHierarchy(spine0NewParent)
        cmds.parent(spineJoints[-1], chestBeginNewParent)
        
        # Create IK spine joints.
        ikSpineJoints = []
        preParent = None
        for joint in newSpineJoints:
            ikSpineJoint = cmds.createNode('joint', n = SERigNaming.sIKPrefix + joint)
            cmds.delete(cmds.parentConstraint(joint, ikSpineJoint))
            
            if preParent:
                cmds.parent(ikSpineJoint, preParent)

            preParent = ikSpineJoint
            ikSpineJoints.append(ikSpineJoint)

        # Move IK spine joints to component's joint group.
        cmds.parent(ikSpineJoints[0], self.JointsGrp)
        cmds.makeIdentity(ikSpineJoints[0], apply = True, t = 1, r = 1, s = 1, n = 0,  pn = 1)
        cmds.hide(ikSpineJoints[0])

        # Create IK handle on IK spine joints.
        resList = cmds.ikHandle(n = self.Prefix + SERigNaming.s_SplineIKHandle, 
                                sol = 'ikSplineSolver', sj = ikSpineJoints[0], ee = ikSpineJoints[-1], ccv = 1, parentCurve = 0, numSpans = 4)
        spineIK = resList[0]
        spineCurve = resList[2]

        spineCurveNewName = self.Prefix + SERigNaming.s_Curve
        cmds.rename(spineCurve, spineCurveNewName)
                                                
        cmds.hide(spineIK)
        cmds.hide(spineCurveNewName)
        cmds.parent(spineIK, spineCurveNewName, self.RigPartsFixedGrp)

        cmds.select(pelvisProxyJoint, chestBeginProxyJoint, spineCurveNewName)
        cmds.skinCluster(toSelectedBones = 1, bindMethod = 0, nw = 1, wd = 0, mi = 5, omi = True, dr = 4, rui = True)

        # Make spine twistable.
        cmds.setAttr(spineIK + '.dTwistControlEnable', 1)
        cmds.setAttr(spineIK + '.dWorldUpType', 4)
        cmds.connectAttr(pelvisCtrl.ControlObject + '.worldMatrix[0]', spineIK + '.dWorldUpMatrix')
        cmds.connectAttr(chestBeginCtrl.ControlObject + '.worldMatrix[0]', spineIK + '.dWorldUpMatrixEnd')

        # Control original spine in-between joints via IK spine joints.
        for ikSpineJoint, spineJoint in zip(ikSpineJoints, newSpineJoints):
            cmds.orientConstraint(ikSpineJoint, spineJoint, mo = 1)
            cmds.pointConstraint(ikSpineJoint, spineJoint, mo = 1)

        # Control original chest begin joint via chest begin local control.
        cmds.orientConstraint(chestBeginLocalCtrl.ControlObject, spineJoints[-1], mo = 1)
        cmds.pointConstraint(chestBeginLocalCtrl.ControlObject, spineJoints[-1], mo = 1)

        # Control original pelvis joint via pelvis local control.
        cmds.orientConstraint(pelvisLocalCtrl.ControlObject, spineJoints[0], mo = 1)
        cmds.pointConstraint(pelvisLocalCtrl.ControlObject, spineJoints[0], mo = 1)

        # Create stretching spine.
        curveInfoNode = cmds.arclen(spineCurveNewName, ch = 1)
        curveLen = cmds.getAttr(curveInfoNode + '.arcLength')

        globalScaleAttr = None
        if self.BaseRig:
            globalScaleAttr = self.BaseRig.getGlobalScaleAttrName()

        mulNode = cmds.createNode('multiplyDivide')
        cmds.setAttr(mulNode + '.operation', 1)
        cmds.setAttr(mulNode + '.input1X', curveLen)
        cmds.setAttr(mulNode + '.i1', l = 1)

        if globalScaleAttr:
            cmds.connectAttr(globalScaleAttr, mulNode + '.input2X', f = 1)

        divNode = cmds.createNode('multiplyDivide')
        cmds.setAttr(divNode + '.operation', 2)
        cmds.connectAttr(curveInfoNode + '.arcLength', divNode + '.input1X', f = 1)
        cmds.connectAttr(mulNode + '.outputX', divNode + '.input2X', f = 1)

        blender = cmds.createNode('blendColors')
        cmds.connectAttr(divNode + '.outputX', blender + '.color1R', f = 1)
        cmds.setAttr(blender + '.color2R', 1.0)

        if self.BaseRig:
            stretchSpineAttr = self.BaseRig.addStretchSpineAttr()
            mainControlObj = self.BaseRig.getMainControlObject()

            if mainControlObj and stretchSpineAttr:
                cmds.connectAttr(mainControlObj + '.' + stretchSpineAttr, blender + '.blender')

                for i in range(len(ikSpineJoints) - 1):
                    curIKSpineJoint = ikSpineJoints[i + 1]
                    curDefaultTransX = cmds.getAttr(curIKSpineJoint + '.translateX')
                    curMulNode = cmds.createNode('multiplyDivide')
                    cmds.setAttr(curMulNode + '.input2X', curDefaultTransX)
                    cmds.setAttr(curMulNode + '.i2', l = 1)
                    cmds.connectAttr(blender + '.outputR', curMulNode + '.input1X', f = 1)
                    cmds.connectAttr(curMulNode + '.outputX', curIKSpineJoint + '.translateX', f = 1)
            else:
                cmds.warning('Failed creating stretching spine attribute for the main control.')

        if createFKSystem:
            # Create FK joints.
            resCurve = cmds.rebuildCurve(spineCurveNewName, ch = 0, rpo = 0, rt = 0, end = 1, kr = 0, kcp = 0, kep = 1, kt = 0, s = 3, d = 1, tol = 0.00393701)[0]

            cmds.select(cl=1)
            jnt0 = cmds.joint(n = SERigNaming.sFKPrefix + spineJoints[0])
            cmds.delete(cmds.pointConstraint(spineJoints[0], jnt0))

            cmds.select(cl=1)
            jnt1 = cmds.joint(n = SERigNaming.sFKPrefix + 'C_Spine_0')
            cmds.select(resCurve + '.cv[1]')
            res = cmds.pointPosition()
            cmds.move(res[0], res[1], res[2], jnt1, rpr = 1)

            cmds.select(cl=1)
            jnt2 = cmds.joint(n = SERigNaming.sFKPrefix + 'C_Spine_1')
            cmds.select(resCurve + '.cv[2]')
            res = cmds.pointPosition()
            cmds.move(res[0], res[1], res[2], jnt2, rpr = 1)

            cmds.select(cl=1)
            jnt3 = cmds.joint(n = SERigNaming.sFKPrefix + spineJoints[-1])
            cmds.delete(cmds.pointConstraint(spineJoints[-1], jnt3))

            RefJnt = cmds.duplicate(jnt2, n =  'Ref_jnt', parentOnly = True)[0]
            cmds.move(0, 0, -10, RefJnt, r = 1, os = 1)

            cmds.delete(cmds.aimConstraint(jnt1, jnt0, offset = [0, 0, 0], w = 1, aim = [1, 0, 0], u = [0, 1, 0], worldUpType = 'object', worldUpObject = RefJnt))
            cmds.delete(cmds.aimConstraint(jnt2, jnt1, offset = [0, 0, 0], w = 1, aim = [1, 0, 0], u = [0, 1, 0], worldUpType = 'object', worldUpObject = RefJnt))
            cmds.delete(cmds.aimConstraint(jnt3, jnt2, offset = [0, 0, 0], w = 1, aim = [1, 0, 0], u = [0, 1, 0], worldUpType = 'object', worldUpObject = RefJnt))

            cmds.delete(cmds.orientConstraint(spineJoints[-1], jnt3))

            cmds.parent(jnt3, jnt2)
            cmds.parent(jnt2, jnt1)
            cmds.parent(jnt1, jnt0)
            cmds.parent(jnt0, self.JointsGrp)

            cmds.makeIdentity(jnt0, apply = True, t = 1, r = 1, s = 1, n = 0,  pn = 1)

            cmds.delete(RefJnt)
            cmds.delete(resCurve)

            # Attach FK root joint to upper body control.
            cmds.parentConstraint(upperBodyCtrl.ControlObject, jnt0, mo = 1)        

            # Create FK spine_0 control.
            FKSpine0Ctrl = None
            if createCircleFkControl:
                FKSpine0Ctrl = SERigControl.RigCircleControl(
                                        rigSide = SERigEnum.eRigSide.RS_Center,
                                        rigType = SERigEnum.eRigType.RT_SpineFK,
                                        rigControlIndex = 0,
                                        prefix = SERigNaming.sFKPrefix + self.Prefix + '_0', 
                                        translateTo = jnt1,
                                        rotateTo = jnt1,
                                        scale = rigScale*20,
                                        parent = upperBodyCtrl.ControlObject,
                                        lockChannels = ['t', 's', 'v'],
                                        overrideControlColor = True, 
                                        controlColor = (0.4, 0.9, 0.9),
                                        fitToSurroundingMeshes = True,
                                        surroundingMeshes = surroundingMeshes,
                                        postFitScale = 1.45
                                        )
            else:
                FKSpine0Ctrl = SERigControl.RigCubeControl(
                                        rigSide = SERigEnum.eRigSide.RS_Center,
                                        rigType = SERigEnum.eRigType.RT_SpineFK,
                                        rigControlIndex = 0,
                                        prefix = SERigNaming.sFKPrefix + self.Prefix + '_0', 
                                        translateTo = jnt1,
                                        rotateTo = jnt1,
                                        scale = rigScale*20,
                                        parent = upperBodyCtrl.ControlObject,
                                        lockChannels = ['t', 's', 'v'],
                                        cubeScaleX = 4.0,
                                        cubeScaleY = 35.0,
                                        cubeScaleZ = 35.0,
                                        transparency = 0.75,
                                        overrideControlColor = True, 
                                        controlColor = (0.4, 0.9, 0.9),
                                        fitToSurroundingMeshes = True,
                                        surroundingMeshes = surroundingMeshes,
                                        postFitScale = 1.1
                                        )
            SERigObjectTypeHelper.linkRigObjects(self.TopGrp, FKSpine0Ctrl.ControlGroup, 'FKSpine0Ctrl', 'ControlOwner')
            self.FKSpine0Ctrl = FKSpine0Ctrl

            cmds.orientConstraint(FKSpine0Ctrl.ControlObject, jnt1)

            # Create FK spine_1 control.
            FKSpine1Ctrl = None
            if createCircleFkControl:
                FKSpine1Ctrl = SERigControl.RigCircleControl(
                                        rigSide = SERigEnum.eRigSide.RS_Center,
                                        rigType = SERigEnum.eRigType.RT_SpineFK,
                                        rigControlIndex = 1,
                                        prefix = SERigNaming.sFKPrefix + self.Prefix + '_1', 
                                        translateTo = jnt2,
                                        rotateTo = jnt2,
                                        scale = rigScale*20,
                                        parent = FKSpine0Ctrl.ControlObject,
                                        lockChannels = ['t', 's', 'v'],
                                        overrideControlColor = True, 
                                        controlColor = (0.4, 0.9, 0.9),
                                        fitToSurroundingMeshes = True,
                                        surroundingMeshes = surroundingMeshes,
                                        postFitScale = 1.45
                                        )
            else:
                FKSpine1Ctrl = SERigControl.RigCubeControl(
                                        rigSide = SERigEnum.eRigSide.RS_Center,
                                        rigType = SERigEnum.eRigType.RT_SpineFK,
                                        rigControlIndex = 1,
                                        prefix = SERigNaming.sFKPrefix + self.Prefix + '_1', 
                                        translateTo = jnt2,
                                        rotateTo = jnt2,
                                        scale = rigScale*20,
                                        parent = FKSpine0Ctrl.ControlObject,
                                        lockChannels = ['t', 's', 'v'],
                                        cubeScaleX = 4.0,
                                        cubeScaleY = 30.0,
                                        cubeScaleZ = 30.0,
                                        transparency = 0.75,
                                        overrideControlColor = True, 
                                        controlColor = (0.4, 0.9, 0.9),
                                        fitToSurroundingMeshes = True,
                                        surroundingMeshes = surroundingMeshes,
                                        postFitScale = 1.1
                                        )
            SERigObjectTypeHelper.linkRigObjects(self.TopGrp, FKSpine1Ctrl.ControlGroup, 'FKSpine1Ctrl', 'ControlOwner')
            self.FKSpine1Ctrl = FKSpine1Ctrl

            cmds.orientConstraint(FKSpine1Ctrl.ControlObject, jnt2)

            # Attach ChestBegin controls to FK spine_1 control.
            cmds.parent(chestBeginCtrl.ControlGroup, FKSpine1Ctrl.ControlObject)
            cmds.parent(chestBeginLocalCtrl.ControlGroup, FKSpine1Ctrl.ControlObject)

            cmds.hide(jnt0)

        # Create controls visibility expression.
        mainControl = SERigNaming.sMainControlPrefix + SERigNaming.sControl
        controlsVisEN = SERigNaming.sExpressionPrefix + self.Prefix + 'ControlsVis'
        controlsVisES = ''
        tempExpressionTail = mainControl + '.' + SERigNaming.sBodyControlsVisibilityAttr + ';'

        if self.UpperBodyCtrl:
            controlsVisES += self.UpperBodyCtrl.ControlGroup + '.visibility = ' + tempExpressionTail

        if self.ChestBeginCtrl:
            controlsVisES += '\n'
            controlsVisES += self.ChestBeginCtrl.ControlGroup + '.visibility = ' + tempExpressionTail

        if self.PelvisCtrl:
            controlsVisES += '\n'
            controlsVisES += self.PelvisCtrl.ControlGroup + '.visibility = ' + tempExpressionTail

        if self.PelvisLocalCtrl:
            controlsVisES += '\n'
            controlsVisES += self.PelvisLocalCtrl.ControlGroup + '.visibility = ' + tempExpressionTail

        if self.FKSpine0Ctrl:
            controlsVisES += '\n'
            controlsVisES += self.FKSpine0Ctrl.ControlGroup + '.visibility = ' + tempExpressionTail

        if self.FKSpine1Ctrl:
            controlsVisES += '\n'
            controlsVisES += self.FKSpine1Ctrl.ControlGroup + '.visibility = ' + tempExpressionTail

        cmds.expression(n = controlsVisEN, s = controlsVisES, ae = 1)
Exemplo n.º 43
0
 def runSetup(self):
     if not self.ployName:
         rig.confirmDialog(t = u'警告',\
                             m = u'没有载入ploygon物体',\
                             ma = 'left',\
                             button = ('OK'),\
                             defaultButton = 'OK',\
                             cancelButton = 'OK',\
                             dismissString = 'OK')
     
     else:
         #=======================================================================
         # 生成毛囊
         #=======================================================================
         Mesh =  self.ployName 
         MeshShape = rig.listRelatives(Mesh,s = True,ni = True)[0]
         FOLS = []
         
         
         if not rig.objExists(Mesh+'_CLM'): #增加closestPointOnMesh节点
             CLM = rig.createNode('closestPointOnMesh',n = Mesh+'_CLM',ss = True)
             rig.connectAttr(MeshShape+'.outMesh',CLM+'.inMesh')
         else:
             CLM = Mesh+'_CLM'
             
         if not rig.objExists(Mesh+'_ScaleSM_GRP'): #增加毛囊缩放组节点
             self.FolScale = rig.group(empty = True,n = Mesh+'_ScaleSM_GRP')
             rig.addAttr(self.FolScale,at = 'float',ln = 'vis',dv = 0)#增加控制器隐藏属性
         else:
             self.FolScale = Mesh+'_ScaleSM_GRP'    
             
         self.allCons = rig.listConnections(self.locatorModel+'.sign',s = False,d = True) #列出所有定位控制器
         if self.allCons:
             for con in self.allCons:
                 if rig.objExists(con+'_FOL'):
                     warning(u'毛囊:'+con+u'_FOL已经存在')
                     continue
                 
                 pos = rig.xform(con,q = True,t = True,ws = True)
                 rig.setAttr(CLM+'.inPositionX',pos[0])
                 rig.setAttr(CLM+'.inPositionY',pos[1])
                 rig.setAttr(CLM+'.inPositionZ',pos[2])
                 U = rig.getAttr(CLM+'.result.parameterU')
                 V = rig.getAttr(CLM+'.result.parameterV') 
                 
                 FOLShape = rig.createNode('follicle',n = con.replace('_P','_'+self.key)+'_FOLShape',ss = True)
                 rig.hide(FOLShape)
                 rig.connectAttr(MeshShape+'.worldMesh[0]',FOLShape+'.inputMesh')
                 FOL = rig.listRelatives(FOLShape,p = True)[0]
                 
                                
                 rig.connectAttr(self.FolScale+'.scale',FOL+'.scale')
                 rig.connectAttr(MeshShape+'.worldMatrix[0]',FOL+'.inputWorldMatrix')
                 
                 newFol = rig.rename(FOL,con.replace('_P','_'+self.key)+'_FOL')
                 rig.connectAttr(FOLShape+'.outTranslate',newFol+'.translate')
                 rig.connectAttr(FOLShape+'.outRotate',newFol+'.rotate')
                 rig.setAttr(FOLShape+'.parameterU',U)
                 rig.setAttr(FOLShape+'.parameterV',V)
                 rig.setAttr(FOLShape+'.simulationMethod',0)
                 
                 FOLS.append(newFol)
                 
             self.origenCurve = rig.group(self.allCons,n = self.ployName+'_origen_ALL_Curves')
         else:
             warning(u'没有找定位控制器')
         #=======================================================================
         # 生成控制器和骨骼
         #=======================================================================
         if FOLS:
             jnts = []
             for fol in FOLS:
                 matFol = rig.getAttr(fol+'.worldMatrix')
                 rig.select(cl = True)
                 
                 JNT = rig.joint(n = fol.replace('_'+self.key+'_FOL','_JNT'+self.key))
                 rig.hide(JNT)
                 grpJnt = rig.group(JNT,n = JNT+'_GRP')
                 con = rig.duplicate(fol.replace('_'+self.key+'_FOL','_P'),n = fol.replace('_'+self.key+'_FOL','_'+self.key))[0]
                 rig.xform(con,t = (0,0,0),wd = True)
                 grpA = rig.group(con,n = con+'_GRP_A')
                 grpB = rig.group(grpA,n = con+'_GRP_B')
                 grpC = rig.group(grpB,n = con+'_GRP_C')
                 
                 rig.parent(grpJnt,con)
                 rig.xform(grpC,matrix = matFol)
                 rig.parent(grpC,fol)
                 
                 jnts.append(JNT)
                 
                 rig.connectAttr(self.FolScale+'.vis',grpA+'.visibility')
                 
             #复制出新的模型对其蒙皮  
             if not rig.objExists(self.ployName+'_SKIN'):
                 self.skinMesh = rig.duplicate(self.ployName,n = self.ployName+'_SKIN')[0]
                 skin = rig.skinCluster(jnts,self.skinMesh)[0]
                 
                 #连接矩阵
                 infs = rig.skinCluster(skin,q = True,inf = True)
                 for i,inf in enumerate(infs):
                     linkGrp = inf.replace('_JNT'+self.key,'_'+self.key+'_GRP_C')
                     rig.connectAttr(linkGrp+'.worldInverseMatrix[0]',skin+'.bindPreMatrix['+str(i)+']')
                     
                
             else:
                 warning(u'蒙皮物体已经存在')
                 
             self.FOLGRP = rig.group(FOLS,n = self.ployName+'_ALL_FOL_GRP')
             rig.blendShape(self.ployName,self.skinMesh,n = self.ployName+'_BS',foc = True,w = (0,1))#创建blendShape
Exemplo n.º 44
0
def unitConversion(plug,
                   conversionFactor=1.0,
                   conversionFactorSourcePlug='',
                   plugIsSource=True,
                   prefix=''):
    '''
	Create a unit conversion node for the given destination attribute
	@param plug: Plug to be connected to the unitConversion node
	@type plug: str
	@param conversionFactor: Conversion factor value
	@type conversionFactor: float
	@param conversionFactorSourcePlug: Plug to supply incoming connection for conversion factor
	@type conversionFactorSourcePlug: str
	@param plugIsSource: Specifies the plug as either the source or destination of the unitConversion
	@type plugIsSource: bool
	@param prefix: Name prefix for newly created nodes
	@type prefix: str
	'''
    # Check plug
    if not mc.objExists(plug):
        raise Exception('Plug ' + plug + ' does not exist!!')
    if not plug.count('.'):
        raise Exception('Object ' + plug +
                        ' is not a valid plug (node.attr)!!')

    # Check conversionFactorSourcePlug
    if conversionFactorSourcePlug:
        if not mc.objExists(conversionFactorSourcePlug):
            raise Exception('Conversion factor source plug ' +
                            conversionFactorSourcePlug + ' does not exist!')

    # Check prefix
    if not prefix:
        prefix = glTools.utils.stringUtils.stripSuffix(control.split('.')[0])

    # Get existing plug connections
    conns = mc.listConnections(plug,
                               s=not plugIsSource,
                               d=plugIsSource,
                               p=True)

    # Create unitConversion node
    unitConversion = mc.createNode('unitConversion',
                                   n=prefix + '_unitConversion')
    mc.setAttr(unitConversion + '.conversionFactor', conversionFactor)

    # Connect conversion factor
    if conversionFactorSourcePlug:
        mc.connectAttr(conversionFactorSourcePlug,
                       unitConversion + '.conversionFactor',
                       f=True)

    # Connect plug
    if plugIsSource:
        mc.connectAttr(plug, unitConversion + '.input', f=True)
    else:
        if conns: mc.connectAttr(conns[0], unitConversion + '.input', f=True)

    # Connect to destination plugs
    if plugIsSource:
        if conns:
            for conn in conns:
                mc.connectAttr(unitConversion + '.output', conn, f=True)
    else:
        mc.connectAttr(unitConversion + '.output', plug, f=True)

    # Return result
    return unitConversion
Exemplo n.º 45
0
    def setUp(self):
        cmds.file(new=True, force=True)

        node_name = cmds.createNode("transform")
        self.meta_node = MetaNode(node_name)
Exemplo n.º 46
0
def cachedObjToTransform(*args):
    '''{'ath':'Animation/Transform/cachedObjToTransform( )',
'ath':'Dynamics/RBD',
'icon':':/transform.svg',
'usage':"""
#将缓存物体bake成关键帧物体。
$fun(  )""",
}
'''
    if len(args):
        cachedObj = qm.checkArg(args[0], nodeType='mesh', tryToShape=True)
    else:
        cachedObj = qm.checkArg(nodeType='mesh', tryToShape=True)

    cmds.constructionHistory(toggle=False)
    #cachedObj = cmds.ls(sl=True,l=True)[0]
    #sepratate cachedObj
    minTime = int(cmds.playbackOptions(q=True, min=True))
    cmds.currentTime(minTime)
    temp = cmds.polySeparate(cachedObj, ch=True)[0]
    rbdGrp = cmds.listRelatives(temp, p=True, f=True)[0]
    childGrp = cmds.duplicate(rbdGrp, rr=True)[0]
    parentList = cmds.listRelatives(rbdGrp, type='transform', f=True)
    childList = cmds.listRelatives(childGrp, type='transform', f=True)
    cmds.delete(cmds.listRelatives(childGrp, f=True), ch=True)

    forRemove = []
    for obj in parentList:
        meshNode = cmds.listRelatives(obj, type='mesh', f=True)
        if meshNode == [] or cmds.getAttr(meshNode[0] +
                                          '.intermediateObject') == 1:
            forRemove.append(obj)
    if obj in forRemove:
        parentList.remove(obj)

    forRemove = []
    for obj in childList:
        meshNode = cmds.listRelatives(obj, type='mesh', f=True)
        if meshNode == [] or cmds.getAttr(meshNode[0] +
                                          '.intermediateObject') == 1:
            forRemove.append(obj)
    if obj in forRemove:
        childList.remove(obj)
    cmds.delete(forRemove)

    unfreeze(childList)

    folGrp = cmds.group(em=True, n=rbdGrp + '_FoGrp')

    for papa in parentList:
        index = parentList.index(papa)
        child = childList[index]
        meshShape = cmds.listRelatives(papa, type='mesh', f=True)[0]

        faceCount = cmds.polyEvaluate(papa, f=True) - 1
        if faceCount > 10:
            faceCount = 10

        newFace = '%s.f[0:%s]' % (papa, faceCount)
        cmds.select(newFace)
        mel.eval('polySplitTextureUV')

        mel.eval('PolySelectConvert 4')
        map = cmds.ls(sl=True)

        cmds.polyNormalizeUV(map, normalizeType=0, preserveAspectRatio=False)

        cmds.polyEditUV(map, pu=.5, pv=.5, su=2, sv=2)

        #create follicle and set attribute
        folShape = cmds.createNode("follicle")

        folTransform = cmds.listRelatives(folShape, p=True, f=True)[0]
        cmds.setAttr(folTransform + '.intermediateObject', 1)

        cmds.setAttr(folShape + '.parameterU', .5, l=True)
        cmds.setAttr(folShape + '.parameterV', .5, l=True)
        cmds.setAttr(folShape + ".simulationMethod", 0)
        cmds.setAttr(folShape + ".collide", 0)
        cmds.setAttr(folShape + ".degree", 1)
        cmds.setAttr(folShape + ".sampleDensity", 0)

        #connection follicles
        cmds.connectAttr(meshShape + '.worldMatrix[0]',
                         folShape + '.inputWorldMatrix',
                         f=True)
        cmds.connectAttr(meshShape + '.outMesh',
                         folShape + '.inputMesh',
                         f=True)
        cmds.connectAttr(folShape + '.outRotate',
                         folTransform + '.rotate',
                         f=True)
        cmds.connectAttr(folShape + '.outTranslate',
                         folTransform + '.translate',
                         f=True)

        parentConNode = cmds.parentConstraint(folTransform, child, mo=True)[0]

        cmds.parent(folTransform, folGrp)

    minTime = int(cmds.playbackOptions(q=True, min=True))
    maxTime = int(cmds.playbackOptions(q=True, max=True))
    cmds.bakeResults(childList,simulation=True, t=(minTime,maxTime),sampleBy=1,\
                    disableImplicitControl=True, preserveOutsideKeys=True, sparseAnimCurveBake=False, removeBakedAttributeFromLayer=False, \
                    bakeOnOverrideLayer=False,at=['tx','ty','tz','rx','ry','rz'])

    cmds.delete([folGrp, rbdGrp])
    cmds.delete(cmds.listRelatives(childGrp, f=True), ch=True)

    cmds.constructionHistory(toggle=True)
Exemplo n.º 47
0
    def rigModule(self, *args):
        Base.StartClass.rigModule(self)
        # verify if the guide exists:
        if cmds.objExists(self.moduleGrp):
            try:
                hideJoints = cmds.checkBox('hideJointsCB',
                                           query=True,
                                           value=True)
            except:
                hideJoints = 1
            # declare lists to store names and attributes:
            self.mainCtrlList, self.wheelCtrlList, self.steeringGrpList, self.ctrlHookGrpList = [], [], [], []
            # start as no having mirror:
            sideList = [""]
            # analisys the mirror module:
            self.mirrorAxis = cmds.getAttr(self.moduleGrp + ".mirrorAxis")
            if self.mirrorAxis != 'off':
                # get rigs names:
                self.mirrorNames = cmds.getAttr(self.moduleGrp + ".mirrorName")
                # get first and last letters to use as side initials (prefix):
                sideList = [
                    self.mirrorNames[0] + '_',
                    self.mirrorNames[len(self.mirrorNames) - 1] + '_'
                ]
                for s, side in enumerate(sideList):
                    duplicated = cmds.duplicate(
                        self.moduleGrp,
                        name=side + self.userGuideName + '_Guide_Base')[0]
                    allGuideList = cmds.listRelatives(duplicated,
                                                      allDescendents=True)
                    for item in allGuideList:
                        cmds.rename(item,
                                    side + self.userGuideName + "_" + item)
                    self.mirrorGrp = cmds.group(name="Guide_Base_Grp",
                                                empty=True)
                    cmds.parent(side + self.userGuideName + '_Guide_Base',
                                self.mirrorGrp,
                                absolute=True)
                    # re-rename grp:
                    cmds.rename(
                        self.mirrorGrp,
                        side + self.userGuideName + '_' + self.mirrorGrp)
                    # do a group mirror with negative scaling:
                    if s == 1:
                        if cmds.getAttr(self.moduleGrp + ".flip") == 0:
                            for axis in self.mirrorAxis:
                                gotValue = cmds.getAttr(
                                    side + self.userGuideName +
                                    "_Guide_Base.translate" + axis)
                                flipedValue = gotValue * (-2)
                                cmds.setAttr(
                                    side + self.userGuideName + '_' +
                                    self.mirrorGrp + '.translate' + axis,
                                    flipedValue)
                        else:
                            for axis in self.mirrorAxis:
                                cmds.setAttr(
                                    side + self.userGuideName + '_' +
                                    self.mirrorGrp + '.scale' + axis, -1)
                # joint labelling:
                jointLabelAdd = 1
            else:  # if not mirror:
                duplicated = cmds.duplicate(self.moduleGrp,
                                            name=self.userGuideName +
                                            '_Guide_Base')[0]
                allGuideList = cmds.listRelatives(duplicated,
                                                  allDescendents=True)
                for item in allGuideList:
                    cmds.rename(item, self.userGuideName + "_" + item)
                self.mirrorGrp = cmds.group(self.userGuideName + '_Guide_Base',
                                            name="Guide_Base_Grp",
                                            relative=True)
                #for Maya2012: self.userGuideName+'_'+self.moduleGrp+"_Grp"
                # re-rename grp:
                cmds.rename(self.mirrorGrp,
                            self.userGuideName + '_' + self.mirrorGrp)
                # joint labelling:
                jointLabelAdd = 0
            # store the number of this guide by module type
            dpAR_count = utils.findModuleLastNumber(CLASS_NAME,
                                                    "dpAR_type") + 1
            # run for all sides
            for s, side in enumerate(sideList):
                # declare guides:
                self.base = side + self.userGuideName + '_Guide_Base'
                self.cvCenterLoc = side + self.userGuideName + "_Guide_CenterLoc"
                self.cvFrontLoc = side + self.userGuideName + "_Guide_FrontLoc"
                self.cvInsideLoc = side + self.userGuideName + "_Guide_InsideLoc"
                self.cvOutsideLoc = side + self.userGuideName + "_Guide_OutsideLoc"

                # create a joint:
                cmds.select(clear=True)
                # center joint:
                self.centerJoint = cmds.joint(
                    name=side + self.userGuideName + "_" +
                    self.langDic[self.langName]['m156_wheel'] + "_Jnt",
                    scaleCompensate=False)
                cmds.addAttr(self.centerJoint,
                             longName='dpAR_joint',
                             attributeType='float',
                             keyable=False)
                # joint labelling:
                utils.setJointLabel(
                    self.centerJoint, s + jointLabelAdd, 18,
                    self.userGuideName + "_" +
                    self.langDic[self.langName]['m156_wheel'])
                # create end joint:
                self.endJoint = cmds.joint(
                    name=side + self.userGuideName + "_" +
                    self.langDic[self.langName]['m156_wheel'] + "_JEnd")
                # main joint:
                cmds.select(clear=True)
                self.mainJoint = cmds.joint(
                    name=side + self.userGuideName + "_" +
                    self.langDic[self.langName]['c058_main'] + "_Jnt",
                    scaleCompensate=False)
                cmds.addAttr(self.mainJoint,
                             longName='dpAR_joint',
                             attributeType='float',
                             keyable=False)
                # joint labelling:
                utils.setJointLabel(
                    self.mainJoint, s + jointLabelAdd, 18, self.userGuideName +
                    "_" + self.langDic[self.langName]['c058_main'])
                # create end joint:
                self.mainEndJoint = cmds.joint(
                    name=side + self.userGuideName + "_" +
                    self.langDic[self.langName]['c058_main'] + "_JEnd")

                # create controls:
                self.wheelCtrl = self.ctrls.cvControl(
                    "id_060_WheelCenter",
                    side + self.userGuideName + "_" +
                    self.langDic[self.langName]['m156_wheel'] + "_Ctrl",
                    r=self.ctrlRadius,
                    d=self.curveDegree)
                self.mainCtrl = self.ctrls.cvControl(
                    "id_061_WheelMain",
                    side + self.userGuideName + "_" +
                    self.langDic[self.langName]['c058_main'] + "_Ctrl",
                    r=self.ctrlRadius * 0.4,
                    d=self.curveDegree)
                self.insideCtrl = self.ctrls.cvControl(
                    "id_062_WheelPivot",
                    side + self.userGuideName + "_" +
                    self.langDic[self.langName]['c011_RevFoot_B'].capitalize()
                    + "_Ctrl",
                    r=self.ctrlRadius * 0.2,
                    d=self.curveDegree,
                    rot=(0, 90, 0))
                self.outsideCtrl = self.ctrls.cvControl(
                    "id_062_WheelPivot",
                    side + self.userGuideName + "_" +
                    self.langDic[self.langName]['c010_RevFoot_A'].capitalize()
                    + "_Ctrl",
                    r=self.ctrlRadius * 0.2,
                    d=self.curveDegree,
                    rot=(0, 90, 0))
                self.mainCtrlList.append(self.mainCtrl)
                self.wheelCtrlList.append(self.wheelCtrl)

                # origined from attributes:
                utils.originedFrom(objName=self.mainCtrl,
                                   attrString=self.base + ";" +
                                   self.cvCenterLoc + ";" + self.cvFrontLoc +
                                   ";" + self.cvInsideLoc + ";" +
                                   self.cvOutsideLoc)
                #utils.originedFrom(objName=self.wheelCtrl, attrString=self.cvCenterLoc)

                # prepare group to receive steering wheel connection:
                self.toSteeringGrp = cmds.group(
                    self.insideCtrl,
                    name=side + self.userGuideName + "_" +
                    self.langDic[self.langName]['c070_steering'].capitalize() +
                    "_Grp")
                cmds.addAttr(
                    self.toSteeringGrp,
                    longName=self.langDic[self.langName]['c070_steering'],
                    attributeType='bool',
                    keyable=True)
                cmds.addAttr(
                    self.toSteeringGrp,
                    longName=self.langDic[self.langName]['c070_steering'] +
                    self.langDic[self.langName]['m151_invert'],
                    attributeType='bool',
                    keyable=True)
                cmds.setAttr(
                    self.toSteeringGrp + "." +
                    self.langDic[self.langName]['c070_steering'], 1)
                self.steeringGrpList.append(self.toSteeringGrp)

                # position and orientation of joint and control:
                cmds.delete(
                    cmds.parentConstraint(self.cvCenterLoc,
                                          self.centerJoint,
                                          maintainOffset=False))
                cmds.delete(
                    cmds.parentConstraint(self.cvFrontLoc,
                                          self.endJoint,
                                          maintainOffset=False))
                cmds.delete(
                    cmds.parentConstraint(self.cvCenterLoc,
                                          self.wheelCtrl,
                                          maintainOffset=False))
                cmds.delete(
                    cmds.parentConstraint(self.cvCenterLoc,
                                          self.mainCtrl,
                                          maintainOffset=False))
                cmds.parentConstraint(self.mainCtrl,
                                      self.mainJoint,
                                      maintainOffset=False)
                cmds.delete(
                    cmds.parentConstraint(self.cvFrontLoc,
                                          self.mainEndJoint,
                                          maintainOffset=False))
                if s == 1 and cmds.getAttr(self.moduleGrp + ".flip") == 1:
                    cmds.move(self.ctrlRadius,
                              self.mainCtrl,
                              moveY=True,
                              relative=True,
                              objectSpace=True,
                              worldSpaceDistance=True)
                else:
                    cmds.move(-self.ctrlRadius,
                              self.mainCtrl,
                              moveY=True,
                              relative=True,
                              objectSpace=True,
                              worldSpaceDistance=True)
                cmds.delete(
                    cmds.parentConstraint(self.cvInsideLoc,
                                          self.toSteeringGrp,
                                          maintainOffset=False))
                cmds.delete(
                    cmds.parentConstraint(self.cvOutsideLoc,
                                          self.outsideCtrl,
                                          maintainOffset=False))

                # zeroOut controls:
                zeroGrpList = utils.zeroOut([
                    self.mainCtrl, self.wheelCtrl, self.toSteeringGrp,
                    self.outsideCtrl
                ])
                wheelAutoGrp = utils.zeroOut([self.wheelCtrl])
                wheelAutoGrp = cmds.rename(
                    wheelAutoGrp, side + self.userGuideName + "_" +
                    self.langDic[self.langName]['m156_wheel'] + "_Auto_Grp")

                # fixing flip mirror:
                if s == 1:
                    if cmds.getAttr(self.moduleGrp + ".flip") == 1:
                        for zeroOutGrp in zeroGrpList:
                            cmds.setAttr(zeroOutGrp + ".scaleX", -1)
                            cmds.setAttr(zeroOutGrp + ".scaleY", -1)
                            cmds.setAttr(zeroOutGrp + ".scaleZ", -1)

                cmds.addAttr(self.wheelCtrl,
                             longName='scaleCompensate',
                             attributeType="bool",
                             keyable=False)
                cmds.setAttr(self.wheelCtrl + ".scaleCompensate",
                             1,
                             channelBox=True)
                cmds.connectAttr(self.wheelCtrl + ".scaleCompensate",
                                 self.centerJoint + ".segmentScaleCompensate",
                                 force=True)
                cmds.addAttr(self.mainCtrl,
                             longName='scaleCompensate',
                             attributeType="bool",
                             keyable=False)
                cmds.setAttr(self.mainCtrl + ".scaleCompensate",
                             1,
                             channelBox=True)
                cmds.connectAttr(self.mainCtrl + ".scaleCompensate",
                                 self.mainJoint + ".segmentScaleCompensate",
                                 force=True)
                # hide visibility attributes:
                self.ctrls.setLockHide(
                    [self.mainCtrl, self.insideCtrl, self.outsideCtrl], ['v'])
                self.ctrls.setLockHide(
                    [self.wheelCtrl],
                    ['tx', 'ty', 'tz', 'rx', 'ry', 'sx', 'sy', 'sz', 'v'])

                # grouping:
                cmds.parentConstraint(self.wheelCtrl,
                                      self.centerJoint,
                                      maintainOffset=False,
                                      name=self.centerJoint +
                                      "_ParentConstraint")
                cmds.scaleConstraint(self.wheelCtrl,
                                     self.centerJoint,
                                     maintainOffset=True,
                                     name=self.centerJoint +
                                     "_ScaleConstraint")
                cmds.parent(zeroGrpList[1], self.mainCtrl, absolute=True)
                cmds.parent(zeroGrpList[0], self.outsideCtrl, absolute=True)
                cmds.parent(zeroGrpList[3], self.insideCtrl, absolute=True)

                # add attributes:
                cmds.addAttr(
                    self.wheelCtrl,
                    longName=self.langDic[self.langName]['c047_autoRotate'],
                    attributeType="bool",
                    defaultValue=1,
                    keyable=True)
                cmds.addAttr(
                    self.wheelCtrl,
                    longName=self.langDic[self.langName]['c068_startFrame'],
                    attributeType="long",
                    defaultValue=1,
                    keyable=False)
                cmds.addAttr(
                    self.wheelCtrl,
                    longName=self.langDic[self.langName]['c067_radius'],
                    attributeType="float",
                    min=0.01,
                    defaultValue=self.ctrlRadius,
                    keyable=True)
                cmds.addAttr(
                    self.wheelCtrl,
                    longName=self.langDic[self.langName]['c069_radiusScale'],
                    attributeType="float",
                    defaultValue=1,
                    keyable=False)
                cmds.addAttr(
                    self.wheelCtrl,
                    longName=self.langDic[self.langName]['c021_showControls'],
                    attributeType="long",
                    min=0,
                    max=1,
                    defaultValue=0,
                    keyable=True)
                cmds.addAttr(
                    self.wheelCtrl,
                    longName=self.langDic[self.langName]['c070_steering'],
                    attributeType="bool",
                    defaultValue=0,
                    keyable=True)
                cmds.addAttr(
                    self.wheelCtrl,
                    longName=self.langDic[self.langName]['i037_to'] +
                    self.langDic[self.langName]['c070_steering'].capitalize(),
                    attributeType="float",
                    defaultValue=0,
                    keyable=False)
                cmds.addAttr(
                    self.wheelCtrl,
                    longName=self.langDic[self.langName]['c070_steering'] +
                    self.langDic[self.langName]['c053_invert'].capitalize(),
                    attributeType="long",
                    min=0,
                    max=1,
                    defaultValue=1,
                    keyable=False)
                cmds.addAttr(
                    self.wheelCtrl,
                    longName=self.langDic[self.langName]['c093_tryKeepUndo'],
                    attributeType="long",
                    min=0,
                    max=1,
                    defaultValue=1,
                    keyable=False)

                # get stored values by user:
                startFrameValue = cmds.getAttr(self.moduleGrp + ".startFrame")
                steeringValue = cmds.getAttr(self.moduleGrp + ".steering")
                showControlsValue = cmds.getAttr(self.moduleGrp +
                                                 ".showControls")
                cmds.setAttr(self.wheelCtrl + "." +
                             self.langDic[self.langName]['c068_startFrame'],
                             startFrameValue,
                             channelBox=True)
                cmds.setAttr(self.wheelCtrl + "." +
                             self.langDic[self.langName]['c070_steering'],
                             steeringValue,
                             channelBox=True)
                cmds.setAttr(self.wheelCtrl + "." +
                             self.langDic[self.langName]['c021_showControls'],
                             showControlsValue,
                             channelBox=True)
                cmds.setAttr(
                    self.wheelCtrl + "." +
                    self.langDic[self.langName]['c070_steering'] +
                    self.langDic[self.langName]['c053_invert'].capitalize(),
                    1,
                    channelBox=True)
                cmds.setAttr(self.wheelCtrl + "." +
                             self.langDic[self.langName]['c093_tryKeepUndo'],
                             1,
                             channelBox=True)
                if s == 1:
                    if cmds.getAttr(self.moduleGrp + ".flip") == 1:
                        cmds.setAttr(
                            self.wheelCtrl + "." +
                            self.langDic[self.langName]['c070_steering'] +
                            self.langDic[
                                self.langName]['c053_invert'].capitalize(), 0)

                # automatic rotation wheel setup:
                receptSteeringMD = cmds.createNode(
                    'multiplyDivide',
                    name=side + self.userGuideName + "_" +
                    self.langDic[self.langName]['c070_steering'] + "_MD")
                inverseSteeringMD = cmds.createNode(
                    'multiplyDivide',
                    name=side + self.userGuideName + "_" +
                    self.langDic[self.langName]['c070_steering'] + "_Inv_MD")
                steeringInvCnd = cmds.createNode(
                    'condition',
                    name=side + self.userGuideName + "_" +
                    self.langDic[self.langName]['c070_steering'] + "_Inv_Cnd")
                cmds.setAttr(steeringInvCnd + ".colorIfTrueR", 1)
                cmds.setAttr(steeringInvCnd + ".colorIfFalseR", -1)
                cmds.connectAttr(
                    self.wheelCtrl + "." +
                    self.langDic[self.langName]['i037_to'] +
                    self.langDic[self.langName]['c070_steering'].capitalize(),
                    receptSteeringMD + ".input1X",
                    force=True)
                cmds.connectAttr(self.wheelCtrl + "." +
                                 self.langDic[self.langName]['c070_steering'],
                                 receptSteeringMD + ".input2X",
                                 force=True)
                cmds.connectAttr(receptSteeringMD + ".outputX",
                                 inverseSteeringMD + ".input1X",
                                 force=True)
                cmds.connectAttr(steeringInvCnd + ".outColorR",
                                 inverseSteeringMD + ".input2X",
                                 force=True)
                cmds.connectAttr(
                    self.wheelCtrl + "." +
                    self.langDic[self.langName]['c070_steering'] +
                    self.langDic[self.langName]['c053_invert'].capitalize(),
                    steeringInvCnd + ".firstTerm",
                    force=True)
                cmds.connectAttr(inverseSteeringMD + ".outputX",
                                 self.toSteeringGrp + ".rotateY",
                                 force=True)
                # create locators (frontLoc to get direction and oldLoc to store wheel old position):
                self.frontLoc = cmds.spaceLocator(
                    name=side + self.userGuideName + "_" +
                    self.langDic[self.langName]['m156_wheel'] +
                    "_Front_Loc")[0]
                self.oldLoc = cmds.spaceLocator(
                    name=side + self.userGuideName + "_" +
                    self.langDic[self.langName]['m156_wheel'] + "_Old_Loc")[0]
                cmds.delete(
                    cmds.parentConstraint(self.cvFrontLoc,
                                          self.frontLoc,
                                          maintainOffset=False))
                cmds.parent(self.frontLoc, self.mainCtrl)
                cmds.delete(
                    cmds.parentConstraint(self.cvCenterLoc,
                                          self.oldLoc,
                                          maintainOffset=False))
                cmds.setAttr(self.frontLoc + ".visibility", 0, lock=True)
                cmds.setAttr(self.oldLoc + ".visibility", 0, lock=True)
                # this wheel auto group locator could be replaced by a decomposeMatrix to get the translation in world space of the Wheel_Auto_Ctrl_Grp instead:
                self.wheelAutoGrpLoc = cmds.spaceLocator(
                    name=side + self.userGuideName + "_" +
                    self.langDic[self.langName]['m156_wheel'] + "_Auto_Loc")[0]
                cmds.pointConstraint(wheelAutoGrp,
                                     self.wheelAutoGrpLoc,
                                     maintainOffset=False,
                                     name=self.wheelAutoGrpLoc +
                                     "_PointConstraint")
                cmds.setAttr(self.wheelAutoGrpLoc + ".visibility",
                             0,
                             lock=True)
                expString = "if ("+self.wheelCtrl+"."+self.langDic[self.langName]['c047_autoRotate']+" == 1) {"+\
                        "\nif ("+self.wheelCtrl+"."+self.langDic[self.langName]['c093_tryKeepUndo']+" == 1) { undoInfo -stateWithoutFlush 0; };"+\
                        "\nfloat $radius = "+self.wheelCtrl+"."+self.langDic[self.langName]['c067_radius']+" * "+self.wheelCtrl+"."+self.langDic[self.langName]['c069_radiusScale']+\
                        ";\nvector $moveVectorOld = `xform -q -ws -t \""+self.oldLoc+\
                        "\"`;\nvector $moveVector = << "+self.wheelAutoGrpLoc+".translateX, "+self.wheelAutoGrpLoc+".translateY, "+self.wheelAutoGrpLoc+".translateZ >>;"+\
                        "\nvector $dirVector = `xform -q -ws -t \""+self.frontLoc+\
                        "\"`;\nvector $wheelVector = ($dirVector - $moveVector);"+\
                        "\nvector $motionVector = ($moveVector - $moveVectorOld);"+\
                        "\nfloat $distance = mag($motionVector);"+\
                        "\n$dot = dotProduct($motionVector, $wheelVector, 1);\n"+\
                        wheelAutoGrp+".rotateZ = "+wheelAutoGrp+".rotateZ - 360 / (6.283*$radius) * ($dot*$distance);"+\
                        "\nxform -t ($moveVector.x) ($moveVector.y) ($moveVector.z) "+self.oldLoc+\
                        ";\nif (frame == "+self.wheelCtrl+"."+self.langDic[self.langName]['c068_startFrame']+") { "+wheelAutoGrp+".rotateZ = 0; };"+\
                        "\nif ("+self.wheelCtrl+"."+self.langDic[self.langName]['c093_tryKeepUndo']+" == 1) { undoInfo -stateWithoutFlush 1; };};"
                # expression:
                cmds.expression(name=side + self.userGuideName + "_" +
                                self.langDic[self.langName]['m156_wheel'] +
                                "_Exp",
                                object=self.frontLoc,
                                string=expString)
                self.ctrls.setLockHide([self.frontLoc, self.wheelAutoGrpLoc], [
                    'tx', 'ty', 'tz', 'rx', 'ry', 'rz', 'sx', 'sy', 'sz', 'v'
                ])

                # deformers:
                self.loadedGeo = cmds.getAttr(self.moduleGrp + ".geo")

                # geometry holder:
                self.geoHolder = cmds.polyCube(
                    name=side + self.userGuideName + "_" +
                    self.langDic[self.langName]['c046_holder'] + "_Geo",
                    constructionHistory=False)[0]
                cmds.delete(
                    cmds.parentConstraint(self.cvCenterLoc,
                                          self.geoHolder,
                                          maintainOffset=False))
                cmds.setAttr(self.geoHolder + ".visibility", 0, lock=True)

                # skinning:
                cmds.skinCluster(self.centerJoint,
                                 self.geoHolder,
                                 toSelectedBones=True,
                                 dropoffRate=4.0,
                                 maximumInfluences=3,
                                 skinMethod=0,
                                 normalizeWeights=1,
                                 removeUnusedInfluence=False,
                                 name=side + self.userGuideName + "_" +
                                 self.langDic[self.langName]['c046_holder'] +
                                 "_SC")
                if self.loadedGeo:
                    if cmds.objExists(self.loadedGeo):
                        baseName = utils.extractSuffix(self.loadedGeo)
                        skinClusterName = baseName + "_SC"
                        if "|" in skinClusterName:
                            skinClusterName = skinClusterName[skinClusterName.
                                                              rfind("|") + 1:]
                        try:
                            cmds.skinCluster(self.centerJoint,
                                             self.loadedGeo,
                                             toSelectedBones=True,
                                             dropoffRate=4.0,
                                             maximumInfluences=3,
                                             skinMethod=0,
                                             normalizeWeights=1,
                                             removeUnusedInfluence=False,
                                             name=skinClusterName)
                        except:
                            childList = cmds.listRelatives(self.loadedGeo,
                                                           children=True,
                                                           allDescendents=True)
                            if childList:
                                for item in childList:
                                    itemType = cmds.objectType(item)
                                    if itemType == "mesh" or itemType == "nurbsSurface":
                                        try:
                                            skinClusterName = utils.extractSuffix(
                                                item) + "_SC"
                                            cmds.skinCluster(
                                                self.centerJoint,
                                                item,
                                                toSelectedBones=True,
                                                dropoffRate=4.0,
                                                maximumInfluences=3,
                                                skinMethod=0,
                                                normalizeWeights=1,
                                                removeUnusedInfluence=False,
                                                name=skinClusterName)
                                        except:
                                            pass

                # lattice:
                latticeList = cmds.lattice(self.geoHolder,
                                           divisions=(6, 6, 6),
                                           outsideLattice=2,
                                           outsideFalloffDistance=1,
                                           position=(0, 0, 0),
                                           scale=(self.ctrlRadius * 2,
                                                  self.ctrlRadius * 2,
                                                  self.ctrlRadius * 2),
                                           name=side + self.userGuideName +
                                           "_FFD")  #[deformer, lattice, base]
                cmds.scale(self.ctrlRadius * 2, self.ctrlRadius * 2,
                           self.ctrlRadius * 2, latticeList[2])
                # clusters:
                upperClusterList = cmds.cluster(
                    latticeList[1] + ".pt[0:5][4:5][0:5]",
                    relative=True,
                    name=side + self.userGuideName + "_" +
                    self.langDic[self.langName]['c044_upper'] +
                    "_Cls")  #[deform, handle]
                middleClusterList = cmds.cluster(
                    latticeList[1] + ".pt[0:5][2:3][0:5]",
                    relative=True,
                    name=side + self.userGuideName + "_" +
                    self.langDic[self.langName]['m033_middle'] +
                    "_Cls")  #[deform, handle]
                lowerClusterList = cmds.cluster(
                    latticeList[1] + ".pt[0:5][0:1][0:5]",
                    relative=True,
                    name=side + self.userGuideName + "_" +
                    self.langDic[self.langName]['c045_lower'] +
                    "_Cls")  #[deform, handle]
                clusterGrpList = utils.zeroOut([
                    upperClusterList[1], middleClusterList[1],
                    lowerClusterList[1]
                ])
                clustersGrp = cmds.group(clusterGrpList,
                                         name=side + self.userGuideName +
                                         "_Clusters_Grp")

                # deform controls:
                upperDefCtrl = self.ctrls.cvControl(
                    "id_063_WheelDeform",
                    side + self.userGuideName + "_" +
                    self.langDic[self.langName]['c044_upper'] + "_Ctrl",
                    r=self.ctrlRadius * 0.5,
                    d=self.curveDegree)
                middleDefCtrl = self.ctrls.cvControl(
                    "id_064_WheelMiddle",
                    side + self.userGuideName + "_" +
                    self.langDic[self.langName]['m033_middle'] + "_Ctrl",
                    r=self.ctrlRadius * 0.5,
                    d=self.curveDegree)
                lowerDefCtrl = self.ctrls.cvControl(
                    "id_063_WheelDeform",
                    side + self.userGuideName + "_" +
                    self.langDic[self.langName]['c045_lower'] + "_Ctrl",
                    r=self.ctrlRadius * 0.5,
                    d=self.curveDegree,
                    rot=(0, 0, 180))
                defCtrlGrpList = utils.zeroOut(
                    [upperDefCtrl, middleDefCtrl, lowerDefCtrl])
                defCtrlGrp = cmds.group(defCtrlGrpList,
                                        name=side + self.userGuideName +
                                        "_Ctrl_Grp")

                # positions:
                cmds.delete(
                    cmds.parentConstraint(upperClusterList[1],
                                          defCtrlGrpList[0],
                                          maintainOffset=False))
                cmds.delete(
                    cmds.parentConstraint(middleClusterList[1],
                                          defCtrlGrpList[1],
                                          maintainOffset=False))
                cmds.delete(
                    cmds.parentConstraint(lowerClusterList[1],
                                          defCtrlGrpList[2],
                                          maintainOffset=False))
                cmds.delete(
                    cmds.parentConstraint(self.cvCenterLoc,
                                          latticeList[1],
                                          maintainOffset=False))
                cmds.delete(
                    cmds.parentConstraint(self.cvCenterLoc,
                                          latticeList[2],
                                          maintainOffset=False))
                cmds.delete(
                    cmds.parentConstraint(self.cvCenterLoc,
                                          clustersGrp,
                                          maintainOffset=False))
                cmds.delete(
                    cmds.parentConstraint(self.cvCenterLoc,
                                          defCtrlGrp,
                                          maintainOffset=False))
                outsideDist = cmds.getAttr(self.cvOutsideLoc + ".tz")
                if s == 1:
                    if cmds.getAttr(self.moduleGrp + ".flip") == 1:
                        outsideDist = -outsideDist
                cmds.move(outsideDist,
                          defCtrlGrp,
                          moveZ=True,
                          relative=True,
                          objectSpace=True,
                          worldSpaceDistance=True)
                self.ctrls.directConnect(upperDefCtrl, upperClusterList[1])
                self.ctrls.directConnect(middleDefCtrl, middleClusterList[1])
                self.ctrls.directConnect(lowerDefCtrl, lowerClusterList[1])
                # grouping deformers:
                if self.loadedGeo:
                    if cmds.objExists(self.loadedGeo):
                        cmds.lattice(latticeList[0],
                                     edit=True,
                                     geometry=self.loadedGeo)
                defGrp = cmds.group(latticeList[1],
                                    latticeList[2],
                                    clustersGrp,
                                    name=side + self.userGuideName +
                                    "_Deform_Grp")
                cmds.parentConstraint(self.mainCtrl,
                                      defGrp,
                                      maintainOffset=True,
                                      name=defGrp + "_ParentConstraint")
                cmds.scaleConstraint(self.mainCtrl,
                                     defGrp,
                                     maintainOffset=True,
                                     name=defGrp + "_ScaleConstraint")
                cmds.parent(defCtrlGrp, self.mainCtrl)
                cmds.connectAttr(
                    self.wheelCtrl + "." +
                    self.langDic[self.langName]['c021_showControls'],
                    defCtrlGrp + ".visibility",
                    force=True)

                # create a masterModuleGrp to be checked if this rig exists:
                self.toCtrlHookGrp = cmds.group(
                    zeroGrpList[2],
                    name=side + self.userGuideName + "_Control_Grp")
                self.toScalableHookGrp = cmds.group(
                    self.centerJoint,
                    self.mainJoint,
                    defGrp,
                    name=side + self.userGuideName + "_Joint_Grp")
                self.toStaticHookGrp = cmds.group(self.toCtrlHookGrp,
                                                  self.toScalableHookGrp,
                                                  self.oldLoc,
                                                  self.wheelAutoGrpLoc,
                                                  self.geoHolder,
                                                  name=side +
                                                  self.userGuideName + "_Grp")
                # add hook attributes to be read when rigging integrated modules:
                utils.addHook(objName=self.toCtrlHookGrp, hookType='ctrlHook')
                utils.addHook(objName=self.toScalableHookGrp,
                              hookType='scalableHook')
                utils.addHook(objName=self.toStaticHookGrp,
                              hookType='staticHook')
                cmds.addAttr(self.toStaticHookGrp,
                             longName="dpAR_name",
                             dataType="string")
                cmds.addAttr(self.toStaticHookGrp,
                             longName="dpAR_type",
                             dataType="string")
                cmds.setAttr(self.toStaticHookGrp + ".dpAR_name",
                             self.userGuideName,
                             type="string")
                cmds.setAttr(self.toStaticHookGrp + ".dpAR_type",
                             CLASS_NAME,
                             type="string")
                # add module type counter value
                cmds.addAttr(self.toStaticHookGrp,
                             longName='dpAR_count',
                             attributeType='long',
                             keyable=False)
                cmds.setAttr(self.toStaticHookGrp + '.dpAR_count', dpAR_count)
                self.ctrlHookGrpList.append(self.toCtrlHookGrp)
                if hideJoints:
                    cmds.setAttr(self.toScalableHookGrp + ".visibility", 0)
                # delete duplicated group for side (mirror):
                cmds.delete(side + self.userGuideName + '_' + self.mirrorGrp)
            # finalize this rig:
            self.integratingInfo()
            cmds.select(clear=True)
        # delete UI (moduleLayout), GUIDE and moduleInstance namespace:
        self.deleteModule()
Exemplo n.º 48
0
if (mc.objExists("pCube1")):
    clean([pathNode, pathNodeCppDraw], [nodeType, nodeTypeDraw])
    mc.error("****CLEAN FOR RECOMPILING NODE*****")

print('BUILD TEST __________________________ PREPARE SCENE')
mc.file(pathBuildTest, i=True)
mc.playbackOptions(min=0, max=400)

inputObj = 'pCube1'
outputObj = 'pCone1'

print('BUILD TEST __________________________ LOAD NODE')
mc.loadPlugin(pathNode)

print('BUILD TEST __________________________ CREATE NODE')
newNode = mc.createNode(nodeType)

print('BUILD TEST __________________________ CONNECT IN')

mc.connectAttr(inputObj + '.translateX', newNode + '.inValue')
mc.connectAttr('time1.outTime', newNode + '.currentFrame')
mc.connectAttr(inputObj + '.worldMatrix[0]', newNode + '.drawMatrix')
print('BUILD TEST __________________________ CONNECT OUT')
mc.connectAttr(newNode + '.outValue', outputObj + '.translateY')

print('BUILD TEST __________________________ SET ATTR')

print('BUILD TEST __________________________ DONE')
mc.select(newNode)

#LOAD DRAW
Exemplo n.º 49
0
 def setUp(self):
     self.a = noca.Node(cmds.createNode("transform", name=TEST_NODES[0]))
     self.b = noca.Node(cmds.createNode("transform", name=TEST_NODES[1]))
     self.c = noca.Node(cmds.createNode("transform", name=TEST_NODES[2]))
     self.m = noca.Node(cmds.createNode("holdMatrix", name=TEST_NODES[3]))
Exemplo n.º 50
0
    def createGuide(self, *args):
        Base.StartClass.createGuide(self)
        # Custom GUIDE:
        cmds.addAttr(self.moduleGrp, longName="flip", attributeType='bool')
        cmds.addAttr(self.moduleGrp, longName="geo", dataType='string')
        cmds.addAttr(self.moduleGrp,
                     longName="startFrame",
                     attributeType='long',
                     defaultValue=1)
        cmds.addAttr(self.moduleGrp,
                     longName="showControls",
                     attributeType='bool')
        cmds.addAttr(self.moduleGrp, longName="steering", attributeType='bool')
        cmds.setAttr(self.moduleGrp + ".flip", 0)
        cmds.setAttr(self.moduleGrp + ".showControls", 1)
        cmds.setAttr(self.moduleGrp + ".steering", 0)

        cmds.setAttr(self.moduleGrp + ".moduleNamespace",
                     self.moduleGrp[:self.moduleGrp.rfind(":")],
                     type='string')

        self.cvCenterLoc, shapeSizeCH = self.ctrls.cvJointLoc(
            ctrlName=self.guideName + "_CenterLoc",
            r=0.6,
            d=1,
            rot=(90, 0, 90),
            guide=True)
        self.connectShapeSize(shapeSizeCH)
        self.jGuideCenter = cmds.joint(name=self.guideName + "_JGuideCenter",
                                       radius=0.001)
        cmds.setAttr(self.jGuideCenter + ".template", 1)
        cmds.parent(self.jGuideCenter, self.moduleGrp, relative=True)

        self.cvFrontLoc = self.ctrls.cvControl("id_059_AimLoc",
                                               ctrlName=self.guideName +
                                               "_FrontLoc",
                                               r=0.3,
                                               d=1,
                                               rot=(0, 0, 90))
        self.ctrls.colorShape([self.cvFrontLoc], "blue")
        shapeSizeCH = self.ctrls.shapeSizeSetup(self.cvFrontLoc)
        self.connectShapeSize(shapeSizeCH)
        cmds.parent(self.cvFrontLoc, self.cvCenterLoc)
        cmds.setAttr(self.cvFrontLoc + ".tx", 1.3)
        self.jGuideFront = cmds.joint(name=self.guideName + "_JGuideFront",
                                      radius=0.001)
        cmds.setAttr(self.jGuideFront + ".template", 1)
        cmds.transformLimits(self.cvFrontLoc,
                             translationX=(1, 1),
                             enableTranslationX=(True, False))
        radiusCtrl = self.moduleGrp + "_RadiusCtrl"
        cvFrontLocPosNode = cmds.createNode("plusMinusAverage",
                                            name=self.cvFrontLoc + "_Pos_PMA")
        cmds.setAttr(cvFrontLocPosNode + ".input1D[0]", -0.5)
        cmds.connectAttr(radiusCtrl + ".translateX",
                         cvFrontLocPosNode + ".input1D[1]")
        cmds.connectAttr(cvFrontLocPosNode + ".output1D",
                         self.cvFrontLoc + ".tx")
        self.ctrls.setLockHide(
            [self.cvCenterLoc, self.cvFrontLoc],
            ['tx', 'ty', 'tz', 'rx', 'ry', 'rz', 'sx', 'sy', 'sz'])

        self.cvInsideLoc, shapeSizeCH = self.ctrls.cvLocator(
            ctrlName=self.guideName + "_InsideLoc", r=0.2, d=1, guide=True)
        self.connectShapeSize(shapeSizeCH)
        cmds.parent(self.cvInsideLoc, self.cvCenterLoc)
        cmds.setAttr(self.cvInsideLoc + ".tz", 0.3)
        self.jGuideInside = cmds.joint(name=self.guideName + "_JGuideInside",
                                       radius=0.001)
        cmds.setAttr(self.jGuideInside + ".template", 1)
        cmds.transformLimits(self.cvInsideLoc, tz=(0.01, 1), etz=(True, False))
        inverseRadius = cmds.createNode("multiplyDivide",
                                        name=self.moduleGrp + "_Radius_Inv_MD")
        cmds.setAttr(inverseRadius + ".input2X", -1)
        cmds.connectAttr(radiusCtrl + ".translateX",
                         inverseRadius + ".input1X")
        cmds.connectAttr(inverseRadius + ".outputX",
                         self.cvInsideLoc + ".translateY")
        self.ctrls.setLockHide(
            [self.cvInsideLoc],
            ['tx', 'ty', 'rx', 'ry', 'rz', 'sx', 'sy', 'sz'])

        self.cvOutsideLoc, shapeSizeCH = self.ctrls.cvLocator(
            ctrlName=self.guideName + "_OutsideLoc", r=0.2, d=1, guide=True)
        self.connectShapeSize(shapeSizeCH)
        cmds.parent(self.cvOutsideLoc, self.cvCenterLoc)
        cmds.setAttr(self.cvOutsideLoc + ".tz", -0.3)
        self.jGuideOutside = cmds.joint(name=self.guideName + "_JGuideOutside",
                                        radius=0.001)
        cmds.setAttr(self.jGuideOutside + ".template", 1)
        cmds.transformLimits(self.cvOutsideLoc,
                             tz=(-1, 0.01),
                             etz=(False, True))
        cmds.connectAttr(inverseRadius + ".outputX",
                         self.cvOutsideLoc + ".translateY")
        self.ctrls.setLockHide(
            [self.cvOutsideLoc],
            ['tx', 'ty', 'rx', 'ry', 'rz', 'sx', 'sy', 'sz'])

        cmds.parent(self.cvCenterLoc, self.moduleGrp)
        cmds.parent(self.jGuideFront, self.jGuideInside, self.jGuideOutside,
                    self.jGuideCenter)
        cmds.parentConstraint(self.cvCenterLoc,
                              self.jGuideCenter,
                              maintainOffset=False,
                              name=self.jGuideCenter + "_ParentConstraint")
        cmds.parentConstraint(self.cvFrontLoc,
                              self.jGuideFront,
                              maintainOffset=False,
                              name=self.jGuideFront + "_ParentConstraint")
        cmds.parentConstraint(self.cvInsideLoc,
                              self.jGuideInside,
                              maintainOffset=False,
                              name=self.cvInsideLoc + "_ParentConstraint")
        cmds.parentConstraint(self.cvOutsideLoc,
                              self.jGuideOutside,
                              maintainOffset=False,
                              name=self.cvOutsideLoc + "_ParentConstraint")
Exemplo n.º 51
0
def main(name="assembly", position=(0,0,0), radius=1, fbx=False,
		cog=True, body=True, pelvis=True):

	if type(position) == str or type(position) == unicode:
		position = mc.xform(position, q=True, rp=True, ws=True)

	grp = mc.createNode("transform", n=name)
	mc.addAttr(grp, ln="joints", at="bool", dv=True, k=True)
	mc.addAttr(grp, ln="editJoints", at="bool", k=True)
	if fbx:
		mc.setAttr(grp+".joints", False)
		mc.addAttr(grp, ln="fbxJoints", at="bool", dv=True, k=True)
		mc.addAttr(grp, ln="editFbxJoints", at="bool", k=True)
	mc.addAttr(grp, ln="controls", at="bool", dv=True, k=True)
	mc.addAttr(grp, ln="_geometry", at="bool", dv=True, k=True)
	mc.addAttr(grp, ln="editGeometry", at="bool", k=True)

	#
	# controls
	#

	ctrl = []
	ctrl.append(common.control(name="world", parent=grp, radius=radius*5, color=13,
					lockAttr=["v"], hideAttr=["v"])[1])

	if cog:
		ctrl.append(common.control(name="cog", parent=ctrl[0], position=position,
					color=13, radius=radius*4, lockAttr=["s","v"],
					hideAttr=["sx","sy","sz","v"])[1])

	if body:
		ctrl.append(common.control(name="body", parent=ctrl[1], position=ctrl[1],
					color=13, radius=radius*3, lockAttr=["s","v"],
					hideAttr=["sx","sy","sz","v"])[1])

	if pelvis:
		ctrl.append(common.control(name="pelvis", parent=ctrl[2], position=ctrl[2],
					radius=radius*2, lockAttr=["s","v"],
					hideAttr=["sx","sy","sz","v"])[1])

	grps = [None]*2
	rev = mc.createNode("reverse")
	if fbx:
		grps[0] = mc.createNode("transform", n="skeleton_fbx")
		grps[1] = mc.createNode("transform", n="geometry_fbx")
		mc.connectAttr(grp+".fbxJoints", grps[0]+".v")
		mc.setAttr(grps[0]+".overrideDisplayType", 2)
		mc.connectAttr(grp+".editFbxJoints", rev+".inputX")
		mc.connectAttr(rev+".outputX", grps[0]+".overrideEnabled")
		mc.createNode("transform", n="constraints_fbx", p=grp)
	else:
		grps[1] = mc.createNode("transform", n="geometry", p=grp)
	mc.connectAttr(grp+"._geometry", grps[1]+".v")
	mc.connectAttr(grp+".editGeometry", rev+".inputY")
	mc.connectAttr(rev+".outputY", grps[1]+".overrideEnabled")
	mc.setAttr(grps[1]+".overrideDisplayType", 2)

	for n in grps:
		for a in ["tx","ty","tz","rx","ry","rz","sx","sy","sz","v"]:
			try: mc.setAttr(n+"."+a, l=True, k=False, cb=False)
			except: pass

	#
	# selection sets
	#

	n1 = mc.sets(n="ik_controls_set", em=True)
	n2 = mc.sets(n="fk_controls_set", em=True)
	for n in ctrl: mc.connectAttr(n+".message", n2+".dnSetMembers", na=True)
	n3 = mc.sets(n="joints_set", em=True)
	n4 = mc.sets(n=name+"_set", em=True)
	mc.sets(n1, n2, n3, add=n4)

	mc.select(grp)
	mc.dgdirty(a=True)

	return grp
Exemplo n.º 52
0
def getOrigShape(shape):

    nodeType = cmds.nodeType(shape)

    outputAttr = ''
    inputAttr = ''
    if nodeType in ['nurbsSurface', 'nurbsCurve']:
        outputAttr = 'local'
        inputAttr = 'create'
    elif nodeType == 'mesh':
        outputAttr = 'outMesh'
        inputAttr = 'inMesh'

    cons = cmds.listConnections(shape, s=1, d=0, c=1, p=1)

    origShapeNode = None

    if cons:
        outputCons = cons[1::2]
        inputCons = cons[::2]

        outputNode = ''
        for i in range(len(inputCons)):
            if inputCons[i].split('.')[1] == inputAttr:
                outputNode = outputCons[i].split('.')[0]

        checkList = []
        if outputNode:

            def getOrigShapeNode(node):
                if node in checkList: return None
                checkList.append(node)
                if not cmds.nodeType(node): return None
                if cmds.nodeType(node) == nodeType:
                    if cmds.getAttr(node + '.io'):
                        return node

                cons = cmds.listConnections(node, s=1, d=0, p=1, c=1)
                nodes = []
                if cons:
                    for con in cons[1::2]:
                        nodes.append(getOrigShapeNode(con.split('.')[0]))
                for node in nodes:
                    if node:
                        return node
                return None

            origShapeNode = getOrigShapeNode(outputNode)

    if origShapeNode:
        return origShapeNode
    else:
        cons = 1
        while (cons):
            cons = cmds.listConnections(shape + '.' + inputAttr, p=1, c=1)
            if cons:
                for con in cons[1::2]:
                    cmds.delete(con.split('.')[0])

        origNode = cmds.createNode(nodeType, n='temp_origNodeShape')
        origP = cmds.listRelatives(origNode, p=1)[0]
        cmds.connectAttr(shape + '.' + outputAttr, origNode + '.' + inputAttr)
        duOrigP = cmds.duplicate(origP)[0]
        duOrig = cmds.listRelatives(duOrigP, s=1)[0]
        cmds.connectAttr(duOrig + '.' + outputAttr, shape + '.' + inputAttr)
        shapeP = cmds.listRelatives(shape, p=1)[0]
        cmds.parent(duOrig, shapeP, add=1, shape=1)
        cmds.delete(origP, duOrigP)
        cmds.setAttr(duOrig + '.io', 1)
        origShapeNode = cmds.rename(duOrig, shape + 'Orig')
        return origShapeNode
Exemplo n.º 53
0
    def rigModule(self, *args):
        Base.StartClass.rigModule(self)
        # verify if the guide exists:
        if cmds.objExists(self.moduleGrp):
            try:
                hideJoints = cmds.checkBox('hideJointsCB', query=True, value=True)
            except:
                hideJoints = 1
            # declaring lists to send information for integration:
            self.scalableGrpList, self.ikCtrlZeroList = [], []
            # start as no having mirror:
            sideList = [""]
            # analisys the mirror module:
            self.mirrorAxis = cmds.getAttr(self.moduleGrp + ".mirrorAxis")
            if self.mirrorAxis != 'off':
                # get rigs names:
                self.mirrorNames = cmds.getAttr(self.moduleGrp + ".mirrorName")
                # get first and last letters to use as side initials (prefix):
                sideList = [self.mirrorNames[0] + '_', self.mirrorNames[len(self.mirrorNames) - 1] + '_']
                for s, side in enumerate(sideList):
                    duplicated = cmds.duplicate(self.moduleGrp, name=side + self.userGuideName + '_Guide_Base')[0]
                    allGuideList = cmds.listRelatives(duplicated, allDescendents=True)
                    for item in allGuideList:
                        cmds.rename(item, side + self.userGuideName + "_" + item)
                    self.mirrorGrp = cmds.group(name="Guide_Base_Grp", empty=True)
                    cmds.parent(side + self.userGuideName + '_Guide_Base', self.mirrorGrp, absolute=True)
                    # re-rename grp:
                    cmds.rename(self.mirrorGrp, side + self.userGuideName + '_' + self.mirrorGrp)
                    # do a group mirror with negative scaling:
                    if s == 1:
                        for axis in self.mirrorAxis:
                            cmds.setAttr(side + self.userGuideName + '_' + self.mirrorGrp + '.scale' + axis, -1)
            else:  # if not mirror:
                duplicated = cmds.duplicate(self.moduleGrp, name=self.userGuideName + '_Guide_Base')[0]
                allGuideList = cmds.listRelatives(duplicated, allDescendents=True)
                for item in allGuideList:
                    cmds.rename(item, self.userGuideName + "_" + item)
                self.mirrorGrp = cmds.group(self.userGuideName + '_Guide_Base', name="Guide_Base_Grp", relative=True)
                # re-rename grp:
                cmds.rename(self.mirrorGrp, self.userGuideName + '_' + self.mirrorGrp)
            # store the number of this guide by module type
            dpAR_count = utils.findModuleLastNumber(CLASS_NAME, "dpAR_type") + 1
            # run for all sides
            for s, side in enumerate(sideList):
                self.skinJointList = []
                self.base = side + self.userGuideName + '_Guide_Base'
                # get the number of joints to be created:
                self.nJoints = cmds.getAttr(self.base + ".nJoints")
                for n in range(0, self.nJoints + 1):
                    cmds.select(clear=True)
                    # declare guide:
                    self.guide = side + self.userGuideName + "_Guide_JointLoc" + str(n)
                    # create a joint:
                    self.jnt = cmds.joint(name=side + self.userGuideName + "_" + str(n) + "_Jnt", scaleCompensate=False)
                    self.skinJointList.append(self.jnt)
                    cmds.addAttr(self.jnt, longName='dpAR_joint', attributeType='float', keyable=False)
                    # create a control:
                    if n == 1:
                        self.ctrl = ctrls.cvFinger(ctrlName=side + self.userGuideName + "_" + str(n) + "_Ctrl", r=self.ctrlRadius)
                        cmds.setAttr(self.ctrl + ".rotateOrder", 1)
                        utils.originedFrom(objName=self.ctrl, attrString=self.base + ";" + self.guide)
                        # edit the mirror shape to a good direction of controls:
                        if s == 1:
                            if self.mirrorAxis == 'X':
                                cmds.setAttr(self.ctrl + '.rotateZ', 180)
                            elif self.mirrorAxis == 'Y':
                                cmds.setAttr(self.ctrl + '.rotateY', 180)
                            elif self.mirrorAxis == 'Z':
                                cmds.setAttr(self.ctrl + '.rotateZ', 180)
                            elif self.mirrorAxis == 'XY':
                                cmds.setAttr(self.ctrl + '.rotateX', 180)
                            elif self.mirrorAxis == 'XYZ':
                                cmds.setAttr(self.ctrl + '.rotateZ', 180)
                            cmds.makeIdentity(self.ctrl, apply=True, translate=False, rotate=True, scale=False)
                    else:
                        self.ctrl = cmds.circle(name=side + self.userGuideName + "_" + str(n) + "_Ctrl", degree=1, normal=(0, 0, 1), r=self.ctrlRadius, s=6, ch=False)[0]
                        cmds.setAttr(self.ctrl + ".rotateOrder", 1)
                        utils.originedFrom(objName=self.ctrl, attrString=self.guide)
                        if n == 0:
                            if self.nJoints == 2:
                                # problably we are creating the first control to a thumb
                                cmds.scale(2, 2, 2, self.ctrl, relative=True)
                                cmds.makeIdentity(self.ctrl, apply=True)
                            else:
                                # problably we are creating other base controls
                                cmds.scale(2, 0.5, 1, self.ctrl, relative=True)
                                cmds.makeIdentity(self.ctrl, apply=True)

                    # scaleCompensate attribute:
                    #Not needed in Maya 2016 since we need to deactivate scale compensate on all finger bone
                    if (int(cmds.about(version=True)[:4]) < 2016):
                        if n > 0 or self.nJoints == 2:
                            cmds.addAttr(self.ctrl, longName="scaleCompensate", attributeType='bool', keyable=True)
                            scaleCompensateCond = cmds.createNode("condition", name=side + self.userGuideName + "_" + str(n) + "_ScaleCompensate_Cnd")
                            cmds.setAttr(scaleCompensateCond + ".secondTerm", 1)
                            cmds.connectAttr(self.ctrl + ".scaleCompensate", scaleCompensateCond + ".colorIfTrueR", force=True)
                            cmds.connectAttr(scaleCompensateCond + ".outColorR", self.jnt + ".segmentScaleCompensate", force=True)

                    # hide visibility attribute:
                    cmds.setAttr(self.ctrl + '.visibility', keyable=False)
                    # put another group over the control in order to use this to connect values from mainFingerCtrl:
                    self.sdkGrp = cmds.group(self.ctrl, name=side + self.userGuideName + "_" + str(n) + "_SDKGrp")
                    if n == 1:
                        # change pivot of this group to control pivot:
                        pivotPos = cmds.xform(self.ctrl, query=True, worldSpace=True, rotatePivot=True)
                        cmds.setAttr(self.sdkGrp + '.rotatePivotX', pivotPos[0])
                        cmds.setAttr(self.sdkGrp + '.rotatePivotY', pivotPos[1])
                        cmds.setAttr(self.sdkGrp + '.rotatePivotZ', pivotPos[2])
                    # position and orientation of joint and control:
                    tempDel = cmds.parentConstraint(self.guide, self.jnt, maintainOffset=False)
                    cmds.delete(tempDel)
                    tempDel = cmds.parentConstraint(self.guide, self.sdkGrp, maintainOffset=False)
                    cmds.delete(tempDel)
                    # zeroOut controls:
                    utils.zeroOut([self.sdkGrp])
                # create end joint:
                self.cvEndJoint = side + self.userGuideName + "_Guide_JointEnd"
                self.endJoint = cmds.joint(name=side + self.userGuideName + "_JEnd", scaleCompensate=False)
                tempDel = cmds.parentConstraint(self.cvEndJoint, self.endJoint, maintainOffset=False)
                cmds.delete(tempDel)
                cmds.parent(self.endJoint, side + self.userGuideName + "_" + str(self.nJoints) + "_Jnt", absolute=True)
                # grouping:
                for n in range(0, self.nJoints + 1):
                    self.jnt = side + self.userGuideName + "_" + str(n) + "_Jnt"
                    self.ctrl = side + self.userGuideName + "_" + str(n) + "_Ctrl"
                    self.zeroCtrl = side + self.userGuideName + "_" + str(n) + "_SDKGrp_Zero"
                    if n > 0:
                        if n == 1:
                            if not cmds.objExists(self.ctrl + '.ikFkBlend'):
                                cmds.addAttr(self.ctrl, longName="ikFkBlend", attributeType='float', keyable=True, minValue=0.0, maxValue=1.0, defaultValue=1.0)
                                self.ikFkRevNode = cmds.createNode("reverse", name=side + self.userGuideName + "_ikFk_Rev")
                                cmds.connectAttr(self.ctrl + ".ikFkBlend", self.ikFkRevNode + ".inputX", force=True)
                            if not cmds.objExists(self.ctrl + '.' + self.langDic[self.langName]['c_showControls']):
                                cmds.addAttr(self.ctrl, longName=self.langDic[self.langName]['c_showControls'], attributeType='float', keyable=True, minValue=0.0, maxValue=1.0, defaultValue=1.0)
                                self.ctrlShape0 = cmds.listRelatives(side + self.userGuideName + "_0_Ctrl", children=True, type='nurbsCurve')[0]
                                cmds.connectAttr(self.ctrl + "." + self.langDic[self.langName]['c_showControls'], self.ctrlShape0 + ".visibility", force=True)
                                cmds.setAttr(self.ctrl + '.' + self.langDic[self.langName]['c_showControls'], keyable=False, channelBox=True)
                            for j in range(1, self.nJoints + 1):
                                cmds.addAttr(self.ctrl, longName=self.langDic[self.langName]['c_falange'] + str(j), attributeType='float', keyable=True)
                        # parent joints as a simple chain (line)
                        self.fatherJnt = side + self.userGuideName + "_" + str(n - 1) + "_Jnt"
                        cmds.parent(self.jnt, self.fatherJnt, absolute=True)
                        # parent zeroCtrl Group to the before ctrl:
                        self.fatherCtrl = side + self.userGuideName + "_" + str(n - 1) + "_Ctrl"
                        cmds.parent(self.zeroCtrl, self.fatherCtrl, absolute=True)
                    # freeze joints rotation
                    cmds.makeIdentity(self.jnt, apply=True)
                    # create parent and scale constraints from ctrl to jnt:
                    cmds.delete(cmds.parentConstraint(self.ctrl, self.jnt, maintainOffset=False, name=self.jnt + "_ParentConstraint"))
                # make first falange be leads from base finger control:
                cmds.parentConstraint(side + self.userGuideName + "_0_Ctrl", side + self.userGuideName + "_1_SDKGrp_Zero", maintainOffset=True, name=side + self.userGuideName + "_1_SDKGrp_Zero" + "_ParentConstraint")
                cmds.scaleConstraint(side + self.userGuideName + "_0_Ctrl", side + self.userGuideName + "_1_SDKGrp_Zero", maintainOffset=True, name=side + self.userGuideName + "_1_SDKGrp_Zero" + "_ScaleConstraint")
                if self.nJoints != 2:
                    cmds.parentConstraint(side + self.userGuideName + "_0_Ctrl", side + self.userGuideName + "_0_Jnt", maintainOffset=True, name=side + self.userGuideName + "_ParentConstraint")
                    cmds.scaleConstraint(side + self.userGuideName + "_0_Ctrl", side + self.userGuideName + "_0_Jnt", maintainOffset=True, name=side + self.userGuideName + "_ScaleConstraint")
                # connecting the attributes from control 1 to falanges rotate:
                for n in range(1, self.nJoints + 1):
                    self.ctrl = side + self.userGuideName + "_1_Ctrl"
                    self.sdkGrp = side + self.userGuideName + "_" + str(n) + "_SDKGrp"
                    cmds.connectAttr(self.ctrl + "." + self.langDic[self.langName]['c_falange'] + str(n), self.sdkGrp + ".rotateY", force=True)
                    if n > 1:
                        self.ctrlShape = cmds.listRelatives(side + self.userGuideName + "_" + str(n) + "_Ctrl", children=True, type='nurbsCurve')[0]
                        cmds.connectAttr(self.ctrl + "." + self.langDic[self.langName]['c_showControls'], self.ctrlShape + ".visibility", force=True)

                # ik and Fk setup
                if self.nJoints == 2:
                    dupIk = cmds.duplicate(self.skinJointList[0])[0]
                    dupFk = cmds.duplicate(self.skinJointList[0])[0]
                else:
                    dupIk = cmds.duplicate(self.skinJointList[1])[0]
                    dupFk = cmds.duplicate(self.skinJointList[1])[0]
                
                # hide ik and fk joints in order to be rigger friendly whe skinning
                cmds.setAttr(dupIk+".visibility", 0)
                cmds.setAttr(dupFk+".visibility", 0)
                
                # ik setup
                childrenIkList = cmds.listRelatives(dupIk, children=True, allDescendents=True, fullPath=True)
                if childrenIkList:
                    for child in childrenIkList:
                        if not cmds.objectType(child) == "joint":
                            cmds.delete(child)
                jointIkList = cmds.listRelatives(dupIk, children=True, allDescendents=True, fullPath=True)
                for jointNode in jointIkList:
                    if "_Jnt" in jointNode[jointNode.rfind("|"):]:
                        cmds.rename(jointNode, jointNode[jointNode.rfind("|") + 1:].replace("_Jnt", "_Ik_Jxt"))
                    elif "_JEnd" in jointNode[jointNode.rfind("|"):]:
                        cmds.rename(jointNode, jointNode[jointNode.rfind("|") + 1:].replace("_JEnd", "_Ik_JEnd"))
                ikBaseJoint = cmds.rename(dupIk, dupIk.replace("_Jnt1", "_Ik_Jxt"))
                ikJointList = cmds.listRelatives(ikBaseJoint, children=True, allDescendents=True)
                ikJointList.append(ikBaseJoint)

                # Fk setup
                childrenFkList = cmds.listRelatives(dupFk, children=True, allDescendents=True, fullPath=True)
                if childrenFkList:
                    for child in childrenFkList:
                        if not cmds.objectType(child) == "joint":
                            cmds.delete(child)
                jointFkList = cmds.listRelatives(dupFk, children=True, allDescendents=True, fullPath=True)
                for jointNode in jointFkList:
                    if "_Jnt" in jointNode[jointNode.rfind("|"):]:
                        cmds.rename(jointNode, jointNode[jointNode.rfind("|") + 1:].replace("_Jnt", "_Fk_Jxt"))
                    elif "_JEnd" in jointNode[jointNode.rfind("|"):]:
                        cmds.rename(jointNode, jointNode[jointNode.rfind("|") + 1:].replace("_JEnd", "_Fk_JEnd"))
                fkBaseJoint = cmds.rename(dupFk, dupFk.replace("_Jnt2", "_Fk_Jxt"))
                fkJointList = cmds.listRelatives(fkBaseJoint, children=True, allDescendents=True)
                fkJointList.append(fkBaseJoint)
                # ik fk blend connnections
                for i, ikJoint in enumerate(ikJointList):
                    if not "_JEnd" in ikJoint:
                        if cmds.objExists(ikJoint + ".dpAR_joint"):
                            cmds.deleteAttr(ikJoint + ".dpAR_joint")
                        fkJoint = ikJoint.replace("_Ik_Jxt", "_Fk_Jxt")
                        skinJoint = ikJoint.replace("_Ik_Jxt", "_Jnt")
                        self.ctrl = side + self.userGuideName + "_1_Ctrl"
                        scaleCompensateCond = ikJoint.replace("_Ik_Jxt", "_ScaleCompensate_Cnd")
                        ikFkParentConst = cmds.parentConstraint(ikJoint, fkJoint, skinJoint, maintainOffset=True, name=skinJoint + "_ParentConstraint")[0]
                        ikFkScaleConst = cmds.scaleConstraint(ikJoint, fkJoint, skinJoint, maintainOffset=True, name=skinJoint + "_ScaleConstraint")[0]
                        cmds.connectAttr(self.ctrl + ".ikFkBlend", ikFkParentConst + "." + fkJoint + "W1", force=True)
                        cmds.connectAttr(self.ikFkRevNode + ".outputX", ikFkParentConst + "." + ikJoint + "W0", force=True)
                        cmds.connectAttr(self.ctrl + ".ikFkBlend", ikFkScaleConst + "." + fkJoint + "W1", force=True)
                        cmds.connectAttr(self.ikFkRevNode + ".outputX", ikFkScaleConst + "." + ikJoint + "W0", force=True)
                        cmds.setAttr(ikJoint + ".segmentScaleCompensate", 1)
                        #Condition for scale compensate will not exist in maya 2016 since we need to have the compensate
                        #off for almost every joint
                        if (int(cmds.about(version=True)[:4]) < 2016):
                            cmds.connectAttr(self.ctrl + ".ikFkBlend", scaleCompensateCond + ".firstTerm", force=True)
                # fk control drives fk joints
                for i, fkJoint in enumerate(fkJointList):
                    if not "_JEnd" in fkJoint:
                        if cmds.objExists(fkJoint + ".dpAR_joint"):
                            cmds.deleteAttr(fkJoint + ".dpAR_joint")
                        fkCtrl = fkJoint.replace("_Fk_Jxt", "_Ctrl")
                        scaleCompensateCond = fkCtrl.replace("_Ctrl", "_ScaleCompensate_Cnd")
                        cmds.parentConstraint(fkCtrl, fkJoint, maintainOffset=True, name=fkJoint + "_ParentConstraint")
                        cmds.scaleConstraint(fkCtrl, fkJoint, maintainOffset=True, name=fkJoint + "_ScaleConstraint")
                        #Not needed in Maya 2016 since we need to deactivate scale compensate on all finger bone
                        if (int(cmds.about(version=True)[:4]) < 2016):
                            cmds.connectAttr(fkCtrl + ".scaleCompensate", fkJoint + ".segmentScaleCompensate", force=True)
                        else:
                            cmds.setAttr(fkJoint + ".segmentScaleCompensate", 0)
                        cmds.setAttr(fkCtrl + ".rotateOrder", 1)

                #Force Scale compensate to prevent scale problem in Maya 2016
                for nJnt in self.skinJointList:
                    if (int(cmds.about(version=True)[:4]) >= 2016):
                        cmds.setAttr(nJnt + ".segmentScaleCompensate", 0)

                # ik handle
                if self.nJoints >= 2:
                    if self.nJoints == 2:
                        ikHandleList = cmds.ikHandle(startJoint=side + self.userGuideName + "_0_Ik_Jxt", endEffector=side + self.userGuideName + "_" + str(self.nJoints) + "_Ik_Jxt", solver="ikRPsolver", name=side + self.userGuideName + "_IkHandle")
                    else:
                        ikHandleList = cmds.ikHandle(startJoint=side + self.userGuideName + "_1_Ik_Jxt", endEffector=side + self.userGuideName + "_" + str(self.nJoints) + "_Ik_Jxt", solver="ikRPsolver", name=side + self.userGuideName + "_IkHandle")
                    cmds.rename(ikHandleList[1], side + self.userGuideName + "_Effector")
                    endIkHandleList = cmds.ikHandle(startJoint=side + self.userGuideName + "_" + str(self.nJoints) + "_Ik_Jxt", endEffector=side + self.userGuideName + "_Ik_JEnd", solver="ikSCsolver", name=side + self.userGuideName + "_EndIkHandle")
                    cmds.rename(endIkHandleList[1], side + self.userGuideName + "_EndEffector")
                    self.ikCtrl = ctrls.cvBox(ctrlName=side + self.userGuideName + "_Ik_Ctrl", r=self.ctrlRadius*0.3)
                    cmds.addAttr(self.ikCtrl, longName='twist', attributeType='float', keyable=True)
                    cmds.connectAttr(self.ikCtrl + ".twist", ikHandleList[0] + ".twist", force=True)
                    cmds.delete(cmds.parentConstraint(side + self.userGuideName + "_Ik_JEnd", self.ikCtrl))
                    cmds.setAttr(self.ikCtrl + ".rotateOrder", 1)
                    self.ikCtrlZero = utils.zeroOut([self.ikCtrl])[0]
                    self.ikCtrlZeroList.append(self.ikCtrlZero)
                    cmds.connectAttr(self.ikFkRevNode + ".outputX", self.ikCtrlZero + ".visibility", force=True)
                    for q in range(2, self.nJoints):
                        cmds.connectAttr(side + self.userGuideName + "_1_Ctrl.ikFkBlend", side + self.userGuideName + "_" + str(q) + "_Ctrl.visibility", force=True)
                    cmds.parentConstraint(self.ikCtrl, ikHandleList[0], name=side + self.userGuideName + "_IkHandle_ParentConstraint", maintainOffset=True)
                    cmds.parentConstraint(self.ikCtrl, endIkHandleList[0], name=side + self.userGuideName + "_EndIkHandle_ParentConstraint", maintainOffset=True)
                    ikHandleGrp = cmds.group(ikHandleList[0], endIkHandleList[0], name=side + self.userGuideName + "_IkHandle_Grp")
                    cmds.setAttr(ikHandleGrp+".visibility", 0)
                    ctrls.setLockHide([self.ikCtrl], ['sx', 'sy', 'sz', 'v'])

                    if self.nJoints == 2:
                        cmds.parentConstraint(side + self.userGuideName + "_0_Ctrl", side + self.userGuideName + "_0_Ik_Jxt", maintainOffset=True, name=side + self.userGuideName + "_0_Ik_Jxt_ParentConstraint")
                        cmds.scaleConstraint(side + self.userGuideName + "_0_Ctrl", side + self.userGuideName + "_0_Ik_Jxt", maintainOffset=True, name=side + self.userGuideName + "_0_Ik_Jxt_ScaleConstraint")

                    # stretch
                    cmds.addAttr(self.ikCtrl, longName='stretchable', attributeType='float', minValue=0, maxValue=1, defaultValue=0, keyable=True)
                    stretchNormMD = cmds.createNode("multiplyDivide", name=side + self.userGuideName + "_StretchNormalize_MD")
                    cmds.setAttr(stretchNormMD + ".operation", 2)
                    distBetweenList = ctrls.distanceBet(side + self.userGuideName + "_0_Ctrl", self.ikCtrl, name=side + self.userGuideName + "_DistBet", keep=True)
                    cmds.connectAttr(self.ikFkRevNode + ".outputX", distBetweenList[5] + "." + self.ikCtrl + "W0", force=True)
                    cmds.connectAttr(self.ctrl + ".ikFkBlend", distBetweenList[5] + "." + distBetweenList[4] + "W1", force=True)
                    cmds.connectAttr(distBetweenList[1] + ".distance", stretchNormMD + ".input1X", force=True)
                    cmds.setAttr(stretchNormMD + ".input2X", distBetweenList[0])
                    stretchScaleMD = cmds.createNode("multiplyDivide", name=side + self.userGuideName + "_StretchScale_MD")
                    cmds.connectAttr(stretchNormMD + ".outputX", stretchScaleMD + ".input1X", force=True)
                    cmds.connectAttr(self.ikCtrl + ".stretchable", stretchScaleMD + ".input2X", force=True)
                    stretchCond = cmds.createNode("condition", name=side + self.userGuideName + "_Stretch_Cnd")
                    cmds.connectAttr(stretchScaleMD + ".outputX", stretchCond + ".firstTerm", force=True)
                    cmds.setAttr(stretchCond + ".secondTerm", 1)
                    cmds.setAttr(stretchCond + ".operation", 2)
                    cmds.connectAttr(stretchScaleMD + ".outputX", stretchCond + ".colorIfTrueR", force=True)
                    for i, ikJoint in enumerate(ikJointList):
                        if not "_JEnd" in ikJoint:
                            if self.nJoints == 2 and i == 0:
                                pass
                            else:
                                cmds.connectAttr(stretchCond + ".outColorR", ikJoint + ".scaleZ", force=True)

                    # create a masterModuleGrp to be checked if this rig exists:
                    self.toCtrlHookGrp = cmds.group(self.ikCtrlZero, side + self.userGuideName + "_0_SDKGrp_Zero", side + self.userGuideName + "_1_SDKGrp_Zero", name=side + self.userGuideName + "_Control_Grp")
                    if self.nJoints == 2:
                        self.toScalableHookGrp = cmds.group(side + self.userGuideName + "_0_Jnt", ikBaseJoint, fkBaseJoint, ikHandleGrp, distBetweenList[2], distBetweenList[3], distBetweenList[4], name=side + self.userGuideName + "_Joint_Grp")
                    else:
                        self.toScalableHookGrp = cmds.group(side + self.userGuideName + "_0_Jnt", ikHandleGrp, distBetweenList[2], distBetweenList[3], distBetweenList[4], name=side + self.userGuideName + "_Joint_Grp")
                else:
                    self.toCtrlHookGrp = cmds.group(side + self.userGuideName + "_0_SDKGrp_Zero", side + self.userGuideName + "_1_SDKGrp_Zero", name=side + self.userGuideName + "_Control_Grp")
                    self.toScalableHookGrp = cmds.group(side + self.userGuideName + "_0_Jnt", name=side + self.userGuideName + "_Joint_Grp")
                self.scalableGrpList.append(self.toScalableHookGrp)
                self.toStaticHookGrp = cmds.group(self.toCtrlHookGrp, self.toScalableHookGrp, name=side + self.userGuideName + "_Grp")
                # add hook attributes to be read when rigging integrated modules:
                utils.addHook(objName=self.toCtrlHookGrp, hookType='ctrlHook')
                utils.addHook(objName=self.toScalableHookGrp, hookType='scalableHook')
                utils.addHook(objName=self.toStaticHookGrp, hookType='staticHook')
                cmds.addAttr(self.toStaticHookGrp, longName="dpAR_name", dataType="string")
                cmds.addAttr(self.toStaticHookGrp, longName="dpAR_type", dataType="string")
                cmds.setAttr(self.toStaticHookGrp + ".dpAR_name", self.userGuideName, type="string")
                cmds.setAttr(self.toStaticHookGrp + ".dpAR_type", CLASS_NAME, type="string")
                # add module type counter value
                cmds.addAttr(self.toStaticHookGrp, longName='dpAR_count', attributeType='long', keyable=False)
                cmds.setAttr(self.toStaticHookGrp + '.dpAR_count', dpAR_count)
                # create a locator in order to avoid delete static group
                loc = cmds.spaceLocator(name=side + self.userGuideName + "_DO_NOT_DELETE")[0]
                cmds.parent(loc, self.toStaticHookGrp, absolute=True)
                cmds.setAttr(loc + ".visibility", 0)
                ctrls.setLockHide([loc], ['tx', 'ty', 'tz', 'rx', 'ry', 'rz', 'sx', 'sy', 'sz', 'v'])
                if hideJoints:
                    cmds.setAttr(self.toScalableHookGrp + ".visibility", 0)
                # delete duplicated group for side (mirror):
                cmds.delete(side + self.userGuideName + '_' + self.mirrorGrp)
            # finalize this rig:
            self.integratingInfo()
            cmds.select(clear=True)
        # delete UI (moduleLayout), GUIDE and moduleInstance namespace:
        self.deleteModule()
Exemplo n.º 54
0
def test_integration_1(manager):
    """
    1) Create a compound
    2) Register the compound
    3) Modify the compound
    4) Register a new version of the compound
    5) Rollback to the previous version
    6) Update to latest
    """

    def _test_compound_v1():
        """
        Validate the namespace actually contain v1 of our test compound.

        :param str namespace: The compound namespace
        """
        # Validate internal connections
        for src, dst in (
            ("foo:inputs.input1X", "foo:multiplyDivide1"),
            ("foo:multiplyDivide1.outputX", "foo:outputs.outputX"),
        ):
            cmds.isConnected(src, dst)

        # Validate external connections
        for src, dst in (
            ("testInn.translateX", "foo:inputs.input1X"),
            ("foo:outputs.outputX", "testOut.translateX"),
        ):
            cmds.isConnected(src, dst)

        # Validate scene content
        for dagpath in (
            "foo:inputs",
            "foo:inputs.input1X",
            "foo:multiplyDivide1",
            "foo:outputs",
            "foo:outputs.outputX",
        ):
            assert cmds.objExists(dagpath)

        for dagpath in ("foo:outputs.outputY",):
            assert not cmds.objExists(dagpath)

    def _test_compound_v2():
        for dagpath in (
            "foo:inputs",
            "foo:inputs.input1X",
            "foo:multiplyDivide1",
            "foo:outputs",
            "foo:outputs.outputX",
            "foo:outputs.outputY",
        ):
            assert cmds.objExists(dagpath)

    # 1) Create a simple network
    mult1 = pymel.createNode("multiplyDivide")

    # Create a compound from the network
    compound = create_from_nodes([mult1], namespace="foo")
    a = mult1.input1X
    compound.expose_input_attr(a)
    compound.expose_output_attr(mult1.outputX)

    # Create connections from outside the compound
    cmds.createNode("transform", name="testInn")
    cmds.createNode("transform", name="testOut")
    cmds.connectAttr("testInn.translateX", "foo:inputs.input1X")
    cmds.connectAttr("foo:outputs.outputX", "testOut.translateX")

    _test_compound_v1()

    # Register the compound?
    compound_def_1 = CompoundDefinition(
        name="compound_name", version="1.0.0", uid="compound_uid"
    )
    compound.set_metadata(dict(compound_def_1))
    manager.publish_compound(compound)

    # Modify the scene content
    compound.expose_output_attr(mult1.outputY)

    _test_compound_v2()

    # TODO: Error if the file does not end with .ma?

    compound_def_2 = CompoundDefinition(
        name="compound_name", version="1.0.1", uid="compound_uid"
    )
    compound.set_metadata(dict(compound_def_2))
    manager.publish_compound(compound)

    cmds.connectAttr("foo:outputs.outputY", "testOut.translateY")

    # Downgrade our compound
    manager.update_compound(compound, "1.0.0")

    _test_compound_v1()

    # Upgrade our compound
    manager.update_compound(compound)
    _test_compound_v2()

    # Verify that we can restore our in-memory registry
    new_registry = Registry()
    new_registry.parse_directory(manager.preferences.compound_location)

    assert manager.registry == new_registry
Exemplo n.º 55
0
def dupToCurveFlow():
    allSel = mc.ls(sl=True)
    count = len(allSel)
    if count < 2:
        om.MGlobal.displayError(
            'Please select some will follow Curve Objects and Curve...')
        return

    curveSel = mc.ls(sl=True, tail=1)
    if mc.nodeType(curveSel[0]) == 'transform':
        curveShape = mc.listRelatives(curveSel, shapes=True)
        if mc.nodeType(curveShape[0]) == 'nurbsCurve':
            shape = curveShape[0]
    elif mc.nodeType(curveSel[0]) == 'nurbsCurve':
        shape = curveSel[0]
    else:
        om.MGlobal.displayError('Please select lastest Curve...')
        return

    _min = mc.getAttr(shape + '.minValue')
    _max = mc.getAttr(shape + '.maxValue')

    objSel = allSel[:count - 1]
    for eachObj in objSel:
        if mc.attributeQuery('translate', node=eachObj, ex=True) == False:
            om.MGlobal.displayWarning(
                '%s Object have not "Transform" attribute,ingore it...' %
                eachObj)
            objSel.remove(eachObj)
        elif mc.attributeQuery('rotate', node=eachObj, ex=True) == False:
            om.MGlobal.displayWarning(
                '%s Object have not "Rotate" attribute,ingore it...' % eachObj)
            objSel.remove(eachObj)

    _length = _max - _min
    segment = _length / (len(objSel) - 1)

    if not mc.pluginInfo('dupToCurveFlowPlugin.py', q=True, l=True):
        mc.loadPlugin(
            r'\\octvision.com\cg\TD\Maya\2012\Plugins\dupToCurveFlowPlugin.py')

    icNode = mc.createNode('ic_dupToCurveFlow')
    mc.connectAttr(shape + '.local', icNode + '.inCurve', f=True)
    for i in range(0, len(objSel)):
        mc.getAttr(icNode + '.outTranslate[%i]' % i)
        mc.getAttr(icNode + '.outRotate[%i]' % i)
        if not mc.attributeQuery('param', node=objSel[i], ex=True):
            mc.addAttr(objSel[i], ln='param', at='double')
            mc.setAttr(objSel[i] + '.param', e=True, keyable=True)

        mc.connectAttr(objSel[i] + '.param',
                       icNode + '.inParam[%i]' % i,
                       f=True)
        mc.connectAttr(icNode + '.outTranslate[%i].outTranslateX' % i,
                       objSel[i] + '.translateX',
                       f=True)
        mc.connectAttr(icNode + '.outTranslate[%i].outTranslateY' % i,
                       objSel[i] + '.translateY',
                       f=True)
        mc.connectAttr(icNode + '.outTranslate[%i].outTranslateZ' % i,
                       objSel[i] + '.translateZ',
                       f=True)
        mc.connectAttr(icNode + '.outRotate[%i].outRotateX' % i,
                       objSel[i] + '.rotateX',
                       f=True)
        mc.connectAttr(icNode + '.outRotate[%i].outRotateY' % i,
                       objSel[i] + '.rotateY',
                       f=True)
        mc.connectAttr(icNode + '.outRotate[%i].outRotateZ' % i,
                       objSel[i] + '.rotateZ',
                       f=True)
        mc.setAttr(objSel[i] + '.param', segment * i)
Exemplo n.º 56
0
	def create(self):
		sGrp = transforms.createTransformNode(naming.oName(sType = 'grp', sSide = self._sSide, sPart = '%s%sRig' %(self._sPart, self._sName), iIndex = self._iIndex).sName, lLockHideAttrs = ['tx', 'ty', 'tz', 'rx', 'ry', 'rz', 'sx', 'sy', 'sz', 'v'], sParent = self._sConnectInJnt)
		sGrpCtrl = transforms.createTransformNode(naming.oName(sType = 'grp', sSide = self._sSide, sPart = '%s%sCtrl' %(self._sPart, self._sName), iIndex = self._iIndex).sName, lLockHideAttrs = ['tx', 'ty', 'tz', 'rx', 'ry', 'rz', 'sx', 'sy', 'sz', 'v'], sParent = self._sConnectInCtrl)
		sParent_jnt = sGrp
		lJnts = []
		for i, sBpJnt in enumerate(self._lBpJnts):
			oJntName = naming.oName(sBpJnt)
			oJntName.sType = 'jnt'
			sJnt = joints.createJntOnExistingNode(sBpJnt, sBpJnt, oJntName.sName, sParent = sParent_jnt)
			lJnts.append(sJnt)
			sParent_jnt = sJnt
		
		## rig each limb
		iJnts_min = len(lJnts)
		dRigLimbs = {}
		lCtrls = []
		for sMode in self._dRigLimbs.keys():
			dRigLimbs_each = {sMode: {
										'iIndex': 0,
										'class': None,
										'lJnts': None,
											}}
			oLimb = self._dRigLimbs[sMode]['class'](sSide = self._sSide, iIndex = self._iIndex)
			oLimb._lBpJnts = self._lBpJnts
			oLimb._sConnectInJnt = sGrp
			oLimb._sConnectInCtrl = sGrpCtrl
			oLimb.create()
			
			if self._dRigLimbs[sMode].has_key('iIndex'):
				dRigLimbs_each[sMode]['iIndex'] = self._dRigLimbs[sMode]['iIndex']
			else:
				dRigLimbs_each[sMode]['iIndex'] = namingDict.spaceDict[sMode]

			dRigLimbs_each[sMode]['class'] = oLimb

			if hasattr(oLimb, 'lJntsOutput'):
				dRigLimbs_each[sMode]['lJnts'] = oLimb.lJntsOutput
				if len(oLimb.lJntsOutput) < iJnts_min:
					iJnts_min = len(oLimb.lJntsOutput)
			else:
				dRigLimbs_each[sMode]['lJnts'] = oLimb.lJnts
				if len(oLimb.lJnts) < iJnts_min:
					iJnts_min = len(oLimb.lJnts)

			lCtrls += oLimb.lCtrls

			dRigLimbs.update(dRigLimbs_each)

		## add shape node
		sCtrlShape = naming.oName(sType = 'ctrl', sSide = self._sSide, sPart = self._sPart, iIndex = self._iIndex).sName
		controls.addCtrlShape(lCtrls, sCtrlShape, bVis = False)

		## blend constraint joints
		for i in range(0, iJnts_min):
			lDrivers = []
			#dDrivers = {'cog': {'iIndex': 0, 'sOutput': 'ctrl_m_cog'}}
			dDrivers = {}
			for sMode in dRigLimbs.keys():
				dDriver_each = {sMode: {'iIndex': dRigLimbs[sMode]['iIndex'], 'sOutput': dRigLimbs[sMode]['lJnts'][i]}}
				dDrivers.update(dDriver_each)
			constraints.spaceConstraint(dDrivers, lJnts[i], sType = self._sConstraintType, sCtrl = sCtrlShape, bMaintainOffset = False, sName = self._sName, lDefaultVal = None)

		## vis switch
		sCondition = naming.oName(sType = 'condition', sSide = self._sSide, sPart = '%s%s%sSelector' %(self._sPart, self._sName[0].upper(), self._sName[1:]), iIndex = self._iIndex).sName
		cmds.createNode('condition', name = sCondition)
		cmds.connectAttr('%s.%sModeA' %(sCtrlShape, self._sName), '%s.colorIfTrueR' %sCondition)
		cmds.connectAttr('%s.%sModeB' %(sCtrlShape, self._sName), '%s.colorIfFalseR' %sCondition)
		cmds.connectAttr('%s.%sModeBlend' %(sCtrlShape, self._sName), '%s.firstTerm' %sCondition)
		cmds.setAttr('%s.secondTerm' %sCondition, 0.5)
		cmds.setAttr('%s.operation' %sCondition, 4)

		lAttrs = []
		lEnumIndex = []
		for sMode in dRigLimbs.keys():
			lAttrs.append('%s.v' %dRigLimbs[sMode]['class'].sGrpCtrl)
			lEnumIndex.append(dRigLimbs[sMode]['iIndex'])

		attributes.enumToMultiAttrs('outColorR', lAttrs, iEnumRange = len(lEnumIndex), lEnumIndex = lEnumIndex, sEnumObj = sCondition)
		#enumToMultiAttrs(sEnumAttr, lAttrs, iEnumRange = 2, lEnumIndex = None, lValRange = [[0,1]], sEnumObj = None)

		#### control connect out node
		sConnectOutCtrl = transforms.createTransformNode(naming.oName(sType = 'grp', sSide = self._sSide, sPart = '%s%sConnectOutCtrl' %(self._sPart, self._sName), iIndex = self._iIndex).sName, lLockHideAttrs = ['tx', 'ty', 'tz', 'rx', 'ry', 'rz', 'sx', 'sy', 'sz', 'v'], sParent = sGrpCtrl, bVis = True)
		constraints.constraint([lJnts[-1], sConnectOutCtrl], sType = 'parent', bForce = True, bMaintainOffset = True)

		lCtrls = sCtrlShape

		## write rig info
		sModuleNodes = ''
		sModuleIndex = ''
		for sMode in dRigLimbs.keys():
			sModuleNodes += '%s,' %dRigLimbs[sMode]['class'].sModuleNode
			sModuleIndex += '%d,' %dRigLimbs[sMode]['iIndex']

		sString_lJnts = self._convertListToString(lJnts)
		sString_lCtrls = self._convertListToString(lCtrls)
		lRigInfo = ['blendModeRig', sGrp, self._sConnectInJnt, self._sConnectInCtrl, lJnts[-1], sConnectOutCtrl, sString_lJnts, sString_lCtrls, sGrpCtrl, sModuleNodes[:-1], sModuleIndex[:-1]]
		lAttrs = ['sModuleType', 'sModuleNode', 'sConnectInJnt', 'sConnectInCtrl', 'sConnectOutJnt', 'sConnectOutCtrl', 'lJnts', 'lCtrls', 'sGrpCtrl', 'lModuleNodes', 'lModuleIndex']

		self._writeRigInfo(sGrp, lRigInfo, lAttrs)

		self._getRigInfo(sGrp)
    def testAnimNurbsPlaneWrite(self, wfg=False):

        ret = MayaCmds.nurbsPlane(p=(0, 0, 0), ax=(0, 1, 0), w=1, lr=1, d=3,
            u=5, v=5, ch=0)
        name = ret[0]

        MayaCmds.lattice(name, dv=(4, 5, 4), oc=True)
        MayaCmds.select('ffd1Lattice.pt[1:2][0:4][1:2]', r=True)

        MayaCmds.currentTime(1, update=True)
        MayaCmds.setKeyframe()
        MayaCmds.currentTime(24, update=True)
        MayaCmds.setKeyframe()
        MayaCmds.currentTime(12, update=True)
        MayaCmds.move( 0, 0.18, 0, r=True)
        MayaCmds.scale( 2.5, 1.0, 2.5, r=True)
        MayaCmds.setKeyframe()

        MayaCmds.curveOnSurface(name,
            uv=((0.597523,0), (0.600359,0.271782), (0.538598,0.564218),
                (0.496932,0.779936),  (0.672153,1)),
            k=(0,0,0,0.263463,0.530094,0.530094,0.530094))

        curvename = MayaCmds.curveOnSurface(name,
            uv=((0.170718,0.565967), (0.0685088,0.393034), (0.141997,0.206296),
                (0.95,0.230359), (0.36264,0.441381), (0.251243,0.569889)),
            k=(0,0,0,0.200545,0.404853,0.598957,0.598957,0.598957))
        MayaCmds.closeCurve(curvename, ch=1, ps=1, rpo=1, bb=0.5, bki=0, p=0.1,
            cos=1)

        MayaCmds.trim(name, lu=0.23, lv=0.39)

        degreeU = MayaCmds.getAttr(name+'.degreeU')
        degreeV = MayaCmds.getAttr(name+'.degreeV')
        spansU  = MayaCmds.getAttr(name+'.spansU')
        spansV  = MayaCmds.getAttr(name+'.spansV')
        formU   = MayaCmds.getAttr(name+'.formU')
        formV   = MayaCmds.getAttr(name+'.formV')
        minU    = MayaCmds.getAttr(name+'.minValueU')
        maxU    = MayaCmds.getAttr(name+'.maxValueU')
        minV    = MayaCmds.getAttr(name+'.minValueV')
        maxV    = MayaCmds.getAttr(name+'.maxValueV')

        MayaCmds.createNode('surfaceInfo')
        MayaCmds.connectAttr(name+'.worldSpace', 'surfaceInfo1.inputSurface',
            force=True)

        MayaCmds.currentTime(1, update=True)
        controlPoints = MayaCmds.getAttr('surfaceInfo1.controlPoints[*]')
        knotsU = MayaCmds.getAttr('surfaceInfo1.knotsU[*]')
        knotsV = MayaCmds.getAttr('surfaceInfo1.knotsV[*]')

        MayaCmds.currentTime(12, update=True)
        controlPoints2 = MayaCmds.getAttr('surfaceInfo1.controlPoints[*]')
        knotsU2 = MayaCmds.getAttr('surfaceInfo1.knotsU[*]')
        knotsV2 = MayaCmds.getAttr('surfaceInfo1.knotsV[*]')

        if wfg:
            self.__files.append(util.expandFileName('testAnimNurbsPlane.abc'))

            MayaCmds.AbcExport(j='-fr 1 24 -frs -0.25 -frs 0.0 -frs 0.25 -wfg -root %s -file %s' % (name, self.__files[-1]))

            # reading test
            MayaCmds.AbcImport(self.__files[-1], mode='open')
        else:
            self.__files.append(util.expandFileName('testAnimNurbsPlane.abc'))
            self.__files.append(util.expandFileName('testAnimNurbsPlane01_14.abc'))
            self.__files.append(util.expandFileName('testAnimNurbsPlane15_24.abc'))

            MayaCmds.AbcExport(j='-fr 1 14 -root %s -file %s' % (name, self.__files[-2]))
            MayaCmds.AbcExport(j='-fr 15 24 -root %s -file %s' % (name, self.__files[-1]))

            # use AbcStitcher to combine two files into one
            subprocess.call(self.__abcStitcher + self.__files[-3:])

            # reading test
            MayaCmds.AbcImport(self.__files[-3], mode='open')

        self.failUnlessEqual(degreeU, MayaCmds.getAttr(name+'.degreeU'))
        self.failUnlessEqual(degreeV, MayaCmds.getAttr(name+'.degreeV'))
        self.failUnlessEqual(spansU, MayaCmds.getAttr(name+'.spansU'))
        self.failUnlessEqual(spansV, MayaCmds.getAttr(name+'.spansV'))
        self.failUnlessEqual(formU, MayaCmds.getAttr(name+'.formU'))
        self.failUnlessEqual(formV, MayaCmds.getAttr(name+'.formV'))
        self.failUnlessEqual(minU, MayaCmds.getAttr(name+'.minValueU'))
        self.failUnlessEqual(maxU, MayaCmds.getAttr(name+'.maxValueU'))
        self.failUnlessEqual(minV, MayaCmds.getAttr(name+'.minValueV'))
        self.failUnlessEqual(maxV, MayaCmds.getAttr(name+'.maxValueV'))

        MayaCmds.createNode('surfaceInfo')
        MayaCmds.connectAttr(name+'.worldSpace', 'surfaceInfo1.inputSurface',
            force=True)

        MayaCmds.currentTime(1, update=True)
        errmsg = "At frame #1, Nurbs Plane's control point #%d.%s not equal"
        for i in range(0, len(controlPoints)):
            cp1 = controlPoints[i]
            cp2 = MayaCmds.getAttr('surfaceInfo1.controlPoints[%d]' % (i))
            self.failUnlessAlmostEqual(cp1[0], cp2[0][0], 3, errmsg % (i, 'x'))
            self.failUnlessAlmostEqual(cp1[1], cp2[0][1], 3, errmsg % (i, 'y'))
            self.failUnlessAlmostEqual(cp1[2], cp2[0][2], 3, errmsg % (i, 'z'))

        errmsg = "At frame #1, Nurbs Plane's control knotsU #%d not equal"
        for i in range(0, len(knotsU)):
            ku1 = knotsU[i]
            ku2 = MayaCmds.getAttr('surfaceInfo1.knotsU[%d]' % (i))
            self.failUnlessAlmostEqual(ku1, ku2, 3, errmsg % (i))

        errmsg = "At frame #1, Nurbs Plane's control knotsV #%d not equal"
        for i in range(0, len(knotsV)):
            kv1 = knotsV[i]
            kv2 = MayaCmds.getAttr('surfaceInfo1.knotsV[%d]' % (i))
            self.failUnlessAlmostEqual(kv1, kv2, 3, errmsg % (i))

        MayaCmds.currentTime(12, update=True)
        errmsg = "At frame #12, Nurbs Plane's control point #%d.%s not equal"
        for i in range(0, len(controlPoints2)):
            cp1 = controlPoints2[i]
            cp2 = MayaCmds.getAttr('surfaceInfo1.controlPoints[%d]' % (i))
            self.failUnlessAlmostEqual(cp1[0], cp2[0][0], 3, errmsg % (i, 'x'))
            self.failUnlessAlmostEqual(cp1[1], cp2[0][1], 3, errmsg % (i, 'y'))
            self.failUnlessAlmostEqual(cp1[2], cp2[0][2], 3, errmsg % (i, 'z'))

        errmsg = "At frame #12, Nurbs Plane's control knotsU #%d not equal"
        for i in range(0, len(knotsU2)):
            ku1 = knotsU2[i]
            ku2 = MayaCmds.getAttr('surfaceInfo1.knotsU[%d]' % (i))
            self.failUnlessAlmostEqual(ku1, ku2, 3, errmsg % (i))

        errmsg = "At frame #12, Nurbs Plane's control knotsV #%d not equal"
        for i in range(0, len(knotsV2)):
            kv1 = knotsV2[i]
            kv2 = MayaCmds.getAttr('surfaceInfo1.knotsV[%d]' % (i))
            self.failUnlessAlmostEqual(kv1, kv2, 3, errmsg % (i))

        MayaCmds.currentTime(24, update=True)
        errmsg = "At frame #24, Nurbs Plane's control point #%d.%s not equal"
        for i in range(0, len(controlPoints)):
            cp1 = controlPoints[i]
            cp2 = MayaCmds.getAttr('surfaceInfo1.controlPoints[%d]' % (i))
            self.failUnlessAlmostEqual(cp1[0], cp2[0][0], 3, errmsg % (i, 'x'))
            self.failUnlessAlmostEqual(cp1[1], cp2[0][1], 3, errmsg % (i, 'y'))
            self.failUnlessAlmostEqual(cp1[2], cp2[0][2], 3, errmsg % (i, 'z'))

        errmsg = "At frame #24, Nurbs Plane's control knotsU #%d not equal"
        for i in range(0, len(knotsU)):
            ku1 = knotsU[i]
            ku2 = MayaCmds.getAttr('surfaceInfo1.knotsU[%d]' % (i))
            self.failUnlessAlmostEqual(ku1, ku2, 3, errmsg % (i))

        errmsg = "At frame #24, Nurbs Plane's control knotsV #%d not equal"
        for i in range(0, len(knotsV)):
            kv1 = knotsV[i]
            kv2 = MayaCmds.getAttr('surfaceInfo1.knotsV[%d]' % (i))
            self.failUnlessAlmostEqual(kv1, kv2, 3, errmsg % (i))
Exemplo n.º 58
0
mc.unloadPlugin("dsRaycast")
# mc.unloadPlugin('drawVector')
# mc.loadPlugin(os.path.join(MAYA_APP_DIR, 'scripts\dsRaycast\dsDrawVector\plugins\dsDrawVector.py'))
mc.loadPlugin(
    os.path.join(MAYA_APP_DIR, 'scripts/dsRaycast/plugins/dsRaycast.py'))

###### Test #########
# Basic test
mesh = mc.polyPlane()[0]
mc.move(0, 4, 0, mesh)
mc.scale(50, 50, 50, mesh)
source = mc.spaceLocator(n='source')[0]
mc.move(0, 10, 0, source)
aim = mc.spaceLocator(n='aim')[0]

dsRaycast = mc.createNode('dsRaycast')

mc.connectAttr(mesh + '.worldMesh', dsRaycast + '.tm')
mc.connectAttr(source + '.worldMatrix', dsRaycast + '.srs')
mc.connectAttr(aim + '.t', dsRaycast + '.aim')

testObj = mc.polyCube(n='testBoi00')

mc.connectAttr(dsRaycast + ".hitPoint", testObj[0] + ".t")
'''
#Wheel test
mesh = mc.polyPlane()
srsLocs =[]
wheelGeo =[]
meshShape = mc.listRelatives(mesh, type='shape')[0]
mc.move(0, 2, 0, mesh[0])
Exemplo n.º 59
0
def build(startJoint,
          endJoint,
          ikSwitchCtrl='',
          ikSwitchAttr='spineIk',
          ctrlScale=1.0,
          prefix='cn_spine'):
    '''
	Build spine rig base.
	@param startJoint: Start joint of the FK spine
	@type startJoint: str
	@param endJoint: End joint of the FK spine
	@type endJoint: str
	@param ikSwitchCtrl: Control to store the IK switch attribute
	@type ikSwitchCtrl: str
	@param ikSwitchAttr: IK switch attribute
	@type ikSwitchAttr: str
	@param prefix: Name prefix for new nodes
	@type prefix: str
	'''
    # ==========
    # - Checks -
    # ==========

    if not mc.objExists(startJoint):
        raise Exception('Start joint "' + startJoint + '" does not exist!')
    if not mc.objExists(endJoint):
        raise Exception('End joint "' + endJoint + '" does not exist!')
    if ikSwitchCtrl and not mc.objExists(ikSwitchCtrl):
        raise Exception('IK switch control "' + ikSwitchCtrl +
                        '" does not exist!')

    # ===================
    # - Configure Spine -
    # ===================

    # Control Scale
    fkCtrlScale = 1.5 * ctrlScale
    spineCtrlScale = 1 * ctrlScale

    # ==========================
    # - Build Module Structure -
    # ==========================

    # Create control group
    ctrl_grp = mc.group(em=True, n=prefix + '_ctrl_grp', w=True)

    # Create rig group
    rig_grp = mc.group(em=True, n=prefix + '_rig_grp', w=True)

    # Create skel group
    skel_grp = mc.group(em=True, n=prefix + '_skel_grp', w=True)

    # Create module group
    module = mc.group(em=True, n=prefix + '_module')
    mc.parent([ctrl_grp, rig_grp, skel_grp], module)

    # - Uniform Scale -
    mc.addAttr(module, ln='uniformScale', min=0.001, dv=1.0)
    mc.connectAttr(module + '.uniformScale', ctrl_grp + '.scaleX')
    mc.connectAttr(module + '.uniformScale', ctrl_grp + '.scaleY')
    mc.connectAttr(module + '.uniformScale', ctrl_grp + '.scaleZ')
    mc.connectAttr(module + '.uniformScale', skel_grp + '.scaleX')
    mc.connectAttr(module + '.uniformScale', skel_grp + '.scaleY')
    mc.connectAttr(module + '.uniformScale', skel_grp + '.scaleZ')

    # =========================
    # - Determine Joint Scale -
    # =========================

    # Get joint list
    spineJnts = glTools.utils.joint.getJointList(startJoint, endJoint)
    jntLen = 0.0
    for jnt in spineJnts:
        cJntLen = glTools.utils.joint.length(jnt)
        if cJntLen > jntLen: jntLen = cJntLen

    # =====================
    # - Create FK Joints -
    # =====================

    # Create Joints
    fkJnts = glTools.utils.joint.duplicateChain(startJoint,
                                                endJoint,
                                                prefix=prefix + '_fk')

    # Create Control Shapes
    fkJntGrps = []
    fkJntShapes = []
    for i in range(len(fkJnts) - 1):
        # Add control shape
        jntShape = glTools.tools.controlBuilder.controlShape(fkJnts[i],
                                                             'circle',
                                                             rotate=[0, 90, 0],
                                                             scale=jntLen *
                                                             fkCtrlScale)
        # Add joint buffer
        jntGrp = glTools.utils.joint.group(fkJnts[i])
        # Tag controls
        glTools.rig.utils.tagCtrl(fkJnts[i], 'primary')
        # Append arrays
        fkJntGrps.append(jntGrp)
        fkJntShapes.extend(jntShape)

    # =======================
    # - Create Spine Joints -
    # =======================

    # For each joint
    spineJntGrps = []
    spineJntShapes = []
    for i in range(len(spineJnts)):
        # Add control curves
        jntShape = glTools.tools.controlBuilder.controlShape(spineJnts[i],
                                                             'square',
                                                             rotate=[0, 90, 0],
                                                             scale=jntLen *
                                                             spineCtrlScale)
        # Add joint buffer
        jntGrp = glTools.utils.joint.group(spineJnts[i])
        # Tag controls
        glTools.rig.utils.tagCtrl(spineJnts[i], 'primary')
        # Append arrays
        spineJntGrps.append(jntGrp)
        spineJntShapes.extend(jntShape)

    # =======================
    # - Parent Spine Joints -
    # =======================

    for i in range(len(spineJnts)):
        mc.parent(spineJntGrps[i], fkJnts[i])

    # =======================
    # - Create Attach Joint -
    # =======================

    mc.select(cl=True)

    # Create attach
    attachJoint = mc.joint(n=prefix + '_attachA_jnt')
    attachJointGrp = glTools.utils.joint.group(attachJoint)
    mc.delete(mc.parentConstraint(spineJnts[0], attachJointGrp))

    # Attach joint display
    mc.setAttr(attachJoint + '.overrideEnabled', 1)
    mc.setAttr(attachJoint + '.overrideLevelOfDetail', 1)

    # Parent attach joint
    mc.parent(fkJntGrps[0], attachJoint)
    mc.parent(attachJointGrp, skel_grp)

    # ========================
    # - Setup IK Mode Switch -
    # ========================

    if ikSwitchCtrl:

        # Check switch attribute
        if not ikSwitchAttr: ikSwitchAttr = 'spineIk'
        if not mc.objExists(ikSwitchCtrl + '.' + ikSwitchAttr):
            mc.addAttr(ikSwitchCtrl,
                       ln=ikSwitchAttr,
                       at='long',
                       min=0,
                       max=1,
                       dv=0,
                       k=True)

        # Create Parent Constraints
        ikConstraint1 = mc.parentConstraint([spineJnts[0], spineJnts[-1]],
                                            spineJntGrps[1],
                                            mo=True)[0]
        ikConstraint2 = mc.parentConstraint([spineJnts[0], spineJnts[-1]],
                                            spineJntGrps[2],
                                            mo=True)[0]

        # Connect to switch
        ikWeightMult1 = mc.createNode('multDoubleLinear',
                                      n=prefix + '_ikWeight1_multDoubleLinear')
        ikWeightMult2 = mc.createNode('multDoubleLinear',
                                      n=prefix + '_ikWeight1_multDoubleLinear')
        mc.connectAttr(ikSwitchCtrl + '.' + ikSwitchAttr,
                       ikWeightMult1 + '.input1')
        mc.connectAttr(ikSwitchCtrl + '.' + ikSwitchAttr,
                       ikWeightMult2 + '.input1')
        mc.setAttr(ikWeightMult1 + '.input2', 0.666)
        mc.setAttr(ikWeightMult2 + '.input2', 0.333)

        # Connect to constraint
        ikWeightAlias1 = mc.parentConstraint(ikConstraint1, q=True, wal=True)
        ikWeightAlias2 = mc.parentConstraint(ikConstraint2, q=True, wal=True)
        mc.connectAttr(ikWeightMult1 + '.output',
                       ikConstraint1 + '.' + ikWeightAlias1[0],
                       f=True)
        mc.connectAttr(ikWeightMult2 + '.output',
                       ikConstraint1 + '.' + ikWeightAlias1[1],
                       f=True)
        mc.connectAttr(ikWeightMult1 + '.output',
                       ikConstraint2 + '.' + ikWeightAlias1[1],
                       f=True)
        mc.connectAttr(ikWeightMult2 + '.output',
                       ikConstraint2 + '.' + ikWeightAlias1[0],
                       f=True)

    # ======================
    # - Set Channel States -
    # ======================

    chStateUtil = glTools.utils.channelState.ChannelState()
    chStateUtil.setFlags([0, 0, 0, 0, 0, 0, 0, 0, 0, 1], objectList=spineJnts)
    chStateUtil.setFlags([2, 2, 2, 2, 2, 2, 2, 2, 2, 1],
                         objectList=spineJntGrps)
    chStateUtil.setFlags([0, 0, 0, 0, 0, 0, 0, 0, 0, 1], objectList=fkJnts)
    chStateUtil.setFlags([2, 2, 2, 2, 2, 2, 2, 2, 2, 1], objectList=fkJntGrps)
    chStateUtil.setFlags([2, 2, 2, 2, 2, 2, 2, 2, 2, 1],
                         objectList=[attachJointGrp])
    chStateUtil.setFlags([1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
                         objectList=[attachJoint])
    chStateUtil.setFlags([2, 2, 2, 2, 2, 2, 2, 2, 2, 1],
                         objectList=[module, ctrl_grp, rig_grp, skel_grp])

    # =================
    # - Return Result -
    # =================

    return [module, attachJoint]
Exemplo n.º 60
0
srcJnt = selLs[0]
trgGeos = selLs[1:]

for geo in trgGeos:
	#geoRpInWs = cmds.xform(geo, q = True, rp = True, ws = True)
	geoJnt = cmds.duplicate(srcJnt, n = geo + '_jnt')
	#cmds.xform(geoJnt, t = geoRpInWs, ws = True)
	
	cmds.skinCluster(geoJnt, geo, mi = 4, dr = 4, tsb = True, omi = False, nw = 1)
	

autoGrps = cmds.ls(sl = True)
for i in xrange(len(autoGrps)):
	if i == 0:
		continue
	pmaNode = cmds.createNode('plusMinusAverage', n = selLs[i] + '_offset_pma')
	cmds.connectAttr(autoGrps[i-1] + '.rotateY', pmaNode + '.input1D[0]')
	cmds.connectAttr('flip_ctrl' + '.offset', pmaNode + '.input1D[2]')
	cmds.connectAttr(pmaNode + '.output1D', autoGrps[i] + '.rotateY')
	cmds.setAttr(pmaNode + '.operation', 2)


geos = cmds.ls(sl = True)
for geo in geos:
	bendGeo = cmds.duplicate(geo, n = geo + '_bend_geo')[0]
	cmds.parent(bendGeo, w = True)
	bsNode = cmds.blendShape(bendGeo, geo, frontOfChain = True)[0]
	cmds.setAttr(bsNode + '.' + bendGeo, 1)
	cmds.setAttr(bendGeo + '.visibility', False)

	bendHndl = cmds.nonLinear(bendGeo, type = 'bend', lowBound = 0, highBound = 1, curvature = 0)[1]