def assetCheckAndTag(type = '', customTag = False):
	"""
	Look for root level groups that have meshes as children and add a a type flag to it with the type as its value
	@param type: The type of asset, eg PROP, BLD, CHAR
	@type type: String
	"""

	for grp in cmds.ls(assemblies=True, long= True):
		if cmds.ls(grp, dag=True, type="mesh"):
			if '|ROOT_ARCHIVES_DNT_hrc' not in grp and '|CORE_ARCHIVES_hrc' not in grp:
				debug(app = None, method = 'assetCheckAndTag', message = 'grp: %s' % grp, verbose = False)
				if not grp.endswith('_hrc'):
					return False
				if type not in grp:
					raise TankError("ROOT NODE MISSING PREFIX \"%s_\"\nPlease visit http://www.anim83d.com/bbb/dokuwiki/doku.php?id=bubblebathbay:pipeline:pipeline:modelling:namingconventions" % type)
				if '_hrc' in grp and type in grp:
					if cmds.objExists('%s.type' % grp):
						cmds.deleteAttr('%s.type' % grp)
					try:
						cmds.addAttr(grp, ln = 'type', dt = 'string')
					except:
						pass
					if customTag:
						cmds.setAttr('%s.type' % grp, customTag, type = 'string')
					else:
						cmds.setAttr('%s.type' % grp, type.lower(), type = 'string')
				else:
					 raise TankError("This does not appear to be a valid %s asset" % type)
Beispiel #2
0
def _removeMetaClassAttr(mfnnode, className, undoable=True):
    """
    Remove a meta class attribute from a node.
    Does nothing if the attribute does not exist.

    Args:
        mfnnode (MFnDependencyNode): The api MFnDependencyNode of a node
        undoable (bool): When True, the operation will be undoable

    Returns:
        True if the attr was removed or didn't exist,
        False if it couldn't be removed.
    """
    classPlug = _getMetaClassPlug(mfnnode, className)
    if not classPlug:
        return True

    if classPlug.isLocked():
        return False
    else:
        if undoable:
            plugName = _getUniquePlugName(mfnnode, classPlug)
            cmds.deleteAttr(plugName)
        else:
            mfnnode.removeAttribute(classPlug.attribute())
        return True
def assetCheckAndTag(type = '', customTag = False):
    """
    Look for root level groups that have meshes as children and add a a type flag to it with the type as its value
    @param type: The type of asset, eg PROP, BLD, CHAR
    @type type: String
    @param customTag: If you want to use a custom tag that differs from the type name.
    @type customTag: String
    """

    for grp in cmds.ls(assemblies = True, long = True):
        if cmds.ls(grp, dag = True, type = "mesh"):
            if '|ROOT_ARCHIVES_DNT_%s' % configCONST.GROUP_SUFFIX not in grp and '|CORE_ARCHIVES_%s' % configCONST.GROUP_SUFFIX not in grp:
                if not grp.endswith('_%s' % configCONST.GROUP_SUFFIX):
                    return False
                if configCONST.INSIST_PREFIX_IN_ROOT:
                    if type not in grp:
                        raise TankError("ROOT NODE MISSING PREFIX \"%s" % type)
                        return -1
                if '_%s' % configCONST.GROUP_SUFFIX in grp:
                    if cmds.objExists('%s.type' % grp):
                        cmds.deleteAttr('%s.type' % grp)
                    try:
                        cmds.addAttr(grp, ln = 'type', dt = 'string')
                    except:
                        pass
                    if customTag:
                        cmds.setAttr('%s.type' % grp, customTag, type = 'string')
                    else:
                        cmds.setAttr('%s.type' % grp, type.lower(), type = 'string')
                else:
                    raise TankError("This does not appear to be a valid %s asset" % type)
def moveSDK(source=None,
            destination=None,
            curAttrs=[],
            drAttrSearch='',
            drAttrReplace='',
            deleteOldAttrs=False):
    ''' Move the specified set driven key attributes from once source driver
    attr to one target destination driver attr.
    '''

    if not source or not destination:
        source, destination = mc.ls(sl=True)

    if not all((mc.objExists(source), mc.objExists(destination))):
        print('One of the nodes does not exist, '
              'please check: %s, %s' % (source, destination))
        return 1

    if curAttrs:

        if isinstance(curAttrs, str) and curAttrs.strip():
            curAttrs = [curAttrs]

        attrs = [
            mc.attributeQuery(x, node=source, ln=True) for x in curAttrs
            if mc.attributeQuery(x, node=source, ex=True)
        ]
        if not attrs:
            print('Specified attributes %s, do not exist on driver %s .' %
                  (', '.join(attrs), source))
            return 1
    else:
        attrs = mc.listAttr(source, k=True)

    # Get the SDK's and any blendwheighted nodes with SDKs.
    driverNodes, blendWeightedNodes = findSDKNodes((), source, attrs, False)

    # Connect all the old connections from the source to the new attr
    # on the destinationn attribute.
    for nodeList in (driverNodes, blendWeightedNodes):
        for node in nodeList:
            # Create the new driver attr if it does not already exist.
            createDriverAttrFunc(source, destination, node[1].split('[')[0],
                                 drAttrSearch, drAttrReplace)

            mc.connectAttr(
                '%s.%s' %
                (destination, node[1].replace(drAttrSearch, drAttrReplace)),
                '%s.%s' % (node[0], node[3]),
                f=True)

    # If specified, delete the old driver attr.
    if not deleteOldAttrs:
        return
    userDefinedAttrs = mc.listAttr(source, ud=True)
    for attr in attrs:
        if attr in userDefinedAttrs and \
                not mc.listConnections('%s.%s' % (source, attr),
                                       scn=True, d=True, s=True, p=False):
            mc.deleteAttr('%s.%s' % (source, attr))
