예제 #1
0
 def checkDisp(self):        
     getExistingText = self.outWindow.toPlainText()
     if len(getExistingText) > 0:
         self.outputText = []   
     getSelect = cmds.ls(sl=True)[0]
     if cmds.objectType(getSelect, isType='objectSet') == True:
         theSet = getSelect           
         if self.dispHeightButton.isChecked()==True:
             if cmds.attributeQuery('aiDispHeight',node=theSet,ex=True) == False: 
                 addDispHeight = cmds.addAttr(ln='aiDispHeight',at='float')
                 self.outputText.append('Created Displacement Height attribute') 
             else:
                 self.outputText.append("<font color=yellow>Displacement Height Already Exists<font/><br>")            
         if self.dispPadButton.isChecked()==True:
             if cmds.attributeQuery('aiDispPadding',node=theSet,ex=True) == False: 
                 addBoundsPad = cmds.addAttr(ln='aiDispPadding',at='float')
                 self.outputText.append('Created Displacement Padding attribute') 
             else:
                 self.outputText.append("<font color=yellow>Displacement Padding Already Exists<font/><br>")
         if self.dispZeroButton.isChecked()==True:
             if cmds.attributeQuery('aiDispZeroValue',node=theSet,ex=True) == False: 
                 addScalarZeroValue = cmds.addAttr(ln='aiDispZeroValue',at='float')
                 self.outputText.append('Created Displacement Zero Value attribute')
             else:
                 self.outputText.append("<font color=yellow>Disp Zero Already Exists<font/><br>")
         if self.autoBumpButton.isChecked()==True:
             if cmds.attributeQuery('aiDispAutobump',node=theSet,ex=True) == False: 
                 addBoundsPad = cmds.addAttr(ln='aiDispAutobump',at='bool',dv=1)
                 self.outputText.append('Created Disp Auto Bump attribute')                     
             else:
                 self.outputText.append("<font color=yellow>AutoBump Already Exists<font/>")   
     else:
         self.outputText.append("<font color=yellow>Select a Set to Add Attributes<font/>")
     
     self.getOutputText()
예제 #2
0
def shapeIsExportable(node_name):
    
    #check the node exists
    if not cmds.objExists(node_name):
        return False
    
    #check if the node has a visibility attribute meaning ita a dag node
    if not cmds.attributeQuery('visibility', node=node_name, exists=True):
        return False
    
    #check visibility flag
    if not cmds.getAttr(node_name+'.visibility'):
        return False

        
    #check to see if its an intermediate mesh

    if cmds.attributeQuery('intermediateObject', node=node_name, exists=True):
        if cmds.getAttr(node_name+'.intermediateObject'):
            return False
        
    #is it in a hidden display layer
    if (cmds.attributeQuery('overrideEnabled', node=node_name, exists=True) and cmds.getAttr(node_name+'.overrideEnabled')):
        if not cmds.getAttr(node_name+'.overrideVisibility'):
            return False
    
    #has it got a parent and is it visible
    if cmds.listRelatives(node_name, parent=True):
        if not shapeIsExportable(cmds.listRelatives(node_name, parent=True)[0]):
            return False

    return True
예제 #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 ) )
예제 #4
0
파일: attribute.py 프로젝트: jonntd/Public
def lock_attributes(obj=None, attr=None, lock=True, hide=True):
    #--- check parameters
    assert obj, check.error(obj, 1, `obj`)
    assert attr, check.error(attr, 1, `attr`)
    assert isinstance(attr, list), check.error(obj, 12, `attr`)

    if isinstance(obj, list):
        for i in obj:
            for a in attr:
                compound = cmds.attributeQuery(a, node=i, listChildren=True)
                if compound:
                    for c in compound:
                        if hide:
                            cmds.setAttr(i + '.' + c, lock=lock, keyable=False)
                        else:
                            cmds.setAttr(i + '.' + c, lock=lock, keyable=True)
                else:
                    if hide:
                        cmds.setAttr(i + '.' + a, lock=lock, keyable=False)
                    else:
                        cmds.setAttr(i + '.' + a, lock=lock, keyable=True)
        return
    for a in attr:
        compound = cmds.attributeQuery(a, node=obj, listChildren=True)
        if compound:
            for c in compound:
                if hide:
                    cmds.setAttr(obj + '.' + c, lock=lock, keyable=False)
                else:
                    cmds.setAttr(obj + '.' + c, lock=lock, keyable=True)
        else:
            if hide:
                cmds.setAttr(obj + '.' + a, lock=lock, keyable=False)
            else:
                cmds.setAttr(obj + '.' + a, lock=lock, keyable=True)
예제 #5
0
def LocateAllMaxwellIblNodes():
	maps = []
	#Maxwell options are not initialised/created until the renderer is selected as the output renderer in maya
	if(cmds.objExists("maxwellRenderOptions")):
		if(cmds.attributeQuery("environment", node="maxwellRenderOptions", exists=True)):

			#is maxwell set to use environments?
			if(cmds.attributeQuery("useEnvironment", node="maxwellRenderOptions", exists=True)):
				mapCount = cmds.getAttr("maxwellRenderOptions.environment", s=True)

				#map attributes may not yet been created/initialised if user has not been into settings (prob. not poss now we check useEnv flag)
				if(mapCount>0):
					for map in range(0, mapCount):
						strNode = "maxwellRenderOptions.environment["+str(map)+"]"

						#explicitally name the first 4 to what Maxwell uses as "freindly names".
						if map == 0:
							maps.append([strNode+".envTexture", "Background", strNode])
						elif map == 1:
							maps.append([strNode+".envTexture", "Reflection", strNode])
						elif map == 2:
							maps.append([strNode+".envTexture", "Refraction", strNode])
						elif map == 3:
							maps.append([strNode+".envTexture", "Illumination", strNode])
						else:
							maps.append([strNode+".envTexture", strNode, strNode])
				else:
					cmds.scrollField("rendererErrorText", edit=True, text="Maxwell environment not initialised until render options set to use IBL environment")
			else:
				cmds.scrollField("rendererErrorText", edit=True, text="Maxwell not set to use image based environment")
		else:
			cmds.scrollField("rendererErrorText", edit=True, text="Maxwell environment not initialised until the Use Image Based Lighting option is set in Render Settings under the Maxwell Render->Image Based tab")
	else:
		cmds.scrollField("rendererErrorText", edit=True, text="Maxwell not yet initialised - set to use Maxwell in Render Settings & select Maxwell Render tab to enable")
	return maps
예제 #6
0
def hijackHybridScale(obj1='', obj2='', lengthAttr='scaleZ', attrPrefix='', attrSuffix='', connectExisting=False):
    '''
    obj1 = slave
    obj2 = master
    lengthAttr = given attr is used as length scale
    remaining scales are combined to control girth of object
    '''
    # find girth attrs
    girthAttrs = []
    if lengthAttr == 'scaleX':
        girthAttrs = ['scaleY', 'scaleZ']
    elif lengthAttr == 'scaleY':
        girthAttrs = ['scaleX', 'scaleZ']
    else:
        girthAttrs = ['scaleX', 'scaleY']
    # connects
    length = attrPrefix + 'Length' + attrSuffix
    girth = attrPrefix + 'Girth' + attrSuffix
    if not cmds.attributeQuery(length, node=obj2, exists=True):
        hijackAttrs(obj1, obj2, attrOrig=lengthAttr, attrNew=length, set=False, default=None)
    else:
        if connectExisting is True:
            cmds.connectAttr(obj2 + '.' + length, obj1 + '.' + lengthAttr)
    if not cmds.attributeQuery(girth, node=obj2, exists=True):
        hijackAttrs(obj1, obj2, attrOrig=girthAttrs[0], attrNew=girth, set=False, default=None)
        # cmds.connectAttr(obj2 + '.' + girth, obj1 + '.' + girthAttrs[1])
        #
        hijackForceAttr(name=girthAttrs[1], objAttr1=(obj1 + '.' + girthAttrs[1]), objAttr2=(obj2 + '.' + girth))
    else:
        if connectExisting is True:
            # cmds.connectAttr(obj2 + '.' + girth, obj1 + '.' + girthAttrs[0])
            # cmds.connectAttr(obj2 + '.' + girth, obj1 + '.' + girthAttrs[1])
            #
            hijackForceAttr(name=girthAttrs[0], objAttr1=(obj1 + '.' + girthAttrs[0]), objAttr2=(obj2 + '.' + girth))
            hijackForceAttr(name=girthAttrs[1], objAttr1=(obj1 + '.' + girthAttrs[1]), objAttr2=(obj2 + '.' + girth))
예제 #7
0
def addDistanceAttrs(attrObject,dist=0.0):
	'''
	Add basic distance attributes to the specified object
	@param attrObject: Object to add distance attributes to
	@type attrObject: str
	@param dist: Rest distance value
	@type dist: int or float
	'''
	# ==========
	# - Checks -
	# ==========
	
	if not mc.objExists(attrObject):
		raise Exception('Attribute object "'+attrObject+'" does not exist!')
	
	# ===========================
	# - Add Distance Attributes -
	# ===========================
	
	if not mc.attributeQuery('distance',n=attrObject,ex=True):
		mc.addAttr(attrObject,ln='distance',min=0,dv=dist,k=True)
	if not mc.attributeQuery('restDistance',n=attrObject,ex=True):
		mc.addAttr(attrObject,ln='restDistance',min=0,dv=dist,k=True)
	
	# =================
	# - Return Result -
	# =================
	
	return attrObject+'.distance'
