Exemplo n.º 1
0
def connectSkins(abc, asset):
    cmds.select("%s:mesh_*" % asset)
    sel = cmds.ls(sl=True, type="transform")
    selShape = cmds.listRelatives(shapes=True)
    selShapeLong = cmds.listRelatives(shapes=True, fullPath=True)

    list = cmds.listConnections(abc + ".outPolyMesh", connections=True, plugs=True)
    sourceList = []

    for l in list:
        if abc in l:
            sourceList.append(l)

    for source in sourceList:
        connect = cmds.listConnections(source, connections=True, plugs=True)
        for c in connect:
            if not abc in c:
                cleanName = c.rsplit("|",1)[-1].rsplit(":",1)[-1].rsplit(".",1)[0]
                attr = "." + c.rsplit("|",1)[-1].rsplit(".",1)[-1]
                if cleanName in sel:
                    print "sel"
                temp = selShape[0].split(":",1)[0]
                if ("%s:%s" % (temp, cleanName)) in selShape:
                    index = selShape.index("%s:%s" % (temp, cleanName))
                    cmds.connectAttr(connect[0], selShapeLong[index] + attr, force=True)
Exemplo n.º 2
0
def keyToOn():
    controller = mc.ls(sl=True)[0]

    channelBox = mel.eval('global string $gChannelBoxName; $temp=$gChannelBoxName;')	#fetch maya's main channelbox
    attrs = mc.channelBox(channelBox, q=True, sma=True)

    if attrs:
        channel = controller + "." + attrs[0]
        constraint = mc.listConnections(channel, type="constraint")[0]
        currentTime = mc.currentTime( query=True )

        # save rest pose on constraint
        # mc.currentTime(currentTime-1)
        constraintChannels = mc.listConnections(constraint, type="animCurve")
        mc.parentConstraint(controller, constraint, edit=True, maintainOffset=True)
        for i in constraintChannels:
            value = mc.getAttr(mc.listConnections(i, plugs=True)[0])
            setKeyframe(mc.listConnections(i, plugs=True)[0], currentTime, value)

        # set key on 1 for controller
        setKeyframe(channel, currentTime-1, value=0)
        setKeyframe(channel, currentTime, value=1)

        # mc.currentTime( currentTime )
    else:
        mc.warning("Select constrain channel!")
Exemplo n.º 3
0
    def __init__( self, fullAttrName ):
        
        self.className = 'AnimCurveForBake'
        
        nodeName, attr = fullAttrName.split( '.' )
        attrType = cmds.attributeQuery( attr, node=nodeName, attributeType=1 )
        
        self.nodeType = ''
        if attrType == 'doubleLinear':
            self.nodeType = 'animCurveTL'
        elif attrType == 'doubleAngle':
            self.nodeType = 'animCurveTA'
        else:
            self.nodeType = 'animCurveTU'

        self.attrName     = fullAttrName
        self.times  = []
        self.values = []

        self.connectionExists = True
        if not cmds.listConnections( fullAttrName, s=1, d=0 ):
            node, attr = fullAttrName.split( '.' )
            parentAttrs = cmds.attributeQuery( attr, node=node, listParent=1 )
            if parentAttrs:
                if cmds.listConnections( node+'.'+parentAttrs[0] ):pass
                else:
                    self.connectionExists = False
                    self.times.append( 1 )
                    self.values.append( cmds.getAttr( fullAttrName ) )
            else:
                self.connectionExists = False
                self.times.append( 1 )
                self.values.append( cmds.getAttr( fullAttrName ) )
Exemplo n.º 4
0
def getKeyAttrConnectedChildren( topObj ):
    
    children = cmds.listRelatives( topObj, c=1, ad=1, f=1 )
    children.append( topObj )
    
    targetChildren = []
    targetCons = []
    for child in children:
        if not cmds.nodeType( child ) in ['joint', 'transform']: continue
        listAttrs = cmds.listAttr( child, k=1 )
        for attr in listAttrs:
            cons = cmds.listConnections( child+'.'+ attr, s=1, d=0 )
            if cons:
                targetChildren.append( child )
                targetCons += cons
            else:
                parentAttrs = cmds.attributeQuery( attr, node=child, listParent = 1 )
                if parentAttrs:
                    cons= cmds.listConnections( child+'.'+parentAttrs[0], s=1, d=0 )
                    if cons:
                        targetChildren.append( child )
                        targetCons += cons
    
    targetChildren = list( set( targetChildren ) )
    targetCons = list( set( targetCons ) )
    return targetChildren, targetCons
Exemplo n.º 5
0
def getSkinClusterNode(obj):
    shapes = []
    objSets = []
    connections = []
    skinClusters = []

    shapes = cmds.listRelatives(obj, shapes=True)
    if shapes and len(shapes) > 0: #found shape node
        directSkinClusters = cmds.listConnections(shapes[0], type='skinCluster')
        if directSkinClusters:
            print '1'
            skinClusters.append(directSkinClusters[0])
        else:
            print '2'
            objSets = cmds.listConnections(shapes[0], type='objectSet')
            if objSets and len(objSets) > 0: #found objectSet node
                print objSets
                for objSet in objSets:
                    connections = cmds.listConnections(objSet, type='skinCluster')
                    if connections and len(connections) > 0: #found skinCluster node
                        print '4'
                        if not connections[0] in skinClusters:
                            skinClusters.append(connections[0])
                            
    if len(skinClusters) > 1:
        print "more than one skinClusters found"
    else:
        return skinClusters[0]
Exemplo n.º 6
0
 def test_connectionsTo_MetaNodes_child(self):   
     '''
     Test how the code handles connections to other MetaNodes
     '''
     facialNode=r9Meta.MetaFacialRig(name='FacialNode')
     self.MClass.connectChild(facialNode,'Facial')
     
     assert self.MClass.Facial.mNode=='FacialNode'
     assert isinstance(self.MClass.Facial, r9Meta.MetaFacialRig)
     assert self.MClass.hasAttr('Facial')
     assert not facialNode.hasAttr('Facial')
     assert facialNode.hasAttr('MetaClass_Test')
     assert cmds.listConnections('%s.Facial' % self.MClass.mNode,c=True,p=True)==['MetaClass_Test.Facial', 
                                                                                  'FacialNode.MetaClass_Test'] 
     #test disconnect call
     self.MClass.disconnectChild(self.MClass.Facial, deleteSourcePlug=True, deleteDestPlug=True)
     assert not self.MClass.hasAttr('Facial')
     assert not facialNode.hasAttr('MetaClass_Test')       
     
     #test the additional attr flag
     self.MClass.connectChild(facialNode,'parentAttr','childAttr')  
     assert cmds.listConnections('%s.parentAttr' % self.MClass.mNode,c=True,p=True)==['MetaClass_Test.parentAttr', 
                                                                                  'FacialNode.childAttr']
     self.MClass.disconnectChild(self.MClass.parentAttr, deleteSourcePlug=True, deleteDestPlug=True)
     assert not self.MClass.hasAttr('parentAttr')
     assert not facialNode.hasAttr('childAttr')  
Exemplo n.º 7
0
 def removeLayTex(self, argsv):
     # get shapes of selection:
     args = cmds.ls(sl=1)
     shapesInSel = cmds.ls(dag=1,o=1,s=1,sl=1)
     shapeIndex = 0
     for arg in args :
         # get shading groups from shapes:
         shadingGrps = cmds.listConnections(shapesInSel[shapeIndex],type='shadingEngine')
         # get the shaders:
         shaders = cmds.ls(cmds.listConnections(shadingGrps),materials=1) 
         shader = shaders[0]
         #print cmds.listRelatives (p=True, arg)
         
         layeredTex = cmds.listConnections(shader, type='layeredTexture')
         layeredTex = layeredTex[0]
         
         if (not layeredTex == None):
             fileTex = cmds.listConnections(layeredTex, type='file')
             fileTex = fileTex[0]
             
             if (not fileTex == None):
                 cmds.delete(layeredTex)
                 print 'Connecting ' + shader + '.color to ' + fileTex + '.outColor'
                 cmds.connectAttr(fileTex+'.outColor', shader+'.color', f=1)
             else:
                 print ('Object ' + arg + ' does not have a file texture attached, skipping')
         else:
             print ('Object ' + arg + ' does not have a layered texture attached, skipping')
         shapeIndex += 1
Exemplo n.º 8
0
 def connectMovedDriverToFixedNode(self):
     
     targetMesh = self._targetMesh
     node = getBlendAndFixedShapeNode( targetMesh )
     
     attrs = []
     
     for driver, attr in self._driverAndAttr:
         value0 = cmds.getAttr( driver+'.'+attr )
         attrs.append( driver+'.'+attr )
     
     self._connectIndices = []
     self._connectWeights = []
     
     for attr in attrs:
         blendAndFixedShapeCons = cmds.listConnections( attr, type='blendAndFixedShape' )
         
         if not blendAndFixedShapeCons:
             targetIndex = fnc.getLastIndex( node+'.driverWeights' )+1
             cmds.connectAttr( attr, node+'.driverWeights[%d]' % targetIndex )
             self._connectIndices.append( targetIndex )
             self._connectWeights.append( value0 )
             continue
         
         if not node in blendAndFixedShapeCons:
             continue
         
         cons = cmds.listConnections( attr, p=1, c=1 )
         targetAttr = cons[1]
         
         connectedIndex = int( targetAttr.split('[')[1].replace(']','' ) )
         connectedValue = cmds.getAttr( cons[1] )
         self._connectIndices.append( connectedIndex )
         self._connectWeights.append( connectedValue )
Exemplo n.º 9
0
def memberList(layer, objectList=True):
    """
    Return a list of objects assigned to the specified layer
    @param obj: The layer to return an object list for
    @type obj: bool
    """
    # Check Layer
    if not isLayer(layer):
        raise Excpetion('Object "' + layer + '" is not a valid layer type!')

    # Get Member List
    members = []
    if isDisplayLayer(layer):
        members = cmds.listConnections(layer + '.drawInfo', s=False, d=True, sh=True)
    if isRenderLayer(layer):
        members = cmds.listConnections(layer + '.renderInfo', s=False, d=True, sh=True)
    if isAnimLayer(layer):
        members = cmds.listConnections(layer + '.dagSetMembers', s=True, d=False, sh=True)

    # Get List of Objects from Member List
    if objectList: members = cmds.ls(members, o=True)

    # Format Result
    if not members: members = []
    members = list(set(members))

    # Return Result
    return members
Exemplo n.º 10
0
def unloadReference( rfn ):
    #Get reference node.
    result = []
    if cmds.nodeType( rfn ) == "reference":
        rfn = rfn
    elif os.path.isfile( rfn ):
        rfn = cmds.referenceQuery( rfn, rfn=True )
    else:
        print "%s is not reference" % rfn
        return None
    relatives = referenceRelatives( rfn, onlyLoaded=True, parents=False )
    if cmds.referenceQuery( rfn, isLoaded=True ):
        if relatives:
            for i in range( len( relatives )-1, -1, -1 ):
                parent = cmds.referenceQuery( relatives[i], parent=True, filename=True )
                parent = parent and parent or "untitled"
                pm = cmds.listConnections( relatives[i], type="proxyManager" )
                if pm:
                    mcache = cmds.listConnections( "%s.proxyList" % pm[0], type="reference" )
                else:
                    mcache = [ relatives[i] ]
                for n in range( 0, len( mcache )):
                    if mcache[n] not in result:
                        result.append( mcache[n] )
                        pcache = cmds.referenceQuery( mcache[n], parent=True, filename=True )
                        pcache = pcache and pcache or "untitled"
                        if parent != pcache:
                            print "//Warning:\n//\treference is not valid:\n//\t{0} has parent {1}\n//\t{2} has parent {3}\n//\tplease check reference nodes connections.\n".format( relatives[i], parent, mcache[n], pcache )
                        if cmds.referenceQuery( mcache[n], isLoaded=True ):
                            print "unload reference: %s" % mcache[n]
                            cmds.file( unloadReference=mcache[n] )
    return result
Exemplo n.º 11
0
def makeActive( rfn ):
    """
    Make active all nested references.
    """
    result = []
    references = referenceRelatives( rfn, onlyLoaded=False, parents=False )
    if references:
        m_count = len( references )
        if m_count > 1:
            for i in range( 0, m_count ):
                if references[i] not in result:
                    result.append( references[i] )
                    pm = cmds.listConnections( "%s.proxyMsg" % references[i], type="proxyManager" )
                    if pm:
                        pm = pm[0]
                        #Get active reference.
                        rfn = ""
                        proxy = cmds.listConnections( "%s.proxyList" % pm, type="reference", source=False, destination=True )
                        if proxy:
                            for n in range( 0, len( proxy )):
                                if cmds.referenceQuery( proxy[n], isLoaded=True ):
                                    rfn = proxy[n]
                                    break
                        if rfn == "":
                            rfn = proxy[0]
                        #Deactivate all non active references.
                        active = cmds.listConnections( "%s.activeProxy" % pm, plugs=True )
                        if active:
                            for n in range( 0, len( active )):
                                cmds.disconnectAttr( "%s.activeProxy" % pm, active[n] )
                        #Make active reference.
                        lproxy = cmds.connectionInfo( "%s.proxyMsg" % rfn, sourceFromDestination=True )
                        if lproxy:
                            cmds.connectAttr( "%s.activeProxy" % pm, lproxy )
    return result
Exemplo n.º 12
0
def cleanupReference( rfn ):
    #Get reference node.
    if cmds.nodeType( rfn ) == "reference":
        rfn = rfn
    elif os.path.isfile( rfn ):
        rfn = cmds.referenceQuery( rfn, rfn=True )
    else:
        print "%s is not reference" % rfn
        return None
    references = []
    pm = cmds.listConnections( rfn, type="proxyManager" )
    if pm:
        references = cmds.listConnections( "%s.proxyList" % pm[0], type="reference" )
    if not references:
        references = [ rfn ]
        m_words = "|".join( references )
    else:
        references = [ rfn ]
        m_words = rfn
    edits = []
    if references:
        for i in range( 0, len( references )):
            strings = cmds.referenceQuery( references[i], failedEdits=True, successfulEdits=True, editStrings=True )
            if strings:
                for i in range( 0, len( strings )):
                    if strings[i] not in edits:
                        if not re.findall( m_words, strings[i] ):
                            edits.append( strings[i] )
    if edits:
        removeEdits( rfn, edits )
Exemplo n.º 13
0
def switchProxy( rfn, to="" ):
    if cmds.nodeType( rfn ) == "reference":
        pm = cmds.listConnections( rfn, type="proxyManager" )
    else:
        print "%s has not any connected proxy references." % rfn
        return None
    if pm:
        pm = pm[0]
        if to == "":
            references = cmds.listConnections( "%s.proxyList" % pm, type="reference", source=False, destination=True )
            active = cmds.listConnections( "%s.activeProxy" % pm, source=False, destination=True, plugs=True )
            if active:
                for i in range( 0, len( references )):
                    connections = cmds.listConnections( "%s.proxyMsg" % references[i], type="proxyManager", source=True, destination=False, plugs=True )
                    if connections and active[0] in connections:
                        return loadReference( references[i-1] )
                        break 
            else:
                return loadReference( references[0] )
        else:
            if cmds.objExists( to ) and cmds.nodeType( to ) == "reference":
                tm = cmds.listConnections( to, type="proxyManager" )
                if tm and pm == tm[0]:
                    return loadReference( to )
                else:
                    print "%s is not proxy reference for current reference." % to
                    return None
            else:
                print "%s is not proxy reference." % to
                return None
Exemplo n.º 14
0
 def finalize(self):
     """ corrective shape finalize """
     mesh = self.mesh
     if not mesh:
         sels = cmds.ls(sl = 1)
         if sels:
             mesh = sels[0]
         #END if
     #END if
     assert mesh, "--\ncorrectiveData.createCorrectiveUI.__finalize: no mesh specified"
     corrs = cmds.ls(type = "correctiveShape")
     if not corrs:
         print "No corrective shapes found in " + mesh + "'s history"
         return
     #END if
     csp = corrs[0]
     sculpt = cmds.listConnections(csp + ".inputMesh")
     shape = cmds.listConnections(csp + ".og[0]")
     if sculpt:
         sculptShapes = cmds.listRelatives(sculpt[0], s=True, ad=True)
         sculpt.insert(0, sculptShapes[0])
     #END if
     cmds.delete(sculpt)
     cmds.select(shape[0])
     cmds.DeleteHistory()  
Exemplo n.º 15
0
def get_shader(node):
    '''Get the shader applied to a transform or mesh

    :param node: Transform or mesh shape
    '''

    node_type = cmds.nodeType(node)

    if node_type == 'transform':
        shape = get_shape(node)
        if not shape:
            return
    elif node_type == 'mesh':
        shape = node

    try:
        shading_engine = cmds.listConnections(shape, type='shadingEngine')[0]
    except IndexError:
        raise Exception('{} is not attached to a shading engine'.format(shape))

    try:
        shader = cmds.listConnections(shading_engine + '.surfaceShader')[0]
    except IndexError:
        raise Exception('{} shadingEngine has no surfaceShader attached'.format(shading_engine))

    return shader
Exemplo n.º 16
0
 def showDCtl(self, winPointer, basePointer, *args ):
     
     surfs = winPointer.getSurfaceShapes( basePointer )
     
     upObjList = []
     for surf in surfs:
         surfObj = cmds.listRelatives( surf, p=1 )[0]
         
         if cmds.attributeQuery( 'upObject', node=surfObj, ex=1 ):
             upObjGrpCons = cmds.listConnections( surfObj+'.upObject' )
             if upObjGrpCons:
                 upObjGrp = upObjGrpCons[0]
         
         upObj = cmds.listRelatives( upObjGrp, c=1 )[0]
         upObjList.append( upObj )
     
     if not upObjList: return None    
     children = cmds.listRelatives( upObjList, c=1, ad=1 )
     
     if not children: return None
     
     dCtls = []
     for child in children:
         nodeCons = cmds.listConnections( child, d=1, s=0, type='clusterControledCurve' )
         if nodeCons:
             dCtls.append( child )
     
     for dCtl in dCtls:
         dhValue = cmds.getAttr( dCtl+'.dh' )
         if dhValue:
             cmds.setAttr( dCtl+'.dh', 0 )
         else:
             cmds.setAttr( dCtl+'.dh', 1 )
Exemplo n.º 17
0
def getMuscle(muscleObject):
    """
    Get muscle connected to the specified muscleObject
    @param muscleObject: Muscle object to query
    @type muscleObject: str
    """
    # Get muscle object type
    muscleObjType = getMuscleObjectType(muscleObject)

    # Get muscle
    muscle = ''
    if muscleObjType == 'geo':
        muscle = muscleObject
    elif (muscleObjType == 'profile') or (muscleObjType == 'attachment') or (muscleObjType == 'spline'):
        muscleConn = cmds.listConnections(muscleObject + '.muscle', s=True, d=False)
        if not muscleConn:
            raise Exception('Unable to determine muscle connection from muscleObject "' + muscleObject + '"!')
        muscle = muscleConn[0]
    elif (muscleObjType == 'attachmentTangent'):
        muscleObjParent = cmds.listRelatives(muscleObject, p=True)[0]
        muscleConn = cmds.listConnections(muscleObjParent + '.muscle', s=True, d=False)
        if not muscleConn:
            raise Exception('Unable to determine muscle connection from muscleObject "' + muscleObject + '"!')
        muscle = muscleConn[0]
    else:
        raise Exception('Invalid muscleObjectType value: "' + muscleObjType + '"!')

    # Return result
    return muscle