Beispiel #5
0
def create_point_space(driven, drivers):
    if cmds.attributeQuery("space", node=driven, exists=True):
        cmds.deleteAttr(attribute="space", name=driven)

    if isinstance(drivers, dict):
        names = drivers.keys()
        drivers = drivers.values()
    else:
        names = drivers

    cmds.addAttr(
        driven,
        longName="space",
        shortName="Point_Space",
        attributeType="enum",
        enumName=":".join(names) + ":",
        keyable=True,
    )

    driven_parent = add_parent_group(driven, suffix="ps")
    mult_mat = cmds.createNode("multMatrix")
    decompose_mat = cmds.createNode("decomposeMatrix")
    offset_choice = cmds.createNode("choice")
    driver_choice = cmds.createNode("choice")
    cmds.connectAttr(driven + ".space", offset_choice + ".selector")
    cmds.connectAttr(driven + ".space", driver_choice + ".selector")

    todel = []
    for i, driver in enumerate(drivers):
        cmds.addAttr(driven_parent,
                     longName=driver + "_offset",
                     attributeType="matrix")
        # get the offset between the driven and driver
        mult_mat_offset = cmds.createNode("multMatrix")
        todel.append(mult_mat_offset)
        cmds.connectAttr(driver + ".worldInverseMatrix[0]",
                         mult_mat_offset + ".matrixIn[0]")
        cmds.connectAttr(driven + ".worldMatrix[0]",
                         mult_mat_offset + ".matrixIn[1]")
        offset_mat = cmds.getAttr(mult_mat_offset + ".matrixSum")

        cmds.setAttr(driven_parent + "." + driver + "_offset",
                     offset_mat,
                     type="matrix")
        cmds.connectAttr(
            driven_parent + "." + driver + "_offset",
            offset_choice + ".input[{}]".format(i),
        )

        cmds.connectAttr(driver + ".worldMatrix[0]",
                         driver_choice + ".input[{}]".format(i))

    cmds.connectAttr(offset_choice + ".output", mult_mat + ".matrixIn[1]")
    cmds.connectAttr(driver_choice + ".output", mult_mat + ".matrixIn[0]")
    cmds.connectAttr(driven_parent + ".worldInverseMatrix[0]",
                     mult_mat + ".matrixIn[2]")
    cmds.connectAttr(mult_mat + ".matrixSum", decompose_mat + ".inputMatrix")

    cmds.connectAttr(decompose_mat + ".outputTranslate", driven + ".translate")
    cmds.delete(todel)
def sculpt(geo, vis=1, shade=1, editMode=0):

    if editMode == 1:
        drv = cmds.channelBox('mainChannelBox', q=1, sma=1)[0]

    # Establish short name
    if ':' in geo:
        name = geo.split(':')[1]
        name = '{}_scu'.format(name)
    else:
        name = '{}_scu'.format(geo)

    # Duplicate and memorize geo name
    scu = cmds.duplicate(geo, n=name)[0]
    cmds.addAttr(scu, dt='string', ln='origGeo')
    cmds.setAttr('{}.origGeo'.format(scu), geo, type='string')
    if editMode == 1:
        cmds.addAttr(scu, dt='string', ln='editDriver')
        cmds.setAttr('{}.editDriver'.format(scu), drv, type='string')

    if shade == 1:
        # Assign new shader
        if not cmds.objExists('sculptimate_SHD'):
            shd = cmds.shadingNode('blinn', n='sculptimate_SHD', asShader=1)
            cmds.setAttr('sculptimate_SHD.color',
                         .2549,
                         .8348,
                         1,
                         type='double3')
            cmds.setAttr('sculptimate_SHD.specularColor',
                         .254438,
                         .254438,
                         .254438,
                         type='double3')
            cmds.setAttr('sculptimate_SHD.eccentricity', .556157)
        else:
            shd = 'sculptimate_SHD'
        cmds.select(scu)
        cmds.hyperShade(assign=shd)

    if vis == 1:
        # Hide original geo
        shps = cmds.listRelatives(geo, s=1)
        for s in shps:
            try:
                cmds.setAttr('{}.v'.format(s), 0)
            except:
                pass

    # Remove sculpt attrs on sculpt
    attrs = cmds.listAttr(scu, k=1)
    for a in attrs:
        if a.endswith('_p2p') or a.endswith('_scu') or (
                a.startswith('p2pLv') and a.endswith('Envelope')):
            cmds.setAttr('{}.{}'.format(scu, a), l=0)
            cmds.deleteAttr('{}.{}'.format(scu, a))

    sys.stdout.write("Sculpting '{}'.".format(scu))

    return scu
Beispiel #7
0
def group(joint,indexStr='A'):
	'''
	Create a joint buffer transform (joint).
	@param joint: Joint to create buffer group for
	@type joint: str
	@param indexStr: Name index string
	@type indexStr: str
	'''
	# Check joint
	if not mc.objExists(joint):
		raise Exception('Joint "'+joint+'" does not exist!')
	
	# Get name prefix
	prefix = glTools.utils.stringUtils.stripSuffix(joint)
	
	# Create joint group
	grp = mc.duplicate(joint,po=True,n=prefix+'Con'+indexStr+'_jnt')[0]
	mc.parent(joint,grp)
	
	# Delete user attrs
	udAttrList = mc.listAttr(grp,ud=True)
	if udAttrList:
		for attr in udAttrList: mc.deleteAttr(grp+'.'+attr)
	
	# Set display overrides
	mc.setAttr(joint+'.overrideEnabled',1)
	mc.setAttr(joint+'.overrideLevelOfDetail',0)
	mc.setAttr(grp+'.overrideEnabled',1)
	mc.setAttr(grp+'.overrideLevelOfDetail',0)
	
	# Return result
	return grp
Beispiel #8
0
def deleteUserAttrs(obj, attrList=[]):
    '''
	Delete user defined attrs from a specified object
	@param obj: The source objects to copy the attributes from 
	@type obj: str
	@param attrList: A list of attributes to delete. If empty, defaults to all. 
	@type attrList: list
	'''
    # Check object
    if not mc.objExists(obj):
        raise Exception('Object "' + obj + '" does not exist!!')

    # Get attribute list
    if not attrList: attrList = mc.listAttr(obj, ud=True)
    if not attrList: attrList = []

    # Delete attributes
    for attr in attrList:
        try:
            mc.setAttr(obj + '.' + attr, l=False)
            mc.deleteAttr(obj, at=attr)
        except:
            print('Problem removing attribute "' + obj + '.' + attr +
                  '". Continuing onto next arttribute.')

    # Return result
    return attrList