예제 #8
0
def messageConnect(fromNode=None, toNode=None, fromName=None, toName=None, category=None):
    '''
    Creates a message attributes on fromNode and toNode with the names fromName and toName respectively
    Connects the two new attributes
    
    '''
    #validation
    if not fromNode or not toNode and (len(cmds.ls(sl=1)) == 2):
        fromNode = cmds.ls(sl=1)[0]
        toNode = cmds.ls(sl=1)[1]
        
    if not fromNode or not toNode:
        return 'Argument Error, messageConnect requires fromNode and toNode as either arguments or 2 selected nodes'
    
    if not fromName or not toName:
        return 'Argument Error, messageConnect requires fromName and toName arguments for newly created attrs'
    
    # Add attributes
    if cmds.attributeQuery(fromName, node = fromNode, exists=1):
        print '%s.%s: Attribute exists' % (fromNode, fromName)
    else:
        cmds.addAttr(fromNode, ln=fromName, at='message', category=category)
        print '%s.%s: Attribute created' % (fromNode, fromName)
        
    if cmds.attributeQuery(toName, node = toNode, exists=1):
        print '%s.%s: Attribute exists' % (toNode, toName)
    else:
        cmds.addAttr(toNode, ln=toName, at='message', category=category)
        print '%s.%s: Attribute created' % (toNode, toName)
        
    # Connect attributes
    cmds.connectAttr('%s.%s' % (fromNode, fromName), '%s.%s' % (toNode, toName), f=1)
    print '%s.%s connected to %s.%s' % (fromNode, fromName, toNode, toName)
    def testImport_HiddenInstanceableKind(self):
        """
        Tests that the adaptor mechanism can import
        hidden, instanceable, and kind metadata properly.
        """
        cmds.file(new=True, force=True)
        usdFile = os.path.abspath('UsdAttrs.usda')
        cmds.usdImport(file=usdFile, shadingMode='none')

        # pCube1 and pCube2 have USD_kind.
        self.assertEqual(cmds.getAttr('pCube1.USD_kind'), 'potato')
        self.assertEqual(cmds.getAttr('pCube2.USD_kind'), 'bakedpotato')
        
        # pCube2, pCube4, and pCube5 have USD_hidden. pCube1 and pCube3 do not.
        self.assertTrue(
            cmds.attributeQuery('USD_hidden', node='pCube2', exists=True))
        self.assertTrue(
            cmds.attributeQuery('USD_hidden', node='pCube4', exists=True))
        self.assertTrue(
            cmds.attributeQuery('USD_hidden', node='pCube5', exists=True))
        self.assertFalse(
            cmds.attributeQuery('USD_hidden', node='pCube1', exists=True))
        self.assertFalse(
            cmds.attributeQuery('USD_hidden', node='pCube3', exists=True))

        self.assertTrue(cmds.getAttr('pCube2.USD_hidden'))
        self.assertTrue(cmds.getAttr('pCube4.USD_hidden'))
        self.assertFalse(cmds.getAttr('pCube5.USD_hidden'))
        
        # pCube3 and pCube4 have USD_instanceable.
        self.assertTrue(cmds.getAttr('pCube3.USD_instanceable'))
        self.assertTrue(cmds.getAttr('pCube4.USD_instanceable'))
예제 #10
0
def mirrorConnect( target ):
    
    import sgBFunction_attribute
    
    if cmds.nodeType( target ) in [ 'transform', 'joint' ]:
        mirrorTarget = mirrorTransform( target )
    else:
        mirrorTarget = mirrorNode( target )
    
    srcCons = cmds.listConnections( target, s=1, d=0, p=1, c=1 )
    
    outCons = srcCons[1::2]
    inCons  = srcCons[::2]
    
    for i in range( len( outCons ) ):
        outputNode, outputAttr = outCons[i].split( '.' )
        inputAttr = inCons[i].split( '.' )[-1]
        
        if cmds.nodeType( outputNode ) in [ 'transform', 'joint' ]:
            mirrorOutputNode = mirrorTransform( outputNode )
        else:
            mirrorOutputNode = mirrorNode( outputNode )
        
        if not cmds.attributeQuery( outputAttr, node=mirrorOutputNode, ex=1 ):
            sgBFunction_attribute.copyAttribute( outputNode+'.'+outputAttr, mirrorOutputNode )
        if not cmds.attributeQuery( inputAttr, node=mirrorTarget, ex=1 ):
            sgBFunction_attribute.copyAttribute( target+'.'+inputAttr, mirrorTarget )

        if not cmds.isConnected( mirrorOutputNode+'.'+outputAttr, mirrorTarget+'.'+inputAttr ):
            cmds.connectAttr( mirrorOutputNode+'.'+outputAttr, mirrorTarget+'.'+inputAttr )
    
    return mirrorTarget
예제 #11
0
    def editPivotDriver(self, driver):

        self.pivotDriver = driver

        #get driver range
        node,attr = driver.split('.',1)
        value = mc.getAttr(driver)

        minValue = mc.attributeQuery(attr, node=node, minimum=True)[0]
        maxValue = mc.attributeQuery(attr, node=node, maximum=True)[0]

        #create a ui with a slider
        self.pivotDriverWindow = 'ml_pivot_editPivotDriverUI'

        if mc.window(self.pivotDriverWindow, exists=True):
            mc.deleteUI(self.pivotDriverWindow)
        window = mc.window(self.pivotDriverWindow, width=1, height=1)
        mc.columnLayout()
        self.floatSlider = mc.floatSliderButtonGrp(label=attr,
                                                   field=True,
                                                   value=value,
                                                   buttonLabel='Bake',
                                                   minValue=minValue,
                                                   maxValue=maxValue,
                                                   buttonCommand=self.doEditPivotDriver )
        mc.showWindow( window )
        mc.window(self.pivotDriverWindow, edit=True, width=1, height=1)
def exec_import_policy(selection, node_name, file_name):
    """ Import policy example

    :param selection: (list) of selected objects
    :param node_name: (string) created shading node
    :param file_name: (string) texture file name
    """

    file_name = file_name.split('.')[0]

    if file_name.endswith('_DIF'):
        for obj in selection:
            if cmds.attributeQuery('color', node=obj, exists=True):
                cmds.connectAttr('%s.outColor' % node_name, '%s.color' % obj)

    elif file_name.endswith('_SPE'):
        for obj in selection:
            if cmds.attributeQuery('specularColor', node=obj, exists=True):
                cmds.connectAttr('%s.outColor' % node_name, '%s.specularColor' % obj)

    elif file_name.endswith('_NOR'):
        for obj in selection:
            if cmds.attributeQuery('normalCamera', node=obj, exists=True):
                # create bump node
                current_bump_node = cmds.shadingNode('bump2d', name='%s_bump' % node_name, asUtility=True)
                cmds.setAttr('%s.bumpInterp' % current_bump_node, 1)
                # connect nodes
                cmds.connectAttr('%s.outAlpha' % node_name, '%s.bumpValue' % current_bump_node)
                cmds.connectAttr('%s.outNormal' % current_bump_node, '%s.normalCamera' % obj)
예제 #13
0
 def makeSelection(s):
     """
     Finalize Selection
     """
     intersection = s.getPointer()
     if intersection:
         # Pick nearest bone with influence
         mesh, faceID = intersection
         bone = s.pickSkeleton(mesh, faceID)
         if bone:
             # If the bone has an attribute "control"
             # Follow that attribute to the source.
             if cmds.attributeQuery("control", n=bone, ex=True):
                 controller = cmds.getAttr("%s.control" % bone)
             else:
                 controller = bone
             s.expectedChange = True
             s.select.ignore = True
             cmds.select(controller, r=True)
             s.boneSetColour(bone, (0.3, 0.8, 0.1))
             # If we have previously selected a joint. Turn off selected flag
             if s.lastControl:
                 cmds.setAttr(s.lastControl, 0)
             if cmds.attributeQuery("selected", n=controller, ex=True):
                 s.lastControl = "%s.selected" % controller
                 cmds.setAttr(s.lastControl, 1)
     else:
         print "Nothing to select."
     s.revertTool()
    def testImport_GeomModelAPI(self):
        """Tests importing UsdGeomModelAPI attributes."""
        cmds.file(new=True, force=True)
        usdFile = os.path.abspath('UsdAttrs.usda')
        cmds.usdImport(file=usdFile, shadingMode='none',
                apiSchema=['GeomModelAPI'])

        worldProxy = UsdMaya.Adaptor('World')
        modelAPI = worldProxy.GetSchema(UsdGeom.ModelAPI)

        # model:cardGeometry
        self.assertTrue(
            cmds.attributeQuery('USD_ATTR_model_cardGeometry',
            node='World', exists=True))
        self.assertEqual(cmds.getAttr('World.USD_ATTR_model_cardGeometry'),
            UsdGeom.Tokens.fromTexture)
        self.assertEqual(
            modelAPI.GetAttribute(UsdGeom.Tokens.modelCardGeometry).Get(),
            UsdGeom.Tokens.fromTexture)

        # model:cardTextureXPos
        self.assertTrue(
            cmds.attributeQuery('USD_ATTR_model_cardTextureXPos',
            node='World', exists=True))
        self.assertEqual(cmds.getAttr('World.USD_ATTR_model_cardTextureXPos'),
            'right.png')
        self.assertEqual(
            modelAPI.GetAttribute(UsdGeom.Tokens.modelCardTextureXPos).Get(),
            'right.png')
예제 #15
0
def rsChangeCheck(i_b_state, i_s_floatField):
    if i_s_floatField == "rsMinField":
        i_b_state = cmds.checkBox("rsMinBox", query=True, value=True)
    else:
        i_b_state = cmds.checkBox("rsMaxBox", query=True, value=True)
    l_oSels = rsObjList()
    if i_b_state == True:
        if i_s_floatField == "rsMinField":
            b_minimum = cmds.attributeQuery(l_oSels[1], node=l_oSels[0], minExists=True)
            f_atValue = 0.0
            if b_minimum == 1:
                f_atValue = (cmds.attributeQuery(l_oSels[1], node=l_oSels[0], minimum=True))[0]
            else:
                cmds.addAttr(l_oSels[2], edit=True, hasMinValue=True)
        if i_s_floatField == "rsMaxField":
            b_maximum = cmds.attributeQuery(l_oSels[1], node=l_oSels[0], maxExists=True)
            f_atValue = 1.0
            if b_maximum == 1:
                f_atValue = (cmds.attributeQuery(l_oSels[1], node=l_oSels[0], maximum=True))[0]
            else:
                cmds.addAttr(l_oSels[2], edit=True, hasMaxValue=True)
                cmds.addAttr(l_oSels[2], edit=True, maxValue=f_atValue)
        cmds.floatField(i_s_floatField, edit=True, value=f_atValue, enable=True)
    else:
        cmds.floatField(i_s_floatField, edit=True, value=0, enable=False)
        if i_s_floatField == "rsMinField":
            cmds.addAttr(l_oSels[2], edit=True, hasMinValue=False)
        else:
            cmds.addAttr(l_oSels[2], edit=True, hasMaxValue=False)
    return True
