Example #1
0
def AttrExists( node , attr):

	if (attr and node):
		if not pm.objExists(node): return 0
		if attr in pm.listAttr(node,shortNames=True): return 1
		if attr in pm.listAttr(node): return 1
		return 0    
Example #2
0
    def findAttributeHolder(self):
        selection = pm.selected()
        heirarchy = pm.listRelatives(selection, ap=True)
        componentRoot = None
        attributeHolder = None
        while componentRoot == None:
            attributes = pm.listAttr(selection, userDefined=True)
            if attributes == None:
                heirarchy = pm.listRelatives(selection, ap=True)
                selection = heirarchy
            else:
                if 'componentRoot' in attributes:
                    componentRoot = selection
                else:
                    heirarchy = pm.listRelatives(selection, ap=True)
                    selection = heirarchy

        if componentRoot != None:
            self.componentRoot = componentRoot
            children = pm.listRelatives(componentRoot, c=True)
            for x in children:
                attributes = pm.listAttr(x, userDefined=True)
                if attributes == None:
                    continue
                else:
                    if 'attributeHolder' in attributes:
                        attributeHolder = x
                        self.attributeHolder = attributeHolder
        else:
            self.componentRoot = componentRoot
            pm.error('Component Root not found')

        if attributeHolder == None:
            self.attributeHolder = attributeHolder
            pm.error('Attribute Holder not found')
Example #3
0
def __restorePosingRIG__(elts):

    if elts==None:
        # get each objects from rigShapesSet
        if pmc.objExists('RIG_bindPose'):
            elts = pmc.sets('RIG_bindPose', query=True)
        fromSelection=False
    else:
        fromSelection=True
    
    if elts:
        for elt in elts:
            if fromSelection:
                if pmc.objExists(elt.name()+'_storedPos'):
                    obj = elt.name()+'_storedPos'
                    attrs = pmc.listAttr(elt, keyable=True)
                    for i in range(len(attrs)):
                        try:
                            pmc.PyNode(elt+'.'+attrs[i]).set(pmc.PyNode(obj+'.'+attrs[i]+'_stored').get())
                        except:
                            vp.vPrint('No data founded from %s in rigPosingSet set' % elt.name(), 1)
                else:
                    vp.vPrint('Object %s doesn\'t exist' % (elt.name()+'_storedPos'), 1)
            else:
                if pmc.objExists(elt.name().replace('_storedPos', '')):
                    obj = pmc.PyNode(elt.name().replace('_storedPos', ''))
                    attrs = pmc.listAttr(obj, keyable=True)
                    for i in range(len(attrs)):
                        try:
                            pmc.PyNode(obj+'.'+attrs[i]).set(pmc.PyNode(elt+'.'+attrs[i]+'_stored').get())
                             
                        except:
                            vp.vPrint('No data founded from %s in rigPosingSet set' % elt.name(), 1)
                else:
                    vp.vPrint('Object %s doesn\'t exist' % elt.name().replace('_storedPos', ''), 1)
Example #4
0
 def create_preset(self):
     '''
     # creates the file for the preset
     ******
     # file pattern
     # data = ['preset name', 'light type', 'description',
                         xform_attrs[], shape_attrs[]] 
     ******
     '''
     sel = pm.ls(selection= True)[0]
     sel_shape = sel.getShape()
     node_type = pm.nodeType(sel_shape)
     
     if 'Light' not in node_type:
         return
     
     data = []
     
     data.append('%s' % (self.field.getText()))
     
     data.append('%s' % (node_type))
     
     data.append('%s' % (self.scroll.getText()))
     
     sel_data = []
     
     sel_shape_data = []
     
     sel_attrs = pm.listAttr(sel)
     sel_shape_attrs = pm.listAttr(sel_shape)
     
     for attr in sel_attrs:
         try :
             value = pm.getAttr('%s.%s' % (sel, attr))
             temp_data = (attr , value)
             sel_data.append(temp_data)
         
         except:
             pass
         
     for attr in sel_shape_attrs:
         try:
             value = pm.getAttr('%s.%s' % (sel_shape, attr))
             temp_data = (attr , value)
             sel_shape_data.append(temp_data)
         
         except:
             pass
         
         
     data.append(sel_data)
     data.append(sel_shape_data)
     
     name ='%s.light'  % (self.field.getText())
     full_path = os.path.join(self.path, name)
     f = open(full_path, 'w')
     pickle_data = pickle.dump(data, f)
     f.close()
     
     preset_ui() # this will list will update the preset section
Example #5
0
def AttrExists(node, attr):

    if (attr and node):
        if not pm.objExists(node): return 0
        if attr in pm.listAttr(node, shortNames=True): return 1
        if attr in pm.listAttr(node): return 1
        return 0
Example #6
0
	def resetTransformAttributes(self,*args):
		
		objs = pm.ls( sl=True )

		for obj in objs:
			
			allAttrs = pm.listAttr( obj, keyable=True, unlocked=True )
			userAttrs =  pm.listAttr(obj, ud=True, unlocked=True)
			
			for attr in allAttrs:
				
				# if attribute has incomming connections, go to next attribute, unless incomming connections is comming from character set
				inConnections = pm.listConnections( obj.attr(attr), d=False, s=True )
				if inConnections:
					if not ( self.alterableInputTypes ): 
						continue
				
				if attr not in userAttrs:# match main attributes
					try:
						if attr == 'visibility':
							pass
						elif ('scale' in attr.lower() ) :
							obj.attr(attr).set( 1 )
						else:
							obj.attr(attr).set( 0 )
					except:
						pm.warning( "ehm_tools...resetAllPose: Could not resetAll some of transform attributes, skipped! \t %s" %obj )
				else:# do not reset user defined attributes
					continue
Example #7
0
    def create_preset(self):
        '''
        # creates the file for the preset
        ******
        # file pattern
        # data = ['preset name', 'light type', 'description',
                            xform_attrs[], shape_attrs[]] 
        ******
        '''
        sel = pm.ls(selection=True)[0]
        sel_shape = sel.getShape()
        node_type = pm.nodeType(sel_shape)

        if 'Light' not in node_type:
            return

        data = []

        data.append('%s' % (self.field.getText()))

        data.append('%s' % (node_type))

        data.append('%s' % (self.scroll.getText()))

        sel_data = []

        sel_shape_data = []

        sel_attrs = pm.listAttr(sel)
        sel_shape_attrs = pm.listAttr(sel_shape)

        for attr in sel_attrs:
            try:
                value = pm.getAttr('%s.%s' % (sel, attr))
                temp_data = (attr, value)
                sel_data.append(temp_data)

            except:
                pass

        for attr in sel_shape_attrs:
            try:
                value = pm.getAttr('%s.%s' % (sel_shape, attr))
                temp_data = (attr, value)
                sel_shape_data.append(temp_data)

            except:
                pass

        data.append(sel_data)
        data.append(sel_shape_data)

        name = '%s.light' % (self.field.getText())
        full_path = os.path.join(self.path, name)
        f = open(full_path, 'w')
        pickle_data = pickle.dump(data, f)
        f.close()

        preset_ui()  # this will list will update the preset section