def edo_rewriteRotationValueList(skdbf, rcattr, mv, mr):
    rl = []
    drsk = ''
    drsks = cmds.listConnections(skdbf + '.SKDB', s=1, d=0)
    if drsks:
        drsk = drsks[0]
    else:
        drsk = edo_findoutDriverSkeletonFromSKDB(skdbf)
    if not drsk:
        return False
    if cmds.objExists(rcattr):
        rl = cmds.getAttr(skdbf + '.' + drsk + '__' + mr)[0]
        cmds.deleteAttr(skdbf + '.' + drsk + '__' + mr)
    cmds.addAttr(skdbf, ln=drsk + '__' + mr, at='double', multi=True)
    if rl:
        rl = list(rl)
    if rl:
        if mv in list(rl):
            print 'remove this rotate value form list'
            rl.remove(mv)
    rl.append(mv)
    print 'reset the rotation list to: \n'
    print rl
    i = 0
    for r in rl:
        #cmds.setAttr(skdbf+'.'+drsk+'__'+mr+'[2]',rl[0])
        cmds.setAttr(skdbf + '.' + drsk + '__' + mr + '[' + str(i) + ']',
                     rl[i])
        i = i + 1
Beispiel #10
0
def delmesh(nodename):
    for attr in [nodename+"."+ext for ext in getnames()]:
        try:
            cmds.getAttr(attr)
            cmds.deleteAttr(attr)
        except:
            pass
Beispiel #11
0
    def testAttributeAliases(self):
        """Tests behavior with the purpose/USD_purpose alias."""
        cmds.file(new=True, force=True)
        cmds.group(name="group1", empty=True)

        cmds.addAttr("group1", longName="USD_purpose", dataType="string")
        cmds.setAttr("group1.USD_purpose", "proxy", type="string")
        self.assertEqual(
            mayaUsdLib.Adaptor("group1").GetSchema(UsdGeom.Xform).GetAttribute(
                UsdGeom.Tokens.purpose).Get(), UsdGeom.Tokens.proxy)

        cmds.addAttr("group1", longName="USD_ATTR_purpose", dataType="string")
        cmds.setAttr("group1.USD_ATTR_purpose", "render", type="string")
        self.assertEqual(
            mayaUsdLib.Adaptor("group1").GetSchema(UsdGeom.Xform).GetAttribute(
                UsdGeom.Tokens.purpose).Get(), UsdGeom.Tokens.render)

        cmds.deleteAttr("group1.USD_purpose")
        self.assertEqual(
            mayaUsdLib.Adaptor("group1").GetSchema(UsdGeom.Xform).GetAttribute(
                UsdGeom.Tokens.purpose).Get(), UsdGeom.Tokens.render)

        cmds.deleteAttr("group1.USD_ATTR_purpose")
        self.assertIsNone(
            mayaUsdLib.Adaptor("group1").GetSchema(UsdGeom.Xform).GetAttribute(
                UsdGeom.Tokens.purpose).Get())

        mayaUsdLib.Adaptor("group1")\
                    .GetSchema(UsdGeom.Xform)\
                    .CreateAttribute(UsdGeom.Tokens.purpose)
        self.assertTrue(
            cmds.attributeQuery("USD_ATTR_purpose", node="group1",
                                exists=True))
Beispiel #12
0
    def remove(self, delAttr=0):
        """Remove tags
        
        Args:
            delAttr (bool): Defines whether or not to remove the attribute entirely
            
        """
        if self.target:
            if allTags:
                if cmds.attributeQuery(self.tagName, node=self.target, ex=1):
                    cmds.setAttr("{0}.{1}".format(self.target, self.tagName),
                                 l=0)
                    cmds.deleteAttr(self.target, at=self.tagName)

            else:
                data = self._read(self.target, self.tagName)

                data = data.split(",")
                data = [x for x in data if x not in self.tagType]

                dataString = None
                for i in data:
                    if dataString:
                        dataString = "{0},{1}".format(dataString, i)
                    else:
                        dataString = i
                if not dataString:
                    dataString = ""

                self._setStrAttr(self.target, self.tagName, dataString)
        else:
            raise ValueError("No target specified for tagging. Aborting...")
    def _WriteExportedAttributesToNode(nodeName, exportedAttrs):
        """
        Given a Maya node name, this method records the given list of
        ExportedAttribute objects in exportedAttrs in the Maya attribute. the
        passed in list replaces any previous data.

        NOTE: This method will likely only ever be called by the Remove and
        Update methods above since multiple nodes may be selected and only the
        common attributes between them will be displayed.
        """
        jsonDict = {}
        for exportedAttr in exportedAttrs:
            jsonDict.update(exportedAttr.GetJsonDict())

        exportAttrExists = cmds.attributeQuery(EXPORTED_ATTRS_MAYA_ATTR_NAME,
                                               node=nodeName,
                                               exists=True)

        if not jsonDict:
            if exportAttrExists:
                # The export attribute exists but we'd be emptying it, so just
                # remove the attribute instead.
                cmds.deleteAttr('%s.%s' %
                                (nodeName, EXPORTED_ATTRS_MAYA_ATTR_NAME))
            return

        if not exportAttrExists:
            cmds.addAttr(nodeName,
                         ln=EXPORTED_ATTRS_MAYA_ATTR_NAME,
                         dt='string')

        jsonString = json.dumps(jsonDict)
        cmds.setAttr('%s.%s' % (nodeName, EXPORTED_ATTRS_MAYA_ATTR_NAME),
                     jsonString,
                     type='string')
