Beispiel #1
0
 def doAlias(self,arg):
     """ 
     Set the alias of an attribute
     
     Keyword arguments:
     arg(string) -- name you want to use as an alias
     """     
     assert type(arg) is str or unicode,"Must pass string argument into doAlias"                
     if arg:
         try:
             if arg != self.nameAlias:
                 if mc.aliasAttr(arg,self.nameCombined):
                     self.nameAlias = arg
             else:
                 guiFactory.report("'%s.%s' already has that alias!"%(self.obj.nameShort,self.attr,arg))
                 
         except:
             guiFactory.warning("'%s.%s' failed to set alias of '%s'!"%(self.obj.nameShort,self.attr,arg))
                 
     else:
         if self.nameAlias:
             self.attr = self.nameLong                
             mc.aliasAttr(self.nameCombined,remove=True)
             self.nameAlias = False
             self.updateData()
Beispiel #2
0
def addPose(tangentBlend, baseGeo='', offsetGeo='', poseName=''):
    """
    @param tangentBlend:
    @param baseGeo:
    @param offsetGeo:
    @param poseName:
    """
    # Define suffix tags
    tangentBlend_baseTag = '_poseBase'
    tangentBlend_offsetTag = '_poseOffset'

    # Get connected geometry
    geo = findAffectedGeometry(tangentBlend)

    # Check pose geometry
    if not baseGeo: baseGeo = duplicateGeo(geo, geo + tangentBlend_baseTag)
    if not offsetGeo: baseGeo = duplicateGeo(geo, geo + tangentBlend_offsetTag)

    # Connect to deformer
    poseIndex = connectPose(baseGeo, offsetGeo, tangentBlend)

    # Alias pose name and set keyable
    if poseName:
        cmds.aliasAttr(poseName, tangentBlend + '.pose[' + str(poseIndex) + '].poseWeight')
        cmds.setAttr(tangentBlend + '.pose[' + str(poseIndex) + '].poseWeight', cb=True)
        cmds.setAttr(tangentBlend + '.pose[' + str(poseIndex) + '].poseWeight', k=True)

    return [baseGeo, offsetGeo]
Beispiel #3
0
	def add(self,objectList):
		'''
		Adds the channel state attr to all specified objects
		@param objectList: List of objects to add flags to
		@type objectList: list
		'''
		# Add Channel State Attrs
		for obj in objectList:
			
			# Check obj
			if not mc.objExists(obj):
				raise Exception('Object "'+obj+'" does not exist!')
			if not glTools.utils.transform.isTransform(obj):
				raise Exception('Object "'+obj+'" is not a valid transform!')
			if mc.objExists(obj+'.channelState'):
				print ('Object "'+obj+'" already has a "channelState" attribute! Skipping...')
			
			# Add channelState attr
			#mc.addAttr(obj,ln='channelState',at='enum',en=':Keyable:NonKeyable:Locked:',m=1,dv=-1)
			mc.addAttr(obj,ln='channelState',at='enum',en=':Keyable:NonKeyable:Locked:',m=1)
			
			# Set channelState flag values
			for i in range(len(self.channel)):
				if mc.getAttr(obj+'.'+self.channel[i],l=1):
					# Set Locked State
					mc.setAttr(obj+'.channelState['+str(i)+']',2)
				elif not mc.getAttr(obj+'.'+self.channel[i],k=1):
					# Set NonKeyable State
					mc.setAttr(obj+'.channelState['+str(i)+']',1)
				else:
					# Set Keyable State
					mc.setAttr(obj+'.channelState['+str(i)+']',0)
				# Alias Attribute
				mc.aliasAttr(self.channel[i]+'_state',obj+'.channelState['+str(i)+']')
Beispiel #4
0
def _disconnectAndRemoveAttr(attr, remove=False):
	"""Disconnects inputs and outputs from the given attribute."""
	
	sel = cmds.ls(sl=True)
	cmds.select(cl=True)
	
	# unlock if needed
	cmds.setAttr(attr, l=False)
	
	# if any connection, disconnect
	srcAttrs = cmds.listConnections(attr, d=False, p=True) or []
	destAttrs = cmds.listConnections(attr, s=False, p=True) or []
	for srcAttr in srcAttrs:
		cmds.disconnectAttr(srcAttr, attr)
	
	for destAttr in destAttrs:
		cmds.disconnectAttr(attr, destAttr)
	
	# remove element
	if remove:
		cmds.removeMultiInstance(attr)
		
		# remove alias
		if cmds.aliasAttr(attr, q=True):
			cmds.aliasAttr(attr, rm=True)
	
	cmds.select(sel or None)