Exemplo n.º 18
0
def cacheFluidsToCTemp():
	if cmds.objExists(CONST.FOAM_FLUID_SHAPENODE) and cmds.objExists(CONST.WAKE_FLUID_SHAPENODE):
		## Get default non-cached wake and foam
		fluidsToCache = []
		for cache in [CONST.FOAM_FLUID_SHAPENODE, CONST.WAKE_FLUID_SHAPENODE]:
			fluidConnection = cmds.listConnections(cache, type = 'cacheFile') or cmds.listConnections(cache, type = 'cacheBlend')
			if fluidConnection:
				if cmds.nodeType(fluidConnection[0]) == 'cacheFile' or cmds.nodeType(fluidConnection[0]) == 'cacheBlend':
					cmds.confirmDialog(title = 'CACHE FLUIDS', message = 'Cache already exist for "%s". You should cleanup your caches if you want to re-cache a newer one!' % cache, button = 'OK')
				else:
					fluidsToCache.append(cache)
			else:
				fluidsToCache.append(cache)

		## Cache em fluids at one go to save time
		if fluidsToCache:
			cachePath = _getPathFromSceneName()
			if cachePath:
				if os.path.exists(cachePath):
					_cacheWake(cachepath = cachePath, fluids = fluidsToCache)

					## Set time to min
					[cmds.currentTime( cmds.playbackOptions(q = True, min = True) ) for x in range(2)]
	else:
		cmds.confirmDialog(title = 'CACHE FLUIDS', message = 'Both "%s" and "%s" fluids don\'t exist in your scene!' % (CONST.FOAM_FLUID_SHAPENODE, CONST.WAKE_FLUID_SHAPENODE), button = 'OK')
Exemplo n.º 19
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.º 20
0
def pfxhairDynamicSetting( hairSystems, skinMesh ):

    startCurvesAll = []
    for hairSystem in hairSystems:
        hairSystemShape = cmds.listRelatives( hairSystem, s=1 )[0]
        follicles = cmds.listConnections( hairSystemShape+'.inputHair', s=1, d=0, type='follicle', shapes=1 )
        startCurves = cmds.listConnections( follicles, s=1, d=0, type='nurbsCurve' )
        
        startCurvesShapes = cmds.listRelatives( startCurves, s=1, f=1 )
        
        for shape in startCurvesShapes:
            cons = cmds.listConnections( shape, d=1, s=0, shapes=1 )
            if not cons: 
                cmds.delete( shape )
                continue
            if cmds.nodeType( cons[0] ) == 'follicle':
                cmds.setAttr( shape+'.io', 1 )
        
        startCurvesAll += startCurves
    
    grp = cmds.group( startCurvesAll, n='startCurveGrps' )
    
    startCurvesAll = cmds.listRelatives( grp, c=1, type='transform', f=1 )
    
    import sgRigSkinCluster
    
    for curve in startCurvesAll:
        sgRigSkinCluster.autoCopyWeight( skinMesh, curve )
    
    return grp
Exemplo n.º 21
0
def setRestCurve( startCurves ):
    
    restCurves = []
    index = 0
    for startCurve in startCurves:
        
        follicle = cmds.listConnections( startCurve+'.wm', type='follicle', shapes=1 )[0]
        
        if cmds.listConnections( follicle+'.restPosition', s=1, d=0 ): continue
        
        startShape = cmds.listConnections( follicle+'.startPosition', s=1, d=0, shapes=1 )[0]
        
        rebuildCurve= cmds.listConnections( startShape+'.create', type='rebuildCurve' )[0]
        
        crvShape = cmds.createNode( 'nurbsCurve' )
        cmds.connectAttr( rebuildCurve+'.outputCurve', crvShape+'.create' )
        cmds.connectAttr( crvShape+'.worldSpace', follicle+'.restPosition' )
        cmds.setAttr( crvShape+'.io', 1 )
        
        crv = cmds.listRelatives( crvShape, p=1 )[0]
        crv = cmds.rename( crv, 'restCurve_%03d' % index )
        
        startMtx = cmds.getAttr( crv+'.wm' )
        cmds.xform( crv, ws=1, matrix=  startMtx )
        
        restCurves.append( crv )
        index += 1
    
    cmds.group( restCurves, n='restCurveGrps' )
Exemplo n.º 22
0
def reorderInfluence(glusterNode):

    influenceList = mc.listConnections(glusterNode + ".matrix", s=1, d=0)
    bindPreMatrixList = mc.listConnections(glusterNode + ".bindPreMatrix", s=1, d=0)
    indexArray = range(len(influenceList))
    indexArray.reverse()

    popWeightList = mc.getAttr(glusterNode + ".influenceWeight[" + str(indexArray[0]) + "]")

    for ind in indexArray:
        if ind:
            copyWeightList = mc.getAttr(glusterNode + ".influenceWeight[" + str(ind - 1) + "]")
            mc.setAttr(glusterNode + ".influenceWeight[" + str(ind) + "]", copyWeightList, type="doubleArray")
            mc.connectAttr(influenceList[(ind - 1)] + ".worldMatrix[0]", glusterNode + ".matrix[" + str(ind) + "]", f=1)
            mc.connectAttr(
                bindPreMatrixList[(ind - 1)] + ".worldInverseMatrix[0]",
                glusterNode + ".bindPreMatrix[" + str(ind) + "]",
                f=1,
            )
        else:
            mc.setAttr(glusterNode + ".influenceWeight[" + str(ind) + "]", popWeightList, type="doubleArray")
            mc.connectAttr(influenceList[indexArray[0]] + ".worldMatrix[0]", glusterNode + ".matrix[0]", f=1)
            mc.connectAttr(
                bindPreMatrixList[indexArray[0]] + ".worldInverseMatrix[0]", glusterNode + ".bindPreMatrix[0]", f=1
            )
Exemplo n.º 23
0
def createMaterialSelect():
       
    selNodes = cmds.ls(selection=True) # get selection
    
    mtlSelectToCreate = [] # clean out array
    
    for node in selNodes:
        if cmds.nodeType(node) == 'VRayBlendMtl': #make sure it's a vray blend mat
            mat = (cmds.listConnections('%s.base_material' % (node))[0])
            print mat, node
            if mat != None and mat not in mtlSelectToCreate:
                mtlSelectToCreate.append(mat)
            for n in range(0,9):
                mat = (cmds.listConnections('%s.coat_material_%d' % (node,n))) # go thru each coat and add if it's there
                if mat != None and mat not in mtlSelectToCreate:
                    mtlSelectToCreate.append(mat[0])
        if cmds.nodeType(node) == 'VRayMtl':
            if node not in mtlSelectToCreate:
                mtlSelectToCreate.append(node) 
                
    for curMat in mtlSelectToCreate:
        matSelName = 'mtl_%s' % (curMat) # create a reasonable name
        if not cmds.objExists(matSelName): # make sure it doesn't already exist
            renderElement = mel.eval('vrayAddRenderElement MaterialSelectElement;') # create render element
            renderElement = cmds.rename(renderElement,matSelName) # rename the old to new
            cmds.connectAttr (curMat + '.outColor', renderElement + '.vray_mtl_mtlselect') # connect up the shader to the render element
            cmds.setAttr (renderElement + '.vray_explicit_name_mtlselect', matSelName, type = 'string') # make sure the name that gets shoved in the exr is named the same
Exemplo n.º 24
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.º 25
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.º 26
0
def deleteExpression(con='', attr=''):
    '''
    #
    '''
    # find exp
    cnn = cmds.listConnections(con + '.' + attr, s=True, d=False)
    if cnn:
        if cmds.nodeType(cnn[0]) == 'unitConversion':
            cnn_uc = cmds.listConnections(cnn, s=True, d=False, type='expression')
            if cnn_uc:
                if cmds.nodeType(cnn_uc[0]) == 'expression':
                    exp = cnn_uc[0]
        elif cmds.nodeType(cnn[0]) == 'expression':
            exp = cnn[0]
        # delete exp
        if exp:
            st1 = cmds.expression(exp, q=True, s=True)
            st2 = 'frame'
            if st2 in st1:
                cmds.delete(exp)
                print 'deleted___  ', con, '  ___  ', exp
            else:
                print '    nope     '
        else:
            print 'no expression  ', attr
Exemplo n.º 27
0
def separateMeshsBySkinWeight2( meshObjs ):
    
    import sgBFunction_connection
    import sgBFunction_dag
    
    meshObjs = sgBFunction_dag.getChildrenMeshExists( meshObjs )
    
    
    meshs = []
    for meshObj in meshObjs:
        meshs += separateMeshBySkinWeight2( meshObj )
    
    jntAndBindTargets = {}
    appendedJnts = []
    
    for sel in meshs:
        mmdc = cmds.listConnections( sel, s=1, d=0 )[0]
        bindObj = cmds.listConnections( mmdc, s=1, d=0 )[0]
        bindObjP = cmds.listRelatives( bindObj, p=1, f=1 )[0]
        
        if not bindObjP in appendedJnts:
            appendedJnts.append( bindObjP )
            jntAndBindTargets.update( {bindObjP:[]} )
        
        jntAndBindTargets[ bindObjP ].append( sel )
    
    for jnt, bindObjs in jntAndBindTargets.items():
        
        if len( bindObjs ) == 1: continue
        
        bindObj, polyUnite = cmds.polyUnite( bindObjs, n=bindObjs[0] )
        bindObj = cmds.rename( bindObj, jnt.split( '|' )[-1]+'_mesh' )
        sgBFunction_connection.bindConnect( bindObj, jnt )
Exemplo n.º 28
0
    def ConstraintVisibility(self, Objects , ControlObject , SpaceSwitchName = 'spaceSwitch', reverse = False ):
        if (self.AddNumericParameter (ControlObject, Name = SpaceSwitchName)):
            SWMultDiv = cmds.shadingNode("multiplyDivide",asUtility = True ,name = SpaceSwitchName + "SWMultDivide" )
            SWMultDiv = self.NameConv.RMRenameBasedOnBaseName(ControlObject, SWMultDiv, NewName = SWMultDiv)
            cmds.connectAttr(ControlObject+"."+SpaceSwitchName ,SWMultDiv+".input1X")
            cmds.setAttr(SWMultDiv+".input2X",10)
            cmds.setAttr(SWMultDiv+".operation",2)
        else:
            SWMultDiv = cmds.listConnections(ControlObject + "." + SpaceSwitchName, type = "multiplyDivide")[0]

        if reverse == True:
            ConnectionsList = cmds.listConnections (SWMultDiv + ".outputX", type = "reverse")
            reverseSW = ""
            if ConnectionsList and len(ConnectionsList) >= 1:
                reverseSW = ConnectionsList[0]
            else :
                reverseSW = cmds.shadingNode('reverse', asUtility=True, name = SpaceSwitchName + "SWReverse")
                reverseSW = self.NameConv.RMRenameBasedOnBaseName(ControlObject, reverseSW, NewName ="SWReverse")
                cmds.connectAttr( SWMultDiv + ".outputX", reverseSW + ".inputX")

                if self.NameConv.RMIsNameInFormat (ControlObject):
                    reverseSW = self.NameConv.RMRenameBasedOnBaseName(ControlObject,reverseSW, NewName = reverseSW)
                else:
                    reverseSW = self.NameConv.RMRenameNameInFormat(reverseSW)
            for eachObject in Objects:
                cmds.connectAttr(reverseSW + ".outputX", eachObject + ".visibility")
        
        else:
            for eachObject in Objects:
                cmds.connectAttr(SWMultDiv + ".outputX", eachObject + ".visibility")
Exemplo n.º 29
0
def chimaPullThemDown() :

	num = -6975.209
	nodes = mc.ls( sl=True )
	tys = []

	for node in nodes :
		
		src = mc.listConnections( '%s.ty' % node , p=True , s=True , d=False )[0]
		srcType = mc.nodeType( src )
		ty = ''

		if srcType == 'character' :
			ty = mc.listConnections( src , s=True , d=False )[0]
		elif srcType == 'animCurveTL' :
			ty = src.split( '.' )[0]
		else :
			print '%s has been constrained to object' % node
			ty = None
		if ty :
			tys.append( ty )
	
	mc.keyframe( tys ,
					e=True ,
					includeUpperBound=False ,
					animation='objects' ,
					time=(0,100000) ,
					r=True ,
					o='move' ,
					timeChange=0 ,
					valueChange=num
				)
Exemplo n.º 30
0
def getAffectedJoints(ikHandle):
    """
    Get a list of joints affected by a specified ikHandle
    @param ikHandle: IK Handle to query affected joints for
    @type ikHandle: str
    """
    # Check ikHandle
    if not cmds.objExists(ikHandle):
        raise Exception('IK handle ' + ikHandle + ' does not exist!')
    if cmds.objectType(ikHandle) != 'ikHandle':
        raise Exception('Object ' + ikHandle + ' is not a valid ikHandle!')

    # Get startJoint
    startJoint = cmds.listConnections(ikHandle + '.startJoint', s=True, d=False)[0]
    # Get endEffector
    endEffector = cmds.listConnections(ikHandle + '.endEffector', s=True, d=False)[0]
    endJoint = cmds.listConnections(endEffector + '.translateX', s=True, d=False)[0]

    # Get list of joints affected by ikHandle
    ikJoints = [endJoint]
    while ikJoints[-1] != startJoint:
        ikJoints.append(cmds.listRelatives(ikJoints[-1], p=True)[0])
    # Reverse joint list
    ikJoints.reverse()

    # Return ik joints list
    return ikJoints
def edo_autoConnectCorrectBlendShape(clearbs=1):
    #axis=8
    sels = cmds.ls(sl=1)
    if len(sels) >= 3:
        target = sels[0]
        skmesh = sels[1]
        skdbf = sels[2]
        dctrl = skdbf.replace('_FRAME', '_CONNECT')
        #record driver angle
        drsk = ''
        drsks = None
        if cmds.objExists(skdbf + '.SKDB'):
            drsks = cmds.listConnections(skdbf + '.SKDB', s=1, d=0)
        if drsks:
            drsk = drsks[0]
        else:
            drsk = edo_findoutDriverSkeletonFromSKDB(skdbf)
        maxrt = edo_getSKDBCurrenctAttrFromAttrs(skdbf)
        if float(maxrt.split(':')[1]) <= 0.001:
            print 'attributes are too small,please repose your character'
            return False
        #rcattr=''
        #if not mr=='':
        #    rcattr=skdbf+'.'+drsk+'__'+mr
        #if rcattr=='':
        #    print 'the joint doesnt have any rotation, so you don\t need add any correct blendshape to it'
        #    return
        ##rewrite rotation Value list
        #edo_rewriteRotationValueList(skdbf,rcattr,mv,mr)
        edo_rewriteDirValueList(skdbf, maxrt, drsk)
        #auto calculate and connect  blendshape
        fbs = edo_calculateBlendShape(target, skmesh)
        axis = 4
        if cmds.objExists(skdbf.replace('FRAME', 'eightDirPlane_curve')):
            axis = 8
        mxattr = ''
        if axis == 4:
            mxattr = edo_getSKDBmaxCurrentAttrFromFourAttrs(skdbf)
        else:
            mxattr = edo_getSKDBmaxCurrentAttrFromEightAttrs(skdbf)
        outs = cmds.listConnections(skdbf + '.' + mxattr[0], d=1, s=0, p=1)
        animCurves = []
        if outs:
            for out in outs:
                #out = outs[0]
                outobj = cmds.ls(out.split('.')[0], type='animCurve')
                if outobj:
                    animCurves.append(outobj[0])
        #print animCurve
        dirvalue = mxattr[1]
        outvalue = mxattr[1]
        cbs = edo_findNodeFromHis(skmesh, 'blendShape')
        canim = ''
        if not cbs == None:
            if animCurves:
                for am in animCurves:
                    #am = animCurves[0]
                    outputs = cmds.listConnections(am, s=0, d=1)
                    if outputs:
                        for output in outputs:
                            #output = outputs[0]
                            if output == cbs:
                                canim = am
        if not canim == '':
            outvalue = cmds.getAttr(canim + '.output')
        cmds.select(fbs)
        #skmesh=skmesh+'_'
        cmds.select(skmesh, add=1)
        bsmeshes = edo_skautoConnectBlendShapes.edo_renameBlendShapeMeshInbetween(
            outvalue)
        cmds.parent(bsmeshes, dctrl + '_' + mxattr[0])
        cmds.select(dctrl)
        allbms = edo_skautoConnectBlendShapes.edo_autoConnectBlendshapes()
        allbms = cmds.ls(bsmeshes.split('__')[0] + '__' +
                         bsmeshes.split('__')[1] + '*',
                         type='transform')
        #delete blendshape mesh
        if clearbs == 1:
            print 'clear blendshape : ' + bsmeshes
            if allbms:
                for bm in allbms:
                    #bm=allbms[0]
                    if cmds.objExists(bm):
                        shs = cmds.listRelatives(bm, p=1, pa=1)
                        if shs:
                            sh = shs[0]
                            if dctrl + '_' in sh:
                                cmds.delete(bm)
        #convert expression to setDriven Key
        cbs = edo_findNodeFromHis(skmesh, 'blendShape')
        if cbs == skmesh + '_BLENDSHAPE':
            #cbs mxattr[1]
            edo_convertBlendShapeDrivingExToSdk(cbs, canim, dirvalue, outvalue)
        return [maxrt]