Beispiel #14
0
def shiftAttr(attrs, node, mode='up', amnt=1):
    if cmds.objExists(node):
        udAttr = cmds.listAttr(node, ud=1)
        if not type(attrs) == type(list()):
            attrs = [attrs]
        for attr in attrs:
            if attr not in udAttr:
                cmds.warning('Attribute is static and connot be shifted.')
                return False
            attrL = cmds.listAttr(node, ud=1, l=1)
        if attrL:
            for each in attrL:
                cmds.setAttr('{}.{}'.format(node, each), lock=0)
        for x in range(amnt):
            udAttr = cmds.listAttr(node, ud=1)
            if mode == 'down':
                if len(attrs) > 1:
                    attrs.reverse()
                for each in attrs:
                    attrPos = udAttr.index(each)
                    cmds.undo(cmds.deleteAttr(node, at=udAttr[attrPos]))
                    for i in range(attrPos + 2, len(udAttr), 1):
                        cmds.undo(cmds.deleteAttr(node, at=udAttr[i]))
            elif mode == 'up':
                for each in attrs:
                    attrPos = udAttr.index(each)
                    if udAttr[attrPos - 1]:
                        cmds.undo(cmds.deleteAttr(node,
                                                  at=udAttr[attrPos - 1]))
                    for i in range(attrPos + 1, len(udAttr), 1):
                        cmds.undo(cmds.deleteAttr(node, at=udAttr[i]))

        if attrL:
            for each in attrL:
                cmds.setAttr('{}.{}'.format(node, each), lock=1)
Beispiel #15
0
	def __updateSub(self):
		cmds.setAttr('%s.sSub' %self.__sName, lock = False)
		if self.__bSub:
			lChilds = cmds.listRelatives(self.__sSub, c = True, type = 'transform')
			print lChilds
			if lChilds:
				cmds.parent(lChilds, self.__sName)
			cmds.delete(self.__sSub)
			cmds.setAttr('%s.sSub' %self.__sName, '', type = 'string', lock = True)
			cmds.deleteAttr('%s.subCtrlVis' %self.__sName)
		else:
			cmds.addAttr(self.__sName, ln = 'subCtrlVis', at = 'long', keyable = False, min = 0, max = 1, dv = 0)
			cmds.setAttr('%s.subCtrlVis' %self.__sName, channelBox = True)
			sSub = naming.oName(sType = 'ctrl', sSide = self.__sSide, sPart = '%sSub' %self.__sPart, iIndex = self.__iIndex).sName
			sSub = transforms.createTransformNode(sSub, sParent = self.__sName)
			transforms.transformSnap([self.__sName], [sSub])
			attributes.connectAttrs(['%s.subCtrlVis' %self.__sName], ['%s.v' %sSub], bForce = True)
			for sAttr in ['tx', 'ty', 'tz', 'rx', 'ry', 'rz', 'sx', 'sy', 'sz', 'v']:
				if cmds.getAttr('%s.%s' %(self.__sName, sAttr), lock = True):
					cmds.setAttr('%s.%s' %(sSub, sAttr), keyable = False, lock = True, channelBox = False)
			dCtrlShapeInfo = getCtrlShapeInfo(self.__sName)
			addCtrlShape([sSub], '%sShape' %sSub, bVis = True, dCtrlShapeInfo = dCtrlShapeInfo[self.__sName])
			scaleCtrlShape(sSub, fScale = 0.9)
			cmds.setAttr('%s.sSub' %self.__sName, sSub, type = 'string', lock = True)
		cmds.select(self.__sName)
		self.__getCtrlInfo(self.__sName)
Beispiel #16
0
	def updateOrigNamesFormat(self,objectList=[]):
		'''
		Update a combined meshes origNames attribute to the newest format.
		@param objectList: list of mesh objects to update origNames attribute on.
		@type objectList: list
		'''
		# Confirm list
		if type(objectList) == str:
			objectList = [objectList]
		
		# Iterate through object list
		for obj in objectList:
			
			# Check origNames attribute
			if not mc.objExists(obj+'.origNames'):
				raise Exception('Object '+obj+' does not have a "origNames" attribute!')
			if mc.addAttr(obj+'.origNames',q=True,multi=True):
				print(obj+'.origNames is already in the correct format.')
				continue
			
			# Extract original names list from old format
			origNamesList = []
			index = 0
			while True:
				if mc.objExists(obj+'.origNames.origNames_'+str(index)):
					origNamesList.append(mc.getAttr(obj+'.origNames.origNames_'+str(index)))
					index+=1
				else: break
			
			# Re-create the origNames attribute in the new format
			mc.deleteAttr(obj+'.origNames')
			mc.addAttr(obj,ln='origNames',dt='string',multi=True)
			for i in range(len(origNamesList)):
				mc.setAttr( obj+'.origNames['+str(i)+']', origNamesList[i], type='string')
	def utils_dictionaryToMayaObjInfo( self ,  obj  , dictionary ):
		#INIT		
		dictValues = {}		
		if not( mc.objExists(obj) )and not( mc.nodeType(obj) == 'transform' ):
			return 0
		#DELETE
		objAttrs = mc.listAttr(obj)

		if( mc.objExists(obj+'.'+self.utilsClasseInfoAttr) ):
			mc.deleteAttr(obj+'.'+self.utilsClasseInfoAttr)			

		#WRITE
		dictKeys = dictionary.keys()
		dictStr  = '{'
		for i in range( 0 , len(dictKeys) ):

			value = dictionary[dictKeys[i]]

			if( type(value) == types.InstanceType):
				value = str(value)
			if( type(value) == types.StringType ) or ( type(value) == types.UnicodeType):
				value = ( '\'' + value + '\'' ) 

			dictStr += '\'' +dictKeys[i] + '\':' + str(value)
			if not( len(dictKeys) - 1 <= i ):
				dictStr += ','

		dictStr += '}'

		mc.addAttr( obj , longName=self.utilsClasseInfoAttr, dataType='string' )
		mc.setAttr( obj + '.' + self.utilsClasseInfoAttr , dictStr , type = 'string' )

		return 1  		
Beispiel #18
0
def deleteUserAttrs(obj,attrList=[]):
	'''
	Delete user defined attrs from a specified object
	@param obj: The source objects to copy the attributes from 
	@type obj: str
	@param attrList: A list of attributes to delete. If empty, defaults to all. 
	@type attrList: list
	'''
	# Check object
	if not mc.objExists(obj):
		raise Exception('Object "'+obj+'" does not exist!!')
	
	# Get attribute list
	if not attrList: attrList = mc.listAttr(obj,ud=True)
	if not attrList: attrList = []
	
	# Delete attributes
	for attr in attrList:
		try:
			mc.setAttr(obj+'.'+attr,l=False)
			mc.deleteAttr(obj,at=attr)
		except:
			print('Problem removing attribute "'+obj+'.'+attr+'". Continuing onto next arttribute.')
	
	# Return result
	return attrList