Beispiel #5
0
def setDefaultAttrState(objList,attrList,valueList=[]):
	'''
	Set default attribute state values for a specified list of object attributes.
	@param objList: List of objects to store default attribute state values for.
	@type objList: list
	@param attrList: List of attributes to store default attribute state values for.
	@type attrList: list
	@param valueList: List of attributes values to assign to the default attribute states. If empty, use current object attribute values.
	@type valueList: list
	'''
	# Check Object List
	if not objList: return
	if not attrList: return
	if len(attrList) != len(valueList):
		print ('Attribute and value list mis-match! Recording existing attribute values.')
		valueList = []
	
	# Define defaultAttrState attribute name
	defAttr = 'defaultAttrState'
	aliasSuffix = 'defaultState'
	
	# For each object in list
	for obj in objList:
		
		# Check Object
		if not mc.objExists(obj):
			raise Exception('Object "'+obj+'" does not exist!')
		if not mc.attributeQuery(defAttr,n=obj,ex=True):
			addDefaultAttrState([obj])
		
		# For each attribute in list
		for i in range(len(attrList)):
			
			# Get current attribute
			attr = attrList[i]
			attrAlias = attr+'_'+aliasSuffix
			
			# Check attribute
			if not mc.attributeQuery(attr,n=obj,ex=True):
				raise Exception('Object "'+obj+'" has no attribute "'+attr+'"!')
			
			# Get attribute value
			if valueList: value = valueList[i]
			else: value = mc.getAttr(obj+'.'+attr)
			
			# Add default attribute state
			if not mc.attributeQuery(attrAlias,n=obj,ex=True):
				try: index = mc.getAttr(obj+'.'+defAttr,s=True)
				except: print('Error getting multi length from "'+obj+'.'+defAttr+'"')
				mc.setAttr(obj+'.'+defAttr+'['+str(index)+']',0)
				try: mc.aliasAttr(attrAlias,obj+'.'+defAttr+'['+str(index)+']')
				except: print('Error setting attribute alias ("'+attrAlias+'") for node attr "'+obj+'.'+defAttr+'['+str(index)+']"')
			
			# Set default attribute state
			try: mc.setAttr(obj+'.'+attrAlias,value)
			except: print('Unable to set default attr state ("'+attrAlias+'") for object "'+obj+'" to value ('+str(value)+')!')
Beispiel #6
0
	def init_module_trans(self,root_pos):

		ctrl_grp_file = os.environ["mlrig_tool"]+"/controlobjects/blueprint/controlGroup_control.ma"
		cmds.file(ctrl_grp_file, i=True)

		self.module_trans = cmds.rename("controlGroup_control", self.module_namespace+":module_transform")

		cmds.xform(self.module_trans, worldSpace=True, absolute=True, translation=root_pos)

		# mirroring method
		if self.mirrored:

			duplicate_transform = cmds.duplicate(self.original_module+":module_transform", parentOnly=True, name="TEMP_TRANSFORM")[0]
			empty_group = cmds.group(empty=True)
			cmds.parent(duplicate_transform, empty_group, absolute=True)

			scale_attr = ".scaleX"

			if self.mirror_plane == "XZ":

				scale_attr = ".scaleY"

			elif self.mirror_plane == "XY":

				scale_attr = ".scaleZ"

			cmds.setAttr(empty_group+scale_attr, -1)

			parent_constraint = cmds.parentConstraint(duplicate_transform, self.module_trans, maintainOffset=False)
			
			cmds.delete(parent_constraint)
			cmds.delete(empty_group)

			temp_locator = cmds.spaceLocator()[0]
			scale_constraint = cmds.scaleConstraint(self.original_module+":module_transform", temp_locator, maintainOffset=False)[0]

			scale = cmds.getAttr(temp_locator+".scaleX")
			cmds.delete([temp_locator, scale_constraint])

			cmds.xform(self.module_trans, objectSpace=True, scale=[scale, scale, scale])

		utils.add_node_to_container(self.container_name, self.module_trans, ihb=True)

		# Setup global scaling 

		cmds.connectAttr(self.module_trans+".scaleY", self.module_trans+".scaleX")
		cmds.connectAttr(self.module_trans+".scaleY", self.module_trans+".scaleZ")

		cmds.aliasAttr("globalScale", self.module_trans+".scaleY")

		cmds.container(self.container_name, edit=True, publishAndBind=[self.module_trans+".translate", "moduleTransform_T"])
		cmds.container(self.container_name, edit=True, publishAndBind=[self.module_trans+".rotate", "moduleTransform_R"])
		cmds.container(self.container_name, edit=True, publishAndBind=[self.module_trans+".globalScale", "moduleTransform_globalScale"])
	def createTemporaryGroupRepresentation(self):
		controlGrpFile = os.environ['RIGGING_TOOL_ROOT'] + '/ControlObjects/Blueprint/controlGroup_control.ma'
		cmds.file(controlGrpFile, i=True)
		
		self.tempGroupTransform = cmds.rename('controlGroup_control', 'Group_tempGroupTransform__')
		
		cmds.connectAttr((self.tempGroupTransform + '.scaleY'),(self.tempGroupTransform + '.scaleX'))
		cmds.connectAttr((self.tempGroupTransform + '.scaleY'),(self.tempGroupTransform + '.scaleZ'))
		
		for attr in ['scaleX', 'scaleZ','visibility']:
			cmds.setAttr((self.tempGroupTransform + '.' + attr), l=True, k=False)
			
		cmds.aliasAttr('globalScale', (self.tempGroupTransform + '.scaleY'))