예제 #16
0
def getSpaceSwitchData(node):

    data = {}

    attrs = mc.listAttr(node, userDefined=True, keyable=True)

    if not attrs:
        return data

    ssAttrs = [x for x in attrs if 'paceSwitch' in x]
    for attr in ssAttrs:
        enumValues = []
        spaceEnum = 'space'
        if attr == 'spaceSwitch':
            if not 'space' in attrs:
                spaceEnum = 'spaceSwitch'
            enumValues = mc.attributeQuery(spaceEnum, node=node, listEnum=True)
        elif 'SpaceSwitch' in attr:
            baseName = attr.replace('SpaceSwitch','')
            if baseName + 'Space' in attrs:
                spaceEnum = baseName+'Space'
            else:
                spaceEnum = attr
            if spaceEnum in attrs and mc.attributeQuery(spaceEnum, node=node, attributeType=True) == 'enum':
                enumValues = mc.attributeQuery(spaceEnum, node=node, listEnum=True)
        if not enumValues:
            continue
        data[attr] = {}
        data[attr]['enumValues'] = enumValues[0].split(':')
        data[attr]['currentValue'] = mc.getAttr(node+'.'+spaceEnum, asString=True)

    return data
예제 #17
0
def transform_is_visible(node_name):

    # check if the node exists
    if not cmds.objExists(node_name):
        return False

    # check if the node has a visibility attribute meaning it's a DAG node
    if not cmds.attributeQuery('visibility', node=node_name, exists=True):
        return False

    # check if the visibility set to off
    if not cmds.getAttr(node_name + '.visibility'):
        return False

    # check to see if it's an intermediate mesh
    if cmds.attributeQuery('intermediateObject', node=node_name, exists=True):
        if cmds.getAttr(node_name + '.intermediateObject'):
            return False

    # check if it is a hidden display layer
    if cmds.attributeQuery('overrideEnabled', node=node_name, exists=True) and cmds.getAttr(node_name + '.overrideEnabled'):
        if not cmds.getAttr(node_name + '.overrideVisibility'):
            return False

    return True
예제 #18
0
def addLengthAttrs(attrObject, length=0.0):
    """
    Add basic curve length attributes to the specified object
    @param attrObject: Object to add curve length attributes to
    @type attrObject: str
    @param length: Rest length value
    @type length: int or float
    """
    # ==========
    # - Checks -
    # ==========

    if not cmds.objExists(attrObject):
        raise Exception('Attribute object "' + attrObject + '" does not exist!')

    # ===========================
    # - Add Distance Attributes -
    # ===========================

    if not cmds.attributeQuery('length', n=attrObject, ex=True):
        cmds.addAttr(attrObject, ln='length', min=0, dv=dist, k=True)
    if not cmds.attributeQuery('restLength', n=attrObject, ex=True):
        cmds.addAttr(attrObject, ln='restLength', min=0, dv=dist, k=True)

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

    return attrObject + '.length'
예제 #19
0
    def __init__(self, targetObj, attr ):

        chBox = cmds.attributeQuery( attr, node=targetObj, channelBox=1 )
        key   = cmds.attributeQuery( attr, node=targetObj, keyable=1 )
        atType= cmds.attributeQuery( attr, node=targetObj, attributeType=1 )
        listEnum = cmds.attributeQuery( attr, node=targetObj, listEnum=1 )
        minvalue    = None
        maxValue    = None
        if cmds.attributeQuery( attr, node=targetObj, minExists=1 ):
            minvalue = cmds.attributeQuery( attr, node=targetObj, min=1 )
        if cmds.attributeQuery( attr, node=targetObj, maxExists=1 ):
            maxValue = cmds.attributeQuery( attr, node=targetObj, max=1 )
        shortName = cmds.attributeQuery( attr, node=targetObj, shortName=1 )
        longName  = cmds.attributeQuery( attr, node=targetObj, longName=1 )

        options = { 'sn':shortName, 'ln':longName, 'k':key, 'cb':chBox }

        if listEnum:
            options.update( {'listEnum':listEnum} )
        if minvalue:
            options.update( {'min':minvalue[0]} )
        if maxValue:
            options.update( {'max':maxValue[0]} )
        value = cmds.getAttr( targetObj+'.'+attr )

        self.attr = attr
        self.value = value 
        self.atType = atType
        self.options = options
    def testImport(self):
        """
        Tests that the built-in metadata attribute converters can import
        hidden, instanceable, and kind metadata properly.
        """
        # pCube1 and pCube2 have USD_kind.
        self.assertEqual(cmds.getAttr('pCube1.USD_kind'), 'potato')
        self.assertEqual(cmds.getAttr('pCube2.USD_kind'), 'bakedpotato')
        
        # pCube2, pCube4, and pCube5 have USD_hidden. pCube1 and pCube3 do not.
        self.assertTrue(
            cmds.attributeQuery('USD_hidden', node='pCube2', exists=True))
        self.assertTrue(
            cmds.attributeQuery('USD_hidden', node='pCube4', exists=True))
        self.assertTrue(
            cmds.attributeQuery('USD_hidden', node='pCube5', exists=True))
        self.assertFalse(
            cmds.attributeQuery('USD_hidden', node='pCube1', exists=True))
        self.assertFalse(
            cmds.attributeQuery('USD_hidden', node='pCube3', exists=True))

        self.assertTrue(cmds.getAttr('pCube2.USD_hidden'))
        self.assertTrue(cmds.getAttr('pCube4.USD_hidden'))
        self.assertFalse(cmds.getAttr('pCube5.USD_hidden'))
        
        # pCube3 and pCube4 have USD_instanceable.
        self.assertTrue(cmds.getAttr('pCube3.USD_instanceable'))
        self.assertTrue(cmds.getAttr('pCube4.USD_instanceable'))
예제 #21
0
 def blendSetups(self):
     constraintsList=[]
     for i, jnt in enumerate(self._originalJoints):
         const=cmds.parentConstraint(self._ikJoints[i], self._bakingJoints[i], jnt)[0]
         constraintsList.append(const)
         cmds.addAttr(const, longName="settingsGrp", attributeType="message")
         cmds.connectAttr(self.settingsGrp+".blendConstraints", const+".settingsGrp")
     #add blending attribute to the settings GRP
     if not cmds.attributeQuery("dynamicsSwitch", node=self.settingsGrp, exists=True):
         cmds.addAttr(self.settingsGrp, longName="dynamicsSwitch", attributeType="double", keyable=True, min= 0, max=1 ,dv=1)
     if not cmds.attributeQuery("bakingRig", node=self.settingsGrp, exists=True):
         cmds.addAttr(self.settingsGrp, longName="bakingRig", attributeType="double", keyable=True, min= 0, max=1 ,dv=0)
     #create the blendshape Node
     splineCurveBS=cmds.blendShape(self.dynamicOutCurve, self.ikCurve, name="%s_BS"%getShortName(self.ikCurve))[0]
     #connect blending attrs
     cmds.connectAttr("%s.dynamicsSwitch"%self.settingsGrp, "%s.%s"%(splineCurveBS, self.dynamicOutCurve))
     #create the reverse node
     reverseNode=cmds.shadingNode("reverse", asUtility=True, name="%s_rev"%getShortName(self.settingsGrp))
     cmds.connectAttr("%s.bakingRig"%self.settingsGrp, "%s.inputX"%reverseNode)
     for const in constraintsList:
         weights=cmds.parentConstraint(const, weightAliasList=True, query=True)
         cmds.connectAttr("%s.outputX"%reverseNode, "%s.%s"%(const, weights[0]))
         cmds.connectAttr("%s.bakingRig"%self.settingsGrp, "%s.%s"%(const, weights[1]))
     #connect the reverse output to the ik setup controllers visibility
     for ctrl in self.ikControllers:
         cmds.connectAttr("%s.outputX"%reverseNode, "%s.visibility"%cmds.listRelatives(ctrl, shapes=True)[0])
     for ctrl in self.bakeControllers:
         cmds.connectAttr("%s.bakingRig"%self.settingsGrp, "%s.visibility"%cmds.listRelatives(ctrl, shapes=True)[0])