Beispiel #19
0
def zeroOut(transformList=[], offset=False):
    """ Create a group over the transform, parent the transform in it and set zero all transformations of the transform node.
        If don't have a transformList given, try to get the current selection.
        If want to create with offset, it'll be a, offset group between zeroGrp and transform.
        Return a list of names of the zeroOut groups.
    """
    zeroList = []
    if not transformList:
        transformList = cmds.ls(selection=True)
    if transformList:
        for transform in transformList:
            zeroGrp = cmds.duplicate(transform,
                                     name=transform + '_Zero_Grp')[0]
            zeroUserAttrList = cmds.listAttr(zeroGrp, userDefined=True)
            if zeroUserAttrList:
                for zUserAttr in zeroUserAttrList:
                    try:
                        cmds.deleteAttr(zeroGrp + "." + zUserAttr)
                    except:
                        pass
            allChildrenList = cmds.listRelatives(zeroGrp,
                                                 allDescendents=True,
                                                 children=True,
                                                 fullPath=True)
            if allChildrenList:
                cmds.delete(allChildrenList)
            if offset:
                offsetGrp = cmds.duplicate(zeroGrp,
                                           name=transform + '_Offset_Grp')[0]
                cmds.parent(transform, offsetGrp, absolute=True)
                cmds.parent(offsetGrp, zeroGrp, absolute=True)
            else:
                cmds.parent(transform, zeroGrp, absolute=True)
            zeroList.append(zeroGrp)
    return zeroList
def _deleteAllBakeAttrsOnLocators():
	boatHookList = getBoatHooks()
	if boatHookList:
		for eachHook in boatHookList:
			if cmds.objExists('%s.bakedBoat' % eachHook):
				cmds.deleteAttr('%s.bakedBoat' % eachHook)
				debug(None, method  = 'performHookBoatsToOcean', message = 'deleteAttr("%s.bakedBoat")' % eachHook, verbose = False)
 def deleteColorAttr(self, nodes):
     nodeList = nodes
     # add attribute to selected meshes
     for node in nodeList:
         for i in range(1,100):
             if mc.objExists(node + '.' + self.idColorAttr + str(i)):
                 mc.deleteAttr(node + '.' + self.idColorAttr + str(i))
Beispiel #22
0
    def updateOld(self):
        '''
		Update old style spaces setup to work with new spaces procedures.
		'''
        # Get list of existing spaces nodes
        spacesNodeList = mc.ls('*_spn', r=1, et='transform')
        for spacesNode in spacesNodeList:
            spacesChild = mc.listRelatives(spacesNode,
                                           c=True,
                                           type='transform')[0]

            # Transfer .spaces attribute
            if mc.objExists(spacesChild + '.spaces'):
                enumString = mc.addAttr(spacesChild + '.spaces',
                                        q=True,
                                        en=True)
                mc.addAttr(spacesNode, ln='spaces', at='enum', en=enumString)
                mc.setAttr(spacesNode + '.spaces', k=1)
                mc.deleteAttr(spacesChild + '.spaces')

            # Transfer .nameTag attribute
            if mc.objExists(spacesChild + '.nameTag'):
                nameTagStr = mc.getAttr(spacesChild + '.nameTag')
                mc.addAttr(spacesNode, ln='nameTag', dt='string')
                mc.setAttr(spacesNode + '.nameTag', nameTagStr, type='string')
                mc.deleteAttr(spacesChild + '.nameTag')
Beispiel #23
0
    def setAttr(self, target, intersectList=[], evalOrderList=[]):
        '''
		Store the calculated evaluation order list as a string array attribute to a specified control.
		@param target: The maya node that will hold the evaluation order array attribute.
		@type target: str
		@param intersectList: Perform a list intersection between the calculated evaluation order with this list. If empty, no intersection is performed.
		@type intersectList: list
		@param evalOrderList: You can override the calculated evaluation order with a custom ordered list. If empty, use calculated evaluation order.
		@type evalOrderList: list
		'''
        # Check object exists
        if not mc.objExists(target):
            raise Exception('Target object ' + target + ' does not exist!')
        # Create attribute
        if mc.objExists(target + '.' + self.attribute):
            mc.deleteAttr(target, at=self.attribute)
        self.addAttribute(target)
        # Get calculated evaluation order list
        if not evalOrderList: evalOrderList = self.hierarchy.generationList()
        # Perform list intersection
        if intersectList:
            evalOrderList = [
                i for i in evalOrderList if intersectList.count(i)
            ]
        # Set evaluation order array attribute
        for i in range(len(evalOrderList)):
            mc.setAttr(target + '.' + self.attribute + '[' + str(i) + ']',
                       evalOrderList[i],
                       type='string')
        # Return evaluation order list
        return evalOrderList
def fixResolution():
    log(app = None, method = 'fixResolution', message = 'Fixing Resolutions now...', printToLog = False, verbose = configCONST.DEBUGGING)
    allLambert = cmds.ls(type = 'lambert')
    
    for eachLambert in allLambert:
        log(app = None, method = 'fixResolution', message = 'Processing: %s now...' % eachLambert, printToLog = False, verbose = configCONST.DEBUGGING)
        if cmds.ls('%s.message' % eachLambert):
            
            matInfo = findMaterialInfo('%s.message' % eachLambert)
            log(app = None, method = 'fixResolution', message = 'matInfo: %s' % matInfo, printToLog = False, verbose = configCONST.DEBUGGING)
            
            if matInfo:
                texture = ''
                try:
                    texture = cmds.listConnections("%s.texture[0]" % matInfo)[0]
                except TypeError:
                    pass
                
                if texture:            
                    try:
                        resolution = cmds.listAttr(texture, string = 'resolution')
                    except ValueError:
                        pass
        
                    if resolution:
                        cmds.deleteAttr(texture, at = 'resolution')
                        disconnectTextureInfo(matInfo)
                        cmds.addAttr(texture, ln = "resolution", at = 'long', dv = 32)
                        cmds.connectAttr("%s.message" % texture, "%s.texture[0]" % matInfo)
                        cmds.setAttr("%s.resolution" % texture, 256)
                    else:
                        cmds.addAttr(texture, ln = "resolution", at = 'long', dv = 32)
                        cmds.setAttr("%s.resolution" % texture, 256)