Exemplo n.º 32
0
    def overlap(self):
        NotUseFirstCtrl = self.First_CB.isChecked()
        CycleCheckBox = self.Cycle_CB.isChecked()
        TRANSLATEmode = self.Translate_CB.isChecked()
        OnLayerSwitch = self.Bake_CB.isChecked()

        WindSwitch = self.Wind_CB.isChecked()
        windScaleValue = self.Wind_Scale_SP.value()
        windSpeedValue = self.Wind_Speed_SP.value()

        overlapIntensity = self.Scale_SP.value()
        timeShift = self.Softness_SP.value()
        timeStart = cmds.playbackOptions(q=1, min=1)
        timeEnd = cmds.playbackOptions(q=1, max=1)

        controller_list = cmds.ls(sl=1)

        # NOTE 生成骨骼 | 调整轴向
        cmds.select(cl=1)
        jnt_list = []
        _jnt = None
        for controller in controller_list:
            pos = cmds.xform(controller, q=1, rp=1, ws=1)
            jnt = cmds.joint(p=pos, rad=1, n="%s_OverlapJoint" % controller)
            if _jnt:
                cmds.joint(_jnt, e=1, zso=1, oj="xyz", sao="yup")
            jnt_list.append(jnt)
            _jnt = jnt
        else:
            last_jnt = cmds.duplicate(jnt,
                                      rr=1,
                                      n="%s_LastOrientJoint" % controller)[0]
            cmds.move(2, 0, 0, r=1, ls=1, wd=1)
            cmds.parent(last_jnt, jnt)
            jnt_list.append(last_jnt)
            cmds.joint(jnt, e=1, zso=1, oj="xyz", sao="yup")

            sumLenghtJoints = sum(
                [cmds.getAttr("%s.tx" % jnt) for jnt in jnt_list])
            averageLenghtJoints = (sumLenghtJoints - 2) / len(jnt_list)
            cmds.setAttr(last_jnt + ".tx", averageLenghtJoints)

        constraint_list = []
        for controller, jnt in zip(controller_list, jnt_list):
            constraint_list.extend(cmds.parentConstraint(controller, jnt,
                                                         mo=1))

        # NOTE 烘焙骨骼跟随控制器的关键帧
        cmds.bakeResults(
            jnt_list,
            simulation=1,  # NOTE 开启模拟 解决卡顿问题
            t=(timeStart, timeEnd),
            sampleBy=1,
            oversamplingRate=1,
            disableImplicitControl=1,
            preserveOutsideKeys=1,
            sparseAnimCurveBake=0,
            removeBakedAttributeFromLayer=0,
            removeBakedAnimFromLayer=0,
            bakeOnOverrideLayer=0,
            minimizeRotation=1,
            at=['tx', 'ty', 'tz', 'rx', 'ry', 'rz'])

        cmds.delete(constraint_list)

        if CycleCheckBox:
            # NOTE 将骨骼关键帧复制多几份
            for i, jnt in enumerate(jnt_list):
                cmds.selectKey(cmds.listConnections(jnt + ".tx",
                                                    type="animCurve"),
                               cmds.listConnections(jnt + ".ty",
                                                    type="animCurve"),
                               cmds.listConnections(jnt + ".tz",
                                                    type="animCurve"),
                               cmds.listConnections(jnt + ".rx",
                                                    type="animCurve"),
                               cmds.listConnections(jnt + ".ry",
                                                    type="animCurve"),
                               cmds.listConnections(jnt + ".rz",
                                                    type="animCurve"),
                               r=1,
                               k=1,
                               t=(timeStart, timeEnd))
                cmds.copyKey()
                cmds.pasteKey(time=(timeEnd, timeEnd),
                              float=(timeEnd, timeEnd),
                              option="insert",
                              copies=2,
                              connect=0,
                              timeOffset=0,
                              floatOffset=0,
                              valueOffset=0)

            cycleLenghts = timeEnd - timeStart
            timeEnd = timeEnd + 2 * cycleLenghts

        # NOTE 进行 overlap
        overlapIntensityMult = averageLenghtJoints / overlapIntensity * 5
        timeShiftNeg = -timeShift
        timeShiftCurrent = 1 + timeShift

        gc_list = []
        aim_data = {}
        for i, jnt in enumerate(jnt_list):

            offset_loc = cmds.spaceLocator(n="overlapOffsetLocator%s" % i)[0]
            cmds.delete(cmds.parentConstraint(jnt, offset_loc, w=1))

            cmds.move(overlapIntensityMult, 0, 0, r=1, os=1, ls=1)
            con = cmds.parentConstraint(jnt, offset_loc, mo=1)

            cmds.bakeResults(offset_loc,
                             simulation=0,
                             t=(timeStart, timeEnd),
                             sampleBy=1,
                             disableImplicitControl=1,
                             preserveOutsideKeys=1,
                             minimizeRotation=1,
                             at=['tx', 'ty', 'tz', 'rx', 'ry', 'rz'])

            cmds.delete(con)

            wind_loc = cmds.spaceLocator(n="overlapOffsetLocatorWind%s" % i)[0]
            gc_list.append(wind_loc)
            cmds.parent(wind_loc, offset_loc)
            cmds.makeIdentity(wind_loc, a=0, t=1, r=1, s=1, n=0, pn=1)

            animCurve_list = [
                (offset_loc + "_translateX"),
                (offset_loc + "_translateY"),
                (offset_loc + "_translateZ"),
                (offset_loc + "_rotateX"),
                (offset_loc + "_rotateY"),
                (offset_loc + "_rotateZ"),
            ]

            for animCurve in animCurve_list:
                cmds.keyframe(animCurve,
                              e=1,
                              iub=1,
                              r=1,
                              o="over",
                              tc=timeShift)
                cmds.keyframe(animCurve,
                              t=(timeShiftCurrent, timeShiftCurrent),
                              option="over",
                              relative=1,
                              timeChange=timeShiftNeg)

            aim_loc = cmds.spaceLocator(n="overlapInLocator_aim_%s" % i)[0]

            aim_grp = cmds.group(aim_loc, n=aim_loc + "_grp")
            cmds.pointConstraint(jnt, aim_grp)
            aim_data[aim_loc] = aim_grp

            cmds.aimConstraint(wind_loc,
                               aim_grp,
                               aimVector=[1, 0, 0],
                               upVector=[0, 1, 0],
                               worldUpType="object",
                               worldUpObject=wind_loc)
            cmds.orientConstraint(wind_loc,
                                  aim_loc,
                                  mo=1,
                                  skip=["y", "z"],
                                  w=1)

            # NOTE 添加控制器 translate 坐标位移
            if TRANSLATEmode and i != len(jnt_list) - 1:
                IK_loc = cmds.spaceLocator(n="overlapOffsetIKLocator%s" % i)[0]
                cmds.pointConstraint(jnt, IK_loc)
                cmds.bakeResults(IK_loc,
                                 simulation=0,
                                 t=(timeStart, timeEnd),
                                 sampleBy=1,
                                 disableImplicitControl=1,
                                 preserveOutsideKeys=1,
                                 minimizeRotation=1,
                                 at=['tx', 'ty', 'tz'])
                animCurve_list = [
                    (IK_loc + "_translateX"),
                    (IK_loc + "_translateY"),
                    (IK_loc + "_translateZ"),
                ]
                for animCurve in animCurve_list:
                    cmds.keyframe(animCurve,
                                  e=1,
                                  iub=1,
                                  r=1,
                                  o="over",
                                  tc=timeShift)
                    cmds.keyframe(animCurve,
                                  t=(timeShiftCurrent, timeShiftCurrent),
                                  option="over",
                                  relative=1,
                                  timeChange=timeShiftNeg)

                cmds.pointConstraint(IK_loc, aim_loc)
                gc_list.append(IK_loc)

            # NOTE 添加随机风向控制
            if WindSwitch:
                windMultiply = 0.07 * overlapIntensityMult * windScaleValue
                speedMultiply = 20 / windSpeedValue

                cmds.setKeyframe(wind_loc,
                                 attribute=['translateY', 'translateZ'],
                                 t=[timeStart, timeStart])

                cmds.bakeResults(wind_loc,
                                 simulation=0,
                                 t=(timeStart, timeEnd + speedMultiply),
                                 sampleBy=speedMultiply,
                                 oversamplingRate=1,
                                 disableImplicitControl=1,
                                 preserveOutsideKeys=1,
                                 at=['ty', 'tz'])

                for attr in cmds.listAttr(wind_loc, k=1):
                    animCurve = cmds.listConnections("%s.%s" %
                                                     (wind_loc, attr),
                                                     type="animCurve")
                    if not animCurve:
                        continue
                    for animCurveCurrent in animCurve:
                        for animCurveCurrentKeysTime in cmds.keyframe(
                                animCurveCurrent,
                                q=1,
                                t=(timeStart, timeEnd),
                                tc=1):
                            t = (animCurveCurrentKeysTime,
                                 animCurveCurrentKeysTime)
                            animCurveCurrentKeysTimeArray = cmds.keyframe(
                                animCurveCurrent, q=1, time=t, vc=1)
                            RandomizerValue = random.random() * 2 - 1
                            animCurveCurrentKeysValueArrayAddRandom = animCurveCurrentKeysTimeArray[
                                0] + windMultiply * RandomizerValue
                            cmds.keyframe(
                                animCurveCurrent,
                                e=1,
                                iub=1,
                                r=1,
                                o="over",
                                vc=animCurveCurrentKeysValueArrayAddRandom,
                                t=t)

                attr = (wind_loc + "_translateY")
                cmds.keyframe(attr,
                              e=1,
                              iub=1,
                              r=1,
                              o="over",
                              tc=speedMultiply / 2)
                t = (speedMultiply / 2) + 1
                cmds.selectKey(attr, add=1, k=1, t=(t, t))
                cmds.keyframe(attr,
                              animation="keys",
                              r=1,
                              o="over",
                              tc=speedMultiply / -2)

            cmds.bakeResults(aim_grp,
                             aim_loc,
                             simulation=0,
                             t=(timeStart, timeEnd),
                             sampleBy=1,
                             disableImplicitControl=1,
                             preserveOutsideKeys=1,
                             minimizeRotation=1,
                             at=['tx', 'ty', 'tz', 'rx', 'ry', 'rz'])

            cmds.parentConstraint(aim_loc, jnt, mo=1)

            gc_list.append(offset_loc)
            gc_list.append(aim_grp)

        # NOTE 动画循环控制
        if CycleCheckBox:
            timeStart = cmds.playbackOptions(q=1, min=1)
            timeEnd = cmds.playbackOptions(q=1, max=1)
            cycleLenghts = timeEnd - timeStart
            # NOTE 将关键帧挪动回去两个时间范围
            for aim_loc, aim_grp in aim_data.items():
                cmds.keyframe(cmds.listConnections(aim_loc + ".tx",
                                                   type="animCurve"),
                              cmds.listConnections(aim_loc + ".ty",
                                                   type="animCurve"),
                              cmds.listConnections(aim_loc + ".tz",
                                                   type="animCurve"),
                              cmds.listConnections(aim_loc + ".rx",
                                                   type="animCurve"),
                              cmds.listConnections(aim_loc + ".ry",
                                                   type="animCurve"),
                              cmds.listConnections(aim_loc + ".rz",
                                                   type="animCurve"),
                              cmds.listConnections(aim_grp + ".tx",
                                                   type="animCurve"),
                              cmds.listConnections(aim_grp + ".ty",
                                                   type="animCurve"),
                              cmds.listConnections(aim_grp + ".tz",
                                                   type="animCurve"),
                              cmds.listConnections(aim_grp + ".rx",
                                                   type="animCurve"),
                              cmds.listConnections(aim_grp + ".ry",
                                                   type="animCurve"),
                              cmds.listConnections(aim_grp + ".rz",
                                                   type="animCurve"),
                              e=1,
                              iub=1,
                              r=1,
                              o="over",
                              tc=cycleLenghts * -2)

        constraint_list = []
        for i, [controller, jnt] in enumerate(zip(controller_list, jnt_list)):
            if NotUseFirstCtrl and i == 0:
                continue
            if cmds.getAttr(controller+".tx",k=1) and not cmds.getAttr(controller+".tx",l=1) and \
               cmds.getAttr(controller+".ty",k=1) and not cmds.getAttr(controller+".ty",l=1) and \
               cmds.getAttr(controller+".tz",k=1) and not cmds.getAttr(controller+".tz",l=1):
                constraint_list.extend(
                    cmds.pointConstraint(jnt, controller, mo=1))
            if cmds.getAttr(controller+".rx",k=1) and not cmds.getAttr(controller+".rx",l=1) and \
               cmds.getAttr(controller+".ry",k=1) and not cmds.getAttr(controller+".ry",l=1) and \
               cmds.getAttr(controller+".rz",k=1) and not cmds.getAttr(controller+".rz",l=1):
                constraint_list.extend(
                    cmds.orientConstraint(jnt, controller, mo=1))

        if NotUseFirstCtrl:
            controller_list = controller_list[1:]

        # NOTE 输出到控制器上
        cmds.bakeResults(
            controller_list,
            simulation=1,  # NOTE 开启模拟 解决卡顿问题
            t=(timeStart, timeEnd),
            sampleBy=1,
            disableImplicitControl=1,
            bakeOnOverrideLayer=OnLayerSwitch,
            preserveOutsideKeys=1,
            minimizeRotation=1,
            at=['tx', 'ty', 'tz', 'rx', 'ry', 'rz'])

        cmds.delete(constraint_list)
        cmds.delete(jnt_list)
        cmds.delete(gc_list)
Exemplo n.º 33
0
    def Light_Export_Fn(self):
        File_Path = QFileDialog.getSaveFileName(self,
                                                caption=u"1",
                                                directory=".",
                                                filter="json (*.json)")
        # 空数组处理
        try:
            if type(File_Path) is tuple:
                File_Path = File_Path[0]
            if type(File_Path) is list:
                File_Path = File_Path[0]
        except:
            traceback.print_exc()
            return

        Light_Json = {}
        Light_Json['Application'] = "Maya"
        Light_Json['LightData'] = {}

        lightList = cmds.ls(type='lightList')[0]
        lightList = cmds.listConnections(lightList + ".lights")
        for lightName in lightList:
            if cmds.getAttr(lightName + ".visibility") == 0:
                continue
            light = cmds.listRelatives(lightName, c=1)[0]
            Light_Json['LightData'][lightName] = {}
            Light_Json['LightData'][lightName]['Name'] = lightName
            Light_Json['LightData'][lightName]['Type'] = cmds.objectType(light)
            Light_Json['LightData'][lightName]['Intensity'] = cmds.getAttr(
                light + ".intensity")
            Light_Json['LightData'][lightName]['Exposure'] = cmds.getAttr(
                light + ".aiExposure")
            Light_Json['LightData'][lightName]['color'] = {}
            Light_Json['LightData'][lightName]['color']["R"] = cmds.getAttr(
                light + ".color")[0][0]
            Light_Json['LightData'][lightName]['color']["G"] = cmds.getAttr(
                light + ".color")[0][1]
            Light_Json['LightData'][lightName]['color']["B"] = cmds.getAttr(
                light + ".color")[0][2]
            Light_Json['LightData'][lightName]['Translate'] = {}
            Light_Json['LightData'][lightName]['Translate'][
                'tx'] = cmds.getAttr(lightName + ".tx")
            Light_Json['LightData'][lightName]['Translate'][
                'ty'] = cmds.getAttr(lightName + ".ty")
            Light_Json['LightData'][lightName]['Translate'][
                'tz'] = cmds.getAttr(lightName + ".tz")
            Light_Json['LightData'][lightName]['Rotate'] = {}
            Light_Json['LightData'][lightName]['Rotate']['rx'] = cmds.getAttr(
                lightName + ".rx")
            Light_Json['LightData'][lightName]['Rotate']['ry'] = cmds.getAttr(
                lightName + ".ry")
            Light_Json['LightData'][lightName]['Rotate']['rz'] = cmds.getAttr(
                lightName + ".rz")
            Light_Json['LightData'][lightName]['Sacle'] = {}
            Light_Json['LightData'][lightName]['Sacle']['sx'] = cmds.getAttr(
                lightName + ".sx")
            Light_Json['LightData'][lightName]['Sacle']['sy'] = cmds.getAttr(
                lightName + ".sy")
            Light_Json['LightData'][lightName]['Sacle']['sz'] = cmds.getAttr(
                lightName + ".sz")

        try:
            with open(File_Path, 'w') as f:
                json.dump(Light_Json, f, indent=4)
        except:
            if path != "":
                QMessageBox.warning(self, u"Warning", u"空路径读取失败")
Exemplo n.º 34
0
def edo_mirrorSKDBdeform(rp=['L_', 'R_'], mode=0):
    #mode=1
    sels = cmds.ls(sl=1)
    mesh = sels[0]
    skdbs = sels[1:]
    cmds.select(skdbs, r=1)
    edo_mirrorSKDBvalue(rp)
    #
    af = 0
    af = edo_checkTheEndStr(mesh)
    if af == 1:
        mesh = mesh + '_'
    oaf = 0
    omesh = ''
    if mode == 1:
        omesh = mesh.replace(rp[0], rp[1])
        if omesh[-1] == '_':
            omesh = omesh[:-1]
        oaf = edo_checkTheEndStr(omesh)
        if not omesh[-1] == '_':
            omesh = omesh + '_'
        if not cmds.objExists(omesh):
            print 'can not find the mesh in the other side'
            return False
    #mirrorBs
    allbs = edo_findAllBlendshapeInTheFrame(rp)
    fallbs = []
    for bs in allbs:
        #bs=allbs[0]
        edo_lockAndUnlockTransform.edo_unLockReferenceObjectTransformAttrs(bs)
        if mesh in bs:
            fallbs.append(bs)
    allbs = fallbs
    allmirrorbs = []
    if mode == 0:
        edo_lockAndUnlockTransform.edo_unLockReferenceObjectTransformAttrs(
            mesh)
        orgmesh = cmds.duplicate(mesh, n='ORG_' + mesh)[0]
        cmds.select(orgmesh, r=1)
        cmds.select(allbs, add=1)
        allmirrorbs = edo_mirrorBlendShape.edo_mirrorBlendShape()
        cmds.delete(orgmesh)
    if mode == 1:
        for bs in allbs:
            #bs=allbs[0]
            dbs = cmds.duplicate(bs, n=bs.replace(rp[0], rp[1]))[0]
            cmds.parent(dbs, w=1)
            cmds.xform(dbs, ws=1, t=[0, 0, 0], ro=[0, 0, 0], s=[-1, 1, 1])
            cmds.makeIdentity(dbs, a=1, t=0, r=1, s=1, n=0)
            allmirrorbs.append(dbs)
    #cmds.select(allmirrorbs)
    mirroredCurve = []
    for bs in allmirrorbs:
        #bs=allmirrorbs[0]
        #bsname=bs.split()
        #rbs=bs.replace('CTRR_','CTRL_')
        rbs = bs
        rbs = cmds.rename(bs, rbs)
        frame = rbs.split('__')[-1]
        if cmds.objExists(frame):
            cmds.parent(rbs, frame)
            ms = frame.split('_CONNECT')[0] + '_CONNECT'
            if cmds.objExists(ms):
                cmds.select(ms, r=1)
                #reload(edo_autoConnectBlendShapes)
                allbms = edo_autoConnectBlendShapes.edo_autoConnectBlendshapes(
                )
                #delete blendshape mesh
                cbs = ''
                #cbs=allbms[2]
                for bms in allbms:
                    if bms:
                        bms = bms[0]
                        if cmds.objExists(bms):
                            cmds.delete(bms)
                            cbs = bms
                if cmds.objExists(rbs):
                    cmds.delete(rbs)
                tmp = rbs.split('__')
                rbs = tmp[0] + '__' + tmp[1] + '__' + tmp[3]
                if cmds.objExists(rbs):
                    cmds.delete(rbs)
                #mirror set driven key
                #if cbs=='':
                #    continue
                bsn = rbs.split('__')[1] + '__BLENDSHAPE'
                lbsn = bsn.replace(rp[1], rp[0])
                tmp = rbs.replace(rp[1], rp[0]).split('__')
                ocbs = tmp[0] + '__' + tmp[1] + '__' + tmp[2]
                if cmds.objExists(lbsn + '.' + ocbs):
                    anc = cmds.listConnections(lbsn + '.' + ocbs,
                                               s=1,
                                               d=0,
                                               p=1)
                    if anc:
                        an = anc[0]
                        if cmds.nodeType(an)[0:9] == 'animCurve':
                            print 'duplicate anim curve'
                            if an in mirroredCurve:
                                continue
                            if cmds.objExists(
                                    an.split('.')[0].replace(rp[0], rp[1])):
                                print 'delete animCurve ... ' + an.split(
                                    '.')[0].replace(rp[0], rp[1])
                                cmds.delete(
                                    an.split('.')[0].replace(rp[0], rp[1]))
                            oc = cmds.duplicate(an,
                                                n=an.split('.')[0].replace(
                                                    rp[0], rp[1]))
                            mirroredCurve.append(an)
                            if oc:
                                c = oc[0]
                                #rnc=c.replace('_CTRR','_CTRL')
                                rnc = c
                                #if cmds.objExists(rnc):
                                #    print 'delete animCurve ... '+rnc
                                #    cmds.delete(rnc)
                                #rnc=cmds.rename(c,rnc)
                                #bsattr=(bsn+'.'+ocbs).replace(rp[0],rp[1]).replace('_CTRR','_CTRL')
                                bsattr = (bsn + '.' + ocbs).replace(
                                    rp[0], rp[1])
                                if cmds.objExists(bsattr):
                                    cmds.connectAttr(rnc + '.output',
                                                     bsattr,
                                                     f=1)
                                inattr = rnc.split('__')[-1].replace(
                                    '_CONNECT_', '_FRAME.')
                                if cmds.objExists(inattr):
                                    cmds.connectAttr(inattr,
                                                     rnc + '.input',
                                                     f=1)
                                    print 'mirror  ..  ' + bs + '  ..  was successful.'
    if af == 1:
        cmds.rename(mesh, mesh[:-1])
    if oaf == 1:
        cmds.rename(omesh, omesh[:-1])
    cmds.delete(allbs)