Beispiel #8
0
 def createTemporaryGroupRepresentation(self):
     #063
     # Import a new transform
     controlGrpFile = os.environ["GEPPETTO"] + "/ControlObjects/Blueprint/controlGroup_control.ma"
     cmds.file(controlGrpFile, i=True)
     # rename the transform
     self.tempGroupTransform = cmds.rename("controlGroup_control", "Group__tempGroupTransform__")
     # Hook all scale attributes to scaleY
     cmds.connectAttr(self.tempGroupTransform+".scaleY", self.tempGroupTransform+".scaleX")
     cmds.connectAttr(self.tempGroupTransform+".scaleY", self.tempGroupTransform+".scaleZ")
     # Lock unused attributes
     for attr in ["scaleX", "scaleZ", "visibility"]:
         cmds.setAttr(self.tempGroupTransform+"."+attr, l=True, k=False)
         
     cmds.aliasAttr("globalScale", self.tempGroupTransform+".scaleY")
	def rename( self, oldName, newName ):
		'''will rename a blend shape target - if the target doesn't exist, the method does nothing...'''
		names = self.targets
		aliasList = cmd.aliasAttr(self.name,query=True)
		if oldName in names:
			idx = aliasList.index(oldName)
			aliasList[idx] = newName
			for n in range(1,len(aliasList),2): aliasList[n] = self.name +'.'+ aliasList[n]

			#now remove all the alias'
			for name in names: cmd.aliasAttr(self.name +'.'+ name,remove=True)

			#finally rebuild the alias'
			cmdStr = 'aliasAttr ' + ' '.join(aliasList) +';'
			maya.mel.eval(cmdStr)
	def create_temp_grp_representation(self):

		control_group_file = os.environ["mlrig_tool"]+"/controlobjects/blueprint/controlGroup_control.ma"
		cmds.file(control_group_file, i=True)

		self.temp_group_transform = cmds.rename("controlGroup_control", "Group__tempGroupTransform__")

		cmds.connectAttr(self.temp_group_transform+".scaleY", self.temp_group_transform+".scaleX")
		cmds.connectAttr(self.temp_group_transform+".scaleY", self.temp_group_transform+".scaleZ")

		for attr in ["scaleX", "scaleZ", "visibility"]:

			cmds.setAttr(self.temp_group_transform+"."+attr, keyable=False, lock=True)

		cmds.aliasAttr("globalScale", self.temp_group_transform+".scaleY")
Beispiel #11
0
    def loadModuleControl(self, rootJoint):

        path = environ.ControlObjectsPath + "module_control.ma"
        cmds.file(path, i = True, ignoreVersion = True,  renameAll=True, mergeNamespacesOnClash=True, namespace=':', options='v=0;')

        self.moduleControl = cmds.rename("module_control", self.moduleName + ":module_control")

        cmds.xform(self.moduleControl, ws = True, translation = cmds.xform(rootJoint, q = True, ws = True, a = True, translation = True) )

        cmds.connectAttr(self.moduleControl + '.scaleY', self.moduleControl + '.scaleX')
        cmds.connectAttr(self.moduleControl + '.scaleY', self.moduleControl + '.scaleZ')

        cmds.aliasAttr('globalScale', self.moduleControl + '.scaleY')

        return