Beispiel #25
0
    def _WriteExportedAttributesToNode(nodeName, exportedAttrs):
        """
        Given a Maya node name, this method records the given list of
        ExportedAttribute objects in exportedAttrs in the Maya attribute. the
        passed in list replaces any previous data.

        NOTE: This method will likely only ever be called by the Remove and
        Update methods above since multiple nodes may be selected and only the
        common attributes between them will be displayed.
        """
        jsonDict = {}
        for exportedAttr in exportedAttrs:
            jsonDict.update(exportedAttr.GetJsonDict())

        exportAttrExists = cmds.attributeQuery(EXPORTED_ATTRS_MAYA_ATTR_NAME,
            node=nodeName, exists=True)

        if not jsonDict:
            if exportAttrExists:
                # The export attribute exists but we'd be emptying it, so just
                # remove the attribute instead.
                cmds.deleteAttr('%s.%s' % (nodeName, EXPORTED_ATTRS_MAYA_ATTR_NAME))
            return

        if not exportAttrExists:
            cmds.addAttr(nodeName, ln=EXPORTED_ATTRS_MAYA_ATTR_NAME, dt='string')

        jsonString = json.dumps(jsonDict)
        cmds.setAttr('%s.%s' % (nodeName, EXPORTED_ATTRS_MAYA_ATTR_NAME),
            jsonString, type='string')
Beispiel #26
0
    def delete(self):
        '''
        Delete all dynamic nodes
        '''
        # check if mNode still exists
        if self.mNode:
            if cmds.objExists(self.mNode):
                # nodes not to delete
                startJoint = self.startJoint
                endJoint = self.endJoint
                joints = self.joints
                # to store nodes to keep
                nodes = []
                for node in [startJoint, endJoint, joints]:
                    nodes.extend(node)
                # get all the connections
                connections = self.listConnections()
                # delete all custom attributes - if any node connected to it is deleted the node is deleted
                # so delete attributes first, then delete nodes to avoid runtime errors
                attrs = cmds.listAttr(self.mNode, ud=True, u=True)

                for attr in attrs:
                    cmds.deleteAttr(self.mNode + "." + attr)

                # now lets delete the nodes
                for conn in connections:
                    if conn not in nodes:
                        # check if node exists to avoid errors
                        if cmds.objExists(conn):
                            cmds.delete(conn)

                # finally delete the mNode
                cmds.delete(self.mNode)
    def delete(self):
        '''
        Delete all dynamic nodes
        '''
        # check if mNode still exists
        if self.mNode:
            if cmds.objExists(self.mNode):
                # nodes not to delete
                startJoint = self.startJoint
                endJoint = self.endJoint
                joints = self.joints
                # to store nodes to keep
                nodes = []
                for node in [startJoint, endJoint, joints]:
                    nodes.extend(node)
                # get all the connections
                connections = self.listConnections()
                # delete all custom attributes - if any node connected to it is deleted the node is deleted
                # so delete attributes first, then delete nodes to avoid runtime errors
                attrs = cmds.listAttr(self.mNode, ud=True, u=True)
                 
                for attr in attrs:
                    cmds.deleteAttr(self.mNode + "." + attr)
 
                # now lets delete the nodes 
                for conn in connections:
                    if conn not in nodes:
                        # check if node exists to avoid errors
                        if cmds.objExists(conn):
                            cmds.delete(conn)
                 
                # finally delete the mNode
                cmds.delete(self.mNode)
	def setAttr(self,target,intersectList=[],evalOrderList=[]):
		'''
		Store the calculated evaluation order list as a string array attribute to a specified control.
		@param target: The maya node that will hold the evaluation order array attribute.
		@type target: str
		@param intersectList: Perform a list intersection between the calculated evaluation order with this list. If empty, no intersection is performed.
		@type intersectList: list
		@param evalOrderList: You can override the calculated evaluation order with a custom ordered list. If empty, use calculated evaluation order.
		@type evalOrderList: list
		'''
		# Check object exists
		if not mc.objExists(target):
			raise UserInputError('Target object '+target+' does not exist!')
		# Create attribute
		if mc.objExists(target+'.'+self.attribute):
			mc.deleteAttr(target,at=self.attribute)
		self.addAttribute(target)
		# Get calculated evaluation order list
		if not evalOrderList: evalOrderList = self.hierarchy.generationList()
		# Perform list intersection
		if intersectList: evalOrderList = [i for i in evalOrderList if intersectList.count(i)]
		# Set evaluation order array attribute
		for i in range(len(evalOrderList)):
			mc.setAttr(target+'.'+self.attribute+'['+str(i)+']',evalOrderList[i],type='string')
		# Return evaluation order list
		return evalOrderList
Beispiel #29
0
def MESH_delete_custom_attributes():
    ''' delete all custom attributes '''
    rawSel = cmds.ls(sl=True)  # raw selection
    rawMesh = cmds.listRelatives(rawSel, pa=True,
                                 type="mesh")  # filter shapes (meshes)
    # get transforms names of the shapes
    allSel = cmds.listRelatives(rawMesh, parent=True, fullPath=False)
    if allSel is None:
        return "Select Meshes to delete custom attributes first.", 0

    count = 0
    mesh_count = 0  # channel count
    user_att_count = 0
    mesh_count = 0
    if count > 0:  # 1 o varios items
        for each in allSel:
            mesh_count += 1
            at_list = cmds.listAttr(each, ud=True)
            if at_list > 0:
                for at in at_list:
                    user_att_count += 1
                    attribute = each + "." + at
                    if cmds.objExists(attribute):
                        cmds.setAttr(attribute, l=False)
                        cmds.deleteAttr(attribute)
    msg = "({}) custom attributes deleted over ({}) transform nodes".format(
        user_att_count, mesh_count)
    return msg, 1