Exemplo n.º 35
0
def patch(reference_node):
    """A patch after commit 06c2ef9 and should be removed ASAP

    Before commit 06c2ef9, published rig has no namespace on imported
    models or shaders.

    And sometimes animator may make their own change on referenced rig
    that may create extra meshes under referenced transform node, which
    Maya will not able to re-apply those edits when replacing reference
    if the original rig was published before commit 06c2ef9 and the new
    rig was published after that (because new node will have namespace).

    Hence we need this patch for the transition, and will remove this once
    we could pin config version on each project.

    """
    from maya import cmds

    referenced = cmds.referenceQuery(reference_node, nodes=True, dagPath=True)
    transforms = cmds.ls(referenced, type="transform", long=True)
    meshes = cmds.listRelatives(
        transforms, shapes=True, fullPath=True, type="mesh") or []

    # Collect meshes(uuid) that were created in scene

    mesh_uuids = dict()
    for mesh in meshes:
        if cmds.referenceQuery(mesh, isNodeReferenced=True):
            continue

        parent = cmds.ls(mesh.rsplit("|", 1)[0], uuid=True)[0]
        shading = cmds.ls(cmds.listConnections(mesh,
                                               source=False,
                                               destination=True,
                                               connections=True,
                                               type="shadingEngine"),
                          uuid=True)
        mesh = cmds.ls(mesh, uuid=True)[0]
        mesh_uuids[mesh] = (parent, shading)

    yield

    # Adopt new parent

    foster = cmds.listConnections(reference_node + ".fosterParent")
    if foster and mesh_uuids:
        foster = foster[0]

        shapes = cmds.listRelatives(foster, shapes=True, fullPath=True)
        shapes = cmds.ls(shapes, uuid=True)
        for uuid in shapes:
            if uuid not in mesh_uuids:
                continue

            parent, shading = mesh_uuids[uuid]
            parent = cmds.ls(parent)
            fostered_shape = cmds.ls(uuid, long=True)

            if parent and fostered_shape:
                # Move fostered mesh node to newly referenced transform node
                fostered_shape = fostered_shape[0]
                shape = cmds.parent(fostered_shape,
                                    parent[0],
                                    addObject=True,
                                    shape=True)
                cmds.parent(fostered_shape, removeObject=True, shape=True)

                # Try to fix shading
                if shading:
                    shading = iter(shading)
                    for src, dst in zip(shading, shading):
                        dst = cmds.ls(dst)
                        if not dst:
                            continue
                        src = shape[0] + "." + src.split(".", 1)[-1]
                        dst = dst[0] + ".dagSetMembers"

                        try:
                            cmds.connectAttr(src, dst, nextAvailable=True)
                        except Exception as e:
                            cmds.warning(str(e))
Exemplo n.º 36
0
    def doIt(self, mArgs):
        ret, argData = self.grabArgDb(mArgs)
        if ret:
            return

        sel = OpenMaya.MSelectionList()
        argData.getObjects(sel)

        objs = []
        for n in range(sel.length()):
            obj = MObject()
            sel.getDependNode(n, obj)
            objs.append(obj)

        #
        if argData.isQuery():
            rotNode = objs[0]

            if argData.isFlagSet(self.kFlagAxis):
                self.setResult(cmd.getAttr('%s.mirrorAxis' % rotNode))

            elif argData.isFlagSet(self.kFlagMode):
                self.setResult(cmd.getAttr('%s.mirrorTranslation' % rotNode))

            return

        #if we're in edit mode, find the node
        elif argData.isEdit():
            rotNode = objs[0]

        #otherwise we're in creation mode - so build the node and connect things up
        else:
            obj, tgt = objs

            #is dummy mode set?
            isDummyMode = argData.isFlagSet(
                self.kFlagDummy) or argData.isFlagSet(self.kFlagDummy)

            #see if there is already a node connected
            existing = cmd.listConnections('%s.t' % tgt,
                                           '%s.r' % tgt,
                                           type=MirrorNode.NODE_TYPE_NAME)
            if existing:
                self.displayWarning(
                    "There is a %s node already connected - use edit mode!" %
                    MirrorNode.NODE_TYPE_NAME)
                self.setResult(existing[0])

                return
            else:
                rotNode = cmd.createNode('rotationMirror')
                cmd.connectAttr('%s.worldMatrix' % obj,
                                '%s.inWorldMatrix' % rotNode)
                cmd.connectAttr('%s.parentInverseMatrix' % obj,
                                '%s.inParentInverseMatrix' % rotNode)

                cmd.connectAttr('%s.parentInverseMatrix' % tgt,
                                '%s.targetParentInverseMatrix' % rotNode)

                joAttrpath = '%s.jo' % tgt
                if cmd.objExists(joAttrpath):
                    cmd.connectAttr(joAttrpath,
                                    '%s.targetJointOrient' % rotNode)

                cmd.connectAttr('%s.rotateOrder' % tgt,
                                '%s.targetRotationOrder' % rotNode)

                if not isDummyMode:
                    cmd.connectAttr('%s.outTranslate' % rotNode, '%s.t' % tgt)
                    cmd.connectAttr('%s.outRotate' % rotNode, '%s.r' % tgt)

                cmd.select(obj)

        #set the result to the node created...
        self.setResult(rotNode)

        #set any attributes passed in from the command-line
        if argData.isFlagSet(self.kFlagAxis):
            axisInt = Axis.FromName(
                argData.flagArgumentString(self.kFlagAxis, 0))
            cmd.setAttr('%s.mirrorAxis' % rotNode, axisInt)

        if argData.isFlagSet(self.kFlagMode):
            modeStr = argData.flagArgumentString(self.kFlagMode, 0)
            modeIdx = list(MirrorNode.MIRROR_MODE_NAMES).index(modeStr)
            cmd.setAttr('%s.mirrorTranslation' % rotNode, modeIdx)
def edo_calculateBlendShape(target, skmesh, method=2):
    #target='body_skin_proxy2'
    #skmesh='body_skin_proxy'
    #load plugin
    ELPLUGIN.edo_loadPlugin('geometryComputer.mll')
    sk = edo_findNodeFromHis(skmesh, 'skinCluster')
    tw = edo_findNodeFromHis(skmesh, 'tweak')
    bs = edo_findNodeFromHis(skmesh, 'blendShape')
    org = ''
    orgid = -1
    skorg = cmds.listRelatives(skmesh, s=1, pa=1)
    if not skorg:
        cmds.error('skin mesh has no org node')
        return False
    norg = cmds.listRelatives(skmesh, s=1, pa=1, ni=1)[0]
    skorg.remove(norg)
    i = 0
    for so in skorg:
        #so=skorg[1]
        if cmds.listConnections(so + '.worldMesh', d=1, s=0, p=1):
            org = so
            orgid = i
        i += 1
    if org == '':
        cmds.error('skin mesh has no org node')
        return False
    tm = cmds.duplicate(org, n='CALCULATE_BLENDSHAPE_TARGETMESH')[0]
    shs = cmds.listRelatives(tm, s=1, pa=1)
    if not shs:
        cmds.error('skin mesh has no org node')
        return False
    sh = cmds.listRelatives(tm, s=1, pa=1, ni=1)[0]
    shs.remove(sh)
    cmds.delete(sh)
    org = shs[orgid]
    osh = cmds.rename(org, tm + 'Shape')
    cmds.setAttr(osh + '.io', 0)
    #turnOff blendShape
    bsst = 1
    try:
        bsst = cmds.getAttr(bs + '.nodeState')
        cmds.setAttr(bs + '.nodeState', 1)
    except:
        print 'turn off the blendShape effect has been failed,please check the result.'
    try:
        gcnode = edo_mathBlendShapeCmd.edo_mathBlendShape(
            '', tm, target, '', 'SkinCluster_inverse', tw, sk)
    except:
        print 'calculate blendshape has been failed,please check the result.'
        cmds.delete(tm)
        try:
            cmds.setAttr(bs + '.nodeState', bsst)
        except:
            print 'turn off the blendShape effect has failed,please check the result.'
        return False
    finalbs = cmds.duplicate(tm)[0]
    cmds.delete(tm)
    try:
        cmds.setAttr(bs + '.nodeState', bsst)
    except:
        print 'turn off the blendShape effect has failed,please check the result.'
    edo_lockAndUnlockTransform.edo_unLockReferenceObjectTransformAttrs(finalbs)
    return finalbs
Exemplo n.º 38
0
    def buildData(self, nodeList=None, chanList=None):
        '''
		Build ChannelData class.
		@param nodeList: List of nodes to store channel values and connections for.
		@type nodeList: list
		'''
        # ==========
        # - Checks -
        # ==========

        # Node List
        if not nodeList:
            print('ChannelData: Empty node list! Unable to build channelData!')
            return

        # Channel List
        if not chanList: chanList = self.userChannelList
        if not chanList: chanList = []

        # ==============
        # - Build Data -
        # ==============

        # Start timer
        timer = mc.timerX()

        # Reset Data --- ?
        self.reset()

        # Build Node Channel Data
        self._data['channelDataNodes'] = []
        for node in nodeList:

            # Initialize Node Data
            self._channelData[node] = {}
            self._data['channelDataNodes'].append(node)

            # Build Node.Channel List
            nodeChanList = [
                node + '.' + i for i in chanList
                if mc.objExists(node + '.' + i)
            ]

            # Get Value Channel List
            valChanList = []
            if chanList: valChanList = chanList
            else:
                valChanList = mc.listAttr(node,
                                          se=True,
                                          r=True,
                                          w=True,
                                          m=True,
                                          v=True)

            # Get Source Connection Channel List
            srcChanList = []
            if nodeChanList:
                srcChanList = mc.listConnections(
                    nodeChanList, s=True, d=False, p=True, c=True,
                    sh=True) or []
            else:
                srcChanList = mc.listConnections(
                    node, s=True, d=False, p=True, c=True, sh=True) or []

            # Get Destination Connection Channel List
            dstChanList = []
            if nodeChanList:
                dstChanList = mc.listConnections(
                    nodeChanList, s=False, d=True, p=True, c=True,
                    sh=True) or []
            else:
                dstChanList = mc.listConnections(
                    node, s=False, d=True, p=True, c=True, sh=True) or []

            # Add Channel Value Data
            for chan in valChanList:

                # Check Attribute
                #if not mc.attributeQuery(chan,n=node,ex=True):
                if not mc.objExists(node + '.' + chan):
                    if self.verbosity > 0:
                        print('ChannelData: Node "' + node +
                              '" has no attribute "' + chan + '"! Skipping...')
                    continue

                # Check Settable
                if not mc.getAttr(node + '.' + chan, se=True):
                    if not mc.listConnections(
                            node + '.' + chan, s=True, d=False):
                        if self.verbosity > 0:
                            print('ChannelData: Attribute "' + node + '.' +
                                  chan + '" is not settable! Skipping...')
                        continue

                # Get Channel Value
                chanVal = None
                try:
                    chanVal = mc.getAttr(node + '.' + chan)
                except Exception, e:
                    if self.verbosity > 0:
                        print('ChannelData: Error getting channel value "' +
                              node + '.' + chan + '"! Skipping...')
                    if self.verbosity > 1:
                        print('ChannelData: Exception message: ' + str(e))
                else:
                    # Create Channel Entry
                    if not self._channelData[node].has_key(chan):
                        self._channelData[node][chan] = {}

                    # Store Channel Value
                    if not chanVal == None:
                        if type(chanVal) == list:
                            if type(chanVal[0]) == tuple:
                                chanVal = list(chanVal[0])
                        self._channelData[node][chan]['value'] = chanVal

            # Add Channel Source Data
            for i in range(0, len(srcChanList), 2):

                # Get Channel Name
                chan = str(srcChanList[i].replace(node + '.', ''))

                # Create Channel Entry
                if not self._channelData[node].has_key(chan):
                    self._channelData[node][chan] = {}

                # Store Channel Source Data
                self._channelData[node][chan]['source'] = srcChanList[i + 1]

                # Store Channel Value Data
                try:
                    chanVal = mc.getAttr(srcChanList[i])
                except Exception, e:
                    if self.verbosity > 0:
                        print('ChannelData: Error getting channel value "' +
                              node + '.' + chan + '"! Skipping...')
                    if self.verbosity > 1:
                        print('ChannelData: Exception message: ' + str(e))
                else:
                    self._channelData[node][chan]['value'] = chanVal
Exemplo n.º 39
0
def CreateConstraints(fingerCount, spineAmount):

    #left
    l_wristCtrl = base.ls("CTRL_L_Wrist", type='transform')
    l_wristIK = base.ls("IK_L_Arm")
    l_wristJoint = base.ls("RIG_L_Wrist")

    #right
    r_wristCtrl = base.ls("CTRL_R_Wrist", type='transform')
    r_wristIK = base.ls("IK_R_Arm")
    r_wristJoint = base.ls("RIG_R_Wrist")

    base.pointConstraint(l_wristCtrl, l_wristIK, mo=True)
    base.orientConstraint(l_wristCtrl, l_wristJoint, mo=True)
    base.connectAttr("CTRL_L_Wrist.Elbow_PV", "IK_L_Arm.twist")

    base.pointConstraint(r_wristCtrl, r_wristIK, mo=True)
    base.orientConstraint(r_wristCtrl, r_wristJoint, mo=True)
    base.connectAttr("CTRL_R_Wrist.Elbow_PV", "IK_R_Arm.twist")

    base.orientConstraint("CTRL_L_Clavicle", "RIG_L_Clavicle", mo=True)
    base.orientConstraint("CTRL_R_Clavicle", "RIG_R_Clavicle", mo=True)
    base.orientConstraint("CTRL_NECK", "RIG_Neck_Start", mo=True)
    base.orientConstraint("CTRL_HEAD", "RIG_Neck_End", mo=True)
    base.orientConstraint("CTRL_JAW", "RIG_Jaw_Start", mo=True)
    if (base.objExists("CTRL_BREATHING")):
        base.orientConstraint("CTRL_BREATHING", "RIG_BREATHING_START", mo=True)

    base.connectAttr("CTRL_SPINE_" + str(spineAmount - 1) + ".rotateY",
                     "IK_Spine.twist")

    if base.objExists("RIG_L_ArmTwist_0"):
        l_twistJoints = base.ls("RIG_L_ArmTwist_*")
        r_twistJoints = base.ls("RIG_L_ArmTwist_*")
        for i, x in enumerate(l_twistJoints):
            l_wristMultiply = base.shadingNode("multiplyDivide",
                                               asUtility=True,
                                               n="L_ArmTwist_Node_" + str(i))
            base.setAttr(l_wristMultiply + ".operation", 1)
            base.setAttr(l_wristMultiply + ".input2Y",
                         (1.0 - (1.0 / len(l_twistJoints) * (i + 1))) * -1)

            #check connections
            print base.listConnections("L_ArmTwist_Node_" + str(i), plugs=True)

            #input
            base.connectAttr("CTRL_L_Wrist.rotateY",
                             "L_ArmTwist_Node_" + str(i) + ".input1Y")
            #output
            base.connectAttr("L_ArmTwist_Node_" + str(i) + ".outputY",
                             "RIG_L_ArmTwist_" + str(i) + ".rotateX")

            r_wristMultiply = base.shadingNode("multiplyDivide",
                                               asUtility=True,
                                               n="R_ArmTwist_Node_" + str(i))
            base.setAttr(r_wristMultiply + ".operation", 1)
            base.setAttr(r_wristMultiply + ".input2Y",
                         (1.0 - (1.0 / len(r_twistJoints) * (i + 1))) * -1)
            #input
            base.connectAttr("CTRL_R_Wrist.rotateY",
                             "R_ArmTwist_Node_" + str(i) + ".input1Y")
            #output
            base.connectAttr("R_ArmTwist_Node_" + str(i) + ".outputY",
                             "RIG_R_ArmTwist_" + str(i) + ".rotateX")

    clusters = base.ls("Spine_Cluster_*", type='transform')
    spineCtrl = base.ls("CTRL_SPINE_*", type='transform')

    for j, cl in enumerate(clusters):
        if j > 0:
            print j
            base.parent(cl, spineCtrl[j - 1])
            print spineCtrl[j - 1]
        else:
            base.parent(cl, "CTRL_PELVIS")

    for k in range(0, fingerCount):
        l_allFingers = base.ls("RIG_L_Finger_" + str(k) + "_*")
        r_allFingers = base.ls("RIG_R_Finger_" + str(k) + "_*")

        for l in range(0, 3):
            if (k > 0):
                base.connectAttr(
                    "CTRL_L_Finger_" + str(k) + "_" + str(l) + ".rotateZ",
                    l_allFingers[l] + ".rotateZ")
                base.connectAttr(
                    "CTRL_R_Finger_" + str(k) + "_" + str(l) + ".rotateZ",
                    r_allFingers[l] + ".rotateZ")
                base.connectAttr(
                    "CTRL_L_Finger_" + str(k) + "_" + str(l) + ".rotateX",
                    l_allFingers[l] + ".rotateY")
                base.connectAttr(
                    "CTRL_R_Finger_" + str(k) + "_" + str(l) + ".rotateX",
                    r_allFingers[l] + ".rotateY")
            else:
                base.connectAttr(
                    "CTRL_L_Finger_" + str(k) + "_" + str(l) + ".rotateZ",
                    l_allFingers[l] + ".rotateZ")
                base.connectAttr(
                    "CTRL_R_Finger_" + str(k) + "_" + str(l) + ".rotateZ",
                    r_allFingers[l] + ".rotateZ")
                base.connectAttr(
                    "CTRL_L_Finger_" + str(k) + "_" + str(l) + ".rotateX",
                    l_allFingers[l] + ".rotateY")
                base.connectAttr(
                    "CTRL_R_Finger_" + str(k) + "_" + str(l) + ".rotateX",
                    r_allFingers[l] + ".rotateY")
        """
        if(k > 0):
            base.connectAttr("CTRL_L_Finger_"+str(k)+".rotateZ", l_allFingers[0]+".rotateY")
            base.connectAttr("CTRL_R_Finger_"+str(k)+".rotateZ", r_allFingers[0]+".rotateY")
        
            for l, l_finger in enumerate(l_allFingers):
                base.connectAttr("CTRL_L_Finger_"+str(k)+".rotateY", l_finger+".rotateZ")
            
            for m, r_finger in enumerate(r_allFingers):
                base.connectAttr("CTRL_R_Finger_"+str(k)+".rotateY", r_finger+".rotateZ")
        else:
            base.connectAttr("CTRL_L_Finger_"+str(k)+".rotateZ", l_allFingers[0]+".rotateY")
            base.connectAttr("CTRL_R_Finger_"+str(k)+".rotateZ", r_allFingers[0]+".rotateY")
        
            for l, l_finger in enumerate(l_allFingers):
                base.connectAttr("CTRL_L_Finger_"+str(k)+".rotateX", l_finger+".rotateZ")
            
            for m, r_finger in enumerate(r_allFingers):
                base.connectAttr("CTRL_R_Finger_"+str(k)+".rotateX", r_finger+".rotateZ")            
        """
    if base.objExists("RIG_L_INV_Heel"):
        base.pointConstraint("RIG_L_INV_Toes", "IK_L_Toes", mo=True)
        base.pointConstraint("RIG_L_INV_Ball", "IK_L_FootBall", mo=True)
        base.pointConstraint("RIG_L_INV_Ankle", "IK_L_Leg", mo=True)

        base.pointConstraint("RIG_R_INV_Toes", "IK_R_Toes", mo=True)
        base.pointConstraint("RIG_R_INV_Ball", "IK_R_FootBall", mo=True)
        base.pointConstraint("RIG_R_INV_Ankle", "IK_R_Leg", mo=True)

        base.pointConstraint("CTRL_L_Foot", "RIG_L_INV_Heel", mo=True)
        base.orientConstraint("CTRL_L_Foot", "RIG_L_INV_Heel", mo=True)

        base.pointConstraint("CTRL_R_Foot", "RIG_R_INV_Heel", mo=True)
        base.orientConstraint("CTRL_R_Foot", "RIG_R_INV_Heel", mo=True)

        base.connectAttr("CTRL_L_Foot.Foot_Roll", "RIG_L_INV_Ball.rotateX")
        base.connectAttr("CTRL_L_Foot.Ball_Roll", "RIG_L_INV_Toes.rotateX")

        base.connectAttr("CTRL_R_Foot.Foot_Roll", "RIG_R_INV_Ball.rotateX")
        base.connectAttr("CTRL_R_Foot.Ball_Roll", "RIG_R_INV_Toes.rotateX")

    else:
        base.parent("IK_L_Toes", "IK_L_FootBall")
        base.parent("IK_L_FootBall", "IK_L_Leg")

        base.parent("IK_R_Toes", "IK_R_FootBall")
        base.parent("IK_R_FootBall", "IK_R_Leg")

        base.pointConstraint("CTRL_R_Foot", "IK_R_Leg", mo=True)
        base.orientConstraint("CTRL_R_Foot", "IK_R_Leg", mo=True)

        base.pointConstraint("CTRL_L_Foot", "IK_L_Leg", mo=True)
        base.orientConstraint("CTRL_L_Foot", "IK_L_Leg", mo=True)

    #feet constraints

    #lleft
    base.setAttr("IK_L_Leg.poleVectorX", 1)
    base.setAttr("IK_L_Leg.poleVectorZ", 0)
    l_footAverage = base.shadingNode("plusMinusAverage",
                                     asUtility=True,
                                     n="L_Foot_Node")
    base.setAttr(l_footAverage + ".operation", 2)
    base.connectAttr("CTRL_L_Foot.Knee_Fix", l_footAverage + ".input1D[0]")
    base.connectAttr("CTRL_L_Foot.Knee_Twist", l_footAverage + ".input1D[1]")
    base.connectAttr(l_footAverage + ".output1D", "IK_L_Leg.twist")
    base.setAttr("CTRL_L_Foot.Knee_Fix", 90)

    #right
    base.setAttr("IK_R_Leg.poleVectorX", 1)
    base.setAttr("IK_R_Leg.poleVectorZ", 0)
    r_footAverage = base.shadingNode("plusMinusAverage",
                                     asUtility=True,
                                     n="R_Foot_Node")
    base.setAttr(r_footAverage + ".operation", 2)
    base.connectAttr("CTRL_R_Foot.Knee_Fix", r_footAverage + ".input1D[0]")
    base.connectAttr("CTRL_R_Foot.Knee_Twist", r_footAverage + ".input1D[1]")
    base.connectAttr(r_footAverage + ".output1D", "IK_R_Leg.twist")
    base.setAttr("CTRL_R_Foot.Knee_Fix", 90)

    SetAttributes.LockAttributes()