Example #8
0
def up_down_attribute(up=False, down=False):
    """

    Args:
        up: Set the selected attribute go up 1 index in the main channel box
        down: Set the selected attribute go down 1 index in the main channel box

    Returns: Relocation of selected attribute in main channel box

    """
    selections = pm.ls(sl=True)
    if len(selections) != 1:
        return om.MGlobal.displayError("This function only work with one object per time")

    selection = selections[0]

    selected_attr = pm.channelBox("mainChannelBox", query=True, selectedMainAttributes=True)
    list_attr = pm.listAttr(selection, userDefined=True, locked=True)

    if len(list_attr) > 0:
        for attr in list_attr:
            pm.setAttr("{0}.{1}".format(selection, attr), lock=False)

    if down:
        if len(selected_attr) > 1:
            selected_attr.reverse()
            sort = selected_attr
        if len(selected_attr) == 1:
            sort = selected_attr
        for i in sort:
            attr_list = pm.listAttr(selection, userDefined=True)
            attr_list_size = len(attr_list)
            attr_position = attr_list.index(i)
            pm.deleteAttr(selection, attribute=attr_list[attr_position])
            pm.undo()

            for x in range(attr_position + 2, attr_list_size, 1):
                pm.deleteAttr(selection, attribute=attr_list[x])
                pm.undo()

    if up:
        for i in selected_attr:
            attr_list = pm.listAttr(selection, userDefined=True)
            attr_list_size = len(attr_list)
            attr_position = attr_list.index(i)
            if attr_list[attr_position - 1]:
                pm.deleteAttr(selection, attribute=attr_list[attr_position - 1])
                pm.undo()
            for x in range(attr_position + 1, attr_list_size, 1):
                pm.deleteAttr(selection, attribute=attr_list[x])
                pm.undo()

    if len(list_attr) > 0:
        for attr in list_attr:
            pm.setAttr("{0}.{1}".format(selection, attr), lock=True)

    sys.stdout.write("Complete.\n")
Example #9
0
 def getControlAttrs(self,ctrl=None):
     if pm.objectType(ctrl) == 'transform':
         return pm.listAttr(ctrl,unlocked=True,k=True)
     else:
         attrs = pm.listAttr(ctrl,connectable=True)
         for attr in attrs:
             if attr == 'distance':
                 return ['distance']
         return None
Example #10
0
 def getControlAttrs(self, ctrl=None):
     if pm.objectType(ctrl) == 'transform':
         return pm.listAttr(ctrl, unlocked=True, k=True)
     else:
         attrs = pm.listAttr(ctrl, connectable=True)
         for attr in attrs:
             if attr == 'distance':
                 return ['distance']
         return None
Example #11
0
	def load_Object(self):
		self.ui.attr_listView.clear()
		sel_Obj = pm.ls(sl = True)[0]
		if sel_Obj:
			if self.ui.keyable_check_Box.isChecked():
				self.attr_List = pm.listAttr(sel_Obj, ud = True, k  = True)
			else:
				self.attr_List = pm.listAttr(sel_Obj, ud = True)
			self.ui.object_name.setText(sel_Obj.name())
			self.ui.attr_listView.addItems(self.attr_List)
Example #12
0
def rigMake(mayaFalse):
    #check
    if not pm.ls(
            'Locator_Pivot'
    ):  #first, perform a check to see if locatorMake() has been performed.
        pm.confirmDialog(title=u'SER ę­¦å™ØćƒŖ悰', message=u'å…ˆćšć€ćƒ”ćƒœćƒƒćƒˆčØ­å®šć‚’ć—ć¦ćć ć•ć„ć€‚')
        return

    #rest of rig start
    constrLoc = pm.spaceLocator(
        name="Locator_Constraint")  #creating locator to constraint the bone to

    weapJoint = pm.ls('*Joint_Weapon', type='joint')[0]
    pm.xform(
        constrLoc, ws=True, t=pm.xform(weapJoint, q=True, t=True, ws=True)
    )  #moving the newly created constraint locator to the translation position of the joint

    pm.parentConstraint(constrLoc, weapJoint, mo=False)
    contr1 = pm.circle(name='Controller_Weapon_Global', r=9, nr=[0, 1, 0])
    contr2 = pm.circle(name='Controller_Weapon_Local', r=7, nr=[0, 1, 0])

    pm.parent(contr2[0], contr1[0])
    pm.xform(contr1,
             ws=True,
             t=pm.xform('Locator_Pivot', q=True, t=True, ws=True),
             ro=pm.xform('Locator_Pivot', q=True, ro=True, ws=True))
    pm.delete(
        'Locator_Pivot'
    )  #deleting locator pivot after rig controllers have been created.
    pm.parent(constrLoc, contr2[0])

    R_Constr = pm.parentConstraint(
        pm.ls('*Helper_Weapon1')[0],
        contr1[0],
        name='Constraint_Weapon_Global')  #parent constraint to right hand
    L_Constr = pm.parentConstraint(pm.ls('*Helper_Weapon2')[0],
                                   contr1[0])  #parent constraint to left hand
    pm.setAttr(
        'Constraint_Weapon_Global.%s' %
        pm.listAttr('Constraint_Weapon_Global', k=True)[-1], 0)

    pm.setKeyframe('Controller_Weapon_Global')
    pm.setKeyframe('Controller_Weapon_Global',
                   v=1,
                   at='blendWeaponGlobal',
                   itt='auto',
                   ott='step')
    pm.setKeyframe('Constraint_Weapon_Global',
                   v=1,
                   at=pm.listAttr('Constraint_Weapon_Global',
                                  k=True)[-2])  #sets RH constraint to 1
    pm.setKeyframe('Constraint_Weapon_Global',
                   v=0,
                   at=pm.listAttr('Constraint_Weapon_Global',
                                  k=True)[-1])  #sets LH constraint to 0
Example #13
0
	def bdCreateFkDynSwitch(self):
		parentCnstrAll = self.rootObj.listRelatives(type='parentConstraint', ad=True, f=True)
		reverseNode = pm.createNode('reverse',n=self.rootObj.name() + '_DYN_REV')
		self.fkCtrlTop.attr('dynamic').connect(reverseNode.inputX)
		
		
		for cnstr  in parentCnstrAll:
			dynAttrW = pm.listAttr(cnstr, st='anim*DYN*')[0]
			fkAttrW = pm.listAttr(cnstr, st='anim*FK*')[0]
			self.fkCtrlTop.attr('dynamic').connect(cnstr.attr(dynAttrW))
			reverseNode.outputX.connect(cnstr.attr(fkAttrW))
Example #14
0
def hidari(mayaFalse):
    pm.setKeyframe(
        'WeaponMotion_R', v=1, at='blendWeaponGlobal', itt='auto',
        ott='step')  # sets the blend parent of the controller transform to 1
    pm.setKeyframe('Constraint_Weapon_Global',
                   v=0,
                   at=pm.listAttr('Constraint_Weapon_Global', k=True)[-2],
                   ott='step')  # sets RH constraint to 0
    pm.setKeyframe('Constraint_Weapon_Global',
                   v=1,
                   at=pm.listAttr('Constraint_Weapon_Global', k=True)[-1],
                   ott='step')  # sets LH constraint to 1
    pm.currentTime(pm.currentTime(), update=True)  # updating the viewport