def removeCloneAttributes():
    
    import sgBModel_dag
    targetAttrs = cmds.ls( '*.'+sgBModel_dag.cloneTargetAttrName )
    
    for targetAttr in targetAttrs:
        cmds.deleteAttr( targetAttr )
Beispiel #31
0
	def on_remove( self, *a ):
		for item in cmd.ls( sl=True ):
			for attrName in listAttr( item, ud=True ):
				if attrName.startswith( '_skeletonPart' ) or attrName.startswith( '_skeletonFinalize' ):
					cmd.deleteAttr( '%s.%s' % (item, attrName) )

		self.populate()
def rsReAtt():
    l_oSels = rsObjList()
    l_AttributeList = (cmds.textScrollList("rsAttributeScroll", query=True, allItems=True))
    for s_Att in l_AttributeList:
        s_orig = l_oSels[0] + "." + s_Att
        i_LockState = cmds.getAttr(s_orig, lock=True)
        if i_LockState:
            cmds.setAttr(s_orig, lock=False)
        l_paramDest = cmds.listConnections(s_orig, plugs=True, destination=True, source=True)
        l_paramDestLock = []
        if l_paramDest:
            for z in range(len(l_paramDest)):
                l_paramDestLock.append(cmds.getAttr(l_paramDest[z], lock=True))
                if l_paramDestLock[z]:
                    cmds.setAttr(l_paramDest[z], lock=False)
        cmds.deleteAttr(l_oSels[0], at=s_Att)
        cmds.undo()
        if l_paramDest:
            for z in range(len(l_paramDest)):
                l_paramDestLock.append(cmds.getAttr(l_paramDest[z], lock=True))
                if l_paramDestLock[z]:
                    cmds.setAttr(l_paramDest[z], lock=True)
        if i_LockState:
            cmds.setAttr(s_orig, lock=True)
    cmds.select(cl=True)
    cmds.select(l_oSels[0], r=True)
    return True
Beispiel #33
0
	def updateOrigNamesFormat(self,objectList=[]):
		'''
		Update a combined meshes origNames attribute to the newest format.
		@param objectList: list of mesh objects to update origNames attribute on.
		@type objectList: list
		'''
		# Confirm list
		if type(objectList) == str:
			objectList = [objectList]
		
		# Iterate through object list
		for obj in objectList:
			
			# Check origNames attribute
			if not mc.objExists(obj+'.origNames'):
				raise UserInputError('Object '+obj+' does not have a "origNames" attribute!')
			if mc.addAttr(obj+'.origNames',q=True,multi=True):
				print(obj+'.origNames is already in the correct format.')
				continue
			
			# Extract original names list from old format
			origNamesList = []
			index = 0
			while True:
				if mc.objExists(obj+'.origNames.origNames_'+str(index)):
					origNamesList.append(mc.getAttr(obj+'.origNames.origNames_'+str(index)))
					index+=1
				else: break
			
			# Re-create the origNames attribute in the new format
			mc.deleteAttr(obj+'.origNames')
			mc.addAttr(obj,ln='origNames',dt='string',multi=True)
			for i in range(len(origNamesList)):
				mc.setAttr( obj+'.origNames['+str(i)+']', origNamesList[i], type='string')
def _addVersionTag(assetName, versionNumber):
    if cmds.objExists('%s.%sversion' % (assetName, configCONST.SURFACE_SHORTNAME)):
        cmds.deleteAttr('%s.%sversion' % (assetName, configCONST.SURFACE_SHORTNAME))
    try:
        cmds.addAttr(assetName, ln = '%sversion' % configCONST.SURFACE_SHORTNAME, at = 'long', min = 0, max  = 50000, dv = 0)
    except:
        pass
    cmds.setAttr('%s.%sversion' % (assetName, configCONST.SURFACE_SHORTNAME), int(versionNumber))
Beispiel #35
0
 def J_deleteImagePlane(self):
     cameraShape=self.J_mainWindow.comboBox_cam.itemText(self.J_mainWindow.comboBox_cam.currentIndex())
     cameraTransform=cmds.listRelatives(cameraShape,parent=True)
     if cmds.attributeQuery('J_ImageFilePath',node=cameraShape,exists=True):
         cameraConnections=cmds.listConnections(cameraShape,connections=False,source=True,plugs=False,type='imagePlane')
         cmds.delete(cameraConnections) 
         cmds.select(cameraShape)
         cmds.deleteAttr(name=cameraShape, attribute='J_ImageFilePath')
Beispiel #36
0
def _remove_constraint_blend_attr_from_nodes(nodes):
    for node in nodes:
        attr_list = cmds.listAttr(node)
        for attr in attr_list:
            if ("blendPoint" in attr or "blendOrient" in attr
                    or "blendParent" in attr):
                cmds.deleteAttr(str(node) + "." + str(attr))
    return
    def fix_invalid(cls, instance):
        from maya import cmds

        invalid = cls.get_invalid(instance)

        for node, attrs in invalid.items():
            for attr_long, attr_nice in attrs:
                cmds.deleteAttr(node, attribute=attr_long)
	def setCmd( self, cmdStr ):
		cmdAttr = "zooTrigCmd0"
		if not objExists( "%s.%s" % ( self.obj, cmdAttr ) ): cmd.addAttr(self.obj, ln=cmdAttr, dt="string")
		if cmdStr is None or cmdStr == '':
			cmd.deleteAttr(self.obj, at=cmdAttr)
			return

		cmd.setAttr('%s.%s' % ( self.obj, cmdAttr ), cmdStr, type='string')
Beispiel #39
0
def btnDel(opt): #deletes all sets and locators
	if opt=='all':
		for each in mc.ls():
			if mc.objExists(each+'.FuriosoFlag'): mc.deleteAttr(each+'.FuriosoFlag')
	if opt=='sel':
		for each in mc.ls(sl=1):
			if mc.objExists(each+'.FuriosoFlag'): mc.deleteAttr(each+'.FuriosoFlag')
	buildUILists()