Exemplo n.º 40
0
def serialise_shaders(nodes):
    """Generate a shader set dictionary

    Arguments:
        nodes (list): Absolute paths to nodes

    Returns:
        dictionary of (shader: id) pairs

    Schema:
        {
            "shader1": ["id1", "id2"],
            "shader2": ["id3", "id1"]
        }

    Example:
        {
            "Bazooka_Brothers01_:blinn4SG": [
                "f9520572-ac1d-11e6-b39e-3085a99791c9.f[4922:5001]",
                "f9520572-ac1d-11e6-b39e-3085a99791c9.f[4587:4634]",
                "f9520572-ac1d-11e6-b39e-3085a99791c9.f[1120:1567]",
                "f9520572-ac1d-11e6-b39e-3085a99791c9.f[4251:4362]"
            ],
            "lambert2SG": [
                "f9520571-ac1d-11e6-9dbb-3085a99791c9"
            ]
        }

    """

    valid_nodes = cmds.ls(nodes,
                          long=True,
                          recursive=True,
                          showType=True,
                          objectsOnly=True,
                          type="transform")

    meshes_by_id = {}
    for mesh in valid_nodes:
        shapes = cmds.listRelatives(valid_nodes[0], shapes=True,
                                    fullPath=True) or list()

        if shapes:
            shape = shapes[0]
            if not cmds.nodeType(shape):
                continue

            try:
                id_ = cmds.getAttr(mesh + ".modelID")

                if id_ not in meshes_by_id:
                    meshes_by_id[id_] = list()

                meshes_by_id[id_].append(mesh)

            except ValueError:
                continue

    meshes_by_shader = dict()
    for id_, mesh in meshes_by_id.items():
        shape = cmds.listRelatives(mesh, shapes=True, fullPath=True) or list()

        for shader in cmds.listConnections(shape,
                                           type="shadingEngine") or list():

            # Objects in this group are those that haven't got
            # any shaders. These are expected to be managed
            # elsewhere, such as by the default model loader.
            if shader == "initialShadingGroup":
                continue

            if shader not in meshes_by_shader:
                meshes_by_shader[shader] = list()

            shaded = cmds.sets(shader, query=True) or list()
            meshes_by_shader[shader].extend(shaded)

    shader_by_id = {}
    for shader, shaded in meshes_by_shader.items():

        if shader not in shader_by_id:
            shader_by_id[shader] = list()

        for mesh in shaded:

            # Enable shader assignment to faces.
            name = mesh.split(".f[")[0]

            transform = name
            if cmds.objectType(transform) == "mesh":
                transform = cmds.listRelatives(name, parent=True)[0]

            try:
                id_ = cmds.getAttr(transform + ".modelID")
                shader_by_id[shader].append(mesh.replace(name, id_))
            except KeyError:
                continue

        # Remove duplicates
        shader_by_id[shader] = list(set(shader_by_id[shader]))

    return shader_by_id
Exemplo n.º 41
0
def kinematify(mainChainStartJoint, mainChainEndJoint, ikControl, ikfkSwitch,
               jointNameSuffix):

    mainChain = getJointChainBetween(mainChainStartJoint, mainChainEndJoint,
                                     [])
    numLayers = len(mainChain)

    # Create IK chain
    cmds.select(clear=1)
    ikChain = []
    for joint in mainChain:
        jointPos = cmds.xform(joint, q=1, rotatePivot=1, worldSpace=1)
        ikJoint = cmds.joint(position=jointPos,
                             name=joint.replace(jointNameSuffix,
                                                '_IK' + jointNameSuffix),
                             radius=cmds.joint(joint, q=1, radius=1)[0])
        ikChain.append(ikJoint)

    ikChainStartJoint = ikChain[0]
    ikChainEndJoint = ikChain[len(ikChain) - 1]

    # ...Create IK handle
    ikHandle = cmds.ikHandle(startJoint=ikChainStartJoint,
                             endEffector=ikChainEndJoint)[0]
    ikHandle = cmds.rename(ikHandle, ikControl.replace('_CTRL', '_IK'))
    cmds.parent(ikHandle, ikControl)

    # Create FK chain
    cmds.select(clear=1)
    fkChain = []
    for joint in mainChain:
        jointPos = cmds.xform(joint, q=1, rotatePivot=1, worldSpace=1)
        fkJoint = cmds.joint(position=jointPos,
                             name=joint.replace(jointNameSuffix,
                                                '_FK' + jointNameSuffix),
                             radius=cmds.joint(joint, q=1, radius=1)[0])
        fkChain.append(fkJoint)

    fkChainStartJoint = fkChain[0]
    fkChainEndJoint = fkChain[len(ikChain) - 1]

    # Orient main chain to IK and FK chains
    orientConstrs = []
    for i in range(len(mainChain)):
        orientConstr = cmds.orientConstraint(ikChain[i],
                                             fkChain[i],
                                             mainChain[i],
                                             maintainOffset=1)[0]
        cmds.setAttr(orientConstr + '.interpType', 2)  # Shortest interpolation
        orientConstrs.append(orientConstr)

    cmds.orientConstraint(ikControl, ikChainEndJoint, maintainOffset=1)

    # Connect IKFK switch control to all orient constraints' attributes
    cmds.addAttr(ikfkSwitch, ln='IK', at='float', min=0, max=1, keyable=1)
    cmds.addAttr(ikfkSwitch, ln='FK', at='float', min=0, max=1, keyable=1)

    for orientConstr in orientConstrs:
        attrs = cmds.listAttr(orientConstr, keyable=1)
        for attr in attrs:
            for fkJoint in fkChain:
                if fkJoint in attr:
                    orientConstrAttr = orientConstr + '.' + attr
                    ikfkSwitchFK = ikfkSwitch + '.FK'
                    if not cmds.isConnected(ikfkSwitchFK, orientConstrAttr):
                        cmds.connectAttr(ikfkSwitchFK, orientConstrAttr)
            for ikJoint in ikChain:
                if ikJoint in attr:
                    orientConstrAttr = orientConstr + '.' + attr
                    ikfkSwitchIK = ikfkSwitch + '.IK'
                    if not cmds.isConnected(ikfkSwitchIK, orientConstrAttr):
                        cmds.connectAttr(ikfkSwitchIK, orientConstrAttr)

    # Relate IK attribute to FK attribute
    cmds.expression(string="%s = 1 - %s" %
                    (ikfkSwitch + '.FK', ikfkSwitch + '.IK'))
    cmds.setAttr(ikfkSwitch + '.FK', keyable=0, channelBox=0)

    # Create FK controls
    fkControl = createFkControls(fkChainStartJoint, jointNameSuffix)

    # Parent constrain FK controls to the main chain's parent control
    mainChainParentJoint = getParentJoint(mainChainStartJoint)
    if mainChainParentJoint is not None:
        parentConstrs = cmds.listConnections(mainChainParentJoint,
                                             type='parentConstraint')
        if parentConstrs is not None:
            parentConstr = parentConstrs[0]
            parentCtrls = [
                ctrl for ctrl in cmds.listConnections(parentConstr,
                                                      type='transform')
                if '_CTRL' in ctrl
            ]
            if parentCtrls is not None:
                parentCtrl = parentCtrls[0]
                cmds.parentConstraint(parentCtrl, fkControl, maintainOffset=1)

    # Point constrain IK start to main chain start
    cmds.pointConstraint(mainChainStartJoint, ikChainStartJoint)

    # Parent constraint IKFK switch to end joint
    cmds.parentConstraint(mainChainEndJoint, ikfkSwitch, maintainOffset=1)

    # Lock IK/FK switch attributes
    cmds.setAttr(ikfkSwitch + '.tx', keyable=0)
    cmds.setAttr(ikfkSwitch + '.ty', keyable=0)
    cmds.setAttr(ikfkSwitch + '.tz', keyable=0)
    cmds.setAttr(ikfkSwitch + '.rx', keyable=0)
    cmds.setAttr(ikfkSwitch + '.ry', keyable=0)
    cmds.setAttr(ikfkSwitch + '.rz', keyable=0)
    cmds.setAttr(ikfkSwitch + '.sx', keyable=0)
    cmds.setAttr(ikfkSwitch + '.sy', keyable=0)
    cmds.setAttr(ikfkSwitch + '.sz', keyable=0)
    cmds.setAttr(ikfkSwitch + '.visibility', keyable=0)

    # Handle controls/joints visibility
    cmds.connectAttr(ikfkSwitch + '.IK', ikControl + '.visibility')
    cmds.connectAttr(ikfkSwitch + '.FK', fkControl + '.visibility')
    cmds.setAttr(fkChainStartJoint + '.visibility', 0)
    cmds.setAttr(ikChainStartJoint + '.visibility', 0)

    # Group everything for cleanup
    worldGroup = 'world'
    if not cmds.objExists(worldGroup):
        cmds.group(name=worldGroup, empty=1)

    ikfkGrp = cmds.group(ikChainStartJoint,
                         fkChainStartJoint,
                         fkControl,
                         name=mainChainStartJoint.replace(
                             jointNameSuffix, '_IKFK_GRP'))
    cmds.parent(ikfkGrp, worldGroup)
Exemplo n.º 42
0
                                'ChannelData: Node channel "' + node + '.' +
                                chan +
                                '" is not settable!! Unable to restore channel value...'
                            )

                # Restore Channel Destination Connection
                if connectDestination:
                    if self._channelData[node][chan].has_key('destination'):
                        src = node + '.' + chan
                        dst = self._channelData[node][chan]['destination']

                        # Check existing connections
                        connect = True
                        dstConn = mc.listConnections(dst,
                                                     s=True,
                                                     d=False,
                                                     p=True,
                                                     sh=True)
                        if dstConn:
                            if dstConn[0] == src:
                                if self.verbosity > 0:
                                    print('ChannelData: "' + src +
                                          '" already connected to "' + dst +
                                          '"! Skipping...')
                                connect = False

                        # Check Locked Destination
                        if connect:
                            dstLocked = mc.getAttr(dst, l=True)
                            if dstLocked:
                                try:
Exemplo n.º 43
0
def getUVData(meshName, jointName, borderEdges):

    getObj = cmds.ls(meshName, dag=1)[1]
    print "meshName", meshName
    shadingGrps = cmds.listConnections(getObj, type='shadingEngine')

    #cmds.polyEditUV("pPlane8.map[3]",q=True)
    #shadingGrps = cmds.listConnections(meshName,type='shadingEngine')
    shaders = cmds.ls(cmds.listConnections(shadingGrps), materials=1)
    fileNode = cmds.listConnections('%s.color' % (shaders[0]), type='file')[0]
    print fileNode
    imageWidth = getImageMetaData(fileNode)[1]
    imageHeight = getImageMetaData(fileNode)[2]
    #print imageWidth,imageHeight, getImageMetaData(fileNode)
    # scaleRatio = imageHeight/imageWidth
    # print "scaleRatio",scaleRatio.imageWidth,imageHeight
    uvCount = cmds.polyEvaluate(meshName, uv=True)
    uvCoordDict = {}
    for i in range(0, uvCount):
        uvCoord = cmds.polyEditUV("%s.map[%s]" % (meshName, i), q=True)

        uvCoordDict.update({i: uvCoord})
    triangleVertexDict = {}
    faceCount = cmds.polyEvaluate(meshName, f=True)
    for i in range(0, faceCount):
        toVertex = cmds.polyListComponentConversion(
            "%s.f[%s]" % (meshName, i),
            tv=True,
        )
        cmds.select(toVertex)
        faceRefVertex = cmds.ls(sl=True, fl=True)
        triangleVertexDict.update({i: faceRefVertex})
    cmds.select(cl=True)

    edgeCount = cmds.polyEvaluate(meshName, e=True)

    border = cmds.polyListComponentConversion(cmds.ls(sl=True, fl=True),
                                              uvs=True)

    cmds.select(cl=True)

    uvCoordListForSpine = []
    for i in uvCoordDict.keys():
        #   print i
        uvCoordListForSpine.append(uvCoordDict[i][0])
        uvCoordListForSpine.append((1 - uvCoordDict[i][1]))
# print "uvCoordListForSpine",uvCoordListForSpine

    trianglesListForSpine = []
    for i in triangleVertexDict.keys():
        trianglesListForSpine.append(
            int(triangleVertexDict[i][0].split("[")[1].split("]")[0]))
        trianglesListForSpine.append(
            int(triangleVertexDict[i][1].split("[")[1].split("]")[0]))
        trianglesListForSpine.append(
            int(triangleVertexDict[i][2].split("[")[1].split("]")[0]))

# print "trianglesListForSpine",trianglesListForSpine

    allvertexs = cmds.polyListComponentConversion(meshName, tv=True)
    #vertexList = []
    cmds.select(allvertexs)
    vertexList = cmds.ls(sl=True, fl=True)
    cmds.select(cl=True)
    ox = cmds.getAttr("%s.translateX" % jointName)
    oy = cmds.getAttr("%s.translateY" % jointName)
    print ox, oy

    #  print vertexList
    vertexPositionForSpine = []
    for i in vertexList:
        #   print cmds.pointPosition(i)
        vertexPositionForSpine.append(cmds.pointPosition(i)[0] - ox)
        vertexPositionForSpine.append(cmds.pointPosition(i)[1] - oy)

# print "vertexPositionForSpin",vertexPositionForSpine

# borderEdgesString = cmds.getAttr("%s.borderList"%meshName)
# borderEdges = borderEdgesString.split(",")
    borderEdgesCount = len(borderEdges)

    edgesVertexDict = {}
    for i in range(0, borderEdgesCount):
        toVertex = cmds.polyListComponentConversion(
            borderEdges[i],
            tv=True,
        )
        cmds.select(toVertex)
        edgeRefVertex = cmds.ls(sl=True, fl=True)
        edgesVertexDict.update({i: edgeRefVertex})

    edgesVertexForSpineList = []
    for i in edgesVertexDict.keys():
        v1 = edgesVertexDict[i][0].split("[")[-1].split("]")[0]
        v2 = edgesVertexDict[i][1].split("[")[-1].split("]")[0]

        edgesVertexForSpineList.append(int(v1) * 2)
        edgesVertexForSpineList.append(int(v2) * 2)
    #print "edgesVertexForSpineList",edgesVertexForSpineList
    width = imageWidth  #cmds.getAttr("%s.scaleX"%meshName)
    height = imageHeight  #cmds.getAttr#("%s.scaleZ"%meshName)

    dataForSpine = {
        "type": "mesh",
        "width": width,
        "height": height,
        "uvs": uvCoordListForSpine,
        "triangles": trianglesListForSpine,
        "vertices": vertexPositionForSpine,
        "hull": borderEdgesCount,
        "edges": edgesVertexForSpineList
    }

    return dataForSpine
Exemplo n.º 44
0
############################################################################ BUILD RIG PUPPET

import maya.cmds as mc

attr = 'pCube1.ty'
anm = mc.listConnections(attr, s=True, d=False)[0]

breakdown = mc.keyframe(anm, q=1, breakdown=1)
eval = mc.keyframe(anm, q=1, eval=1)
floatChange = mc.keyframe(anm, q=1, floatChange=1)  # NONE TIME INPUT
valueChange = mc.keyframe(anm, q=1, valueChange=1)
timeChange = mc.keyframe(anm, q=1, timeChange=1)

inTangentType = mc.keyTangent(anm, q=1, inTangentType=1)
outTangentType = mc.keyTangent(anm, q=1, outTangentType=1)
weightedTangents = mc.keyTangent(anm, q=1, weightedTangents=1)
mc.keyTangent(anm, e=1, weightedTangents=1)
ix = mc.keyTangent(anm, q=1, ix=1)
iy = mc.keyTangent(anm, q=1, iy=1)
ox = mc.keyTangent(anm, q=1, ox=1)
oy = mc.keyTangent(anm, q=1, oy=1)
#mc.keyTangent(anm, e=1, weightedTangents=weightedTangents)