Beispiel #12
0
def getTargetIndex(blendShape, target):
    """
    Get the target index of the specified blendShape and target name
    @param blendShape: Name of blendShape to get target index for
    @type blendShape: str
    @param target: BlendShape target to get the index for
    @type target: str
    """
    # Check blendShape
    if not isBlendShape(blendShape):
        raise Exception('Object "' + blendShape + '" is not a valid blendShape node!')

    # Check target
    if not cmds.objExists(blendShape + '.' + target):
        raise Exception('Blendshape "' + blendShape + '" has no target "' + target + '"!')

    # Get attribute alias
    aliasList = cmds.aliasAttr(blendShape, q=True)
    aliasIndex = aliasList.index(target)
    aliasAttr = aliasList[aliasIndex + 1]

    # Get index
    targetIndex = int(aliasAttr.split('[')[-1].split(']')[0])

    # Return result
    return targetIndex
Beispiel #13
0
def connectInbetween(
						blendShapeObject = '' ,
						blendShapeNode = '' ,
						inbetweenBlendShape = '' ,
						targetBlendShapeName = '' ,
						weightValue = ''
					) :
	
	# Add inbetween blend shape.

	aliasAttrList = mc.aliasAttr( blendShapeNode , q=True )

	for each in aliasAttrList :

		if each == targetBlendShapeName :

			idx = aliasAttrList.index( each )
			wStr = str( aliasAttrList[ idx+1 ] )
			wIdx = re.findall( r'\d+' , wStr )[0]

			cmd = 'blendShape -e  -ib -t %s %s %s %s %s;' % (
																blendShapeObject ,
																wIdx ,
																inbetweenBlendShape ,
																weightValue ,
																blendShapeNode
															)
			
			mm.eval( cmd )
    def _buildPoseDict(self, nodes):
        """
        Build the internal poseDict up from the given nodes. This is the
        core of the Pose System
        """
        if self.metaPose:
            getMetaDict = self.metaRig.getNodeConnectionMetaDataMap  # optimisation

        for i, node in enumerate(nodes):
            key = r9Core.nodeNameStrip(node)
            self.poseDict[key] = {}
            self.poseDict[key]["ID"] = i  # selection order index
            self.poseDict[key]["longName"] = node  # longNode name

            if self.metaPose:
                self.poseDict[key]["metaData"] = getMetaDict(node)  # metaSystem the node is wired too

            channels = r9Anim.getSettableChannels(node, incStatics=True)
            if channels:
                self.poseDict[key]["attrs"] = {}
                for attr in channels:
                    if attr in self.skipAttrs:
                        log.debug("Skipping attr as requested : %s" % attr)
                        continue
                    try:
                        if (
                            cmds.getAttr("%s.%s" % (node, attr), type=True) == "TdataCompound"
                        ):  # blendShape weights support
                            attrs = cmds.aliasAttr(node, q=True)[::2]  # extract the target channels from the multi
                            for attr in attrs:
                                self.poseDict[key]["attrs"][attr] = cmds.getAttr("%s.%s" % (node, attr))
                        else:
                            self.poseDict[key]["attrs"][attr] = cmds.getAttr("%s.%s" % (node, attr))
                    except:
                        log.debug("%s : attr is invalid in this instance" % attr)
Beispiel #15
0
def getObjAttrNames( obj, attrNamesToSkip=() ):

	#grab attributes
	objAttrs = cmd.listAttr( obj, keyable=True, visible=True, scalar=True ) or []

	#also grab alias' - its possible to pass in an alias name, so we need to test against them as well
	aliass = cmd.aliasAttr( obj, q=True ) or []

	#because the aliasAttr cmd returns a list with the alias, attr pairs in a flat list, we need to iterate over the list, skipping every second entry
	itAliass = iter( aliass )
	for attr in itAliass:
		objAttrs.append( attr )
		itAliass.next()

	filteredAttrs = []
	for attr in objAttrs:
		skipAttr = False
		for skipName in attrNamesToSkip:
			if attr == skipName:
				skipAttr = True
			elif attr.startswith( skipName +'[' ) or attr.startswith( skipName +'.' ):
				skipAttr = True

		if skipAttr:
			continue

		filteredAttrs.append( attr )

	return filteredAttrs