예제 #22
0
파일: autorig.py 프로젝트: Regnareb/Maya
    def getattributes(self):
        for key, nodes in self.oldNodes.iteritems():
            if key == 'expression':
                expression = True
            else:
                expression = False
            for oldNode in nodes:
                listAttr = cmds.listAttr(oldNode)
                if listAttr:
                    self.attributes[nodes[oldNode]] = {}
                    for attr in listAttr:
                        try:
                            self.attributes[nodes[oldNode]].update({attr: {'value': cmds.getAttr(oldNode + '.' + attr)}})
                            self.attributes[nodes[oldNode]][attr].update({'type': cmds.getAttr(oldNode + '.' + attr, type=True)})
                            if expression and attr == 'expression':
                                self.expressions.update({nodes[oldNode]: self.attributes[nodes[oldNode]][attr]['value']})
                        except RuntimeError as e:
                            pass
                        except ValueError as e:
                            pass

                listAttrCustom = cmds.listAttr(oldNode, userDefined=True)
                if listAttrCustom:
                    self.newAttributes[nodes[oldNode]] = {}
                    for attr in listAttrCustom:
                        try:
                            self.newAttributes[nodes[oldNode]].update({attr: {'type': cmds.getAttr(oldNode + '.' + attr, type=True)}})
                            if cmds.attributeQuery(attr, node=oldNode, minExists=True):
                                self.newAttributes[nodes[oldNode]][attr].update({'min': cmds.attributeQuery(attr, node=oldNode, min=True)})
                            if cmds.attributeQuery(attr, node=oldNode, maxExists=True):
                                self.newAttributes[nodes[oldNode]][attr].update({'max': cmds.attributeQuery(attr, node=oldNode, max=True)})
                        except RuntimeError as e:
                            pass
                        except ValueError as e:
                            pass
    def setSoftMinMaxValue(fieldName, nodeName):
        # Some values do not have a sotft min / max -> set manually

        # Dynaimc Simulation
        if fieldName == 'viscosity':
            minSoft = 0
            maxSoft = 1
        # Velocity
        elif fieldName == 'velocitySwirl':
            minSoft = 0
            maxSoft = 10
        # Turbulence
        elif fieldName == 'turbulenceStrength':
            minSoft = 0
            maxSoft = 1
        elif fieldName == 'turbulenceFrequency':
            minSoft = 0
            maxSoft = 2
        elif fieldName == 'turbulenceSpeed':
            minSoft = 0
            maxSoft = 2

        else:
            minSoft = cmds.attributeQuery(fieldName, node=nodeName, softMin=True)
            maxSoft = cmds.attributeQuery(fieldName, node=nodeName, softMax=True)
            minSoft = minSoft[0]
            maxSoft = maxSoft[0]

        return [minSoft, maxSoft]
예제 #24
0
 def get_bounds(obj, attr, min_default, max_default):
     """
     Try to retrieve the range for the given attribute, if min or max fail it'll set default values
     :param         obj: the object's name
     :type          obj: str
     :param        attr: attribute's name
     :type         attr: str
     :param min_default: minimum default value
     :param max_default: max default value
     :type  min_default: float | int
     :type  max_default: float | int
     :return: minimum, maximum
     :rtype : tuple
     """
     try:
         assert cmds.attributeQuery(attr, n=obj, mxe=True)
         maxi = cmds.attributeQuery(attr, n=obj, max=True)[0]
     except (RuntimeError, AssertionError):
         maxi = max_default
     try:
         assert cmds.attributeQuery(attr, n=obj, mne=True)
         mini = cmds.attributeQuery(attr, n=obj, min=True)[0]
     except (RuntimeError, AssertionError):
         mini = min_default
     return mini, maxi
예제 #25
0
def createAttribute():
    if(not cmds.textField(tf01, text = True, query = True) == ''):
        niceName, longName = attrNameDefC()
        sel = selectListC()
        if(dataTypeC == 'float3'):
            for obj in sel:
                if(not cmds.attributeQuery(longName, node = obj, exists = True)):
                    cmds.addAttr(obj, niceName = niceName, longName = longName, usedAsColor = True, attributeType = dataTypeC)
                    cmds.addAttr(obj, longName = '%sR' % longName, attributeType = 'float', parent = longName)
                    cmds.addAttr(obj, longName = '%sG' % longName, attributeType = 'float', parent = longName)
                    cmds.addAttr(obj, longName = '%sB' % longName, attributeType = 'float', parent = longName)
        elif(dataTypeC == 'double3'):
            for obj in sel:
                if(not cmds.attributeQuery(longName, node = obj, exists = True)):
                    cmds.addAttr(obj, niceName = niceName, longName = longName, attributeType = dataTypeC)
                    cmds.addAttr(obj, longName = '%sX' % longName, attributeType = 'double', parent = longName)
                    cmds.addAttr(obj, longName = '%sY' % longName, attributeType = 'double', parent = longName)
                    cmds.addAttr(obj, longName = '%sZ' % longName, attributeType = 'double', parent = longName)
        elif(dataTypeC == 'string'):
            for obj in sel:
                if(not cmds.attributeQuery(longName, node = obj, exists = True)):
                    cmds.addAttr(obj, niceName = niceName, longName = longName, dataType = dataTypeC)
        else:
            for obj in sel:
                if(not cmds.attributeQuery(longName, node = obj, exists = True)):
                    cmds.addAttr(obj, niceName = niceName, longName = longName, attributeType = dataTypeC)
        cmds.textField(tf01, text = '', edit = True)
예제 #26
0
파일: polyShell.py 프로젝트: skarone/PipeL
def ftb_gen_shell_doIt(dist,distUV,div):
	if (mc.window('shellUiWin',q=True,exists=True)):
		mc.deleteUI('shellUiWin')
	#mc.loadPlugin( 'c:/ftb_mayaplugins/ppl/2011 x64/shellNode.mll')
	sel = mc.ls(sl=True)
	if(len(sel)!= 0):
		shape = mc.listRelatives(sel[0],noIntermediate = True,shapes=True)
		His = mc.listHistory(shape[0])
		shell = ''
		for h in His:
			if(mc.nodeType(h) == 'polyShell'):
				shell = h
		if(shell == ''):
			if(mc.attributeQuery('shThickness',node=shape[0],ex=True)):
				dist = mc.getAttr(shape[0]+'.shThickness')
			else:
				mc.addAttr(shape[0],ln="shThickness",at='double',dv=0)
				mc.setAttr(shape[0]+'.shThickness',e=True,keyable=True)
			if(mc.attributeQuery('shUvThickness',node=shape[0],ex=True)):
				distUV = mc.getAttr(shape[0]+'.shUvThickness')
			else:
				mc.addAttr(shape[0],ln="shUvThickness",at='double',dv=0)
				mc.setAttr(shape[0]+'.shUvThickness',e=True,keyable=True)
			if(mc.attributeQuery('shDiv',node=shape[0],ex=True)):
				div = mc.getAttr(shape[0]+'.shDiv')
			else:
				mc.addAttr(shape[0],ln="shDiv",at='long',dv=0,min=0)
				mc.setAttr(shape[0]+'.shDiv',e=True,keyable=True)
			faceInitalCount = mc.polyEvaluate(sel[0],f=True)
			mc.polyShell(thickness = dist,uvOffset = distUV);
			sel2 = mc.ls(sl=True)
			faceFinalCount = mc.polyEvaluate(sel[0],f=True)
			mc.addAttr(sel2[0],ln="div",at='long',min=0,dv=0)
			mc.setAttr(sel2[0]+'.div',e=True,keyable=True)
			mc.setAttr(sel2[0]+'.div',div)
			mc.addAttr(sel2[0],ln="splits",dt="string")
			mc.setAttr(sel2[0]+'.splits',e=True,keyable=True)
			mc.select((sel[0]+'.f[%i' % (faceInitalCount*2)+':%i' % faceFinalCount+']'))
			faceList = mc.ls(sl=True,fl=True)
			facesRings = makeFaceRingGroups(faceList)
			for faceRing in facesRings:
				mc.select(facesRings[faceRing])
				mc.ConvertSelectionToContainedEdges()
				mc.setAttr(sel2[0]+'.thickness',0.2)
				split = mc.polySplitRing(mc.ls(sl=True),ch=True,splitType=2,divisions=0,useEqualMultiplier=1,smoothingAngle=30,fixQuads=1)
				splits = mc.getAttr(sel2[0]+'.splits')
				if(splits == None):
					splits = ""
				mc.setAttr(sel2[0]+'.splits',("%s"%splits+"%s,"%split[0]),type="string")
				mc.connectAttr(sel2[0]+'.div', (split[0]+'.divisions'))
				mc.setAttr(sel2[0]+'.thickness',dist)
				
			mc.connectAttr(sel2[0]+'.thickness',shape[0]+'.shThickness')
			mc.connectAttr(sel2[0]+'.uvOffset',shape[0]+'.shUvThickness')
			mc.connectAttr(sel2[0]+'.div',shape[0]+'.shDiv')
		else:
			print('This mesh have a shellModifier allready!!!!!')
	else:
		mc.error("please select some mesh")
예제 #27
0
 def unlockOSel( cls, *args ):
     
     for jnt in cmds.ls( type='joint' ):
         if not cmds.attributeQuery( 'lockInfluenceWeights', node=jnt, ex=1 ): continue
         cmds.setAttr( jnt+'.lockInfluenceWeights', 1 )
     for jnt in cmds.ls( type='joint', sl=1 ):
         if not cmds.attributeQuery( 'lockInfluenceWeights', node=jnt, ex=1 ): continue
         cmds.setAttr( jnt+'.lockInfluenceWeights', 0 )