inAngle = mc.keyTangent(anm, q=1, inAngle=1)
inWeight = mc.keyTangent(anm, q=1, inWeight=1)
lock = mc.keyTangent(anm, q=1, lock=1)
outAngle = mc.keyTangent(anm, q=1, outAngle=1)
outWeight = mc.keyTangent(anm, q=1, outWeight=1)

weightLock = mc.keyTangent(anm, q=1, weightLock=1)
Exemplo n.º 45
0
def ExportVrayMeshToFbx_ex(mode):
    myPlaneChangeFlag = False
    myactivePlane = ''
    i = 1
    while (i):
        try:
            tmp = mc.modelEditor('modelPanel%d' % i, q=True, av=True)
        except:
            pass
        else:
            if tmp:
                myactivePlane = 'modelPanel%d' % i
                break
        i += 1
    myActivePlaneV = mc.modelEditor(myactivePlane, q=True, da=True)
    if myActivePlaneV != "boundingBox":
        #mc.modelEditor(myactivePlane, e=True, da='boundingBox')
        myPlaneChangeFlag = True
    myAllVrayPath = []
    try:
        allVrayMeshs = mc.ls(type="VRayMesh")
    except:
        mc.warning(u'没有VrayMesh缓存')
    else:
        if allVrayMeshs:
            #判断如果有文件不存在退出
            for myVrayMesh in allVrayMeshs:
                myeachName = mc.getAttr('%s.fileName' % myVrayMesh)
                if not os.path.isfile(myeachName):
                    mc.confirmDialog(title=u'温馨提示',
                                     message=u'代理物体指定的路径找不到相应文件!',
                                     button=['OK'],
                                     defaultButton='Yes',
                                     dismissString='No')
                    #return False
            if not mc.pluginInfo('fbxmaya', query=True, loaded=True):
                mc.loadPlugin("fbxmaya")
            numAllVrayMeshs = len(allVrayMeshs)
            mc.progressWindow(title=u'正在导出VrayMesh为FBX到Data中!\n    请耐心等待',
                              progress=0,
                              status=u'即将开始',
                              min=0,
                              max=numAllVrayMeshs,
                              isInterruptable=True)
            tmp = mc.workspace("FBX export", query=True, renderTypeEntry=True)
            myDataPath = mc.workspace(expandName=tmp)
            allMyVrayMeshs = []
            for i, myVrayMesh in enumerate(allVrayMeshs):
                # print u"正在导出第 %s 个,总共有 %s 个VrayMesh代理文件" % (i, numAllVrayMeshs)
                myVrayPath = mc.getAttr('%s.fileName' % myVrayMesh)
                myVrayMeshTran = ''
                VrayMeshCons = mc.listConnections(myVrayMesh)
                if VrayMeshCons:
                    for eachCon in VrayMeshCons:
                        if mc.nodeType(eachCon) == "transform":
                            myVrayMeshTran = eachCon
                            break
                if myVrayPath in myAllVrayPath:
                    continue
                elif myVrayMeshTran == '':
                    continue
                else:
                    myAllVrayPath.append(myVrayPath)
                    allMyVrayMeshs.append(myVrayMesh)
            if allMyVrayMeshs:
                for myVrayMesh in allMyVrayMeshs:
                    myVrayPath = mc.getAttr('%s.fileName' % myVrayMesh)
                    mc.setAttr("%s.reassignShaders" % myVrayMesh, 1)
                    myBaseName = os.path.basename(myVrayPath)
                    myFileName = os.path.splitext(myBaseName)[0]
                    myNerMeshTr = ""
                    if mode == 1:
                        mm.eval("vray restoreMesh %s;" % myVrayMesh)
                        myNewMeshShape = mc.ls(sl=True)
                        myNerMeshTr = mc.listRelatives(myNewMeshShape[0],
                                                       f=True,
                                                       p=True)[0]
                        mc.setAttr("%s.tx" % myNerMeshTr, 0)
                        mc.setAttr("%s.ty" % myNerMeshTr, 0)
                        mc.setAttr("%s.tz" % myNerMeshTr, 0)
                    elif mode == 2:
                        #print mode
                        BoxChangeFlag = False
                        MeshChangeFlag = False
                        myVrayMeshTran = ""
                        BoxFlag = mc.getAttr("%s.showBBoxOnly" % myVrayMesh)
                        MeshFlag = mc.getAttr("%s.showWholeMesh" % myVrayMesh)
                        if BoxFlag:
                            mc.setAttr("%s.showBBoxOnly" % myVrayMesh, 0)
                            BoxChangeFlag = True
                        if not MeshFlag:
                            mc.setAttr("%s.showWholeMesh" % myVrayMesh, 1)
                            MeshChangeFlag = True
                        #print myVrayMesh
                        VrayMeshCons = mc.listConnections(myVrayMesh)
                        if VrayMeshCons:
                            for eachCon in VrayMeshCons:
                                if mc.nodeType(eachCon) == "transform":
                                    myVrayMeshTran = eachCon
                                    break
                        if myVrayMeshTran:
                            myVrayMeshDTran = mc.duplicate(myVrayMeshTran,
                                                           rr=True)
                            try:
                                myVrayMeshNew = mc.parent(myVrayMeshDTran,
                                                          w=True)
                            except:
                                myVrayMeshNew = myVrayMeshDTran
                            myNerMeshTr = mc.ls(myVrayMeshNew, l=True)
                            if MeshChangeFlag:
                                mc.setAttr("%s.showWholeMesh" % myVrayMesh,
                                           MeshFlag)
                            if BoxChangeFlag:
                                mc.setAttr("%s.showBBoxOnly" % myVrayMesh,
                                           BoxFlag)
                    if myNerMeshTr:
                        myFileFullName = os.path.join(myDataPath,
                                                      myFileName + ".fbx")
                        myFileFullName = os.path.normpath(myFileFullName)
                        myNerMeshTr = mc.rename(myNerMeshTr, myFileName)
                        mc.select(myNerMeshTr)
                        mc.file(myFileFullName,
                                force=True,
                                options="v=0",
                                type="FBX export",
                                pr=True,
                                es=True)
                        mc.delete(myNerMeshTr)
                        mc.progressWindow(edit=True, progress=i + 1)
                        if mc.progressWindow(q=True, isCancelled=True):
                            break
            mc.progressWindow(endProgress=True)
            os.startfile(myDataPath)
        else:
            mc.warning(u'没有VrayMesh缓存')
    if myPlaneChangeFlag:
        mc.modelEditor(myactivePlane, e=True, da=myActivePlaneV)
Exemplo n.º 46
0
def getAnimationList(slotList, boneList, fps, start, end, offsetRange,
                     actionName):
    animationList = {}
    actionAnimation = {actionName: {"slots": {}, "bones": {}}}

    soltsAnimationDict = {}
    for slot in slotList:
        slotName = slot["name"]
        tempSlotDict = {slotName: {"color": []}}
        soltsAnimationDict.update(tempSlotDict)
        getObj = cmds.ls(slotName, dag=1)[1]
        shadingGrps = cmds.listConnections(getObj, type='shadingEngine')
        shaders = cmds.ls(cmds.listConnections(shadingGrps), materials=1)
        fileNode = cmds.listConnections('%s.color' % (shaders[0]),
                                        type='file')[0]
        attachment = slot["attachment"]
        keyFrameList = getAllkeyFrameList(fileNode, start, end)

        for i in keyFrameList:
            if int(i) in range(start, end + 1):
                cmds.currentTime(i, e=True)
                alphaGain = cmds.getAttr("%s.alphaGain" % fileNode)
                colorGain = cmds.getAttr("%s.colorGain" % fileNode)[0]

                alphaGainHex = "%02x" % int((alphaGain / 1) * 255)
                colorGainHex = "%02x" % int(
                    (colorGain[0] / 1) * 255) + "%02x" % int(
                        (colorGain[1] / 1) * 255) + "%02x" % int(
                            (colorGain[2] / 1) * 255)
                exportColorHex = str(colorGainHex + alphaGainHex)
                soltsAnimationDict[slotName]["color"].append({
                    "time":
                    float(i) / fps,
                    "color":
                    exportColorHex
                })
            else:
                pass

        if cmds.getAttr("%s.useFrameExtension" % fileNode) == True:
            sequenceFrameList = []
            soltsAnimationDict[slotName].update({"attachment": []})
            fileName = cmds.getAttr("%s.fileTextureName" %
                                    fileNode).split("/")[-1]
            fileDir = cmds.getAttr("%s.fileTextureName" %
                                   fileNode).split(fileName)[0]

            allFiles = os.listdir(fileDir)
            sequenceList = []
            for j in allFiles:
                # print i.split(".")
                if j.split(".")[0] == fileName.split(".")[0]:
                    sequenceList.append(j)

        # print sequenceList

            for i in range(start, end):
                sequenceFrameList.append(i)
            offsetFrame = random.randint(0, offsetRange)
            # print offsetFrame
            for i in sequenceFrameList:
                # print i ,float(i)/fps
                if int(i) in range(start, end + 1):

                    # print fileDir

                    attachmentFile = sequenceList[(i + offsetFrame) %
                                                  (len(sequenceList)) -
                                                  1].split(".png")[0]
                    soltsAnimationDict[slotName]["attachment"].append({
                        "time":
                        float(i) / fps,
                        "name":
                        attachmentFile
                    })

                else:
                    pass
        else:
            pass

    actionAnimation[actionName]["slots"].update(soltsAnimationDict)
    animationList.update(actionAnimation)

    # print "keyFrameList",keyFrameList

    #  return animationList

    for bone in boneList:
        # boneKeyFrameList = []
        boneName = bone["name"]
        keyFrameList = getAllkeyFrameList(boneName, start, end)
        # print "keyFrameList",keyFrameList

        translateKeyValueList = []
        scaleKeyValueList = []
        rotateKeyValueList = []
        #  print keyFrameList
        if keyFrameList == None:
            pass
        else:
            for i in range(0, len(keyFrameList)):
                frame = float(keyFrameList[i])
                print "frame", frame
                if i == 0:
                    preFrame = 0
                    #  frame = 0.0
                    translateX = float("%.4f" % (cmds.keyframe(
                        boneName, at='tx', t=(0, 0), q=True, eval=True)[0]))
                    translateY = float("%.4f" % (cmds.keyframe(
                        boneName, at='ty', t=(0, 0), q=True, eval=True)[0]))
                    rotate = float("%.4f" % (cmds.keyframe(
                        boneName, at='rz', t=(0, 0), q=True, eval=True)[0]))
                    scaleX = float("%.4f" % (cmds.keyframe(
                        boneName, at='sx', t=(0, 0), q=True, eval=True)[0]))
                    scaleY = float("%.4f" % (cmds.keyframe(
                        boneName, at='sy', t=(0, 0), q=True, eval=True)[0]))

                else:

                    preFrame = keyFrameList[i - 1]

                    translateXFrame = float("%.4f" % (cmds.keyframe(
                        boneName, at='tx', t=(frame, frame), q=True,
                        eval=True)[0]))
                    translateXpreFrame = float(
                        "%.4f" % (cmds.keyframe(boneName,
                                                at='tx',
                                                t=(preFrame, preFrame),
                                                q=True,
                                                eval=True)[0]))
                    translateX = translateXFrame - translateXpreFrame

                    translateYFrame = float("%.4f" % (cmds.keyframe(
                        boneName, at='ty', t=(frame, frame), q=True,
                        eval=True)[0]))
                    translateYpreFrame = float(
                        "%.4f" % (cmds.keyframe(boneName,
                                                at='ty',
                                                t=(preFrame, preFrame),
                                                q=True,
                                                eval=True)[0]))
                    translateY = translateYFrame - translateYpreFrame

                    rotateFrame = float("%.4f" % (cmds.keyframe(
                        boneName, at='rz', t=(frame, frame), q=True,
                        eval=True)[0]))
                    rotatePreFrame = float(
                        "%.4f" % (cmds.keyframe(boneName,
                                                at='rz',
                                                t=(preFrame, preFrame),
                                                q=True,
                                                eval=True)[0]))
                    rotate = rotateFrame  #-rotatePreFrame

                    scaleXFrame = float("%.4f" % (cmds.keyframe(
                        boneName, at='sx', t=(frame, frame), q=True,
                        eval=True)[0]))
                    scaleXPreFrame = float(
                        "%.4f" % (cmds.keyframe(boneName,
                                                at='sx',
                                                t=(preFrame, preFrame),
                                                q=True,
                                                eval=True)[0]))
                    scaleX = scaleXFrame / scaleXPreFrame

                    scaleYFrame = float("%.4f" % (cmds.keyframe(
                        boneName, at='sy', t=(frame, frame), q=True,
                        eval=True)[0]))
                    scaleYPreFrame = float(
                        "%.4f" % (cmds.keyframe(boneName,
                                                at='sy',
                                                t=(preFrame, preFrame),
                                                q=True,
                                                eval=True)[0]))
                    scaleY = scaleYFrame / scaleYPreFrame

            # print boneName,frame,rotateFrame,rotatePreFrame,rotate
                translateKeyValueList.append({
                    "time": frame / fps,
                    "x": translateX,
                    "y": translateY
                })  #,"curve": [ 0.25, 0, 0.75, 1 ]
                scaleKeyValueList.append({
                    "time": frame / fps,
                    "x": scaleX,
                    "y": scaleY
                })
                rotateKeyValueList.append({
                    "time": frame / fps,
                    "angle": rotate
                })
            '''
            for i in keyFrameList:
                if int(i) in range(start,end+1):
                    print i,boneName

                    translateX = float("%.4f"%(cmds.keyframe( boneName,at='tx',t=(i,i),q=True,eval=True)[0]))          
                    translateY = float("%.4f"%(cmds.keyframe( boneName,at='ty',t=(i,i),q=True,eval=True)[0]))
                    rotate = float( "%.4f"%(cmds.keyframe( boneName,at='rz',t=(i,i),q=True,eval=True)[0]))
                    width = float("%.4f"%(cmds.keyframe( boneName,at='sx',t=(i,i),q=True,eval=True)[0]))
                    height = float("%.4f"%(cmds.keyframe( boneName,at='sy',t=(i,i),q=True,eval=True)[0]))
                    originalWidth = float("%.4f"%(cmds.keyframe( boneName,at='sx',t=(0,0),q=True,eval=True)[0]))
                    originalHeight = float("%.4f"%(cmds.keyframe( boneName,at='sy',t=(0,0),q=True,eval=True)[0]))
                    scaleX = width/ originalWidth
                    scaleY = height /originalHeight
                   # print i ,boneName,rotate

                    if i == 0:
                       # print "0000" getAnimationList
                        translateKeyValueList.append({"time":i/fps,"x":translateX,"y":translateY})  #,"curve": [ 0.25, 0, 0.75, 1 ]
                    else:
                        translateKeyValueList.append({"time":i/fps,"x":translateX,"y":translateY})  #,"curve": [ 0.25, 0, 0.75, 1 ]
                    scaleKeyValueList.append({"time":i/fps,"x":scaleX,"y":scaleY})
                    rotateKeyValueList.append({"time":i/fps,"angle":rotate})

                else:
                    pass
            '''
            boneAnimationDict = {
                str(boneName): {
                    "translate": translateKeyValueList,
                    "scale": scaleKeyValueList,
                    "rotate": rotateKeyValueList
                }
            }
            animationList[actionName]["bones"].update(boneAnimationDict)

    return animationList
Exemplo n.º 47
0
def bakeControlOverride(controlList, start=None, end=None, bakeSim=True):
    '''
	Bake control constraint to transform channel keys.
	@param controlList: The control list that will have its constraints baked to keyframes.
	@type controlList: list
	@param start: Start frame of the bake animation range. If greater that end, use current playback settings.
	@type start: float
	@param end: End frame of the bake animation range. If less that start, use current playback settings.
	@type end: float
	@param bakeSim: Bake results using simulation option which updates the entire scene at each bake sample.
	@type bakeSim: bool
	'''
    print(
        '!!==== DEPRICATED ====!! (glTools.rig.mocapOverride.bakeControlOverride)'
    )

    # ==========
    # - Checks -
    # ==========

    # Start/End
    if start == None: start = mc.playbackOptions(q=True, min=True)
    if end == None: end = mc.playbackOptions(q=True, max=True)

    # For Each Control
    bakeControlList = []
    constraintList = []
    for control in controlList:

        # Control
        if not mc.objExists(control):
            raise Exception('Rig control transform "' + control +
                            '" does not exist!')

        # Override Target Constraint
        overrideConstraint = mc.ls(mc.listConnections(control + '.' +
                                                      overrideAttribute(),
                                                      d=True,
                                                      s=False),
                                   type='constraint')
        if not overrideConstraint:

            # Check PairBlend (intermediate) Connection
            # - This fix was made in preparation for baking keys from multiple mocap sources (bake in frame chunks).
            overridePairBlend = mc.ls(mc.listConnections(control,
                                                         s=True,
                                                         d=False),
                                      type='pairBlend')
            if overridePairBlend:
                overrideConstraint = mc.ls(mc.listConnections(
                    overrideTargetPairBlend, s=True, d=False) or [],
                                           type='constraint')

            if not overrideConstraint:
                print(
                    'Unable to determine override constraint from control transform "'
                    + control + '"!')
                continue

        # Append to Override Target List
        bakeControlList.append(control)
        # Append to Override Constraint List
        [
            constraintList.append(i) for i in overrideConstraint
            if not i in constraintList
        ]

    # =================================
    # - Bake Override Target Channels -
    # =================================

    # Check Bake Control List
    if not bakeControlList:
        print('Found no controls to bake! Skipping...')
        return None

    # Bake to Controls
    mc.bakeResults(bakeControlList,
                   t=(start, end),
                   at=['tx', 'ty', 'tz', 'rx', 'ry', 'rz'],
                   preserveOutsideKeys=True,
                   simulation=bakeSim)

    # ======================
    # - Delete Constraints -
    # ======================

    if constraintList: mc.delete(constraintList)

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

    return bakeControlList
Exemplo n.º 48
0
def getSlotData(boneName):

    for i in cmds.listConnections(boneName):
        print i, cmds.nodeType(i)
        print cmds.listConnections(i, d=True, type="mesh")
Exemplo n.º 49
0
def getSkinsListB(slotList):
    skinList = {"default": {}}

    # print "slotList",slotList
    # print "slotListLength",len(slotList)

    for i in slotList:
        slotName = i["name"]
        #print "slotName",slotName
        getObj = cmds.ls(slotName, dag=1)[1]
        shadingGrps = cmds.listConnections(getObj, type='shadingEngine')
        shaders = cmds.ls(cmds.listConnections(shadingGrps), materials=1)
        fileNode = cmds.listConnections('%s.color' % (shaders[0]),
                                        type='file')[0]
        currentFile = cmds.getAttr("%s.fileTextureName" % fileNode)
        fileInSlot = currentFile.split("/")[-1].split(".png")[0]
        attachmentImage = fileInSlot
        width = int(cmds.getAttr("%s.scaleX" % slotName))
        height = int(cmds.getAttr("%s.scaleZ" % slotName))
        x = int(cmds.getAttr("%s.translateX" % slotName))
        y = int(cmds.getAttr("%s.translateY" % slotName))
        # print "slotList",slotList
        # print "fileNode",fileNode
        if cmds.getAttr("%s.useFrameExtension" % fileNode) == True:
            fileName = cmds.getAttr("%s.fileTextureName" %
                                    fileNode).split("/")[-1]
            fileDir = cmds.getAttr("%s.fileTextureName" %
                                   fileNode).split(fileName)[0]

            allFiles = os.listdir(fileDir)
            sequenceList = []
            for j in allFiles:
                # print i.split(".")
                if j.split(".")[0] == fileName.split(".")[0]:
                    sequenceList.append(j)

        #  print "sequenceList",sequenceList

        #  print width,height
            sequenceFrameInfoDict = {}
            for index in range(0, len(sequenceList)):
                # print sequenceList[index]
                sequenceFrameInfoDict.update({
                    sequenceList[index].split(".png")[0]: {
                        "width": width,
                        "height": height,
                        "x": x,
                        "y": y
                    }
                })
        #  print "sequenceFrameInfoDict",sequenceFrameInfoDict,type(sequenceFrameInfoDict)

            skinList["default"].update({slotName: sequenceFrameInfoDict})

        else:

            #  print width,height

            skinList["default"].update({
                slotName: {
                    attachmentImage: {
                        "width": width,
                        "height": height,
                        "x": x,
                        "y": y
                    }
                }
            })
    return skinList