Example #15
0
def multinode(arg):
    num = pm.textField('multinum',q=True,tx=True)
    sels =pm.ls(sl=1,type="file")
    for sel in sels:
        choiceNodes =   pm.listConnections(sel,d=0,type="choice")
        udimNumsample=set(range(1001,1900))
        path  =pm.getAttr(sel+".fileTextureName")
        filepath = set([int(u) for u in re.findall("\d+",str(path))])
        udimjudge=list(filepath&udimNumsample)
        types = path.split(".")[-1]
        if udimjudge==[] and path.find("<UDIM>")==-1 :
            if choiceNodes==[]:
                choicesel = pm.shadingNode("choice",asUtility=1,name = sel[0])
                pm.connectAttr(choicesel+".output",sel+".fileTextureName",f=1)
                for n in range(int(num)):
                    pm.addAttr(sel,ln="Tex"+str(n),dt="string")
                    pm.connectAttr(sel+".Tex"+str(n),choicesel.input[n],f=1)
                    if n==0:
                        pm.setAttr(sel+".Tex"+str(n),path,type="string")
                    else:
                        pm.setAttr(sel+".Tex"+str(n),path[:-4]+"_"+str(n+1)+"."+types,type="string")
            else:
                Texlists = [a for a in pm.listAttr(sel) if a.find('Tex')!=-1 and len(a)<=5]
                texnum = len(Texlists)
                for n in range(int(num)):
                    pm.addAttr(sel,ln="Tex"+str(n+texnum),dt="string")
                    pm.connectAttr(sel+".Tex"+str(n+texnum),choiceNodes[0]+".input["+str(n+texnum)+"]",f=1)
                    pm.setAttr(sel+".Tex"+str(n+texnum),path[:-4]+"_"+str(n+1+texnum)+"."+types,type="string")
        else:
            if udimjudge!=[]:
                udimpath= path[:-4].replace(str(udimjudge[-1]),"<UDIM>")
            else:
                udimpath =  path[:-4]
            if choiceNodes==[]:
                choicesel = pm.shadingNode("choice",asUtility=1,name = sel[0])
                pm.connectAttr(choicesel+".output",sel+".fileTextureName",f=1)
                for n in range(int(num)):
                    pm.addAttr(sel,ln="Tex"+str(n),dt="string")
                    pm.connectAttr(sel+".Tex"+str(n),choicesel.input[n],f=1)
                    if n==0:
                        pm.setAttr(sel+".Tex"+str(n),udimpath+"."+types,type="string")
                    else:
                        pm.setAttr(sel+".Tex"+str(n),udimpath[:-7]+"_"+str(n+1)+udimpath[-7:]+"."+types,type="string")
            else:
                Texlists = [a for a in pm.listAttr(sel) if a.find('Tex')!=-1 and len(a)<=5]
                texnum = len(Texlists)
                for n in range(int(num)):
                    pm.addAttr(sel,ln="Tex"+str(n+texnum),dt="string")
                    pm.connectAttr(sel+".Tex"+str(n+texnum),choiceNodes[0]+".input["+str(n+texnum)+"]",f=1)
                    pm.setAttr(sel+".Tex"+str(n+texnum),udimpath[:-7]+"_"+str(n+1+texnum)+udimpath[-7:]+"."+types,type="string")
Example #16
0
def connectBlendShapesToLoc(geos, locator='flexShapes_LOC'):
    shapeList = pm.listAttr(locator, ud=True)
    for geo in geos:
        blendShapes = mm.eval('rig_returnDeformers("' + geo +
                              '", "blendShape")')
        if len(blendShapes) == 1:
            bs = blendShapes[0]
            geoShapeList = pm.listAttr(bs + '.weight', m=True)
            for shape in geoShapeList:
                if shape in shapeList:
                    pm.connectAttr(locator + '.' + shape,
                                   bs + '.' + shape,
                                   f=True)
                    print 'Connected ' + shape + ' on ' + geo
Example #17
0
    def duplicate(self, *args):
        '''
        # duplicates selected lights
        '''
        selected = pm.ls(sl=True)

        for sel in selected:
            sel_shape = sel.getShape()  # getting the shape node
            sel_type = pm.nodeType(sel_shape)  # getting the node type

            xform = self.xform.getValue()

            if 'Light' not in sel_type:
                print '# wrong object type ', sel
                continue
            # creating a new light based on the recieved node type
            new_light = pm.shadingNode('%s' % (sel_type), asLight=True)
            new_light = pm.rename(new_light, '%s_copy' % (sel))  # renaming
            new_shape = new_light.getShape()  # getting the shape
            # listing transform attrs
            input_attrs = pm.listAttr(sel)
            # listing shape attrs
            shape_attrs = pm.listAttr(sel_shape)

            if xform == 1:
                for attr in input_attrs:
                    try:
                        value = pm.getAttr('%s.%s' % (sel, attr))
                        pm.setAttr('%s.%s' % (new_light, attr), value)

                    except:
                        pass

            for attr in shape_attrs:
                try:
                    value = pm.getAttr('%s.%s' % (sel_shape, attr))
                    pm.setAttr('%s.%s' % (new_shape, attr), value)

                except:
                    pass

            pm.select(new_light)
            if self.override_intensity.getValue() == 1:
                #pm.setAttr('%s.intensity' % (new_light), self.int_slider.getValue())
                new_light.intensity.set(self.int_slider.getValue())

            if self.override_color.getValue() == 1:
                #pm.setAttr('%s.color' % (new_light), self.color_slider.getRgbValue())
                new_light.color.set(self.color_slider.getRgbValue())
Example #18
0
 def duplicate(self, * args):
     '''
     # duplicates selected lights
     '''
     selected = pm.ls(sl= True)
                
     for sel in selected:
         sel_shape = sel.getShape() # getting the shape node
         sel_type = pm.nodeType(sel_shape) # getting the node type
         
         xform = self.xform.getValue()
         
         if 'Light' not in sel_type:
             print '# wrong object type ', sel
             continue
         # creating a new light based on the recieved node type
         new_light = pm.shadingNode('%s' % (sel_type), asLight= True)
         new_light = pm.rename(new_light, '%s_copy' % (sel)) # renaming
         new_shape = new_light.getShape() # getting the shape
         # listing transform attrs
         input_attrs = pm.listAttr(sel) 
         # listing shape attrs
         shape_attrs = pm.listAttr(sel_shape)
         
         if xform == 1:
             for attr in input_attrs:
                 try:
                     value = pm.getAttr('%s.%s' % (sel, attr))
                     pm.setAttr('%s.%s' % (new_light, attr), value)
                 
                 except:
                     pass
                 
         for attr in shape_attrs:
             try:
                 value = pm.getAttr('%s.%s' % (sel_shape, attr))
                 pm.setAttr('%s.%s' % (new_shape, attr), value)
             
             except:
                 pass
         
         pm.select(new_light)
         if self.override_intensity.getValue() == 1:
             #pm.setAttr('%s.intensity' % (new_light), self.int_slider.getValue())
             new_light.intensity.set(self.int_slider.getValue())
         
         if self.override_color.getValue() == 1:
             #pm.setAttr('%s.color' % (new_light), self.color_slider.getRgbValue())
             new_light.color.set(self.color_slider.getRgbValue())