예제 #28
0
    def install(self):

        controlZroGrp = cmds.listConnections(cmds.listConnections(self.nodes['control']+".controlMetadata")[0] + ".zeroGroup")
        
        if not cmds.objExists(self.nodes['switcher']):
            utils_transforms.createZeroGroup(controlZroGrp, name=self.nodes['switcher'])
          
        # translate Spaces
        for space in self.translateSpaces:
            spaceGrp = space + "_space"
            attrName = self.nodes['control']+"_translateSpace"
            
            if cmds.attributeQuery(attrName, n = self.customAttribute, exists=True):
                enumName = cmds.addAttr(self.customAttribute +'.'+ attrName, q=True, enumName=True)
                enumName = enumName + ":" + space
                cmds.addAttr(self.customAttribute +'.'+ attrName, e=True, enumName=enumName, k=True)
            else:            
                cmds.addAttr(self.customAttribute, at='enum', enumName = space, ln=attrName, k=len(self.translateSpaces) > 1)
                            
            ## space locator
            spaceLoc = self.nodes['control'] + "_AT_" + space
            if not cmds.objExists(spaceLoc):
                cmds.spaceLocator(name = spaceLoc)[0]
                cmds.setAttr(spaceLoc+".visibility", 0)
                cmds.delete(cmds.parentConstraint(self.nodes['switcher'], spaceLoc, maintainOffset=False))
                cmds.parent(spaceLoc, spaceGrp , absolute=True)
    
            pCon = cmds.pointConstraint(spaceLoc, self.nodes['switcher'], name = self.nodes['switcher'] + "_pointConst")[0]
            transWeights = cmds.pointConstraint(pCon, q=True, wal=True)
            pCondition = self.enumCondition(self.customAttribute + '.' + self.nodes['control'] + "_translateSpace", self.nodes['control']+"_AT_"+ space + "_translateSpace_condition")
            cmds.connectAttr(pCondition+".outColorR", pCon + "." + transWeights[-1])
    
        # orient Spaces
        for space in self.orientSpaces:
            spaceGrp = space + "_space"
            attrName = self.nodes['control']+"_orientSpace"
            
            if cmds.attributeQuery(attrName, n = self.customAttribute, exists=True):
                enumName = cmds.addAttr(self.customAttribute +'.'+ attrName, q=True, enumName=True)
                enumName = enumName + ":" + space
                cmds.addAttr(self.customAttribute +'.'+ attrName, e=True, enumName=enumName, k=True)
            else:            
                cmds.addAttr(self.customAttribute, at='enum', enumName = space, ln=attrName, k=len(self.orientSpaces) > 1)
                            
            ## space locator
            spaceLoc = self.nodes['control'] + "_AT_" + space
            if not cmds.objExists(spaceLoc):
                cmds.spaceLocator(name = spaceLoc)[0]
                cmds.setAttr(spaceLoc+".visibility", 0)
                cmds.delete(cmds.parentConstraint(self.nodes['switcher'], spaceLoc, maintainOffset=False))
                cmds.parent(spaceLoc, spaceGrp , absolute=True)
                
            oCon = cmds.orientConstraint(spaceLoc, self.nodes['switcher'], name = self.nodes['switcher'] + "_orientConst")[0]
            orientWeights = cmds.orientConstraint(oCon, q=True, wal=True)
            oCondition = self.enumCondition(self.customAttribute + '.' + self.nodes['control'] + "_orientSpace", self.nodes['control']+"_AT_"+space + "_orientSpace_condition")      
            cmds.connectAttr(oCondition+".outColorR", oCon + "." + orientWeights[-1])   
        
        return
예제 #29
0
def BT_AddPose(set = None, poseName = '', index = None):

    prefixedPoseName = 'BT_' +poseName

    if not set:
        return False
    
    if not cmds.attributeQuery('Blend_Node', ex = True, n = set):
        return False

    if BT_IsSetupConnected(set = set):
        cmds.warning('Disconnect setup first!')
        return False
    
    blendNode = cmds.getAttr(set +'.Blend_Node')
    
    if not cmds.objExists(blendNode) or not cmds.objExists(set):
        return False

    if cmds.attributeQuery(prefixedPoseName, ex = True, n = set):
        return False

    transforms = cmds.listConnections(set +'.dagSetMembers')

    numTransforms = len(transforms)
    poseIndex = cmds.getAttr(blendNode +'.transforms[0].poses', size = True) 

    if index is not None:
        poseIndex = index
    
    if index is None:
        cmds.addAttr(set, ln = prefixedPoseName, nn = poseName,  k = True, min = 0, max = 1.0, at = 'double')

    # print ('Num poses = ' +str(numPoses))
    for i in range(0, numTransforms):
        #get the base matrix
        baseScale = cmds.getAttr(blendNode +'.transforms[' +str(i) +'].baseScale')[0]
        baseMatrix = cmds.getAttr(blendNode +'.transforms[' +str(i) +'].baseMatrix')

        #store the scale and set it 
        transformScale = cmds.getAttr(transforms[i] +'.scale')[0]

        #set the scale back to 1.0
        cmds.setAttr(transforms[i] +'.scale', 1.0, 1.0, 1.0, type = 'double3')
        transformMatrix = cmds.xform(transforms[i], q = True, m = True)

        poseMatrix = [x-y for x, y in zip(transformMatrix, baseMatrix)]
        poseScale = [x-y for x, y in zip(transformScale, baseScale)]

        #set the scale back to what the user had it at
        cmds.setAttr(transforms[i] +'.scale', transformScale[0], transformScale[1], transformScale[2], type = 'double3')
        cmds.setAttr(blendNode +'.transforms[' +str(i) +'].poses[' +str(poseIndex) +'].matrix', poseMatrix, type = 'matrix')
        BT_Double3ValuesToNode(values = poseScale, node = blendNode, attr = 'transforms[' +str(i) +'].poses[' +str(poseIndex) +'].scale' )

        if index is None:
            cmds.connectAttr(set +'.' +prefixedPoseName, blendNode +'.transforms[' +str(i) +'].poses[' +str(poseIndex) +'].weight')

    return True
예제 #30
0
	def __init__( self, obj=None, attr=None, start=None, end=None, populateTangents=True ):
		self.obj = obj
		self.attr = attr
		self.weighted = True
		self.keys = []

		#unless an attrpath has been specified, we're done...
		if obj is None or attr is None: return
		attrpath = '.'.join((obj,attr))

		if start is None:
			#get the timecount of the first key
			start = cmd.keyframe(attrpath,index=(0,),query=True)[0]
		if end is None:
			#get the timecount of the first key
			lastKeyIdx = cmd.keyframe(attrpath,keyframeCount=True,query=True)-1
			end = cmd.keyframe(attrpath,index=(lastKeyIdx,),query=True)[0]

		self.attr = str( cmd.attributeQuery(self.attr,longName=True,node=self.obj) )
		self.attrShort = str( cmd.attributeQuery(self.attr,shortName=True,node=self.obj) )
		self.weighted = cmd.keyTangent(attrpath,query=True,weightedTangents=True)

		if self.weighted == 1: self.weighted = True
		else: self.weighted = False

		if cmd.objExists(attrpath):
			times = cmd.keyframe(attrpath,time=(start,end),query=True)
			values = cmd.keyframe(attrpath,time=(start,end),query=True,vc=True)

			#if there are no keys - bail
			if times is None: return
			self.keys = [Key(obj,attr,time=k,value=v,populateTangents=False) for k,v in zip(times,values)]
			if populateTangents:
				#querying heaps of tangent data at once is much more efficient than throwing a query for
				#each key created - so although uglier, its quite significantly faster...
				iws = cmd.keyTangent(attrpath,time=(start,end),query=True,iw=True)
				ows = cmd.keyTangent(attrpath,time=(start,end),query=True,ow=True)
				ias = cmd.keyTangent(attrpath,time=(start,end),query=True,ia=True)
				oas = cmd.keyTangent(attrpath,time=(start,end),query=True,oa=True)
				itts = cmd.keyTangent(attrpath,time=(start,end),query=True,itt=True)
				otts = cmd.keyTangent(attrpath,time=(start,end),query=True,ott=True)
				locks = cmd.keyTangent(attrpath,time=(start,end),query=True,lock=True)

				#remove all instances of 'fixed' tangent types.  maya will return a type of fixed, but it throws an exception if
				#you try to set a tangent type of fixed...  nice...
				try:
					while True: itts.remove('fixed')
				except ValueError: pass
				try:
					while True: otts.remove('fixed')
				except ValueError: pass

				#
				for key,iw,ow,ia,oa,itt,ott,lock in zip(self.keys,iws,ows,ias,oas,itts,otts,locks):
					key.iw,key.ow,key.ia,key.oa,key.itt,key.ott,key.lock = iw,ow,ia,oa,itt,ott,lock

			self.keys.sort()
예제 #31
0
    def __update(self, attributes):  # pylint: disable=too-many-locals
        """
        Build the internal tree.

        :param attributes: A list of attributes.
        :return: The tree root item.
        """
        root = self.invisibleRootItem()
        root.setDragEnabled(False)

        # Note: sorted will put None first
        attributes_by_parent = itertools.groupby(
            sorted(attributes, key=_get_attribute_parent),
            _get_attribute_parent)

        item_by_attr = {}
        for parent_attr, attributes_ in attributes_by_parent:
            attributes_ = tuple(attributes)

            for attribute in attributes_:

                # Get data from attribute
                parent = item_by_attr.get(parent_attr, root)
                node_name, attr_name = attribute.split(".", 1)
                attr_type = cmds.getAttr(attribute, type=True)
                attr_multi = cmds.attributeQuery(attr_name,
                                                 node=node_name,
                                                 multi=True)

                item1 = QtGui.QStandardItem(attr_name)
                item1.setData(attribute, DataRole)
                item2 = QtGui.QStandardItem(attr_type)
                item3 = QtGui.QStandardItem(str(attr_multi))

                # Prevent item overwrite with a drop
                item1.setDropEnabled(False)
                item2.setDropEnabled(False)
                item3.setDropEnabled(False)

                # Prevent re-ordering of child attributes
                if parent is not root:
                    item1.setDragEnabled(False)
                    item2.setDragEnabled(False)
                    item3.setDragEnabled(False)

                parent.appendRow([item1, item2, item3])
                item_by_attr[attribute] = item1