Exemplo n.º 50
0
    def test_auto_consolidate(self):
        """ Test automatic attribute consolidating: .tx, .ty, .tz -> .t """

        # Test that by default consolidating takes place
        self.node_a.s = self.node_a.t
        child_connections = [
            cmds.listConnections("{}.sx".format(TEST_NODES[0]),
                                 connections=True,
                                 plugs=True),
            cmds.listConnections("{}.sy".format(TEST_NODES[0]),
                                 connections=True,
                                 plugs=True),
            cmds.listConnections("{}.sz".format(TEST_NODES[0]),
                                 connections=True,
                                 plugs=True),
        ]
        parent_connections = cmds.listConnections("{}.s".format(TEST_NODES[0]),
                                                  connections=True,
                                                  plugs=True)[1]
        self.assertEqual(child_connections, [None, None, None])
        self.assertEqual(parent_connections, "A.translate")

        # Test individual auto consolidate setting
        node_b_no_auto_consolidate = noca.Node(TEST_NODES[1],
                                               auto_consolidate=False)
        node_b_no_auto_consolidate.s = self.node_a.t
        child_connections = [
            cmds.listConnections("{}.sx".format(TEST_NODES[1]),
                                 connections=True,
                                 plugs=True)[1],
            cmds.listConnections("{}.sy".format(TEST_NODES[1]),
                                 connections=True,
                                 plugs=True)[1],
            cmds.listConnections("{}.sz".format(TEST_NODES[1]),
                                 connections=True,
                                 plugs=True)[1],
        ]
        parent_connections = cmds.listConnections("{}.s".format(TEST_NODES[1]),
                                                  connections=True,
                                                  plugs=True)
        self.assertEqual(child_connections,
                         ["A.translateX", "A.translateY", "A.translateZ"])
        self.assertEqual(parent_connections, None)

        # Test global auto consolidate setting
        noca.set_global_auto_consolidate(False)
        self.node_c.s = self.node_a.t
        child_connections = [
            cmds.listConnections("{}.sx".format(TEST_NODES[2]),
                                 connections=True,
                                 plugs=True)[1],
            cmds.listConnections("{}.sy".format(TEST_NODES[2]),
                                 connections=True,
                                 plugs=True)[1],
            cmds.listConnections("{}.sz".format(TEST_NODES[2]),
                                 connections=True,
                                 plugs=True)[1],
        ]
        parent_connections = cmds.listConnections("{}.s".format(TEST_NODES[2]),
                                                  connections=True,
                                                  plugs=True)
        self.assertEqual(child_connections,
                         ["A.translateX", "A.translateY", "A.translateZ"])
        self.assertEqual(parent_connections, None)
Exemplo n.º 51
0
def renameSkinClusters():
    for skincluster in cmds.ls(type="skinCluster"):
        sc_object = cmds.listConnections(
            "{}.outputGeometry[0]".format(skincluster))[0]
        cmds.rename(skincluster, "{}_SkinCluster".format(sc_object))
Exemplo n.º 52
0
def constrainControlOverrideTarget(control,
                                   constraintTarget,
                                   constraintType='parent',
                                   maintainOffset=False,
                                   skipTranslate=[],
                                   skipRotate=[],
                                   interpType=None,
                                   prefix=''):
    '''
	Constrain the override target transform of the specified control to a given target transform.
	This function can be used to constrain rig controls to a mocap driven skeleton.
	@param control: The control that will have its override target transform constrainted to the specified target transform.
	@type control: str
	@param constraintTarget: The target transform that the override target transform will be constrainted to.
	@type constraintTarget: str
	@param constraintType: The constraint type to apply to the override target transform.
	@type constraintType: str
	@param maintainOffset: Initialize the constraint offset necessary for the slave transform to mainatain its current position and orientation.
	@type maintainOffset: bool
	@param skipTranslate: List the translate channels to leave unaffected by the constraint.
	@type skipTranslate: list
	@param skipRotate: List the rotate channels to leave unaffected by the constraint.
	@type skipRotate: list
	@param interpType: Orientation interpolation type. "average", "shortest", "longest"
	@type interpType: str or None
	@param prefix: Name prefix for override nodes created by the function. If empty, prefix is taken from the input control name.
	@type prefix: str
	'''
    # ==========
    # - Checks -
    # ==========

    # Control
    if not mc.objExists(control):
        raise Exception('Rig control transform "' + control +
                        '" does not exist!')

    # Constraint Target
    if isinstance(constraintTarget, types.StringTypes):
        if not mc.objExists(constraintTarget):
            raise Exception('Override transform target "' + constraintTarget +
                            '" does not exist!')
    elif isinstance(constraintTarget, types.ListType):
        for target in constraintTarget:
            if not mc.objExists(target):
                raise Exception('Override transform target "' + target +
                                '" does not exist!')
    else:
        raise Exception('Invalid argument type for constraintTarget!')

    # Constraint Type
    if not constraintType in ['point', 'orient', 'parent']:
        raise Exception('Unsupported constraint type "' + constraintType +
                        '"!')

    # Override Enable Attribute
    overrideAttr = overrideAttribute()
    if not mc.objExists(control + '.' + overrideAttr):
        raise Exception('OverrideEnable attribute "' + control + '.' +
                        overrideAttr + '" does not exist!')

    # Override Constraint
    overrideConstraint = mc.listConnections(control + '.' + overrideAttr,
                                            s=False,
                                            d=True)
    if not overrideConstraint:
        raise Exception(
            'Override constraint could not be determined from overrideEnabled attribute "'
            + control + '.' + overrideAttr + '"!')
    overrideConstraint = mc.ls(overrideConstraint, type='constraint')
    if not overrideConstraint:
        raise Exception(
            'Override constraint could not be determined from overrideEnabled attribute "'
            + control + '.' + overrideAttr + '"!')

    # Override Target
    overrideTarget = glTools.utils.constraint.targetList(overrideConstraint[0])
    if not overrideTarget:
        raise Exception(
            'Unable to determine override target transform from constraint "' +
            overrideConstraint[0] + '"!')

    # InterpType
    interpIndex = {'average': 1, 'shortest': 2, 'longest': 3}
    if constraintType == 'parent' or constraintType == 'orient':
        if interpType and not interpType in interpIndex.keys():
            raise Exception('Invalid interpolation type "' + interpType + '"!')

    # Prefix
    if not prefix:
        prefix = glTools.utils.stringUtils.stripSuffix(control)

    # =====================================
    # - Create Override Target Constraint -
    # =====================================

    overrideTargetConstraint = ''

    # Create pointConstraint
    if constraintType == 'point':
        overrideTargetConstraint = mc.pointConstraint(
            constraintTarget,
            overrideTarget[0],
            mo=maintainOffset,
            sk=skipTranslate,
            n=prefix + '_overrideTarget_pointConstraint')[0]

    # Create orientConstraint
    elif constraintType == 'orient':
        overrideTargetConstraint = mc.orientConstraint(
            constraintTarget,
            overrideTarget[0],
            mo=maintainOffset,
            sk=skipRotate,
            n=prefix + '_overrideTarget_orientConstraint')[0]
        # Interp Type
        if interpType:
            mc.setAttr(overrideTargetConstraint + '.interpType',
                       interpIndex[interpType])

    # Create parentConstraint
    elif constraintType == 'parent':
        overrideTargetConstraint = mc.parentConstraint(
            constraintTarget,
            overrideTarget[0],
            mo=maintainOffset,
            st=skipTranslate,
            sr=skipRotate,
            n=prefix + '_overrideTarget_parentConstraint')[0]
        # Interp Type
        if interpType:
            mc.setAttr(overrideTargetConstraint + '.interpType',
                       interpIndex[interpType])

    # Unsupported Constraint Type
    else:
        raise Exception('Unsupported constraint type "' + constraintType +
                        '"!')

    # Enable overrideConstraint
    mc.setAttr(control + '.' + overrideAttr, True)

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

    return overrideTargetConstraint
Exemplo n.º 53
0
def patch():

    facialDrv = 'facialDrivers'

    eyeMaskOrig = 'eyeMask_ctrl_orig'

    JawClenchLOrig = 'Jaw_Clench_l_ctrl_orig'
    JawClenchROrig = 'Jaw_Clench_r_ctrl_orig'
    jawChinOrig = 'jawChin_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'
    mouthSquashSKN = 'mouthSquash_SKN'
    mouthGlobal = 'mouthGlobal_ctrl_orig'
    foreheadGrp = 'forehead_grp'
    headSKN = 'head_SKN'
    jawctrl = 'jaw_ctrl'
    jawJntOrig = 'jaw_jnt_orig'
    jawShapeGrp = 'jaw_SHAPE_grp'
    jawMidSkin = 'jaw_02_SKN'
    noseGrp = 'nose_grp'
    noseUp = 'nose_up_ctrl'
    noseUpOrig = 'nose_up_ctr_orig'
    neckTrash = 'neck_grpTRASH'
    earGrp = 'ear_grp'
    eyeGrp = 'eye_grp'
    eyeMaskGrp = 'eyeMask_ctrl_orig'

    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]

    #try :

    #reparent halfSkulls
    mc.parent(eyeMaskOrig, UpHeadOrig, LowerHeadOrig, headSKN)
    #reparent jawClenches
    mc.parent(JawClenchLOrig, JawClenchROrig, jawctrl)
    #reparent foreHead into topSKull
    mc.parent(foreheadGrp, UpHeadCtrl)
    #reparent mouthSquash et nose into lowerSkull
    mc.parent(noseGrp, mouthSquashOrig, LowerHeadCtrl)
    #deparent halfSkulls guides
    mc.parent(UpHeadGuide, LowerHeadGuide, facialDrv)
    # reparent jawChin in MidHJaw
    mc.parent(jawChinOrig, jawMidSkin)

    #change midSkulls ctrlShapes
    shapes.create(UpHeadCtrl,
                  shape='circleHalf',
                  size=2,
                  scale=[1.25, 1, 1.75],
                  axis='y',
                  twist=-90,
                  offset=[0, 0, 0.5],
                  color=[255, 255, 0],
                  colorDegradeTo=None,
                  replace=True,
                  middle=False)
    shapes.create(LowerHeadCtrl,
                  shape='circleHalf',
                  size=2,
                  scale=[1.25, 1, 1.75],
                  axis='y',
                  twist=90,
                  offset=[0, 0, -0.5],
                  color=[255, 255, 0],
                  colorDegradeTo=False,
                  replace=True,
                  middle=False)

    # --- add upjaw ctrl
    ## create jawUp and jawUp proxies
    mc.select(cl=True)
    upJaw = mc.joint(n='upJaw_ctrl')
    mc.setAttr('{}.radius'.format(upJaw), 0.01)
    mc.select(cl=True)
    upJawLoHeadProxy = mc.joint(n='upJaw_loHead_proxy')
    mc.setAttr('{}.radius'.format(upJawLoHeadProxy), 0.01)
    mc.select(cl=True)
    upJawMSquashProxy = mc.joint(n='upJaw_mSquash_proxy')
    mc.setAttr('{}.radius'.format(upJawMSquashProxy), 0.01)

    jawpPos = mc.xform(jawctrl, q=True, ws=True, t=True)
    mc.xform(upJaw, ws=True, t=jawpPos)
    mc.xform(upJawLoHeadProxy, ws=True, t=jawpPos)
    mc.xform(upJawMSquashProxy, ws=True, t=jawpPos)
    jawPosOrigs = orig.orig(
        objlist=[upJaw, upJawLoHeadProxy, upJawMSquashProxy],
        suffix=['_orig'],
        origtype='joint',
        fromsel=False,
        viz=False,
        get_ssc=False,
        rtyp='auto')

    ## reparent nodes in jawUp nodes
    mc.parent(eyeGrp, eyeMaskGrp, UpHeadOrig, upJaw)
    mc.parent(noseGrp, upJawLoHeadProxy)
    mSquashSKNChilds = mc.listRelatives(mouthSquashSKN, c=True)
    for child in mSquashSKNChilds:
        if not (child == jawJntOrig or child == jawShapeGrp):
            print child
            mc.parent(child, upJawMSquashProxy)
    ## reparent jawUp nodes
    mc.parent(jawPosOrigs[0], headSKN)
    mc.parent(jawPosOrigs[1], LowerHeadCtrl)
    mc.parent(jawPosOrigs[2], mouthSquashSKN)
    ## connectJawUps
    smartConnect(upJaw, upJawLoHeadProxy)
    smartConnect(upJaw, upJawMSquashProxy)
    # --- add shape to UpJaw
    shapes.create(upJaw,
                  shape='pinSphere',
                  size=0.75,
                  scale=[1, 1, 1],
                  axis='y',
                  twist=0,
                  offset=[0, .75, 0],
                  color=[1, 1, 0],
                  colorDegradeTo=None,
                  replace=True,
                  middle=False)
    # --- change mouthGlobal parentConstraint targets
    mouthGlobalCns = mc.listConnections('{}.translateX'.format(mouthGlobal),
                                        s=True)[0]
    mc.delete(mouthGlobalCns)
    mc.parentConstraint(upJaw, jawctrl, mouthGlobal, mo=True)
    # --- add upJaw to skinSet
    mc.sets(upJaw, add='head_jnt_skin_set')

    # --- reparent and adjust Shapes for flaps ctrls
    mainColList = [[0.0, 0.0, 1.0], [1.0, 0.0, 0.0], [1.0, 1.0, 0.0]]
    secColList = [[0.5, 0.5, 1.0], [1.0, 0.5, 0.5], [1.0, 1.0, 0.65]]
    sizeList = [0.07, 0.07, 0.04]

    for s, side in enumerate(sides):
        ## --- reparent dKey ctrls to world
        allCtrl = '%s_%s' % (side, lipflapAll)
        tipCtrl = '%s_%s' % (side, lipflapTip)

        allCtrlOrig = mc.listRelatives('%s_%s' % (side, lipflapAll), p=True)[0]
        mc.parent(allCtrlOrig, w=True)

        if side == 'L':
            shapes.create(allCtrl,
                          shape='pyramid',
                          size=sizeList[s],
                          scale=[1.5, -1.5, 1.5],
                          axis='y',
                          twist=0,
                          offset=[0, -0.5, 0],
                          color=mainColList[s],
                          colorDegradeTo=None,
                          replace=True,
                          middle=False)
            shapes.create(tipCtrl,
                          shape='arrowFourCurve',
                          size=sizeList[s],
                          scale=[0.8, -0.8, 0.8],
                          axis='y',
                          twist=0,
                          offset=[0, -0.28, 0],
                          color=secColList[s],
                          colorDegradeTo=None,
                          replace=True,
                          middle=False)

        elif side == 'R':
            shapes.create(allCtrl,
                          shape='pyramid',
                          size=sizeList[s],
                          scale=[1.5, 1.5, 1.5],
                          axis='y',
                          twist=0,
                          offset=[0, 0.5, 0],
                          color=mainColList[s],
                          colorDegradeTo=None,
                          replace=True,
                          middle=False)
            shapes.create(tipCtrl,
                          shape='arrowFourCurve',
                          size=sizeList[s],
                          scale=[0.8, 0.8, 0.8],
                          axis='y',
                          twist=0,
                          offset=[0, 0.28, 0],
                          color=secColList[s],
                          colorDegradeTo=None,
                          replace=True,
                          middle=False)

        elif side == 'C':
            shapes.create(allCtrl,
                          shape='pyramid',
                          size=sizeList[s],
                          scale=[1.5, -1.5, 1.5],
                          axis='y',
                          twist=0,
                          offset=[0, -0.2, 0],
                          color=mainColList[s],
                          colorDegradeTo=None,
                          replace=True,
                          middle=False)
            shapes.create(tipCtrl,
                          shape='arrowFourCurve',
                          size=sizeList[s],
                          scale=[0.8, -0.8, 0.8],
                          axis='y',
                          twist=0,
                          offset=[0, -0.12, 0],
                          color=secColList[s],
                          colorDegradeTo=None,
                          replace=True,
                          middle=False)

    # add hierarchy for drivenKeys on lipFlaps fk joints
    dKeyAllNodesList = []
    dKeyTipNodesList = []
    for side in sides:
        sideDKeyNodesList = []
        firstOrig = '%s_%s' % (side, lipFlapOrig)
        flapRoot = orig.orig(objlist=[firstOrig],
                             suffix=['_root'],
                             origtype='joint',
                             fromsel=False,
                             viz=False,
                             get_ssc=False,
                             rtyp='auto')[0]
        allChilds = mc.listRelatives(flapRoot,
                                     c=True,
                                     typ='transform',
                                     ad=True)
        allChilds.reverse()
        for child in allChilds:
            stripName = child.rsplit('_', 1)[-1]
            if not stripName == 'orig' and not stripName == 'end':
                dkeyNode = orig.orig(objlist=[child],
                                     suffix=['_dKeyAll'],
                                     origtype='joint',
                                     fromsel=False,
                                     viz=False,
                                     get_ssc=False,
                                     rtyp='auto')[0]
                sideDKeyNodesList.append(dkeyNode)
        dKeyAllNodesList.append(sideDKeyNodesList)

    for list in dKeyAllNodesList:
        sideDKeyNodesList = []
        listLen = len(list)
        for i in range((listLen / 2), listLen):
            ctrl = mc.listRelatives(list[i], c=True, typ='transform')[0]
            dkeyNode = orig.orig(objlist=[ctrl],
                                 suffix=['_dKeyTip'],
                                 origtype='joint',
                                 fromsel=False,
                                 viz=False,
                                 get_ssc=False,
                                 rtyp='auto')[0]
            sideDKeyNodesList.append(dkeyNode)
        dKeyTipNodesList.append(sideDKeyNodesList)
    # change controls shapes on lipFlaps FKs
    attrName = 'showLipFlapsFK'
    for s, side in enumerate(sides):
        mainFlapCtrl = '%s_%s' % (side, lipflapAll)
        mc.addAttr(mainFlapCtrl, ln=attrName, at='bool')
        mc.setAttr('%s.%s' % (mainFlapCtrl, attrName), edit=True, k=True)

        flapRoot = '%s_%s_root' % (side, lipFlapOrig)
        allChilds = mc.listRelatives(flapRoot,
                                     c=True,
                                     typ='transform',
                                     ad=True)
        allChilds.reverse()
        for child in allChilds:
            stripName = child.rsplit('_', 1)[-1]
            if not stripName == 'orig' and not stripName == 'end' and not stripName == 'dKeyAll' and not stripName == 'dKeyTip':
                if not side == 'R':
                    shapes.create(child,
                                  shape='pinPyramid',
                                  size=sizeList[s],
                                  scale=[4, 5, 5],
                                  axis='-X',
                                  twist=0,
                                  offset=[0, 0, 0],
                                  color=mainColList[s],
                                  colorDegradeTo=None,
                                  replace=True,
                                  middle=False)
                else:
                    shapes.create(child,
                                  shape='pinPyramid',
                                  size=sizeList[s],
                                  scale=[-4, 5, 5],
                                  axis='-X',
                                  twist=0,
                                  offset=[0, 0, 0],
                                  color=mainColList[s],
                                  colorDegradeTo=None,
                                  replace=True,
                                  middle=False)

            childShapes = mc.listRelatives(child, s=True)
            if childShapes:
                for childShape in childShapes:
                    mc.connectAttr('%s.%s' % (mainFlapCtrl, attrName),
                                   '%s.visibility' % childShape)

    # scale R side -1 to get propper symmetrical behavior
    for each in (lipFlapList[0], lipFlapList[1]):
        if each == 'lipFlap_cup_ctrl':
            mc.setAttr('%s_%s.jointOrientY' % (sides[1], each), 180)
        else:
            mc.setAttr('%s_%s_orig.scale' % (sides[1], each), -1, -1, -1)

    for side in sides[1]:
        root = '%s_%s_root' % (side, lipFlapOrig)
        allChilds = mc.listRelatives(root, c=True, typ='transform', ad=True)
        allChilds.reverse()
        for child in allChilds:
            stripName = child.rsplit('_', 1)[-1]
            if stripName == 'orig' or stripName == 'dKeyAll' or stripName == 'dKeyTip':
                mc.setAttr('%s.scale' % child, -1, -1, -1)

    #reparent all flaps inside mouthSquash
    for side in sides:
        mc.parent('%s_%s_root' % (side, lipFlapOrig),
                  '%s_%s_orig' % (side, lipflapAll), mouthSquashSKN)
        mc.parent('%s_%s_orig' % (side, lipflapCup), mouthSquashSKN)

    # --- create smart_flaps joints
    smartFlapsGrp = mc.group(n='flaps_smart_grp', em=True)
    mc.parent(smartFlapsGrp, 'facial_fGrp')
    mc.setAttr('%s.inheritsTransform' % smartFlapsGrp, False)
    mc.select(cl=True)
    smartFlapsHoldJnt = mc.joint(n='flaps_smart_hold_jnt')
    mc.parent(smartFlapsHoldJnt, smartFlapsGrp)

    smartTrgt = [
        '%s_%s_root' % (sides[0], lipFlapOrig),
        '%s_%s_root' % (sides[1], lipFlapOrig),
        '%s_%s_root' % (sides[2], lipFlapOrig)
    ]
    smartDupTargets = []
    for each in smartTrgt:
        newTrgt = mc.duplicate(each, n='%s_smart' % each)[0]
        smartDupTargets.append(newTrgt)
    mc.parent(smartDupTargets, smartFlapsGrp)

    # --- add dkNode on top of nose_upCtrl
    noseUpDkey = mc.group(n='{}_dKey'.format(noseUp), em=True)
    mc.parent(noseUpDkey, mouthSquashSKN)
    mc.setAttr('{}.translate'.format(noseUpDkey), 0, 0, 0)
    mc.parent(noseUpDkey, noseGrp)
    mc.parent(noseUpOrig, noseUpDkey)

    # --- goes into the hierarchy of duplicated Fks and counts the depth of the hierarchy. stops when arrived at end of hierarchy
    for i, each in enumerate(smartDupTargets):
        nexChild = ''
        stopLoop = False
        for j in range(0, 30):
            if j == 0:
                nexChild = each
            getChild = mc.listRelatives(nexChild, c=True, f=True)
            if getChild:
                for child in getChild:
                    if mc.objectType(child) == 'nurbsCurve':
                        mc.delete(child)

                    else:
                        if mc.objectType(child) == 'joint':
                            splittedName1 = child.rsplit('|')[-1]
                            checkEnd = splittedName1.rsplit('_', 1)[-1]

                            newName = mc.rename(child,
                                                '%s_smart' % splittedName1)
                            smartConnect(splittedName1, newName)

                            if not checkEnd == 'end':
                                nexChild = newName
                            else:
                                stopLoop = True
            if stopLoop == True:
                break

    # --- add dkNode on top of C_lipFlap_dKey
    CNoseSideDKeyAll = orig.orig(objlist=['C_lipFlap_ctrl_01_dKeyAll'],
                                 suffix=['_side'],
                                 origtype='transform',
                                 fromsel=False,
                                 viz=False,
                                 get_ssc=False,
                                 rtyp='auto')[0]
    CNoseSideDKeyAllSmart = orig.orig(
        objlist=['C_lipFlap_ctrl_01_dKeyAll_smart'],
        suffix=['_side'],
        origtype='transform',
        fromsel=False,
        viz=False,
        get_ssc=False,
        rtyp='auto')[0]
    smartConnect(CNoseSideDKeyAll, CNoseSideDKeyAllSmart)

    #save lists in tempNode
    tempSaveGrp = mc.group(n='tempSaveGrp', em=True)
    mc.hide(tempSaveGrp)
    mc.addAttr(tempSaveGrp, ln='dKeyAllNodesList', dt='string')
    mc.addAttr(tempSaveGrp, ln='dKeyTipNodesList', dt='string')
    mc.setAttr('%s.dKeyAllNodesList' % tempSaveGrp,
               dKeyAllNodesList,
               type='string')
    mc.setAttr('%s.dKeyTipNodesList' % tempSaveGrp,
               dKeyTipNodesList,
               type='string')

    # --- do teeth generate
    teethGen.generateTeeth()