Example #19
0
def unlock_all():
    selection = pm.selected()
    pymel_attributes = []
    for each in selection:
        temp_holding_list = []

        attributes_k = pm.listAttr(each, keyable=True)
        temp_holding_list.extend(attributes_k)

        attributes_nk = pm.listAttr(each, cb=True)
        temp_holding_list.extend(attributes_nk)

        for attribute in temp_holding_list:
            pymel_attributes.append(each.attr(attribute))
    attr_unlock(pymel_attributes)
Example #20
0
def queryAttributeChoice(parentDialog):
  objName = str(pm.ls(sl=1)[0]) # getting the first selected object

  if QApplication.keyboardModifiers() == Qt.ControlModifier:
    attrs = pm.listAttr(objName, w=1) # Ctrl pressed => showing all writeable channels
  elif QApplication.keyboardModifiers() == Qt.AltModifier:
    attrs = pm.listAttr(objName, ud=1) # Alt pressed => showing only user defined channels
  else:
    attrs = pm.listAttr(objName, k=1) # otherwise showing only keyable channels

  choice = QInputDialog.getItem(parentDialog, "Attributes", "Choose an attribute to be driven", attrs)
  if choice[1]:
    return "{obj}.{attr}".format(obj=objName, attr=choice[0]) # formatting the full attribute name
  else: # if no choice has been made (window closed etc)
    return None
Example #21
0
def weaponGlobal_single(mayaFalse):
    pm.setKeyframe('WeaponMotion_R', at=['translate', 'rotate'])
    pm.setKeyframe(
        'WeaponMotion_R', v=0, at='blendWeaponGlobal', itt='auto',
        ott='step')  # sets the blend parent of the controller transform to 0
    pm.setKeyframe(
        'Constraint_Weapon_Global',
        v=0,
        at=[
            pm.listAttr('Constraint_Weapon_Global', k=True)[-2],
            pm.listAttr('Constraint_Weapon_Global', k=True)[-1]
        ],
        itt='auto',
        ott='step')  # sets both left and right hand constraints to 0
    pm.currentTime(pm.currentTime(), update=True)  # updating the viewport
Example #22
0
def copyAnim():
    selection = pm.ls(sl=True)
    if len(selection) != 2:
        pm.warning('Need exactly two objects to copy')
        return
    try:
        namespace = selection[0].namespace()
    except:
        namespace = ''

    print namespace
    holders = pm.ls('*_HOLDE*')
    if namespace != '':
        holders = pm.ls('*:*_HOLDE*')

    if holders:
        pm.delete(holders)

    source = selection[0]
    target = selection[1]

    pm.setKeyframe(source)
    pm.setKeyframe(target)

    sourceName = source.name()
    targetName = target.name()
    if namespace != '':
        sourceName = source.stripNamespace()
        targetName = target.stripNamespace()

    pm.select(cl=True)

    sourceAttr = pm.listAttr(source, k=True)
    sourceHolder = pm.group(n=namespace + sourceName + '_SOURCE_HOLDER')
    for attr in sourceAttr:
        attrType = source.attr(attr).type()
        pm.addAttr(sourceHolder, ln='__' + attr, nn=attr, at=attrType)
        sourceHolder.attr('__' + attr).set(source.attr(attr).get())

    pm.select(cl=True)
    targetAttr = pm.listAttr(target, k=True)
    targetHolder = pm.group(n=namespace + targetName + '_TARGET_HOLDER')
    for attr in targetAttr:
        attrType = target.attr(attr).type()
        pm.addAttr(targetHolder, ln='__' + attr, nn=attr, at=attrType)
        targetHolder.attr('__' + attr).set(target.attr(attr).get())

    pm.select([target, source])
Example #23
0
def copyAnim():
	selection = pm.ls(sl=True)
	if len(selection) != 2:
		pm.warning('Need exactly two objects to copy')
		return
	try:
		namespace = selection[0].namespace()
	except:
		namespace = ''
		
	print namespace
	holders = pm.ls('*_HOLDE*')
	if namespace != '':
		holders = pm.ls('*:*_HOLDE*')
	
	if holders:
		pm.delete(holders)

	source = selection[0]
	target = selection[1]
	
	pm.setKeyframe(source)
	pm.setKeyframe(target)
	
	sourceName = source.name()
	targetName = target.name()
	if namespace != '':
		sourceName =  source.stripNamespace()
		targetName =  target.stripNamespace()
		
	pm.select(cl=True)

	sourceAttr = pm.listAttr(source,k=True)
	sourceHolder = pm.group(n=namespace + sourceName + '_SOURCE_HOLDER')
	for attr in sourceAttr:
		attrType = source.attr(attr).type()
		pm.addAttr(sourceHolder,ln='__' + attr,nn=attr,at = attrType)
		sourceHolder.attr('__' + attr).set(source.attr(attr).get())
	
	pm.select(cl=True)
	targetAttr = pm.listAttr(target,k=True)
	targetHolder = pm.group(n=namespace + targetName + '_TARGET_HOLDER')
	for attr in targetAttr:
		attrType = target.attr(attr).type()
		pm.addAttr(targetHolder,ln='__' + attr,nn=attr,at = attrType)
		targetHolder.attr('__' + attr).set(target.attr(attr).get())
	
	pm.select([target,source])
Example #24
0
def ar_bakeShapeUsingWrap(baseGeo, newGeo):
    """
    @ bake blendshape using wrap deformer.
    Args:
        baseGeo (str, PyNode): base geometry transform.
        newGeo (str, PyNode): edited shape transform.

    Returns:
            newShape.
    """
    oldGeo = pm.PyNode(baseGeo)
    newGeo = pm.PyNode(newGeo)
    # find blendshape node.
    bShpNode = ar_find.ar_findInputNodeType(oldGeo, 'blendShape')[0]
    bShpNode = pm.PyNode(bShpNode)
    # set all weight at zero.
    for i in range(bShpNode.getWeightCount()):
        bShpNode.setWeight(i, 0)
    # create targets.
    for each in pm.listAttr(bShpNode + '*.w', k=True, m=True):
        # duplicate new geometry.
        dupNewGeo = pm.duplicate(newGeo, rr=True, n=each)[0]
        pm.select(dupNewGeo, oldGeo)
        pm.runtime.CreateWrap()
        # on blendShape.
        pm.setAttr(bShpNode + '.' + each, 1)
        pm.runtime.DeleteHistory(dupNewGeo)
        pm.delete(oldGeo + 'Base')
        pm.setAttr(bShpNode + '.' + each, 0)
        ar_qui.ar_displayMessage('success', '% shape created' % each)