예제 #32
0
def alembic_import_assignMaterialsFromAttr(objects=None ):
    '''{'path':'Pipeline Cache/Material/alembic_import_assignMaterialsFromAttr( )',
'html':'http://10.99.17.61/hq_maya/alembicPipeline',
'icon':':/render_lambert.png',
'tip':'根据matInfo属性,恢复材质',
'usage':"""
#根据选择物体的matInfo属性,将材质恢复回来。
#使用方法:选择要物体材质物体或组
$fun( )""",
}
'''
    startTime = time.time()
    #Function in there
    if objects==None:
        selectedObj = cmds.ls(sl=True, l=True)        
    else:
        selectedObj = objects

    #cmds.select(all=True, ado=True, r=True)
    #selectedObj = cmds.ls('*_AbcGrp', sl=True, type='transform')

    allMeshFullPath = cmds.listRelatives(selectedObj, type=['mesh','nurbsSurface'], noIntermediate=True, ad=True, f=True)
    #allMeshFullPath = cmds.ls(exactType=['mesh','nurbsSurface'], noIntermediate=False, l=True)
    for child in allMeshFullPath[:]:
        if cmds.getAttr( child+'.intermediateObject')==True:
            allMeshFullPath.remove( child )
    
    
    allMeshFullPath = [mesh for mesh in allMeshFullPath if cmds.attributeQuery('matInfo', node=mesh, exists=True) ]
    for mesh in allMeshFullPath:
        cmds.setAttr( mesh+'.matInfo', l=True)
        matDic = json.loads( cmds.getAttr( mesh+'.matInfo') )

        if not matDic:
            continue        
        
        for mat, fSet in matDic.items():            
            if fSet == 'All':
                cmds.select( mesh, r=True)                
            else:
                faces = ['%s.%s'%(mesh,f) for f in fSet]                    
                cmds.select(faces, r=True )
                
            if cmds.objExists(mat):
                cmds.hyperShade( assign=mat )
    cmds.select( cl=True )
    print time.time() - startTime
예제 #33
0
def expression():
    grps = cmds.listRelatives(root,
                              children=True,
                              type='transform',
                              fullPath=True)
    random.seed(cmds.currentTime(q=True))
    length = cmds.getAttr(root + '.length')
    for g in grps:
        #print(g)
        children = cmds.listRelatives(g,
                                      children=True,
                                      type='transform',
                                      fullPath=True)
        lightning = None
        for c in children:
            if cmds.attributeQuery('isLightning', n=c, ex=True):
                lightning = c
        if not lightning:
            print('lightning not found for %s. something is wrong' % g)
            continue
        #print(lightning)
        lifespan = cmds.getAttr(lightning + '.lifespan')
        age = cmds.getAttr(lightning + '.age')
        lsrc = cmds.listConnections(g + '.srcLocator')
        ldst = cmds.listConnections(g + '.dstLocator')
        if age >= lifespan:
            lifespan = random.uniform(0, 3)
            age = 0
            #print(lsrc,ldst)
            rpos = random.uniform(0.0, 1.0)
            curve = cmds.listConnections(lightning + '.curve')[0]
            maxVal = cmds.getAttr(curve + '.maxValue')
            spos = cmds.pointOnCurve(curve, pr=rpos * maxVal, p=True)
            rlen = random.uniform(0.0, length)
            drpos = rpos * maxVal + rlen
            if drpos > maxVal:
                drpos = maxVal
            dpos = cmds.pointOnCurve(curve, pr=drpos, p=True)
            cmds.xform(lsrc, translation=spos)
            cmds.xform(ldst, translation=dpos)
        else:
            age += 1
            cmds.xform(lsrc, r=True, translation=[0.001, 0.001, 0.001])
            cmds.xform(ldst, r=True, translation=[0.001, 0.001, 0.001])
        cmds.setAttr(lightning + '.age', age)
        cmds.setAttr(lightning + '.lifespan', lifespan)
예제 #34
0
def findPublishedAssets():
    publishedAssets = []
    allTransforms = cmds.ls(transforms=True, l=True)
    assetFolders = listFolders('maya/scenes/Models')
    for t in allTransforms:
        if cmds.attributeQuery('publishName', node=t, exists=True):
            fullRefPath = cmds.referenceQuery(t, filename=True)
            parentFolder = fullRefPath.split('/')[-2]
            correctFile = 0
            if parentFolder in assetFolders:
                correctFile = 1
            t = t[1:]
            publishedAssets.append({
                "transform": t,
                "correctFile": correctFile
            })
    return publishedAssets
예제 #35
0
def randomizeFloats(*args):
    sel = cmds.ls(sl=True)
    attrs = getChannels()

    minn = cmds.floatFieldGrp(widgets["floatFFG"], q=True, v1=True)
    maxx = cmds.floatFieldGrp(widgets["floatFFG"], q=True, v2=True)
    rel = cmds.checkBox(widgets["floatCB"], q=True, v=True)

    for obj in sel:
        for attr in attrs:
            if (cmds.attributeQuery(attr, node=obj, exists=True)):
                rand = getRandomFloat(minn, maxx)
                current = 0.0
                if rel:
                    current = cmds.getAttr("{0}.{1}".format(obj, attr))
                newVal = rand + current
                cmds.setAttr("{0}.{1}".format(obj, attr), newVal)
def variantSetsChangeCommmand(unused, omg, node, variantSetName):
    val = cmds.optionMenuGrp(omg, q=True, value=True)
    variantAttr = 'usdVariantSet_%s' % variantSetName
    if not cmds.attributeQuery(variantAttr, node=node, exists=True):
        cmds.addAttr(node, ln=variantAttr, dt='string', internalSet=True)
    cmds.setAttr('%s.%s' % (node, variantAttr), val, type='string')

    resolvedVariant = ''
    usdPrim = UsdMaya.GetPrim(node)

    if usdPrim:
        variantSet = usdPrim.GetVariantSet(variantSetName)
        if variantSet:
            resolvedVariant = variantSet.GetVariantSelection()
    cmds.optionMenuGrp(omg, edit=True, extraLabel=resolvedVariant)

    cmds.refreshEditorTemplates()
예제 #37
0
def add(spaceNode, target, name=None, mode='parent'):
    '''
    '''

    if not name:
        space = target
    else:
        space = name

    # Get space node network
    spaceGrp, spaceSwitch, spaceConstraint = getNodes(spaceNode)

    # See if mode is compatible
    conType = cmds.objectType(spaceConstraint)
    if not conType.__contains__(mode):
        cmds.warning('spaces.add: cannot add '+mode+'Constraint target to a '+conType)
        return None

    # Check current spaces
    curSpaces = cmds.attributeQuery(SPACEATTR, node=spaceSwitch, listEnum=True)[0].split(':')
    if space in curSpaces or target in curSpaces:
        print 'spaces.add: "'+spaceSwitch+'" already has a "'+space+'" space, skipping...'
        return None

    # Add enum space
    cmds.addAttr(spaceSwitch+'.'+SPACEATTR, e=True, enumName=':'.join(curSpaces+[space]))

    # Add spaceTarget in space of target object
    spaceTarget = cmds.createNode('transform', name=spaceGrp+'_'+space, parent=spaceGrp)
    matchPose(spaceNode, spaceTarget)

    cmds.parentConstraint(target, spaceTarget, mo=True)
    lockAndHide(['t','r','s','v'], spaceTarget)

    # Add target to spaceNode constraint
    if mode == 'orient':
        spaceConstraint = cmds.orientConstraint(spaceTarget, spaceNode, mo=True)[0]
    elif mode == 'point':
        spaceConstraint = cmds.pointConstraint(spaceTarget, spaceNode, mo=True)[0]
    else:
        spaceConstraint = cmds.parentConstraint(spaceTarget, spaceNode, mo=True)[0]

    # Update weight connections
    connect(spaceConstraint, spaceSwitch)

    return(spaceTarget)
예제 #38
0
def check_metatype(node, metatype):
    """Check if node has meta_type

    Args:
        node:  Node to check existence of metatype
        metatype:  Name of metaType to check for

    Example:
        # Check if rig node is a propIt metaType
        check_metatype('cone:cone_rig', 'propIt')
    """
    if cmds.attributeQuery('metaTypes', node=node, exists=True):
        raw_metatypes = cmds.getAttr('{}.metaTypes'.format(node))
        metatypes = json.loads(raw_metatypes)
        if metatype in metatypes:
            return True
    return
예제 #39
0
파일: ui.py 프로젝트: jonntd/mayadev-1
 def loadCmd(self, *args ):
     
     sels = cmds.ls( sl=1 )
     if not sels: return None
     target = sels[-1]
     
     if cmds.attributeQuery( 'isEditMesh', node=target, ex=1 ):
         target = cmds.listConnections( target+'.message' )[0]
     
     cmds.textField( self._targetMeshField, e=1, tx=target )
     self.refreshTarget()
     
     self._editButton._editCmd = []
     self._editButton._assignCmd = []
     self._editButton._editCmd.append( [mainCmd.createEditMesh, target] )
     self._editButton._assignCmd.append( [mainCmd.assignMesh, target] )
     self._editButton._assignCmd.append( [self.refreshTarget, ''] )
예제 #40
0
def popSubdivLists(notSubList,subList,retards,*args):
    subdivEnabledGeo = []
    notSubdivGeo = []
    geoList = [f for f in cmds.ls(type='mesh') if cmds.getAttr(f+'.intermediateObject') == 0]
    subdivGeo = [f for f in geoList if cmds.attributeQuery('vraySubdivEnable',exists=1,node=f) == True]
    subdivEnabledGeo = [f for f in subdivGeo if cmds.getAttr(f+'.vraySubdivEnable') == 1]
    notSubdivGeo = [f for f in geoList if f not in subdivEnabledGeo and f not in retards]
    subdivEnabledGeo = natSort.natsorted(subdivEnabledGeo)
    notSubdivGeo = natSort.natsorted(notSubdivGeo)
    subdivEnabledGeo.extend(retards)
    cmds.textScrollList(subList,e=1,ra=1)
    cmds.textScrollList(notSubList,e=1,ra=1)
    for i in subdivEnabledGeo:
        cmds.textScrollList(subList,e=1,a=i)
    for i in notSubdivGeo:
        cmds.textScrollList(notSubList,e=1,a=i)
    return notSubdivGeo,subdivEnabledGeo