Exemplo n.º 54
0
def renameUnitConversionNodes():
    for unitconversion in cmds.ls(type="unitConversion"):
        input = cmds.listConnections(unitconversion)[0]
        cmds.rename(unitconversion, "{}_UC".format(input))
Exemplo n.º 55
0
def _getConnections(nodeName):
	c = cmds.listConnections(nodeName,p=True,d=False,c=True,s=True)
	try:
		return zip(c[0::2], c[1::2])
	except:
		return None
Exemplo n.º 56
0
boneList = cmds.listRelatives("root", c=True)
cmds.currentTime(0, e=True)  ## move to frame 0, as bind pose
for i in boneList:
    x = int(cmds.getAttr("%s.translateX" % i))
    y = int(cmds.getAttr("%s.translateY" % i))
    r = int(cmds.getAttr("%s.rotateZ" % i))

    boneDict = {"name": i, "parent": "root", "rotation": r, "x": x, "y": y}
    bones.append(boneDict)

## define slots
slotFileDict = {}
for i in range(0, len(boneList)):

    getObj = cmds.ls(boneList[i], dag=1)[1]
    shadingGrps = cmds.listConnections(getObj, type='shadingEngine')
    shaders = cmds.ls(cmds.listConnections(shadingGrps), materials=1)
    fileNode = cmds.listConnections('%s.color' % (shaders[0]), type='file')
    currentFile = cmds.getAttr("%s.fileTextureName" % fileNode[0])
    fileInSlot = currentFile.split("/")[-1].split(".")[0]
    alphaGain = "%02x" % int(
        (cmds.getAttr("%s.alphaGain" % fileNode[0]) / 1) * 255)
    colorGain = cmds.getAttr("%s.colorGain" % fileNode[0])[0]
    colorGainHex = "%02x" % int((colorGain[0] / 1) * 255) + "%02x" % int(
        (colorGain[1] / 1) * 255) + "%02x" % int((colorGain[2] / 1) * 255)
    exportColorHex = colorGainHex + alphaGain

    slotDict = {
        "name": "pId_%s" % i,
        "bone": boneList[i],
        "color": exportColorHex,
Exemplo n.º 57
0
	def buildData(self,wire):
		'''
		Build wire data and store as class object dictionary entries
		@param wire: Wire deformer to store data for.
		@type wire: str
		'''
		# ==========
		# - Checks -
		# ==========

		# Verify node
		glTools.utils.base.verifyNode(wire,'wire')

		# =====================
		# - Get Deformer Data -
		# =====================

		# Clear Data
		self.reset()

		# Get influence curves
		influenceList = glTools.utils.connection.connectionListToAttr(wire,'deformedWire')

		# Custom Attribute Data
		for inf in influenceList.keys():
			ind = influenceList[inf][1]
			self._data['attrConnectionList'].append('dropoffDistance['+str(ind)+']')
			self._data['attrConnectionList'].append('scale['+str(ind)+']')

		super(WireData, self).buildData(wire)

		# ======================
		# - Get Influence Data -
		# ======================

		for influence in influenceList.keys():
			infIndex = influenceList[influence][1]
			self._influenceData[influence] = {}
			self._influenceData[influence]['index'] = infIndex
			self._influenceData[influence]['influenceBase'] = mc.listConnections(wire+'.baseWire['+str(infIndex)+']',s=True,d=False)[0]
			self._influenceData[influence]['dropoffDist'] = mc.getAttr(wire+'.dropoffDistance['+str(infIndex)+']')
			self._influenceData[influence]['scale'] = mc.getAttr(wire+'.scale['+str(infIndex)+']')

		# ============================
		# - Get Dropoff Locator Data -
		# ============================

		dropoffLocatorList = glTools.utils.connection.connectionListToAttr(wire,'wireLocatorParameter')

		for locator in dropoffLocatorList.keys():

			# Initialize dropoff locator data dictionary
			self._locatorData[locator] = {}

			# Build dropoff locator data
			locIndex = dropoffLocatorList[locator][1]
			self._locatorData[locator]['index'] = locIndex
			self._locatorData[locator]['envelope'] = mc.getAttr(wire+'.wireLocatorEnvelope['+str(locIndex)+']')
			self._locatorData[locator]['twist'] = mc.getAttr(wire+'.wireLocatorTwist['+str(locIndex)+']')
			self._locatorData[locator]['percent'] = mc.getAttr(locator+'.percent')
			self._locatorData[locator]['parameter'] = mc.getAttr(locator+'.param')

			# Get wire curve parent
			locParent = mc.listRelatives(locator,p=True)[0]
			crvParent = mc.listRelatives(locParent,p=True)[0]
			self._locatorData[locator]['parent'] = crvParent
Exemplo n.º 58
0
    def replaceNucleus(self):
        """
        Replace existed nucleus with selected nucleus or new nucleus
        :return: None
        """
        currentNucleus = cmds.listConnections(self.currentSetGrp + '.nucleus',
                                              source=0,
                                              destination=1)[0]

        if currentNucleus == self.repNecleusComBox.currentText():
            return

        elif currentNucleus != self.repNecleusComBox.currentText(
        ) and self.repNecleusComBox.currentText() != 'New...':
            # disconnect original nucleus
            currentNCloth = cmds.listConnections(self.currentSetGrp +
                                                 '.nCloth',
                                                 source=0,
                                                 destination=1,
                                                 shapes=1)[0]

            inputActiveAttr = cmds.listConnections(currentNCloth +
                                                   '.currentState',
                                                   source=0,
                                                   destination=1,
                                                   plugs=1)[0]
            inputActiveStartAttr = cmds.listConnections(currentNCloth +
                                                        '.startState',
                                                        source=0,
                                                        destination=1,
                                                        plugs=1)[0]
            outputObjectAttr = cmds.listConnections(currentNCloth +
                                                    '.nextState',
                                                    source=1,
                                                    destination=0,
                                                    plugs=1)[0]

            cmds.disconnectAttr(currentNCloth + '.currentState',
                                inputActiveAttr)
            cmds.disconnectAttr(currentNCloth + '.startState',
                                inputActiveStartAttr)
            cmds.disconnectAttr(outputObjectAttr, currentNCloth + '.nextState')
            cmds.disconnectAttr(currentNucleus + '.startFrame',
                                currentNCloth + '.startFrame')

            currentNucleusAttr = cmds.listConnections(self.currentSetGrp +
                                                      '.nucleus',
                                                      source=0,
                                                      destination=1,
                                                      plugs=1)[0]
            cmds.disconnectAttr(self.currentSetGrp + '.nucleus',
                                currentNucleusAttr)

            # connect specified nucleus
            index = lib.findTribleAvailableIndex(
                firstAttr=self.repNecleusComBox.currentText() + '.inputActive',
                secondAttr=self.repNecleusComBox.currentText() +
                '.inputActiveStart',
                thirdAttr=self.repNecleusComBox.currentText() +
                '.outputObjects')

            nucleusIndex = lib.findSingleAvailableIndex(
                self.repNecleusComBox.currentText() + '.nucleus')

            cmds.connectAttr(self.repNecleusComBox.currentText() +
                             '.outputObjects[%s]' % (str(index)),
                             currentNCloth + '.nextState',
                             f=1)
            cmds.connectAttr(self.repNecleusComBox.currentText() +
                             '.startFrame',
                             currentNCloth + '.startFrame',
                             f=1)

            cmds.connectAttr(currentNCloth + '.currentState',
                             self.repNecleusComBox.currentText() +
                             '.inputActive[%s]' % (str(index)),
                             f=1)
            cmds.connectAttr(currentNCloth + '.startState',
                             self.repNecleusComBox.currentText() +
                             '.inputActiveStart[%s]' % (str(index)),
                             f=1)

            cmds.connectAttr(self.currentSetGrp + '.nucleus',
                             self.repNecleusComBox.currentText() +
                             '.nucleus[%s]' % (str(nucleusIndex)),
                             f=1)

        else:
            # disconnect original nucleus
            currentNCloth = cmds.listConnections(self.currentSetGrp +
                                                 '.nCloth',
                                                 source=0,
                                                 destination=1,
                                                 shapes=1)[0]

            inputActiveAttr = cmds.listConnections(currentNCloth +
                                                   '.currentState',
                                                   source=0,
                                                   destination=1,
                                                   plugs=1)[0]
            inputActiveStartAttr = cmds.listConnections(currentNCloth +
                                                        '.startState',
                                                        source=0,
                                                        destination=1,
                                                        plugs=1)[0]
            outputObjectAttr = cmds.listConnections(currentNCloth +
                                                    '.nextState',
                                                    source=1,
                                                    destination=0,
                                                    plugs=1)[0]

            cmds.disconnectAttr(currentNCloth + '.currentState',
                                inputActiveAttr)
            cmds.disconnectAttr(currentNCloth + '.startState',
                                inputActiveStartAttr)
            cmds.disconnectAttr(outputObjectAttr, currentNCloth + '.nextState')
            cmds.disconnectAttr(currentNucleus + '.startFrame',
                                currentNCloth + '.startFrame')

            currentNucleusAttr = cmds.listConnections(self.currentSetGrp +
                                                      '.nucleus',
                                                      source=0,
                                                      destination=1,
                                                      plugs=1)[0]
            cmds.disconnectAttr(self.currentSetGrp + '.nucleus',
                                currentNucleusAttr)

            # create and connect
            createdNucleus = lib.createNucleus(
                name=name.removeSuffix(self.currentSetGrp))

            inputActiveIndex = cmds.getAttr(createdNucleus + '.inputActive',
                                            size=1)
            inputActiveStartIndex = cmds.getAttr(createdNucleus +
                                                 '.inputActiveStart',
                                                 size=1)
            outputObjectIndex = cmds.getAttr(createdNucleus + '.outputObjects',
                                             size=1)

            nucleusIndex = cmds.getAttr(createdNucleus + '.nucleus', size=1)

            cmds.connectAttr(createdNucleus + '.outputObjects[%s]' %
                             (str(outputObjectIndex)),
                             currentNCloth + '.nextState',
                             f=1)
            cmds.connectAttr(createdNucleus + '.startFrame',
                             currentNCloth + '.startFrame',
                             f=1)

            cmds.connectAttr(currentNCloth + '.currentState',
                             createdNucleus + '.inputActive[%s]' %
                             (str(inputActiveIndex)),
                             f=1)
            cmds.connectAttr(currentNCloth + '.startState',
                             createdNucleus + '.inputActiveStart[%s]' %
                             (str(inputActiveStartIndex)),
                             f=1)

            cmds.connectAttr(self.currentSetGrp + '.nucleus',
                             createdNucleus + '.nucleus[%s]' %
                             (str(nucleusIndex)),
                             f=1)
            # clean hierarchy
            targetParent = cmds.listRelatives(self.currentSetGrp,
                                              c=0,
                                              p=1,
                                              path=1)[0]
            cmds.parent(createdNucleus, targetParent)

            cmds.select(cl=1)

        self.setCurrentSetGrp()
Exemplo n.º 59
0
	def rebuild(self):
		'''
		Rebuild the wire deformer from the recorded deformerData
		'''
		# ==========
		# - Checks -
		# ==========

		# Check Data
		for influence in self._influenceData.iterkeys():

			# Check Wire Curve
			if not mc.objExists(influence):
				print('Wire curve "'+influence+'" does not exist! Curve will not be added to deformer!')

			# Check Base Curves
			baseCurve = self._influenceData[influence]['influenceBase']
			if not mc.objExists(baseCurve):
					print('Wire curve base "'+baseCurve+'" does not exist! A static base curve will be generated from the deforming wire curve!')

		# Check Dropoff Locators
		for locator in self._locatorData.iterkeys():
			if mc.objExists(locator):
				mc.delete(mc.listRelatives(locator,p=True)[0])

		# ====================
		# - Rebuild Deformer -
		# ====================

		result = super(WireData, self).rebuild()
		wireDeformer = result['deformer']

		# =======================
		# - Connect Wire Curves -
		# =======================

		for influence in self._influenceData.iterkeys():

			# Get current wire curve pair
			wireCurve = influence
			infIndex = self._influenceData[influence]['index']
			baseCurve = self._influenceData[influence]['influenceBase']

			# Connect deformed wire
			if not mc.objExists(influence): continue
			mc.connectAttr(wireCurve+'.worldSpace[0]',wireDeformer+'.deformedWire['+str(infIndex)+']',f=True)

			# Connect base wire
			if not mc.objExists(baseCurve): baseCurve = mc.duplicate(influence,n=baseCurve)[0]
			mc.connectAttr(baseCurve+'.worldSpace[0]',wireDeformer+'.baseWire['+str(infIndex)+']',f=True)
			mc.setAttr(baseCurve+'.v',0)

			# Set Influence Attributes
			if mc.getAttr(wireDeformer+'.dropoffDistance['+str(infIndex)+']',se=True):
				mc.setAttr(wireDeformer+'.dropoffDistance['+str(infIndex)+']',self._influenceData[influence]['dropoffDist'])
			if mc.getAttr(wireDeformer+'.scale['+str(infIndex)+']',se=True):
				mc.setAttr(wireDeformer+'.scale['+str(infIndex)+']',self._influenceData[influence]['scale'])

		# ============================
		# - Rebuild Dropoff Locators -
		# ============================

		for locator in self._locatorData.iterkeys():

			# Get data
			parent = self._locatorData[locator]['parent']
			param = self._locatorData[locator]['parameter']
			env = self._locatorData[locator]['envelope']
			percent = self._locatorData[locator]['percent']
			twist = self._locatorData[locator]['twist']

			# Create Locator
			loc = mc.dropoffLocator(env,percent,wire,parent+'.u['+str(param)+']')[0]

			# Apply Twist
			locConn = mc.listConnections(loc+'.param',s=False,d=True,p=True)[0]
			locConnIndex = locConn.split('[')[-1].split(']')[0]
			mc.setAttr(wireDeformer+'.wireLocatorTwist['+str(locConnIndex)+']',twist)

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

		self.result['influence'] = self._influenceData.keys()
		self.result['dropoffLocator'] = self._locatorData.keys()

		return self.result
Exemplo n.º 60
0
def get_animated_nodes():
    return mc.listConnections(get_anim_curves()) or []