Example #25
0
def identifyCustomAttrs(control):
    '''
    Returns a list of attributes not made by the tool.
    
    Such attrs include 'space', 'stretch' (on ik) and so forth.
    
    
    :return: {'type': 'double', 'min': -3, 'max': 45}
    '''
    userKeyable = listAttr(control, ud=True, k=True)

    mainCtrl = core.findNode.leadController(control)

    func = mainCtrl.getCreateFunction()

    attrInfo = {}

    createAttrs = list(itertools.chain(func.fossilDynamicAttrs, ['space']))

    for attr in userKeyable:

        if attr not in createAttrs:

            attrInfo[attr] = {
                'attributeType': attributeQuery(attr, n=control, at=True)
            }

            min, max = control.attr(attr).getRange()

            if min is not None:
                attrInfo[attr]['min'] = min
            if max is not None:
                attrInfo[attr]['max'] = max

    return attrInfo
def addTargets(sourceObj=None, splittedTargets=list()):
    firstIndex = 0
    bsNode = getBlendShapeNode(sourceObj)

    if bsNode:
        appliedTargetNames = pm.listAttr(bsNode.w, m=True)

        firstIndex = nextFreeIndex(bsNode)
        for i, target in enumerate(splittedTargets):
            if target.name() in appliedTargetNames:
                delete_blendshape_target(bsNode.name(),
                                         getIndexByName(bsNode, target.name()))
                pm.aliasAttr(bsNode.name() + '.' + target.name(), rm=True)

            pm.blendShape(bsNode,
                          edit=True,
                          t=(sourceObj.name(), i + firstIndex, target.name(),
                             1.0))
            print('reapplying target{1} index {0}'.format(
                i + firstIndex, target.name()))
        pm.delete(splittedTargets)
    else:
        firstIndex = 0
        pm.blendShape(splittedTargets, sourceObj)
        pm.delete(splittedTargets)

    return firstIndex
Example #27
0
def ar_convertPerspCamToShotCam(cam, perspCam):
    """
    convert perspective cam as shot cam.
    cam transform node as constraint
    cam shape attributes connect.
    :param cam: string
    :param perspCam: string
    :return: perspCam
    """
    cam = pm.PyNode(cam)
    perspCam = pm.PyNode(perspCam)
    camShape = cam.getShape()
    prspShape = perspCam.getShape()

    camShapeAttrs = pm.listAttr(camShape)

    pm.parentConstraint(cam, perspCam)
    for each in camShapeAttrs:
        try:
            pm.connectAttr(camShape + '.' + each,
                           prspShape + '.' + each,
                           f=True)
        except UserWarning:
            pass
    return perspCam
Example #28
0
def get_io_names(robot_name, only_active=False):
    """
    Gets all IOs assigned to the given robot
    :param robot_name: string, name of selected robot
    :param only_active: bool, if True, removes IOs marked as "ignore"
    :return robots_ios: list, names of all IOs on robot
    """

    target_ctrl_path = mimic_utils.get_target_ctrl_path(robot_name)

    # Find all attributes on the target_CTRL categorized as 'io'
    robot_io_names = pm.listAttr(target_ctrl_path, category='io')

    # Remove parent attribute designation 'io_' from each IO name
    for i, io_name in enumerate(robot_io_names):
        robot_io_names[i] = io_name.replace('io_', '')

    # If only_active is True, remove IOs marked as "Ignore"
    if only_active:
        active_ios = [
            x for x in robot_io_names
            if not pm.getAttr(target_ctrl_path + '.' + x + '_ignore')
        ]

        robot_io_names = active_ios

    return robot_io_names
 def aiMeshLightDupe(self, orig, dupe):
     """
     Sets the object as a mesh light
     if the previous object was a mesh light
     (bug in arnold changes dupes to polymesh)
     """
     relatives = pm.listRelatives(orig,c=1)
     for m in relatives:
         if len(pm.listAttr(m, st='aiTranslator')) is 0:
             continue
         if str(m.getAttr('aiTranslator')) is not 'mesh_light':
             continue
         for d in pm.listRelatives(dupe, c=1):
             if len(pm.listAttr(m, st='aiTranslator')) is 0:
                 continue
             d.setAttr('aiTranslator', 'mesh_light')
Example #30
0
def spread():
    tmp = const(True)
    if tmp:
        objs = pm.ls(sl=True)
        cons = []
        subSpread(objs[-1], len(objs)-2)
        cons += pm.listRelatives(pm.ls(objs[-1]), ad=True, typ='constraint')
        attrs = []
        sel = -1
        for con in cons:
            attrs.append(pm.listAttr(con, ud=True))
        for con_count in range(len(cons)):
            if tmp:
                if sel+3 < len(objs) and con_count < len(objs)-1:
                    if objs[sel] != cons[con_count].split("_")[0]:
                        sel += 3
            attr = attrs[con_count]
            for x in range(len(attr)):
                pm.setAttr(objs[sel]+".spread", x)
                pm.setAttr(cons[con_count]+"."+attr[x], 1)
                for y in range(len(attr)):
                    if x != y:
                        pm.setAttr(cons[con_count]+"."+attr[y], 0)
                for z in range(len(attr)):
                    pm.setDrivenKeyframe(cons[con_count]+"."+attr[z], cd=objs[sel]+".spread")
def FTV_multiConnectAutoKeyableNonLocked(src, dest, attsExcept):
	'''connect every keyable and non locked attribute of src to dest (basically connect parameters from control)'''
	atts = pm.listAttr(src, k=True, u=True)
	for a in atts:
		if a in attsExcept:
			continue
		pm.connectAttr(src+'.'+a, dest+'.'+a)
Example #32
0
def selectKeyAttr():
    window = QtWidgets.QWidget(qt.getMayaWindow())
    window.setWindowFlags(QtCore.Qt.Window)
    window.resize(300, 500)
    layout = QtWidgets.QVBoxLayout(window)

    widget = QtWidgets.QPlainTextEdit(window)

    sels = pm.selected()

    for sel in sels:
        pm.select(sel)
        selLists = pm.listAttr(k=True)
        for selList in selLists:
            selAttr = pm.getAttr(sel + '.' + selList)
            print "'" + sel + "', '" + selList + "', '" + str(round(
                selAttr, 3)) + "'"
            widget.insertPlainText("'" + sel + "', '" + selList + "', '" +
                                   str(round(selAttr, 3)) + "'" + "\n")
        widget.insertPlainText("\n")
    layout.addWidget(widget)

    button = QtWidgets.QPushButton('print', window)
    layout.addWidget(button)

    button.clicked.connect(main)

    window.show()
def populateAttrMen(*args):
    if args[0].getText():
        args[1].deleteAllItems()
        for i in pm.listAttr(args[0].getText(), k=True):
            pm.menuItem(i,
                        p=args[1],
                        c=partial(fillAttrField, args[2], str(i)))
Example #34
0
    def poseExport(self, name, directory, screenshot=True):

        path = os.path.join(directory, '%s.json' % name)

        controlOnScene = self.controlFilter()

        for x in range(len(controlOnScene)):

            valueDic = {}

            parsedControl = str(controlOnScene[x].split('|')[-1])

            if parsedControl not in self.mainData:
                self.mainData[parsedControl] = []

            attrLst = pm.listAttr(controlOnScene[x], k=True, u=True)

            for attr in attrLst:
                attrParsed = str(attr)
                attrStr = getattr(controlOnScene[x], attr)
                attrValue = attrStr.get()

                valueDic[attrParsed] = attrValue

            self.mainData[parsedControl].append(valueDic)

        if screenshot:
            self.mainData['screenshot'] = self.poseScreenShot(
                name, directory=directory)

        with open(path, 'w') as out_file:

            json.dump(self.mainData, out_file)

        return path, name