예제 #41
0
    def export(self):
        """

        saves files, also checks for GoZParent attr

        GoZParent is used to import objects in correct order in ZBrush
        GoZParent determines the top level tool in ZBrush

        If no instance exists, it is created

        GoZParent is also appended to the export string: objectname#gozparentname

        """

        print self.objs

        # default pm3d star

        new_objects = []

        for idx, obj in enumerate(self.objs):

            cmds.select(cl=True)
            cmds.select(obj)
            cmds.delete(ch=True)
            self.ascii_path = utils.make_file_name(obj)
            cmds.file(self.ascii_path,
                      force=True,
                      options="v=0",
                      type="mayaAscii",
                      exportSelected=True)
            if cmds.attributeQuery('GoZParent', node=obj, exists=True):
                # object existed in zbrush, has 'parent' tool
                parent = cmds.getAttr(obj + '.GoZParent')
            else:
                # construct a list of objects to create
                # append all future objects as sub tools
                new_objects.append(obj)
                parent = new_objects[0]
                cmds.addAttr(obj, longName='GoZParent', dataType='string')
                cmds.setAttr(obj + '.GoZParent', parent, type='string')
            self.objs[idx] = obj + '#' + parent

            # maya is often run as root, this makes sure osx can open/save files
            # not needed if maya is run un-privileged
            os.chmod(self.ascii_path, 0o777)
예제 #42
0
def deleteDataAttribute(nodeName="rigDataNode", attributeName="myAttr"):
    """Delete the entire attribute from the node.

    Parameters
    ----------
    nodeName : str
        The name of the node that contains the attribute
    attributeName : str
        The name of the attribute that is going to be deleted
    """
    # Exit the function if the node doesn't exist
    if not cmds.objExists(nodeName):
        return

    # Delete the attribute if it exists
    if cmds.attributeQuery(attributeName, node=nodeName, exists=True):
        cmds.deleteAttr(nodeName, attribute=attributeName)
예제 #43
0
def mGetSmoothMask(assetName):
    """
	"""
    smoothmask = []
    smoothExclusive = False
    setList = cmds.ls('*moGCSmoothMask', r=1, typ='objectSet')
    if setList:
        for set in setList:
            if ':' not in set or (':' in set and set.startswith(assetName)):
                for obj in cmds.sets(set, q=1, no=1):
                    smoothmask.append(obj.split(':')[-1])
                if cmds.attributeQuery('smoothExclusive', node=set, ex=1):
                    smoothExclusive = True if cmds.getAttr(
                        set + '.smoothExclusive') else False
                    break

    return smoothExclusive, smoothmask
예제 #44
0
 def setupActiveModuleControls(self): 
     existingControls = cmds.columnLayout(self.UIElements["activeModuleColumn"], q=True, childArray=True)
     if existingControls != None:
        cmds.deleteUI(existingControls)
        
     cmds.setParent(self.UIElements["activeModuleColumn"])
     
     largeButtonSize = 100
     enumOptionWidth = self.windowWidth - 2*largeButtonSize
     
     self.settingsLocator = self.selectedBlueprintModule + ":SETTINGS"
     activeModuleAttribute = self.settingsLocator + ".activeModule"
     
     currentEntries = cmds.attributeQuery("activeModule", n=self.settingsLocator, listEnum=True)
     enable = True
     if currentEntries[0] == "None":
         enable=False
         
     self.UIElements["activeModule_rowLayout"] = cmds.rowLayout(nc=3, adjustableColumn=1, ct3=("both", "both", "both"), cw3= (enumOptionWidth, largeButtonSize, largeButtonSize))
     
     attributes = cmds.listAttr(self.settingsLocator, keyable=False)
     weightAttributes = []
     for attr in attributes:
         if attr.find("_weight") != -1:
             weightAttributes.append(attr)
             
     self.UIElements["activeModule"] = cmds.attrEnumOptionMenu(label="Active Module", width=enumOptionWidth, attribute=activeModuleAttribute, changeCommand=partial(self.activeModule_enumCallback, weightAttributes), enable=enable)
     self.UIElements["keyModuleWeights"] = cmds.button(label= "Key All", c=partial(self.keyModuleWeights, weightAttributes), annotation='Key Control Switching', enable=enable)
     self.UIElements["graphModuleWeights"] = cmds.button(label="Graph Weights", c=self.graphModuleWeights, enable=enable)
     
     cmds.setParent(self.UIElements["activeModuleColumn"])
     
     self.UIElements["moduleWeights_frameLayout"] = cmds.frameLayout(collapsable=True, collapse=False, label="Module Weights", height=100, collapseCommand = self.moduleWeight_UICollapse, expandCommand=self.moduleWeight_UIExpand)
     cmds.scrollLayout(hst=0)
     cmds.columnLayout(adj=True)
     
     cmds.attrFieldSliderGrp(at=self.settingsLocator+".creationPoseWeight", enable=False)
     cmds.separator
     
     for attr in weightAttributes:
         self.UIElements[attr] = cmds.floatSliderGrp(label=attr, field=True, precision=4, minValue=0.0, maxValue=1.0, value=cmds.getAttr(self.settingsLocator+"."+attr), cc=partial(self.moduleWeights_sliderCallback, attr, weightAttributes))
     
     parentUIElements = self.UIElements["moduleWeights_frameLayout"]
     self.create_moduleWeightsScriptJob(parentUIElements, weightAttributes)
     
     self.moduleWeights_updateMatchingButton()
예제 #45
0
파일: objectId.py 프로젝트: aratakawa/pop
def getObjectsById() :
    result = cmds.promptDialog(title='RenameGeo',message='Enter Name',button=['OK','Cancel'],defaultButton='OK',cancelButton='Cancel',dismissString='Cancel')
    out = []
    if result == 'OK':
        id = int(cmds.promptDialog(q=True,text=True))
        for t in types :
            if t not in cmds.allNodeTypes() :
                continue
            objs = cmds.ls( type=t, long=True )
            for o in objs :
                if cmds.attributeQuery( attr, ex=True, node=o ) :
                    if id == cmds.getAttr( o+'.'+attr ) :
                        out.append( o )

    cmds.select(cl=True)
    if len( out ) > 0 :
        cmds.select( out )
예제 #46
0
파일: lib.py 프로젝트: dayelov/MayaPython
def createNucleus(name):
    """
    create nucleus by given name
    :param name: str, name of the nucleus
    :return: nucleus
    """
    nucleus = cmds.createNode('nucleus', n=name + '_Nucleus_#')

    # connect attr
    cmds.connectAttr('time1.outTime', nucleus + '.currentTime')

    # add attr
    if not cmds.attributeQuery('nucleus', node=nucleus, exists=1):
        cmds.addAttr(nucleus, longName='nucleus', at='message', multi=1)
    cmds.select(cl=1)

    return nucleus
예제 #47
0
def listMVGMeshesTransform():
    import maya.cmds as cmds
    mvgMeshes = []
    meshList = pm.ls(type="mesh")
    for mesh in meshList:
        if not cmds.attributeQuery("mvg", node=mesh.name(), exists=True):
            continue
        mvgAttr = mesh.name() + ".mvg"
        if not cmds.getAttr(mvgAttr):
            continue
        relatives = cmds.listRelatives(mesh.name(),
                                       ad=True,
                                       ap=True,
                                       type="transform")
        for r in relatives:
            mvgMeshes.append(r)
    return mvgMeshes
예제 #48
0
def SK_IKFK_ResetValue(obj):
    attrs = [
        'roll', 'toeLift', 'toeStraight', 'raiseToe', 'swivelToe',
        'raiseToeTip', 'swivelToeTip', 'side', 'swivel', 'raiseBall',
        'swivelBall', 'raiseHeel', 'swivelHee'
    ]
    fillterAttr = [
        attr for attr in attrs if (rig.attributeQuery(attr, node=obj, ex=True))
    ]
    if fillterAttr:
        for attr in fillterAttr:
            if ('toeLift' == attr):
                rig.setAttr(obj + '.' + attr, 30)
            elif ('toeStraight' == attr):
                rig.setAttr(obj + '.' + attr, 60)
            else:
                rig.setAttr(obj + '.' + attr, 0)
예제 #49
0
def getObjectIds():
    shapes = cmds.ls(type='shape', visible=True)
    attr = 'mtoa_objectid'
    objectids = {}
    for s in shapes:
        if cmds.attributeQuery(attr, n=s, ex=True):
            val = cmds.getAttr(s + '.' + attr)
            if not objectids.has_key(val):
                objectids[val] = []
            objectids[val].append(s)

    if objectids:
        for val in objectids:
            print('[%d]:' % val)
            for obj in objectids[val]:
                print('\t%s' % obj)
    return objectids
예제 #50
0
def get_message_attribute_connections(src, attr_name):
    """Returns a list of connection to srcObj message attr

    Args:
        src: Object with message attribute
        attrName:  The name of the message attribute to get connections from

    Usage:
        get_message_attribute_connections("box_fk_ctrl", attr_name="pivot_node")
    """
    try:
        if cmds.attributeQuery(attr_name, exists=True, node=src):
            tgts = cmds.listConnections("%s.%s" % (src, attr_name))
            return tgts
    except RuntimeError:
        LOG.error("Message attr %s cannot be found on %s" % (attr_name, src))
        raise
예제 #51
0
def _ZeroKey(cnt):

    keyableAttr = mc.listAttr(cnt, k=1)
    #recorro los atributos
    for attr in keyableAttr:

        #trato de hacer esto
        try:
            #pregunto cual es el valor default de cada atributo y lo seteo
            mc.setAttr(cnt + "." + attr,
                       mc.attributeQuery(attr, n=cnt, ld=1)[0])
            #coloco un key en esos atributos
            mc.setKeyframe(cnt + "." + attr)

        except:
            #De paso trato de dejar un key en ese atributo
            mc.setKeyframe(cnt + "." + attr)
예제 #52
0
 def _setStrAttr(self, node, name, data):
     """Set string data
     
     Note:
         The data arg should always be supplied as a string, ie. "1,2,3,4".
     
     Args:
         node (str): The target node the attribute should be set on
         name (str): The attribute name
         data (str): The string to be added to the attribute
         
     """
     attrType = "string"
     if cmds.attributeQuery(name, node=node, ex=1):
         cmds.setAttr("{0}.{1}".format(node, name), l=0)
         cmds.setAttr("{0}.{1}".format(node, name), data, type=attrType)
         cmds.setAttr("{0}.{1}".format(node, name), l=1)