def removeBindMarker(ctrls=None, *args):
    '''
    remove the bind markers from nodes, these dictate what gets baked
    '''
    if not ctrls:
        ctrls = cmds.ls(sl=True, l=True)
    for ctr in ctrls:
        cmds.deleteAttr('%s.%s' % (ctr, BAKE_MARKER))
	def setCmd( self, cmdStr ):
		cmdAttr = "zooTrigCmd0"
		if not objExists( "%s.%s" % ( self.obj, cmdAttr ) ): cmd.addAttr(self.obj, ln=cmdAttr, dt="string")
		if cmdStr is None or cmdStr == '':
			cmd.deleteAttr(self.obj, at=cmdAttr)
			return

		cmd.setAttr('%s.%s' % ( self.obj, cmdAttr ), cmdStr, type='string')
Beispiel #42
0
	def _addVersionTag(self, assetName, versionNumber):
		if cmds.objExists('%s.version' % assetName):
			cmds.deleteAttr('%s.version' % assetName)
		try:
			cmds.addAttr(assetName, ln = 'version', at = 'long', min = 0, max  = 50000, dv = 0)
		except:
			pass
		cmds.setAttr('%s.version' % assetName, int(versionNumber))
def removeBindMarker(ctrls=None, *args):
    '''
    remove the bind markers from nodes, these dictate what gets baked
    '''
    if not ctrls:
        ctrls = cmds.ls(sl=True, l=True)
    for ctr in ctrls:
        cmds.deleteAttr('%s.%s' % (ctr, BAKE_MARKER))
Beispiel #44
0
 def deleteAttribute(self, attr):
     plug = self.attribute(attr)
     if plug:
         name = plug.name()
         plug.isLocked = False
         cmds.deleteAttr(name)
         return True
     return False
Beispiel #45
0
 def deleteFollowWeightAttrs( tr ):
     udAttrs = cmds.listAttr( tr, k=1, ud=1 )
     
     if not udAttrs: return None
     
     for attr in udAttrs:
         if attr[-5:] == 'CTL_w':
             cmds.deleteAttr( tr+'.'+attr )
 def deleteIdAttr(self,*args):
     selList = self.listSelected()
     meshList = self.getMeshList(selList)
     self.deleteColorAttr(meshList)
     # add attribute to selected meshes
     for mesh in meshList:
         if mc.objExists(mesh+'.'+self.idGroupAttr):
             mc.deleteAttr(mesh+'.'+self.idGroupAttr)
Beispiel #47
0
 def deleteComponentFromObject( cls, inCompNode ):
     '''
     Deletes the selected component from the object. Used in right-click menu
     for components GUI.
     '''
     obj = NodeUtility.getNodeAttrSource( inCompNode, 'parentName' )
     cmds.deleteAttr( '{0}.{1}'.format( obj[0], obj[1] ) )
     cmds.delete( inCompNode )
     cmds.select( obj[0] )
Beispiel #48
0
def plateOn(plate, connection):
    # check for 'plateOff' string in node
    connectionNode = connection.rpartition('.')[0]
    connectionAttr = connection.rpartition('.')[2]
    cmds.deleteAttr(connectionNode, at=connectionAttr)
    reConnectAttr = connectionAttr.replace('XXX', '[').replace('ZZZ', ']')
    reConnectAttr = reConnectAttr.rpartition('_')[2]
    cmds.connectAttr(plate + '.message', connectionNode + '.' + reConnectAttr, f=True)
    message('plates ON')
Beispiel #49
0
def clearDpArAttr(itemList):
    """ Delete all dpAR (dpAutoRigSystem) attributes in this joint
    """
    dpArAttrList = ['dpAR_joint']
    if itemList:
        for item in itemList:
            for dpArAttr in dpArAttrList:
                if cmds.objExists(item+"."+dpArAttr):
                    cmds.deleteAttr(item+"."+dpArAttr)
	def removeCmd( self, removeConnects=False ):
		'''removes the triggered cmd from self - can optionally remove all the connects as well'''
		try:
			#catches the case where there is no trigger cmd...  faster than a object existence test
			cmd.deleteAttr( '%s.zooTrigCmd0' % self.obj )
			if removeConnects:
				for connect,slot in self.connects():
					self.disconnect(slot)
		except TypeError: pass
Beispiel #51
0
def _set_serialized(node, full_tag, serialize):
	#tag as serialized
	full_tag_serialized = full_tag + "_SERIALIZED"
	serial_tag_exists = cmds.objExists(node + "." + full_tag_serialized)
	if serialize and not serial_tag_exists:
		cmds.addAttr(node, ln=full_tag_serialized, dt="string")

	if not serialize and serial_tag_exists:
		cmds.deleteAttr(node+"."+full_tag_serialized)
 def cleanSceneBuilderHistory(self, asset):
     attr = self.sceneManagerNode+"."+asset
     try:
         mc.deleteAttr(attr)
         if self.debug: print "deleting scenebuilder script node attr: ", attr
         return attr
     except:
         if self.debug: print "delete attribute fail: ", attr
         return None
Beispiel #53
0
def deletePickledAttribute(node):
    ''' Tries to delete a PICKLED_ATTRIBUTE on the given node.  Returns true if
    it succeeds.'''
    try:
        callLockHideCommand(node, PICKLED_ATTRIBUTE, lock=0)
        cmd.deleteAttr(node, attribute=PICKLED_ATTRIBUTE)
        return True
    except Exception as err:
        return False
def removeSettings(name):
    """
        Removes instance setting specific attributes if they exist

        name    :    The object name to attempt to remove the attributes from
    """
    for attribute in attributes:
        if cmds.attributeQuery(attribute, node=name, ex=True):
            cmds.deleteAttr('%s.%s'%(name,attribute))
Beispiel #55
0
    def deleteLayer(self, sLayerName):
        """
        Delete render layer sLayerName from the node by removing all of 
        it's attributes
        """

        for sSuffix in self.lstLayerAttrs:
            if mc.objExists(self.sSwNode + "." + sLayerName + "_" + sSuffix):
                mc.deleteAttr(self.sSwNode, at = sLayerName + "_" + sSuffix)