def get_rman_attr(nodes, debug=False):
    """
    Returns the dictionary of primvar attribute found on the given nodes.

    :param nodes: (List of PyMel nodes) Nodes to query their primvar attributes.
    :param debug: (Boolean) Set True if you want to print out the result.
    """

    global EXISTING_ATTR
    for node in nodes:
        # Go through all attributes of the current node
        for attr in pm.listAttr(node):
            # Check for existance of each primvar attributes
            for attr_type in EXISTING_ATTR.keys():
                if attr_type in attr:
                    # If current attribute doesn't exist in the database
                    # create a list for it
                    if attr not in EXISTING_ATTR[attr_type]:
                        EXISTING_ATTR[attr_type][attr] = []
                        if debug:
                            logging.info("Created the '{}' list on '{}' "
                                         "primvar database".format(attr,
                                                                   attr_type))
                    # Add the founded attribute to the list
                    EXISTING_ATTR[attr_type][attr].append(node)
                    if debug:
                        logging.info("Found '{}' on '{}'".format(attr, node))
    return EXISTING_ATTR
Example #36
0
def import_network(_network):
    if not _network.hasAttr('_class'):
        log.error(
            '[importFromNetwork] Network dont have mandatory attribute _class')
        raise AttributeError

    cls = _network.getAttr('_class').split('.')[-1]
    obj = core.create_class_instance(cls)
    if obj is None:
        return None
    obj._network = _network

    for key in pymel.listAttr(_network, userDefined=True):
        if '_' != key[0]:  # Variables starting with '_' are private
            #logging.debug('Importing attribute {0} from {1}'.format(key, _network.name()))
            val = _getNetworkAttr(_network.attr(key))
            #if hasattr(obj, key):
            setattr(obj, key, val)
            #else:
            #    #logging.debug("Can't set attribute {0} to {1}, attribute does not exists".format(key, obj))

    # Update network _uid to the current python variable context


#    if _network.hasAttr('_uid'):
#        _network._uid.set(id(obj))

    return obj
Example #37
0
def myGetAttr(node, attr, default=False):
    data = default
    isAttrName = pc.listAttr(str(node), st=attr)
    if isAttrName:
        data = cmds.getAttr(str(node) + '.' + attr)

    return data
Example #38
0
    def deleteTag(self):
        self.tagObj.deleteAllTags()

        #maya2scenegraphXML.deleteSgxmlAttrs("|assets")
        l_maya2017_ar = []
        for n_name in self.d_taged_nodes['ignored'].keys(
        ) + self.d_taged_nodes['ref'].keys(
        ) + self.d_taged_nodes['no_bound'].keys():
            try:
                m = pm.PyNode(n_name)
                if not (MAYA_VERSION in ['2017'] and self.in_ar_tree(n_name)):
                    attributes = pm.listAttr(m, userDefined=True)
                    for attr in attributes:
                        if 'arbAttr_' in attr or 'sgxml_' in attr:
                            m.deleteAttr(attr)
                else:
                    if m.nodeType() == 'assemblyReference':
                        l_maya2017_ar.append(n_name)
            except:
                print traceback.format_exc()

        if len(l_maya2017_ar) > 0:
            self.clean_ar(l_maya2017_ar)

        return
Example #39
0
def AddAttr(Ctrl, LongName, AttrType, *args):
    CTL = pm.ls(Ctrl)
    CTLAttr = pm.listAttr(CTL)
    for a in CTLAttr:
        if a == LongName:
            pm.warning('Already Have the Attribute')
            pm.setAttr(Ctrl + '.' + a, k=1)
            return
        else:
            continue
    if AttrType == 'enum':
        pm.addAttr(CTL[0], ln=LongName, at=AttrType, en=args)
        pm.setAttr(Ctrl + '.' + LongName, k=1)

    elif AttrType == 'title':
        pm.addAttr(CTL[0], ln=LongName, nn=LongName, at='enum', en=args, k=1)
        pm.setAttr(Ctrl + '.' + LongName, cb=1)
    elif AttrType == 'bool':
        pm.addAttr(CTL[0], ln=LongName, at=AttrType)
        pm.setAttr(Ctrl + '.' + LongName, e=1, k=1)
    else:
        pm.addAttr(CTL[0],
                   ln=LongName,
                   at=AttrType,
                   min=args[0],
                   max=args[1],
                   dv=0,
                   k=1)
        pm.setAttr(Ctrl + '.' + LongName, cb=1)
Example #40
0
def import_network(_network):
    if not _network.hasAttr('_class'):
        log.error('[importFromNetwork] Network dont have mandatory attribute _class')
        raise AttributeError

    cls = _network.getAttr('_class').split('.')[-1]
    obj = core.create_class_instance(cls)
    if obj is None:
        return None
    obj._network = _network

    for key in pymel.listAttr(_network, userDefined=True):
        if '_' != key[0]: # Variables starting with '_' are private
            #logging.debug('Importing attribute {0} from {1}'.format(key, _network.name()))
            val = _getNetworkAttr(_network.attr(key))
            #if hasattr(obj, key):
            setattr(obj, key, val)
            #else:
            #    #logging.debug("Can't set attribute {0} to {1}, attribute does not exists".format(key, obj))

    # Update network _uid to the current python variable context
    if _network.hasAttr('_uid'):
        _network._uid.set(id(obj))

    return obj
    def attrChanged(self, data, node, attr, type):
        isAttr = pc.listAttr(node, st=attr)
        if not isAttr:
            addvRayAttrs(node, type)
        cmds.setAttr(node + '.' + attr, data)

        obj = self.sender()
        obj.setStyleSheet(self.grayColorSpin)
Example #42
0
 def get_blendshapes(source):
     """ This function will find the blendShapes on the source mesh
     Args:
         None
     Returns [pm.nt.BlendShape]: list of blendshapes attached to source mesh
     """
     facial_shapes = max([blend for blend in pm.ls(type='blendShape')], key=lambda x: len(x.listAliases()))
     shapes = pm.listAttr(facial_shapes + '.w', m=True)
     return [facial_shapes, shapes]
Example #43
0
 def listAttr(self):
     
     self.objectList = pm.ls(sl=1)
     
     obj = self.objectList[-1]
             
     objAttrList = pm.listAttr(obj, s=1)
     
     self.weightListWidget.clear()
     self.weightListWidget.addItems(objAttrList) 
Example #44
0
    def __enter__(self):

        self._lock = self._node.isLocked()
        self._node.unlock()

        if isinstance(self._node, pm.nt.DependNode):

            self._attributes = [self._node.attr(attribute) for attribute in pm.listAttr(self._node, locked = True)]
            for attribute in self._attributes:
                attribute.unlock()