예제 #53
0
def createNucleus(prefixName):
    """
    create nucleus
    :param jointList: list(str), joint chain list.
    :return: nucleus
    """

    nucleus = cmds.createNode('nucleus', n=prefixName + '_nucleus_#')
    cmds.connectAttr('time1.outTime', nucleus + '.currentTime', f=1)

    # add nucleus attr
    if not cmds.attributeQuery('nucleus', node=nucleus, exists=1):
        cmds.addAttr(nucleus, longName='nucleus', at='message', multi=1)

    cmds.select(cl=1)

    return nucleus
예제 #54
0
    def addSystem(self, systemType, side, name=None):
        # Adds a new system to the rig for example 'left_arm'.
        # A network node is created as the root for the system and connected via a message attribute to the rig root
        if not name:
            return 'You must provide a unique name for your new system'

        if name in self.systems:
            return '%s system already exists. Please provide a unique name for your new system' % name

        nw = cmds.createNode('network',
                             name='%s_%s_systemMetaRoot' % (self.name, name))
        messageConnect(fromNode=self.root,
                       toNode=nw,
                       fromName='message',
                       toName='metaRoot',
                       category='metaSystem')
        messageConnect(fromNode=nw,
                       toNode=self.root,
                       fromName='message',
                       toName=name,
                       category='metaSystem')

        cmds.addAttr(nw, ln='systemName', dt="string", category='metaSystem')
        cmds.addAttr(nw, ln='systemType', dt="string", category='metaSystem')
        cmds.setAttr('%s.systemName' % nw, name, type="string")
        cmds.setAttr('%s.systemType' % nw, systemType, type="string")

        cmds.addAttr(nw,
                     ln='side',
                     at='enum',
                     enumName='centre:left:right',
                     category='metaSystem')
        sideIndex = ['centre', 'left', 'right'].index(side)
        cmds.setAttr('%s.side' % nw, sideIndex)

        if not cmds.attributeQuery('metaType', node=nw, exists=1):
            cmds.addAttr(nw,
                         ln='metaType',
                         at='enum',
                         enumName='noSnap:fk:ik',
                         category='metaNode')

        self.addUIAttrs(nw)

        self.systems.append(name)
예제 #55
0
def getLocatorCurveMap(control, attribute):
    """function to get all the driven locators for the specific control and attribute"""

    locatorCurveMap = {}

    #check that the attribute is valid
    if not cmds.attributeQuery(attribute, n=control, ex=1):
        cmds.error("no attribute: " + attribute + " exists on the node: " + control)
        return {}

    #get all the output connections from the control + attribute (eg mouth_ctrl.L_smile)
    animCurves = cmds.listConnections(control + "." + attribute, d=1, s=0, scn=True)
    if not animCurves:
        return {}

    #loop all the animation curves and lets walk their connections to get the transform
    for animCurve in animCurves:

        #list the anim
        animCurveOutputs = cmds.listConnections(animCurve + ".output", p=1, d=1, s=0, scn=1)

        #this means there is no output to animation curve - its dangling - we could delete this
        if not animCurveOutputs:
            continue

        #get the node itself because we asked for the plug
        animCurveOutputNode = animCurveOutputs[0].split(".")[0]

        #if its blendWeighted then we need to get its output to the locator
        if cmds.nodeType(animCurveOutputNode) == "blendWeighted":
            blendWeightedOutputConns = cmds.listConnections(animCurveOutputNode + ".output", p=1, d=1, s=0, scn=1)
            if blendWeightedOutputConns:
                locator, attr = blendWeightedOutputConns[0].split(".")
                if not locatorCurveMap.has_key(locator):
                    locatorCurveMap[locator] = {}
                locatorCurveMap[locator][attr] = animCurve

        else: #if its not blendweigthed then its the locator that we already have
            if cmds.nodeType(animCurveOutputNode) == "transform":
                locator, attr = animCurveOutputs[0].split(".")
                if not locatorCurveMap.has_key(locator):
                    locatorCurveMap[locator] = {}
                locatorCurveMap[locator][attr] = animCurve

    return locatorCurveMap
예제 #56
0
def applyToSelection(*args):
    sel = cmds.ls(sl=True, l=True)
    if len(sel) < 1:
        cmds.warning('Nothing is selected.')
    else:
        children = cmds.listRelatives(sel, c=True, fullPath=True)

        offenders = []

        for c in children:
            if cmds.objectType(c) not in pxrLightType:
                offenders.append(cmds.listRelatives(c, p=True)[0])

        if len(offenders) > 0:
            for o in offenders:
                cmds.warning(o + ' is not a Pixar Light.')

        else:
            for c in children:
                for attr in attributeList:
                    checkEnableCommand = 'cmds.' + attr[0] + '(' + "'" + attr[
                        0] + '_' + attr[1] + "'" + ', q=True, en=True)'

                    if eval(checkEnableCommand) == 1:

                        if attr[1] == 'lightColor':
                            getValueCommand = 'cmds.' + attr[
                                0] + '(' + "'" + attr[0] + '_' + attr[
                                    1] + "'" + ', q=True, rgb=True)'
                            cmds.setAttr(c + '.' + attr[1],
                                         eval(getValueCommand)[0],
                                         eval(getValueCommand)[1],
                                         eval(getValueCommand)[2],
                                         type="double3")

                        else:
                            getValueCommand = 'cmds.' + attr[
                                0] + '(' + "'" + attr[0] + '_' + attr[
                                    1] + "'" + ', q=True, v=True)'

                            if cmds.attributeQuery(attr[1],
                                                   node=c,
                                                   exists=True):
                                cmds.setAttr(c + '.' + attr[1],
                                             eval(getValueCommand))
예제 #57
0
    def __init__(self,
                 name='mlKeyValueDraggerContext',
                 minValue=0,
                 maxValue=None,
                 defaultValue=1,
                 title = 'Scale'):

        self.keySel = utl.KeySelection()
        selected = False
        if self.keySel.selectedKeys():
            selected = True
            pass
        elif self.keySel.visibleInGraphEditor():
            self.keySel.setKeyframe()
        elif self.keySel.keyedChannels():
            self.keySel.setKeyframe()
        elif self.keySel.selectedObjects():
            self.keySel.setKeyframe()

        if not self.keySel.initialized:
            return

        utl.Dragger.__init__(self, defaultValue=defaultValue, minValue=minValue, maxValue=maxValue, name=name, title=title)

        self.time = dict()
        self.default = dict()
        self.value = dict()
        self.curves = self.keySel.curves

        for curve in self.curves:
            if selected:
                self.time[curve] = mc.keyframe(curve, query=True, timeChange=True, sl=True)
                self.value[curve] = mc.keyframe(curve, query=True, valueChange=True, sl=True)
            else:
                self.time[curve] = self.keySel.time
                self.value[curve] = mc.keyframe(curve, time=self.keySel.time, query=True, valueChange=True)

            #get the attribute's default value
            node, attr = mc.listConnections('.'.join((curve,'output')), source=False, plugs=True)[0].split('.')
            self.default[curve] = mc.attributeQuery(attr, listDefault=True, node=node)[0]

        self.setTool()
        onscreenInstructions = 'Drag left to scale toward default, and right to go in the opposite direction.'
        self.drawString(onscreenInstructions)
        OpenMaya.MGlobal.displayWarning(onscreenInstructions)
예제 #58
0
def getMeshes(root):
    children = cmds.listRelatives(root, c=True, f=True)
    if children:
        for child in children:
            shapeNode = cmds.listRelatives(child, c=True, typ='shape')
            if shapeNode:
                if cmds.objectType(shapeNode[0], isType='mesh'):
                    #cmds.parent(child,w=True)
                    mesh = cmds.ls(child, shortNames=True)
                    print mesh
                    listAttr = cmds.attributeQuery('list',
                                                   node='listMeshes',
                                                   listEnum=True)
                    newListAttr = listAttr[0] + ':' + str(mesh[0])
                    cmds.addAttr('listMeshes.list',
                                 edit=True,
                                 enumName=newListAttr)
            getMeshes(child)
예제 #59
0
    def verifySubdivCommonAttributes(self, mesh):
        self.assertTrue(cmds.objExists(mesh))

        schema = mayaUsdLib.Adaptor(mesh).GetSchema(UsdGeom.Mesh)
        subdivisionScheme = \
                schema.GetAttribute(UsdGeom.Tokens.subdivisionScheme).Get()
        self.assertIsNone(subdivisionScheme)

        faceVaryingLinearInterpolation = schema.GetAttribute(
                UsdGeom.Tokens.faceVaryingLinearInterpolation).Get()
        self.assertEqual(faceVaryingLinearInterpolation, UsdGeom.Tokens.all)

        interpolateBoundary = schema.GetAttribute(
                UsdGeom.Tokens.interpolateBoundary).Get()
        self.assertEqual(interpolateBoundary, UsdGeom.Tokens.edgeOnly)

        self.assertFalse(
                cmds.attributeQuery("USD_EmitNormals", node=mesh, exists=True))
예제 #60
0
def addAttribute(objects=[], longName='', niceName='', lock=False, **kwargs):
    #For each object
    for obj in objects:
        #For each attribute
        for x in range(0, len(longName)):
            #See if a niceName was defined
            attrNice = '' if not niceName else niceName[x]
            #If the attribute does not exists
            if not cmds.attributeQuery(longName[x], node=obj, exists=True):
                #Add the attribute
                cmds.addAttr(obj,
                             longName=longName[x],
                             niceName=attrNice,
                             **kwargs)
                #If lock was set to True
                cmds.setAttr((obj + '.' +
                              longName[x]), lock=1) if lock else cmds.setAttr(
                                  (obj + '.' + longName[x]), lock=0)