Beispiel #16
0
    def _buildPoseDict(self, nodes):
        '''
        Build the internal poseDict up from the given nodes. This is the
        core of the Pose System
        '''
        if self.metaPose:
            getMetaDict=self.metaRig.getNodeConnectionMetaDataMap  # optimisation

        for i,node in enumerate(nodes):
            key=r9Core.nodeNameStrip(node)
            self.poseDict[key]={}
            self.poseDict[key]['ID']=i           # selection order index
            self.poseDict[key]['longName']=node  # longNode name
            
            if self.metaPose:
                self.poseDict[key]['metaData']=getMetaDict(node)  # metaSystem the node is wired too

            channels=r9Anim.getSettableChannels(node,incStatics=True)
            if channels:
                self.poseDict[key]['attrs']={}
                for attr in channels:
                    try:
                        if cmds.getAttr('%s.%s' % (node,attr),type=True)=='TdataCompound':  # blendShape weights support
                            attrs=cmds.aliasAttr(node, q=True)[::2]  # extract the target channels from the multi
                            for attr in attrs:
                                self.poseDict[key]['attrs'][attr]=cmds.getAttr('%s.%s' % (node,attr))
                        else:
                            self.poseDict[key]['attrs'][attr]=cmds.getAttr('%s.%s' % (node,attr))
                    except:
                        log.debug('%s : attr is invalid in this instance' % attr)
	def initialiseModuleTransform(self, rootPos):
		controlGrpFile = os.environ['RIGGING_TOOL_ROOT'] + '/ControlObjects/Blueprint/controlGroup_control.ma'
		cmds.file(controlGrpFile, i=True)
		
		self.moduleTransform = cmds.rename('controlGroup_control', self.moduleNamespace + ':module_transform')
		
		cmds.xform(self.moduleTransform, worldSpace=True, absolute=True, translation=rootPos)
		
		if self.mirrored:
			duplicateTransform = cmds.duplicate(self.originalModule + ':module_transform', parentOnly=True,name='TEMP_TRANSFORM')[0]
			emptyGroup = cmds.group(empty=True)
			cmds.parent(duplicateTransform, emptyGroup, absolute=True)
			
			scaleAttr = '.scaleX'
			if self.mirrorPlane == 'XZ':
				scaleAttr = '.scaleY'
			elif self.mirrorPlane == 'XY':
				scaleAttr = '.scaleZ'
				
			cmds.setAttr((emptyGroup + scaleAttr), -1)
			
			parentConstraint = cmds.parentConstraint(duplicateTransform, self.moduleTransform, maintainOffset=False)
			cmds.delete(parentConstraint)
			cmds.delete(emptyGroup)
			
			tempLocator = cmds.spaceLocator()[0]
			scaleConstraint = cmds.scaleConstraint(self.originalModule + ':module_transform', tempLocator,maintainOffset=False)[0]
			scale = cmds.getAttr(tempLocator + '.scaleX')
			cmds.delete([tempLocator,scaleConstraint])
			
			cmds.xform(self.moduleTransform, objectSpace=True, scale=[scale,scale,scale])
			
			
		
		utils.addNodeToContainer(self.containerName, self.moduleTransform, ihb=True)
		
		#Setup global scaling
		cmds.connectAttr((self.moduleTransform + '.scaleY'),(self.moduleTransform + '.scaleX'))
		cmds.connectAttr((self.moduleTransform + '.scaleY'),(self.moduleTransform + '.scaleZ'))
		
		cmds.aliasAttr('globalScale', (self.moduleTransform + '.scaleY'))
		
		cmds.container(self.containerName, edit=True, publishAndBind=[(self.moduleTransform + '.translate'),'moduleTransform_T'])
		cmds.container(self.containerName, edit=True, publishAndBind=[(self.moduleTransform + '.rotate'),'moduleTransform_R'])
		cmds.container(self.containerName, edit=True, publishAndBind=[(self.moduleTransform + '.globalScale'),'moduleTransform_globalScale'])
    def on_btn_builde_clicked(self, args=None):
        if args==None:return
        geometry   = str(self.LET_Geometry.text())
        blendShape = str(self.LET_BlendShape.text())
        if not mc.objExists(geometry):return
        if not mc.objExists(blendShape):return 
        
        #buildTargents(geometry, blendShape)
        targentList = mc.aliasAttr(blendShape, q=True)
        targentDict = {}
        for i in range(len(targentList)):
            if i % 2 != 0:continue
            targentDict[targentList[i]] = re.search('\d+', targentList[i+1]).group()
        
    
        #===========================================================
        self.progressBar.setMinimum(0)
        self.progressBar.setMaximum(len(targentDict))
        self.progressLabel.setText('0 / %d'%len(targentDict))
        mc.setAttr('%s.en'%blendShape, 0)
        #===========================================================
        #- builde
        v = 0
        for name, index in targentDict.iteritems():
            targent = mc.duplicate(geometry, n=name)[0]
            buildTargent(blendShape, targent, index)
            
            targentShape = mc.listRelatives(targent, s=True, path=True)
            mc.connectAttr('%s.worldMesh[0]'%targentShape[0], '%s.it[0].itg[%s].iti[6000].igt'%(blendShape, index), f=True)
            
            #--------------------------------------------------------------
            v += 1
            self.progressBar.setValue(v)
            self.progressLabel.setText('%d / %d'%(v, len(targentDict)))
            self.progressName.setText(targent)
            #--------------------------------------------------------------

        #- move 
        targents = targentList[::2]
        targents.sort()
        W = mc.getAttr('%s.bbmx'%geometry)[0][0] - mc.getAttr('%s.bbmn'%geometry)[0][0]
        H = mc.getAttr('%s.bbmx'%geometry)[0][1] - mc.getAttr('%s.bbmn'%geometry)[0][1]
        for i, targent in enumerate(targents):
            for attr in ('tx', 'ty', 'tz', 'rx', 'ry', 'rz', 'sx', 'sy', 'sz'):
                mc.setAttr('%s.%s'%(targent, attr), l=False, k=True, cb=True)
        
            mc.move(W*(i % 15), H*(i // 15 + 1), 0, targent, r=True)
        
        #================================================
        self.progressBar.setMinimum(0)
        self.progressBar.setMaximum(1)
        self.progressLabel.setText('0 / 0')
        self.progressName.setText('{$targent}')
        mc.setAttr('%s.en'%blendShape, 1)
Beispiel #19
0
	def getTargetIdx( self, target ):
		'''given a target name this method will return its index in the weight attribute'''
		indicies = []
		aliasList = cmd.aliasAttr(self.name,query=True)
		if aliasList == None:
			raise Exception( "not aliasAttr found on %s"%(self.name,))

		for n in range(0,len(aliasList),2):
			if aliasList[n] == target:
				idx = aliasList[n+1][7:][:-1]
				return int(idx)

		raise AttributeError("target doesn't exist")
Beispiel #20
0
def rename(attr, name):
    """
	Rename specified attribute
	"""
    # Check attribute
    if not mc.objExists(attr):
        raise Exception('Attribute "' + attr + '" does not exist!')

        # Rename (alias) attribute
    result = mc.aliasAttr(name, attr)

    # Return result
    return result
Beispiel #21
0
def renameTarget(blendShape, target, newName):
    """
    Rename the specified blendShape target
    @param blendShape: Name of blendShape to rename target from
    @type blendShape: str
    @param target: BlendShape target to rename
    @type target: str
    @param newName: New name for the blendShape target
    @type newName: str
    """
    # Check blendShape
    if not isBlendShape(blendShape):
        raise Exception('Object "' + blendShape + '" is not a valid blendShape node!')

    # Check target
    if not hasTarget(blendShape, target):
        raise Exception('BlendShape "' + blendShape + '" has no target "' + target + '"!')

    # Rename target attribute
    cmds.aliasAttr(newName, blendShape + '.' + target)

    # Return Result
    return newName
Beispiel #22
0
def _getTargetNames(rbsNode, idx=-1):
    if idx == -1:
        idxList = _getTargetIndices(rbsNode)
        return [_getTargetNames(rbsNode, i) for i in idxList]
    
    alias = cmds.aliasAttr('%s.%s[%d]' % (rbsNode, _rbsAttrs[0], idx), q=True)
    
    if not alias:
        return _unnamed
    
    elif alias.endswith(_nameSfx[0]):
        return alias[:-len(_nameSfx[0])]
    
    return alias
Beispiel #23
0
def addEyeCmd():
	"""Adds new eyelid inputs."""
	
	geo = _getGeoFromUI()
	rbsNode = geo and _getRbs(geo)
	
	prfx = cmds.layoutDialog(t='Add eye', ui=lambda *x: _addEyeDialog(rbsNode))
	if len(prfx) > 1:
		return
	
	# find first available lower lid index
	miList = _getEyeIdxList(rbsNode)
	idx = 0
	while idx in miList or (idx+1) in miList:
		idx += 2
	
	lowerAttr = '%s.it[%d]' % (rbsNode, idx)
	upperAttr = '%s.it[%d]' % (rbsNode, idx+1)
	lowerName = '%s_lower' % prfx
	upperName = '%s_upper' % prfx
	
	# add lower and upper indices
	cmds.getAttr('%s.im' % lowerAttr)
	cmds.getAttr('%s.im' % upperAttr)

	# set the aliases for the inputTarget attributes (lower and upper)
	if cmds.aliasAttr(lowerAttr, q=True) != lowerName:
		_setAlias(lowerAttr, lowerName)
	if cmds.aliasAttr(upperAttr, q=True) != upperName:
		_setAlias(upperAttr, upperName)
	
	# create and connect locators
	_createEyeLocators(rbsNode, idx)
	
	# update tab ui
	_updateUI()
	_selectTab(prfx)
Beispiel #24
0
def getTargetName(blendShape, targetGeo):
    """
    Get blendShape target alias for specified target geometry
    @param blendShape: BlendShape node to get target name from
    @type blendShape: str
    @param targetGeo: BlendShape target geometry to get alia name for
    @type targetGeo: str
    """
    # ==========
    # - Checks -
    # ==========

    # BlendShape
    if not isBlendShape(blendShape):
        raise Exception('Object "' + blendShape + '" is not a valid blendShape node!')

    # Target
    if not cmds.objExists(targetGeo):
        raise Exception('Target geometry "' + targetGeo + '" does not exist!')

    # ===================
    # - Get Target Name -
    # ===================

    # Get Target Shapes
    targetShape = glTools.utils.shape.getShapes(targetGeo, nonIntermediates=True, intermediates=False)
    if not targetShape: targetShape = cmds.ls(cmds.listRelatives(targetGeo, ad=True, pa=True), shapes=True,
                                            noIntermediate=True)
    if not targetShape: raise Exception('No shapes found under target geometry "' + targetGeo + '"!')

    # Find Target Connection
    targetConn = cmds.listConnections(targetShape, sh=True, d=True, s=False, p=False, c=True)
    if not targetConn.count(blendShape):
        raise Exception('Target geometry "' + targetGeo + '" is not connected to blendShape "' + blendShape + '"!')
    targetConnInd = targetConn.index(blendShape)
    targetConnAttr = targetConn[targetConnInd - 1]
    targetConnPlug = cmds.listConnections(targetConnAttr, sh=True, p=True, d=True, s=False)[0]

    # Get Target Index
    targetInd = int(targetConnPlug.split('.')[2].split('[')[1].split(']')[0])
    # Get Target Alias
    targetAlias = cmds.aliasAttr(blendShape + '.weight[' + str(targetInd) + ']', q=True)

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

    return targetAlias
    def on_btn_FixSkinBsStart_clicked(self, clicked=None):
        if clicked == None:return
        openCloseDeformer(self.__baseModel, 0, ('skinCluster'))
        self.duplicateScupModel()


        openCloseDeformer(self.__baseModel, 1, ('skinCluster'))
        bs = mc.blendShape(self.__baseModel, self.__sculpmodel)[0]
        attr = mc.aliasAttr(bs, q=True)[0]
        mc.setAttr(bs + '.' + attr, 1)
        mc.delete(self.__sculpmodel, ch=True)



        openCloseDeformer(self.__baseModel, 0, ('skinCluster'))
        self.dupliacteTempModel()
Beispiel #26
0
def getBlendShapeInfo(blendShape):
    '''
    return blendShape's ID and attributes dict..
    '''
    attribute_dict = {}
    if mc.nodeType(blendShape) != 'blendShape':
        return attribute_dict
    
    infomations =  mc.aliasAttr(blendShape, q=True)
    for i in range(len(infomations)):
        if i % 2 == 1:continue
        bs_id   = infomations[i + 1]
        bs_attr = infomations[i + 0]
        bs_id = int(re.search('\d+', bs_id).group())
        attribute_dict[bs_id] = bs_attr

    return attribute_dict
Beispiel #27
0
	def __getTargetNameandIndicies( self ):
		'''returns a list of the target names on the blendshape.  both the index list and
		the name list are guaranteed to be in the correct order'''
		indicies = []
		aliasList = cmd.aliasAttr(self.name,query=True)
		if aliasList == None: return []
		for n in range(1,len(aliasList),2):
			idx = int(aliasList[n][7:][:-1])
			indicies.append(idx)

		indicies.sort()
		names = [None]*len(indicies)  #build the name array of the correct size
		for n in range(0,len(aliasList),2):
			curNameIdx = int(aliasList[n+1][7:][:-1])
			for i in range(len(indicies)):
				if curNameIdx == indicies[i]:
					names[i] = aliasList[n]

		return names,indicies
Beispiel #28
0
 def LRBlendShapeWeight(self, lipCrv, lipCrvBS):
     cvs = cmds.ls(lipCrv+'.cv[*]', fl =1)
     length = len (cvs)
     
     increment = 1.0/(length-1)
     targets = cmds.aliasAttr( lipCrvBS, q=1)
     tNum = len(targets)   
     
     for t in range(0, tNum, 2):
         if targets[t][0] == 'l' :
             indexL=re.findall('\d+', targets[t+1])
             cmds.setAttr(lipCrvBS + '.inputTarget[0].inputTargetGroup[%s].targetWeights[%s]'%(str(indexL[0]), str(length/2)), .5 ) 
             for i in range(0, length/2):                
                 cmds.setAttr(lipCrvBS + '.inputTarget[0].inputTargetGroup[%s].targetWeights[%s]'%(str(indexL[0]), str(i)), 0 ) 
                 cmds.setAttr(lipCrvBS + '.inputTarget[0].inputTargetGroup[%s].targetWeights[%s]'%(str(indexL[0]), str(length-i-1)), 1 )   
                 
         if targets[t][0] == 'r' :
             indexR=re.findall('\d+', targets[t+1])
             cmds.setAttr(lipCrvBS + '.inputTarget[0].inputTargetGroup[%s].targetWeights[%s]'%(str(indexR[0]), str(length/2)), .5 ) 
             for i in range(0, length/2):                
                 cmds.setAttr(lipCrvBS + '.inputTarget[0].inputTargetGroup[%s].targetWeights[%s]'%(str(indexR[0]), str(i)), 1 ) 
                 cmds.setAttr(lipCrvBS + '.inputTarget[0].inputTargetGroup[%s].targetWeights[%s]'%(str(indexR[0]), str(length-i-1)), 0 )     
Beispiel #29
0
def setTargetWeights(blendShape, target, wt, geometry=''):
    """
    Set per vertex target weights for the specified blendShape target
    @param blendShape: Name of blendShape to set target weights for
    @type blendShape: str
    @param target: Name of blendShape target to set weights for
    @type target: str
    @param wt: Weight value list to apply to the specified blendShape target
    @type wt: list
    @param geometry: Name of blendShape driven geometry to set weights on
    @type geometry: str
    """
    # Check blendShape
    if not isBlendShape(blendShape):
        raise Exception('Object "' + blendShape + '" is not a valid blendShape node!')

    # Check target
    if not cmds.objExists(blendShape + '.' + target):
        raise Exception('blendShape "' + blendShape + '" has no "' + target + '" target attribute!')

    # Check geometry
    if geometry and not cmds.objExists(geometry):
        raise Exception('Object "' + geometry + '" does not exist!')

    # Get target index
    aliasList = cmds.aliasAttr(blendShape, q=True)
    aliasTarget = aliasList[(aliasList.index(target) + 1)]
    targetIndex = aliasTarget.split('[')[-1]
    targetIndex = int(targetIndex.split(']')[0])

    # Get geometry index into blendShape
    geomIndex = 0
    if geometry: geomIndex = glTools.utils.deformer.getGeomIndex(geometry, blendShape)
    # Get number of geometry components
    compCount = glTools.utils.component.getComponentCount(geometry)

    # Set target weights
    cmds.setAttr(
        blendShape + '.it[' + str(geomIndex) + '].itg[' + str(targetIndex) + '].tw[0:' + str(compCount - 1) + ']', *wt)
Beispiel #30
0
def copyPose(fromNode, toNode, flip=False):

    attrs = mc.listAttr(fromNode, keyable=True)
    if not attrs:
        return

    #if attributes are aliased, get the real names for mirroring axis
    aliases = mc.aliasAttr(fromNode, query=True)
    if aliases:
        for alias,real in zip(aliases[::2],aliases[1::2]):
            if alias in attrs:
                attrs.remove(alias)
                attrs.append(real)

    axis = getMirrorAxis(toNode)

    for attr in attrs:
        if attr == 'mirrorAxis':
            continue
        if not mc.attributeQuery(attr, node=toNode, exists=True):
            continue
        fromPlug = '{}.{}'.format(fromNode, attr)
        toPlug = '{}.{}'.format(toNode, attr)
        fromValue = mc.getAttr(fromPlug)
        toValue = mc.getAttr(toPlug)

        if attr in axis:
            fromValue *= -1.0
            toValue *= -1.0

        try:
            utl.setAnimValue(toPlug, fromValue)
        except:pass

        if flip:
            try:
                utl.setAnimValue(fromPlug, toValue)
            except:pass