def cbsTrans(*args, **kwargs):
    
    sculptTrans = kwargs.setdefault('sculptTrans', pm.ls(sl=True)[0])# (string) The mesh to get the tweak edits extracted from
    shape = kwargs.setdefault('shape') # (string) The shape node of the sculptTrans node
    tweak = kwargs.setdefault('tweak') # (string) The tweak node that is going to be cleared
    skin = kwargs.setdefault('skin') # (string) The skinCluster node that drives the base mesh
    base = kwargs.setdefault('base') # (string) The base mesh for the character

    #get some info
    sculptTrans, shape, tweak, skin =  gatherInfo(sculptTrans, shape, tweak, skin)
    if not 'baseTransform' in pm.listAttr(sculptTrans, ud=True):
        pm.error('This model has not been prepared for sculpting. If you accidentally started, simply run Clear Tweaks to extract what has been done')
    if not base:
        base = sculptTrans.baseTransform.get()

    baseRef = sculptTrans.baseReference.get()

    #turn off a couple things that might mess with things
    pm.symmetricModelling(e=True, symmetry= False)
    pm.softSelect(e=True, softSelectEnabled=False)

    #first, let's unlock the guys from the old function
    pm.lockNode(base, l=False)
    pm.lockNode(sculptTrans, l=False)
    pm.setAttr('%s.v'%base, True)

    #extract from the sculpted shape
    newShape = clearTweaks(base=base, tweak=tweak)

    pm.delete(sculptTrans)

    newOrig = pm.duplicate(base, n='%s_editReference'%base)[0]
    pm.connectAttr(('%s.outMesh' %newOrig.getShapes()[1]), ('%s.inMesh' %newOrig.getShape()))

    pm.select(cl=True)
    deviation = False
    for v in range(pm.polyEvaluate(base, v=True)):
        refPos = pm.xform('%s.vtx[%i]'%(baseRef, v), q=True, t=True)
        adjPos = pm.xform('%s.vtx[%i]'%(newOrig, v), q=True, t=True)

        if not refPos == adjPos:
            deviation=True
            pm.move('%s.vtx[%i]' %(newShape, v), (refPos[0]-adjPos[0], refPos[1]-adjPos[1], refPos[2]-adjPos[2]), r=True)
            pm.move('%s.vtx[%i]'%(base, v), (refPos[0]-adjPos[0], refPos[1]-adjPos[1], refPos[2]-adjPos[2]), os=True, r=True)
            pm.select('%s.vtx[%i]' %(base, v), add=True)

    if deviation:
        pm.warning('It appears there were issues extracting from the mesh, steps have been taken to try and remedy, but unexpected results may occur')

    #apply a texture to the new shape.
    pm.select(newShape, r=True)
    pm.sets('initialShadingGroup', e=True, forceElement=True)

    pm.delete(newOrig, baseRef)
    return newShape
Example #46
0
def __lockHideTransform__(obj, lock=True, hide=True, channel=['t', 'r', 's', 'v'], channelBox=False):
    # inversing hide
    if hide:
        hide=False
    else:
        hide=True
    
    if channelBox:
        chNew = []
        attrs = pmc.listAttr(obj, keyable=True)
        attrs.extend(pmc.listAttr(obj, channelBox=True))
        for attr in attrs:
            tmp = pmc.PyNode(obj+'.'+attr).getParent()
            if tmp:
                if tmp.shortName() not in chNew:
                    chNew.append(tmp.shortName())
            else:
                chNew.append(attr)
        channel = chNew
    
    # loop on each channel given
    for chan in channel:
        # get pynode about attribut
        try:
            ch = pmc.PyNode(obj+'.'+chan)
        except:
            vp.vPrint('%s has no channel called %s' % (obj.name(), chan), 1)
            ch = None
        if ch:
            # try to get his children
            try:
                children = ch.getChildren()
            except:
                children = []
            # locking and hidding
            for child in children:
                child.showInChannelBox(hide)
                child.setLocked(lock)
                child.setKeyable(hide)
            ch.showInChannelBox(hide) 
            ch.setLocked(lock)
            ch.setKeyable(hide)
 def write_info(self):
     
     self.info_field.setText('')
     
     node = self.connections_list.getSelectItem()[0]
     if self.check_box.getValue() == 1:
         pm.select(node)
     
     node_type = pm.nodeType(node)
     #print node_type
     
     
     if node_type == 'layeredTexture':
         result = self.get_layered_texture_attrs(self.connections_dict[node])
         for r in result:
             self.info_field.insertText('%s\n' % (r) )
             
     if node_type == 'ramp':
         result = self.get_ramp_attrs(node)
         for r in result:
             self.info_field.insertText('%s\n' % (r) )
             
     if node_type == 'noise':
         result = self.get_noise_attrs(node)
         for r in result:
             self.info_field.insertText('%s\n' % (r) )
             
     if node_type != 'ramp' and node_type != 'noise':
         if self.attr_check_box.getValue() == 1:
             attrs = pm.listAttr('%s' % (node), write= True, settable= True,
                         keyable= True)
             
         if self.attr_check_box.getValue() == 0:
             attrs = pm.listAttr('%s' % (node), write= True, settable= True,
                         keyable= True, inUse= True)
             
         for attr in attrs:
             try:
                 value = pm.getAttr('%s.%s' % (node, attr))
                 self.info_field.insertText('%s: %s\n' % (attr, value))
             except:
                 pass
    def hold_avars(self):
        """
        Create a network to hold all the avars complex connection.
        This prevent Maya from deleting our connection when unbuilding.
        """
        if self.grp_rig is None or not self.grp_rig.exists():
            self.warning("Can't hold avars, invalid grp_rig in {0}!".format(self))
            return

        self.avar_network = pymel.createNode(
            'transform',
            name=self.get_nomenclature_rig().resolve('avarBackup')
        )
        self.rig.hold_node(self.avar_network)
        self.add_avars(self.avar_network)

        def attr_have_animcurve_input(attr):
            attr_input = next(iter(attr.inputs(plugs=True, skipConversionNodes=True)), None)
            if attr_input is None:
                return False

            attr_input_node = attr_input.node()

            if isinstance(attr_input_node, pymel.nodetypes.AnimCurve):
                return True

            if isinstance(attr_input_node, pymel.nodetypes.BlendWeighted):
                for blendweighted_input in attr_input_node.input:
                    if attr_have_animcurve_input(blendweighted_input):
                        return True

            return False

        attrs = pymel.listAttr(self.avar_network, userDefined=True)
        for attr_name in attrs:
            if not self.grp_rig.hasAttr(attr_name):
                self.debug("Cannot hold missing attribute {0} in {1}".format(attr_name, self.grp_rig))
                continue

            # attr_name = attr.longName()
            attr_src = self.grp_rig.attr(attr_name)
            attr_dst = self.avar_network.attr(attr_name)
            # libAttr.transfer_connections(attr_src, attr_dst)

            # if attr_have_animcurve_input(attr_src):
            attr_src_inn = next(iter(attr_src.inputs(plugs=True)), None)
            if attr_src_inn:
                pymel.disconnectAttr(attr_src_inn, attr_src)
                pymel.connectAttr(attr_src_inn, attr_dst)

            # Transfer output connections
            for attr_src_out in attr_src.outputs(plugs=True):
                pymel.disconnectAttr(attr_src, attr_src_out)
                pymel.connectAttr(attr_dst, attr_src_out)
Example #49
0
def list_attributes(node, typ="*"):
	results = []

	for a in pm.listAttr(node, w=True, c=True):
		try:
			a_type = pm.getAttr("%s.%s" % (node, a), type=True)
			if a_type == typ or typ == "*":
				results.append(a)
		except Exception, e:
			# Swallow this error, it is thrown by Maya for some plugs.
			pass
Example #50
0
def mirrorAnim():
	selection = pm.ls(sl=True)
	if len(selection) != 2:
		pm.warning('Need exactly two objects to mirror')
		return

	try:
		namespace = selection[0].namespace()
	except:
		namespace = ''
		

	try:
		sourceHolder = pm.ls(namespace + '*_SOURCE_HOLDER')[0]
		targetHolder = pm.ls(namespace + '*_TARGET_HOLDER')[0]
	except:
		pm.warning('No holders found to mirror animations')
		return
	source = pm.ls(sourceHolder.name().replace('_SOURCE_HOLDER',''),type='transform')[0]
	target= pm.ls(targetHolder.name().replace('_TARGET_HOLDER',''),type='transform')[0]
	
	sourceHolderAttr = pm.listAttr(sourceHolder,ud=True)
	targetHolderAttr = pm.listAttr(targetHolder,ud=True)
	
	for attr in sourceHolderAttr:
		print attr
		reverse = 1
		if (attr.find('translateX') > 0) or (attr.find('rotateY') > 0) or (attr.find('KneeTwist') > 0) or (attr.find('rotateZ') > 0):
			reverse = -1
		target.attr(attr.replace('__','')).set(sourceHolder.attr(attr).get() * reverse)
		
	for attr in targetHolderAttr:
		reverse = 1
		if (attr.find('translateX') > 0) or (attr.find('rotateY') > 0) or (attr.find('KneeTwist') > 0) or (attr.find('rotateZ') > 0):
			reverse = -1		
		source.attr(attr.replace('__','')).set(targetHolder.attr(attr).get() * reverse)
		
	pm.delete([sourceHolder,targetHolder])

	pm.setKeyframe(source)
	pm.setKeyframe(target)
Example #51
0
    def allKeyableAttrs(self, keyable):
        """
        returns a list with all keyable attributes
        """
        keyableAttrs = []

        for node in keyable:
            attrs = pm.listAttr(node, k=1, u=1)
            for attr in attrs:
                keyableAttrs.append(str(node.name()) + "." + str(attr))

        return keyableAttrs
Example #52
0
 def load_blendShapeNode(self):
     self.blendShapeNode = self.widgets["blendShapeNode_textField"].getText()
     self.targets = pm.listAttr(self.blendShapeNode + ".w", m=True)
     self.widgets["blendShape_textScroll"].removeAll()
     self.widgets["mask_textScroll"].removeAll()
     self.widgets["blendShape_textScroll"].append([x for x in self.targets if not x.startswith('mask_')])
     self.widgets["mask_textScroll"].append([x for x in self.targets if x.startswith('mask_')])
     
     pm.select(self.object)
     pm.mel.eval('ArtPaintBlendShapeWeightsToolOptions;')
     pm.mel.eval('artSetToolAndSelectAttr( "artAttrCtx", "blendShape.%s.paintTargetWeights");' %self.blendShapeNode)
     pm.mel.eval('artAttrBlendShapeValues artAttrBlendShapeContext;')        
Example #53
0
def get_cb_sel_attrs(transform=None):
    """ Gets the currently selected attributes from the channel box or all keyable as defaults
    Args:
        transform (pm.nt.Transform): returns all keyable attributes on transform
    Returns [str]: List of attributes in string form
    """
    if transform:
        return pm.listAttr(transform, q=True, k=True)
    pm.language.melGlobals.initVar('string', 'gChannelBoxName')
    attrs = pm.channelBox(pm.language.melGlobals['gChannelBoxName'], q=True, sma=True)
    if not attrs:
        attrs=['tx','ty','tz','rx','ry','rz','sx','sy','sz','v']
    return attrs
Example #54
0
 def fetch_avars(self):
     """
     If a previously created network have be created holding avars connection,
     we'll transfert thoses connections back to the grp_rig node.
     Note that the avars have to been added to the grp_rig before..
     """
     if libPymel.is_valid_PyNode(self.avar_network):
         for attr_name in pymel.listAttr(self.avar_network, userDefined=True):
             attr_src = self.avar_network.attr(attr_name)
             attr_dst = self.grp_rig.attr(attr_name)
             libAttr.transfer_connections(attr_src, attr_dst)
         pymel.delete(self.avar_network)
         self.avar_network = None
def buildSelectedItemsDictionary(selectedList):
	
	dbInsertString = ''
	dbInsertDict = {}
	attrList = []
	
	
	#Iterate items of selectedList and get list of not all Attrs != Hidden or locked
	for selectedItem in selectedList:
		attrList.append(pm.listAttr(selectedItem, k = True, u = True))
	
			
	#buildDbInsertDict
	#for item in selectedList
	for selectedListIndex in range(0, len(selectedList)):
		
		#for attrList in attrList
		#build attrAndValueDict
		attrAndValueDict = {}
		for attribute in attrList[selectedListIndex]:
			attrAndValueDict[attribute] = pm.getAttr(selectedList[selectedListIndex].name() +'.' +attribute)
		
		
		#if len of namespace is >1 that means there is a namespace
		#else just get item[0]
		if(len(selectedList[selectedListIndex].name().split(':')) > 1):
			
			#get list of names splitted at ':'
			selectedItemNameList = selectedList[selectedListIndex].name().split(':')
			#Remove first item
			selectedItemNameList.pop(0)
			
			#Iterate selectedItemNameList and concatenate to final string
			selectedItemName = ''
			for splitResult in selectedItemNameList:
				selectedItemName += splitResult
				#Append : sign if splitResult is not last entry of selectedItemNameList
				if not (splitResult == selectedItemNameList[-1]): 
					selectedItemName += ':'
			
		#Else just take item[0]
		else: selectedItemName = selectedList[selectedListIndex].name().split(':')[0]
			
		
		#Add dict of attrs and values to dbInsertDict
		dbInsertDict[selectedItemName] = attrAndValueDict
	
	
	return dbInsertDict
Example #56
0
    def listAttr(self):

        self.objectList = pm.ls(sl=1)
        
        if not len(self.objectList):
            return 0

        self.obj = self.objectList[-1]
                
        self.objAttrList = pm.listAttr(self.obj, s=1)
        
        self.weightListWidget.clear()
        self.weightListWidget.addItems(self.objAttrList)
        
        self.nodeLineEdit.setText(self.obj.nodeType())
 def clearTemp(self):
     for x in self.tempControls:
         node=""
         for x in pm.listAttr(controller, ud=True):
             if x=="driven":
                 node=pm.listConnections("{0}.driven".format(str(controller)),s=1,d=0,p=0)[0]
                 break
         pm.select(node,r=1)
         pm.delete(cn=1)
         pm.delete(x.getParent())
         node.t.set(0,0,0)
         node.r.set(0,0,0)
         node.s.set(1,1,1)
                      
     self.tempControls=[]