def copy_channelbox_attributes(): # copy values from selected main and shape attributes main_channels = pm.channelBox('mainChannelBox', q=True, selectedMainAttributes=True) shape_channels = pm.channelBox('mainChannelBox', q=True, selectedShapeAttributes=True) # input_attr = pm.channelBox('mainChannelBox', q=True, selectedHistoryAttributes=True) # output_attr = pm.channelBox('mainChannelBox', q=True, selectedOutputAttributes=True) clipboard = collections.OrderedDict() for obj in pm.ls(orderedSelection=True): main_attr = {} shape_attr = {} if main_channels: for at in main_channels: if pm.hasAttr(obj, at): main_attr[str(at)] = pm.getAttr(obj + '.' + at) shape_node = obj.getShape() if shape_channels: for at in shape_channels: if pm.hasAttr(obj, at): shape_attr[str(at)] = pm.getAttr(shape_node + '.' + at) clipboard[str(obj.fullPath())] = { 'main_attributes': main_attr, 'shape_attributes': shape_attr } return clipboard
def get_selected_channels_full_path(): """Get the selected channels full path from channel box This function will collect channels from any area of the channel box. This include, Main, shape, input and output Returns: list: list of channels full path """ attrs = [] node = pm.ls(sl=True) if node: node = node[0] collect_attrs(node, attrs, pm.channelBox(get_channelBox(), q=True, sma=True)) # if the attr is from shape node, we need to search in all shapes collect_attrs(node, attrs, pm.channelBox(get_channelBox(), q=True, ssa=True), shapes=True) collect_attrs(node, attrs, pm.channelBox(get_channelBox(), q=True, sha=True)) collect_attrs(node, attrs, pm.channelBox(get_channelBox(), q=True, soa=True)) return attrs
def reset_attrs(node=None): if not node: for node in pm.selected(): reset_attrs(node) return attrs = [] sel_attrs = pm.channelBox('mainChannelBox', q=True, selectedMainAttributes=True) if sel_attrs: attrs += sel_attrs sel_attrs = pm.channelBox('mainChannelBox', q=True, selectedShapeAttributes=True) if sel_attrs: attrs += sel_attrs sel_attrs = pm.channelBox('mainChannelBox', q=True, selectedHistoryAttributes=True) if sel_attrs: attrs += sel_attrs sel_attrs = pm.channelBox('mainChannelBox', q=True, selectedOutputAttributes=True) if sel_attrs: attrs += sel_attrs keyable_attrs = [a.attrName() for a in node.listAttr(keyable=True, shortNames=True)] if not attrs: attrs = keyable_attrs for attr in attrs: if attr in keyable_attrs: if node.getAttr(attr, settable=True): default_value = pm.attributeQuery(attr, listDefault=True, node=node.name())[0] node.setAttr(attr, default_value)
def createPanel(): pm.window(windowID, title='Animation Tools', width=500) form = pm.formLayout(numberOfDivisions=50) pm.columnLayout(adjustableColumn=True, columnAttach=('both', 5), rowSpacing=10, columnWidth=250) pm.autoKeyframe(state=True) pm.text(label='Channel Box') pm.channelBox('myChannelBox') #this section shows the current frame, start frame and the end frame. cmds.rowColumnLayout(w=500, h=100, nc=2, cs=[(1, 30), (2, 100), (3, 30)], rs=(1, 5)) pm.text(label='Current Frame') pm.textField(text=pm.currentTime(query=True)) pm.text(label='Start Frame') pm.textField(text=cmds.playbackOptions(q=True, min=True)) pm.text(label='End Frame') pm.textField(text=cmds.playbackOptions(q=True, max=True)) cmds.setParent('..') seprator1 = cmds.separator(w=400, h=10) cmds.rowColumnLayout(w=500, h=100, nc=2, cs=[(1, 30), (2, 100), (3, 30), (4, 30), (5, 100), (6, 30)], rs=(1, 5)) pm.button(label='Set Keyframe', command=SetKeyframeFromUI) pm.button(label='Copy Keyframe', command=copyKeyframe) pm.button(label='Paste Keyframe', command=pasteKeyframe) pm.button(label='Playblast', command=PlayblastVideo) pm.button(label='Open Graph Editor', command=animationEditor) pm.button(label='Show/Hide Nurbs Curves', command=ToggleNurbsCurves) cmds.setParent('..') seprator1 = cmds.separator(w=400, h=10) pm.text(label='') pm.formLayout(form, edit=True) allowedAreas = ['right', 'left'] cmds.dockControl('Animation Tools', a='right', con=windowID, aa=allowedAreas)
def getAttrsFromChannelbox(): ''' 채널박스에서 선택된 어트리뷰트 이름 리턴 블렌드 쉐입은 잘 안됨..ㅠㅠㅠ @return: 어트리뷰트 리스트 리턴 ''' mainObjs = pm.channelBox(pm.melGlobals['gChannelBoxName'], q=True, mainObjectList=True) mainAttrs = pm.channelBox(pm.melGlobals['gChannelBoxName'], q=True, selectedMainAttributes=True) shapeObjs = pm.channelBox(pm.melGlobals['gChannelBoxName'], q=True, shapeObjectList=True) shapeAttrs = pm.channelBox(pm.melGlobals['gChannelBoxName'], q=True, selectedShapeAttributes=True) histObjs = pm.channelBox(pm.melGlobals['gChannelBoxName'], q=True, historyObjectList=True) histAttrs = pm.channelBox(pm.melGlobals['gChannelBoxName'], q=True, selectedHistoryAttributes=True) outputObjs = pm.channelBox(pm.melGlobals['gChannelBoxName'], q=True, outputObjectList=True) outputAttrs = pm.channelBox(pm.melGlobals['gChannelBoxName'], q=True, selectedOutputAttributes=True) shortNames = [] for pair in ((mainObjs, mainAttrs), (shapeObjs, shapeAttrs), (histObjs, histAttrs), (outputObjs, outputAttrs)): objs, attrs = pair # print pair if attrs: for obj in objs: for attr in attrs: shortNames.append('%s.%s' % (obj, attr)) longNames = [] for pair in ((mainObjs, mainAttrs), (shapeObjs, shapeAttrs), (histObjs, histAttrs), (outputObjs, outputAttrs)): objs, attrs = pair # print pair if attrs is not None: for node in objs: result = [ objs[0] + '.' + pm.attributeQuery(attr, n=node, ln=True) for attr in attrs ] longNames.extend(result) longNames = list(set(longNames)) return shortNames
def aw_copyKeys(source, targets, randomShift=0, increment=0, mo=False): '''This script will copy the keyframes from source to targets from selected channel box attributes Args: source (mayaObject): Source object with animation targets (list[mayaObject]): Copy To Targets randomShift (int): Randomly shift by x, 0 is no shift increment (int): Increment value through selection by x, 0 is no increment mo (Boolean): Maintain the Offset or not Returns (void): no return Example: aw_copyKeys(pm.PyNode('pSphere1'), pm.ls(sl=True), randomShift=0, increment=1, mo=True) ''' args=targets animSrc=source #Determine Selected attributes from channelbox pm.language.melGlobals.initVar( 'string', 'gChannelBoxName' ) attrs = pm.channelBox(pm.language.melGlobals['gChannelBoxName'],q=True,sma=True) #Copy Keys from the Graph Editor for main object (deselect other objects before copying) if not attrs: print 'Nothing selected in channel box, setting copy attributes to default all' attrs=['tx','ty','tz','rx','ry','rz','sx','sy','sz','v'] for arg,i in zip(args, range(len(args))): if arg != animSrc: for attr in attrs: pm.copyKey(animSrc, time = (pm.playbackOptions(q=True,ast=True), pm.playbackOptions(q=True,aet=True)), at=attr,option="curve", hierarchy='none') #Paste keys to all objects depending on attributes selected from the channelBox offsetCheck = attr in ['tx','ty','tz','rx','ry','rz'] offsetSeed = ((i+1) * increment) + int(math.floor( random.random() * randomShift)) pm.pasteKey(arg, option='insert', valueOffset=((offsetCheck * mo) * (arg.attr(attr).get() - animSrc.attr(attr).get())), copies=True, connect=True, at=attr, timeOffset=offsetSeed)
def BreakConnection(self): try: selAttrs = [ x for x in pm.channelBox( "mainChannelBox", q=1, selectedMainAttributes=1) ] param = [x for x in selAttrs] sub = len(pm.selected()) for i in range(0, sub): for each in param: sub1 = str(pm.selected()[i]) sub2 = str(each) fullsub = sub1 + '.' + sub2 attribute = str(fullsub) destinationAttrs = mc.listConnections( attribute, plugs=True, source=False) or [] sourceAttrs = mc.listConnections( attribute, plugs=True, destination=False) or [] for destAttr in destinationAttrs: mc.disconnectAttr(attribute, destAttr) for srcAttr in sourceAttrs: mc.disconnectAttr(srcAttr, attribute) sys.stdout.write('// Result: Break Connection //') except IndexError: pass
def ChnInOut(inoutType='in'): if len(pm.ls(sl=1)) == 0: print 'pz select Obj' return 0 obj = pm.ls(sl=1)[0] channels = pm.channelBox('mainChannelBox', q = 1, sma = 1) objChannels = map(obj.attr, channels) inputList = [] outputList = [] for x in objChannels: if x.isConnected(): inputList.append(x.inputs()) else: inputList.append(None) if not len(x.outputs()) <= 0: outputList.append(x.outputs) else: outputList.append(None) print inputList print outputList if inoutType == 'in': pm.select(inputList, r=1) return inputList else: return outputList
def AddInputs(self): try: selAttrs = [ x for x in pm.channelBox( "mainChannelBox", q=1, selectedMainAttributes=1) ] # UI management self.inputs1 = pm.textFieldGrp(self.Input1, e=True, tx=selAttrs[0]) try: self.inputs2 = pm.textFieldGrp(self.Input2, e=True, tx=selAttrs[1]) except IndexError: pass try: self.inputs3 = pm.textFieldGrp(self.Input3, e=True, tx=selAttrs[2]) except IndexError: pass except TypeError: pass
def getSelectedChannels(): # Get the currently selected attributes from the main channelbox. # From here: http://forums.cgsociety.org/showthread.php?f=89&t=892246&highlight=main+channelbox channelBox = pm.mel.eval('global string $gChannelBoxName; $temp=$gChannelBoxName;') #fetch maya's main channelbox attrs = pm.channelBox(channelBox, q=1, sma=1) if not attrs: return [] return attrs
def LockHideAttr( **kwargs ): objs = kwargs.setdefault( 'objs', pm.ls( sl=True ) ) objs = pm.ls( objs ) attrs = kwargs.setdefault( 'attrs', 'all' ) # if any attribute is selected in channelBox, lock those attributes only selectedAttrs = pm.channelBox( "mainChannelBox", q=True, selectedMainAttributes=True ) if selectedAttrs : attrs=selectedAttrs if not objs: pm.warning('ehm_tools...LockHideAttr: objs argument needs some object to operate on. No object found!' ) for obj in objs: if attrs == "all" : pm.setAttr (obj.tx , lock = True , keyable = False , channelBox = False) pm.setAttr (obj.ty , lock = True , keyable = False , channelBox = False) pm.setAttr (obj.tz , lock = True , keyable = False , channelBox = False) pm.setAttr (obj.rx , lock = True , keyable = False , channelBox = False) pm.setAttr (obj.ry , lock = True , keyable = False , channelBox = False) pm.setAttr (obj.rz , lock = True , keyable = False , channelBox = False) pm.setAttr (obj.sx , lock = True , keyable = False , channelBox = False) pm.setAttr (obj.sy , lock = True , keyable = False , channelBox = False) pm.setAttr (obj.sz , lock = True , keyable = False , channelBox = False) pm.setAttr (obj.v , lock = True , keyable = False , channelBox = False) elif attrs == "t" : pm.setAttr ( obj.tx ,lock=True , keyable=False , cb=False) pm.setAttr ( obj.ty ,lock=True , keyable=False , cb=False) pm.setAttr ( obj.tz ,lock=True , keyable=False , cb=False) elif attrs == "r" : pm.setAttr ( obj.rx ,lock=True , keyable=False , cb=False) pm.setAttr ( obj.ry ,lock=True , keyable=False , cb=False) pm.setAttr ( obj.rz ,lock=True , keyable=False , cb=False) elif attrs == "s" : pm.setAttr ( obj.sx ,lock=True , keyable=False , cb=False) pm.setAttr ( obj.sy ,lock=True , keyable=False , cb=False) pm.setAttr ( obj.sz ,lock=True , keyable=False , cb=False) elif attrs == "v" : # lock visibility pm.setAttr ( obj.v ,lock=True , keyable=False , cb=False) elif attrs == "vv" : # hide the object and lock visibility pm.setAttr ( obj.v , False ,lock=True , keyable=False , cb=False) elif isinstance(attrs,list): for attr in attrs: pm.setAttr ( obj.attr(attr) ,lock=True , keyable=False , cb=False) else: pm.setAttr ( obj.attr(attrs) ,lock=True , keyable=False , cb=False)
def get_selected_channels(): top_attr = pm.channelBox('mainChannelBox', q=True, selectedMainAttributes=True) shape_attr = pm.channelBox('mainChannelBox', q=True, selectedShapeAttributes=True) input_attr = pm.channelBox('mainChannelBox', q=True, selectedHistoryAttributes=True) output_attr = pm.channelBox('mainChannelBox', q=True, selectedOutputAttributes=True) print top_attr print shape_attr print input_attr print output_attr
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")
def assign_input_shape(self, textField): selected_attrs = pm.channelBox("mainChannelBox", q=True, sma=True) if not selected_attrs: pm.warning("no attribute selected, aborting...") return selectd_object = pm.selected() input_shape = "%s.%s" % (selectd_object[0], selected_attrs[0]) textField.setText(input_shape)
def initUI(self): self.setMinimumSize(200, 100) # layout self.setLayout(QtGui.QVBoxLayout()) self.layout().setSpacing(0) self.layout().setContentsMargins(2, 2, 2, 2) self.channelBox = pm.channelBox('channelBox') pySideChannelBox = utils.mayaWindowToPySideWidget(self.channelBox) self.layout().addWidget(pySideChannelBox)
def get_selected_attributes(): """ Get the selected attributes in the ChannelBox. If there are not attributes selected, this method returns a empty list. :return: list with the selected attributes. """ attrs = pm.channelBox('mainChannelBox', q=True, sma=True) if not attrs: return [] return attrs
def mute_toggle(): """mute/unmute selected channel box channels on all selected controls""" selection = pm.ls(sl=True) channels = pm.channelBox('mainChannelBox', q=True, selectedMainAttributes=True) for sel in selection: for channel in channels: if pm.mute('{}.{}'.format(sel.name(), channel), query=True): pm.mute('{}.{}'.format(sel.name(), channel), disable=True) else: pm.mute('{}.{}'.format(sel.name(), channel))
def clearChannelBox(): '''Deselects the channelBox attributes.''' try: # I hear that the select flag was added in Maya 2016 Extension 2 pm.channelBox( pm.melGlobals['gChannelBoxName'], select=None, edit=True) except TypeError: # ## Legacy Approach. # Since Maya does not provide direct access to channel box # selection, we need to trick Maya into de-selecting channel box # attributes by reselecting the current object selection. selected = cmd.ls(sl=1) if selected: cmd.select(clear=1) # We must defer the re-selection, or Maya won't refresh the gui. # The refresh() command won't work because that only refreshes # the viewport (as far as I know). The "channelBox -update" # command does nothing. cmd.evalDeferred(lambda: cmd.select(selected))
def get_selected_cb_attrs(): """Return a list (in pymel attr form) of whatever attributes are selected in the main channel box.""" # these are the different flags for channelBox function (for some reason) cb_types = ("sma", "ssa", "sha", "soa") sel_attrs = [] for t in cb_types: sel = pmc.channelBox("mainChannelBox", q=True, **{t: True}) if sel: sel_attrs.extend(sel) return find_cb_attrs(sel_attrs)
def hudAdd(): section=5 hudPrefix = 'HUD_cbCustom_' resultCb=[] watchList = hud_parseWatchList() hubRem() sel=pm.ls(sl=True) if sel and (pm.channelBox('mainChannelBox',q=True, sma=True) or pm.channelBox('mainChannelBox',q=True, sha=True, soa=True, ssa=True)): for obj in sel: listAttrs = [] if pm.channelBox('mainChannelBox',q=True, sma=True): listAttrs += [pm.PyNode(obj+'.'+attr) for attr in pm.channelBox('mainChannelBox',q=True, sma=True)] if pm.channelBox('mainChannelBox',q=True, sha=True, soa=True, ssa=True): listAttrs += [pm.PyNode(obj+'.'+attr) for attr in pm.channelBox('mainChannelBox',q=True, sha=True, soa=True, ssa=True)] if listAttrs: for listAttr in listAttrs: watchList.append(listAttr) else: return False result = cbChannelsHUD(watchList) if result: #print result.keys() for key in result: hudName = hudPrefix+key pm.headsUpDisplay(hudName, section=section, block=pm.headsUpDisplay(nfb=section), blockSize = 'medium', command = "cbChannelsHUD_parse(\"%s\")"%key, attachToRefresh=True)
def listChannelBoxSelection(self): selAttr = pm.channelBox('mainChannelBox', q=1, sma=1) selObj = pm.ls(selection=1) newList = [] for obj in selObj: for attribute in selAttr: if(obj.attr(attribute).exists()): keyable = obj.attr(attribute).get(k=1) settable = obj.attr(attribute).get(se=1) #TODO:Make sure it's a float value if keyable and settable and isinstance(obj.attr(attribute).get(), float): newList.append(obj.attr(attribute)) return newList
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
def getSel_channelBox(return_pynode=False): pymel_attr_list = [] attr_string = pm.channelBox("mainChannelBox", query=True, sma=True) if return_pynode == True: selection = pm.selected() for ev in selection: for attribute in attr_string: pynode_attr = ev.attr(attribute) pymel_attr_list.append(pynode_attr) return pymel_attr_list else: return attr_string
def AddOutputsBC(self): try: selAttrs = [ x for x in pm.channelBox( "mainChannelBox", q=1, selectedMainAttributes=1) ] self.BConns = pm.textFieldGrp( self.BConn, e=True, tx=str(selAttrs).replace("u'", "").replace("'", " ").replace( "[", " ").replace("]", " ")) except TypeError: pm.warning("Select Attribute in the Channel Box")
def inputChannelboxSelectionTbf(self, name): channelBox = pm.mel.eval( 'global string $gChannelBoxName; $temp=$gChannelBoxName;' ) #fetch maya's main channelbox attrs = pm.channelBox(channelBox, q=True, sma=True) print 'attributes selected are %s' % attrs if not attrs: pm.textFieldButtonGrp(name, e=1, tx='') return [] if len(attrs) is not 1: pm.warning( 'Highlight only the IK/FK Switch Attribute in the Channelbox') return [] pm.textFieldButtonGrp(name, e=1, tx=attrs[0]) return attrs
def TransferOutConnections(**kwargs): source = kwargs.setdefault('source') dest = kwargs.setdefault('dest') #useSelectedAttributes = kwargs.setdefault( 'useSelectedAttributes' ) if not (source and dest): objs = pm.ls(sl=True) if len(objs) != 2: pm.error('select destination and source objects.') source = objs[1] dest = objs[0] # find user difined attributes from source and create them for dest DuplicateAttrs(**kwargs) sourceOuts = pm.listConnections(source, connections=True, source=False, skipConversionNodes=True, plugs=True) if not sourceOuts: pm.warning('No attribute to transfer. Skipped!') return None # if any attribute is selected in channelBox, transfer those attributes only selectedAttrs = pm.channelBox("mainChannelBox", q=True, selectedMainAttributes=True) if selectedAttrs: selectedSourceOuts = [] for i in selectedAttrs: for j in sourceOuts: if source.attr(i) in j: selectedSourceOuts.append(j) sourceOuts = selectedSourceOuts # if no attribute is selected do it for all attributes for i in range(len(sourceOuts)): outAttr = sourceOuts[i][0] inAttr = sourceOuts[i][1] attrName = sourceOuts[i][0].name().split('.')[1] if attrName != 'message': outAttr // inAttr # connections dest.attr(attrName) >> inAttr
def deleteAttr(up=False, tmp=False): objs = pm.ls(sl=True) attrs = pm.channelBox("mainChannelBox", q=True, sma=True) sl_attrs = copy.deepcopy(attrs) for obj in objs: if up: attrs = pm.listAttr(obj, ud=True) for attr in sl_attrs: attrs.remove(attr) for attr in attrs: try: pm.deleteAttr (obj, at=attr) if tmp: pm.undo() except: pass
def TransferOutConnections( **kwargs ): source = kwargs.setdefault( 'source' ) dest = kwargs.setdefault( 'dest' ) useSelectedAttributes = kwargs.setdefault( 'useSelectedAttributes' ) if not ( source and dest ): objs = pm.ls(sl=True) if len( objs )!=2 : pm.error( 'select destination and source objects.') source = objs[1] dest = objs[0] # find user difined attributes from source and create them for dest DuplicateAttrs( **kwargs ) sourceOuts = pm.listConnections( source , connections=True, source=False, skipConversionNodes=True, plugs=True ) if useSelectedAttributes : selectedAttrs = pm.channelBox( "mainChannelBox", q=True, selectedMainAttributes=True ) if selectedAttrs : selectedSourceOuts = [] for i in selectedAttrs: for j in sourceOuts: if source.attr( i ) in j: selectedSourceOuts.append( j ) sourceOuts = selectedSourceOuts else: sourceOuts = None pm.warning( 'selected attributes are not connected. Skipped!' ) if sourceOuts: for i in range( len(sourceOuts) ): outAttr = sourceOuts[i][0] inAttr = sourceOuts[i][1] attrName = sourceOuts[i][0].name().split('.')[1] if attrName != 'message': outAttr // inAttr # connections dest.attr(attrName) >> inAttr else: pm.warning( 'No attribute to transfer. Skipped!' )
def add_attr(self): try: sel_obj = pmc.selected()[0] sel_attr = pmc.channelBox("mainChannelBox", q=True, selectedMainAttributes=True) attr_type = sel_obj.attr(sel_attr[0]).type() if attr_type == "enum": self.switch_attr.setText( sel_obj.attr(sel_attr[0]).name().split(".")[1]) return sel_obj.attr(sel_attr[0]) else: om.MGlobal.displayInfo("Attribute must be an enum data type.") except TypeError: om.MGlobal.displayError( "Select an attribute in the channelbox to add or type the name of an attribute you would like to make." ) return
def getAttrsFromChannelbox(): ''' 채널박스에서 선택된 어트리뷰트 이름 리턴 블렌드 쉐입은 잘 안됨..ㅠㅠㅠ @return: 어트리뷰트 리스트 리턴 ''' mainObjs = pm.channelBox( pm.melGlobals['gChannelBoxName'], q=True, mainObjectList=True ) mainAttrs = pm.channelBox( pm.melGlobals['gChannelBoxName'], q=True, selectedMainAttributes=True ) shapeObjs = pm.channelBox( pm.melGlobals['gChannelBoxName'], q=True, shapeObjectList =True) shapeAttrs = pm.channelBox( pm.melGlobals['gChannelBoxName'], q=True, selectedShapeAttributes=True) histObjs = pm.channelBox( pm.melGlobals['gChannelBoxName'], q=True, historyObjectList =True) histAttrs = pm.channelBox( pm.melGlobals['gChannelBoxName'], q=True, selectedHistoryAttributes=True) outputObjs = pm.channelBox( pm.melGlobals['gChannelBoxName'], q=True, outputObjectList =True) outputAttrs = pm.channelBox( pm.melGlobals['gChannelBoxName'], q=True, selectedOutputAttributes=True) shortNames = [] for pair in ((mainObjs, mainAttrs), (shapeObjs, shapeAttrs), (histObjs, histAttrs), (outputObjs, outputAttrs)): objs, attrs = pair #print pair if attrs: for obj in objs: for attr in attrs: shortNames.append('%s.%s' %(obj,attr) ) longNames = [] for pair in ((mainObjs, mainAttrs), (shapeObjs, shapeAttrs), (histObjs, histAttrs), (outputObjs, outputAttrs)): objs, attrs = pair #print pair if attrs is not None: for node in objs: result = [ objs[0] +'.' + pm.attributeQuery( attr, n=node, ln=True) for attr in attrs ] longNames.extend( result ) longNames = list(set(longNames)) return shortNames
def createTool(sensitivity, timeScale, singleAxis, simplify, tolerance, inverted, vertical): ready = None attributes = pmc.channelBox('mainChannelBox', selectedMainAttributes=True, q=True) if attributes is None and singleAxis: ready = 'No Channels Selected' selection = pmc.selected() if len(selection) < 1: ready = 'No Target Selected' if ready is None: selectionName = selection[0].shortName() if singleAxis: attributeNames = [ selectionName + '.' + attribute for attribute in attributes ] else: attributeNames = [ selectionName + '.tx', selectionName + '.ty', selectionName + '.tz' ] tool.create(attributeNames, sensitivity=sensitivity, timeScale=timeScale, singleAxis=singleAxis, simplify=simplify, verticalControl=vertical, tolerance=tolerance, inverted=inverted) else: logging.warning(ready)
def getSelectedChannels(userDefine=False): """Get the selected channels on the channel box Arguments: userDefine (bool, optional): If True, will return only the user defined channels. Other channels will be skipped. Returns: list: The list of selected channels names """ # fetch core's main channelbox attrs = pm.channelBox(get_channelBox(), q=True, sma=True) if userDefine: oSel = pm.selected()[0] uda = oSel.listAttr(ud=True) if attrs: attrs = [x for x in attrs if oSel.attr(x) in uda] else: return None return attrs
def getSelectedChannels(userDefine=False): """Get the selected channels on the channel box Args: userDefine (bool, optional): If True, will return only the user defined channels. Other channels will be skipped. Returns: list: The list of selected channels names """ channelBox = pm.mel.eval( 'global string $gChannelBoxName; $temp=$gChannelBoxName;' ) #fetch maya's main channelbox attrs = pm.channelBox(channelBox, q=True, sma=True) if userDefine: oSel = pm.selected()[0] uda = oSel.listAttr(ud=True) if attrs: attrs = [x for x in attrs if oSel.attr(x) in uda] else: return None return attrs
def disAttr(): # NOTE 获取当前通道盒选择的属性 attr_list = pm.channelBox('mainChannelBox', q=1, sma=1) # NOTE 没有选择跳过执行 if not attr_list: return for sel in pm.ls(sl=1): for attr in attr_list: if not hasattr(sel, attr): continue attr = pm.PyNode("%s.%s" % (sel, attr)) des = pm.PyNode(pm.connectionInfo(attr, ged=1)) if des == attr: attr.disconnect() else: # NOTE 如果获取的属性不相等说明是 Translate类似集合 的上层链接 src = des.listConnections(d=0, s=1, p=1)[0] des.disconnect() for d_attr, s_attr in zip(des.getChildren(), src.getChildren()): if d_attr != attr: s_attr.connect(d_attr)
def rig_cbRandomValues(controlObject=None, connectTime=True): '''Connects random values to selected objects attributes based on channelbox selection Args: controlObject (pm.PyNode): optional object to place control attributes on connectTime (bool): whether to connect the noise to the frame number or not Returns (boolean): whether we succeeded or not Usage: rig_cbRandomValues(pm.PyNode('handle_CTRL')) ''' attrs = pm.channelBox('mainChannelBox', sma=True, q=True) sel=pm.ls(sl=True) if attrs: for obj in sel: for attr in attrs: if pm.objExists(obj.attr(attr)): noise = pm.shadingNode('noise', asUtility=True, n=obj+attr+'_NOISE') noise.uCoord.set(random.random()) noise.vCoord.set(random.random()) noise.outAlpha.connect(obj.attr(attr), f=True) if controlObject: attrName = obj+'_'+attr.replace('.','')+'_noiseAmount' controlObject.addAttr(attrName, at='float', k=True) controlObject.attr(attrName).connect( noise.amplitude, f=True ) attrName = obj+'_'+attr.replace('.','')+'_noiseFrequency' controlObject.addAttr(attrName, at='float', dv=8.0, k=True) controlObject.attr(attrName).connect( noise.frequency, f=True ) if connectTime: pm.PyNode('time1').outTime.connect(noise.time, f=True) else: pm.warning('You have to select something...') return False pm.select(sel,r=True) return True
def lockUnlock(i, j, tmp=False): ranges = [] objs = cmds.ls(sl=True) if tmp: sl_attrs = pm.channelBox("mainChannelBox", q=True, sma=True) for sl_attr in sl_attrs: ranges.append("."+sl_attr) for obj in objs: for attr1 in ranges: cmds.setAttr(obj+attr1, l=i, k=j) else: if cmds.checkBoxGrp(lock_check, q=True, v1=True): ranges.append(".t") if cmds.checkBoxGrp(lock_check, q=True, v2=True): ranges.append(".r") if cmds.checkBoxGrp(lock_check, q=True, v3=True): ranges.append(".s") for obj in objs: for attr1 in ranges: for attr2 in ["x", "y", "z"]: cmds.setAttr(obj+attr1+attr2, l=i, k=j) if cmds.checkBoxGrp(lock_check, q=True, v4=True): cmds.setAttr(obj+".visibility", l=i, k=j)
def changeAttrOder(updown): objs = pm.ls(sl=True) sl_attrs = pm.channelBox("mainChannelBox", q=True, sma=True) if updown: for obj in objs: attrs = pm.listAttr(obj, ud=True) flag = False for x in range(len(attrs)): if attrs[x] == sl_attrs[0]: subDelAttr(obj, attrs[x-1]) x += len(sl_attrs) flag = True elif attrs[x] in sl_attrs: if x+len(sl_attrs)-1 < len(attrs): subDelAttr(obj, attrs[x+len(sl_attrs)-1]) x += 1 elif flag == True: subDelAttr(obj, attrs[x]) else: for obj in objs: attrs = pm.listAttr(obj, ud=True) flag = False for x in range(len(attrs)): if attrs[x] == sl_attrs[0]: if x+len(sl_attrs) < len(attrs): tmp = attrs[x+len(sl_attrs)] subDelAttr(obj, tmp) subDelAttr(obj, attrs[x]) x += len(sl_attrs) flag = True elif attrs[x] in sl_attrs: subDelAttr(obj, attrs[x]) x += 1 elif flag == True and attrs[x] != tmp: subDelAttr(obj, attrs[x])
def move_attribute_in_channel_box( node, attribute_name=None, exchange_attr_name=None, new_index=None, step_up=True, step_down=None, ): """ Moves a selected user defined attribute in the channelBox by index or step by step. By Default it always takes the selected attribute in the channelBox and moves the attribute one step upwards. Args: node(dagNode): The node the attributes belongs to. attribute_name(str): The name of the attribute. If None it takes the selected attribute in the channelBox. exchange_attr_name(str): The name of the attribute to exchange with. new_index(int): new position of the attribute. step_up(bool): new_index = oldIndex - 1. """ if not attribute_name: if len(pmc.channelBox("mainChannelBox", q=True, sma=True)) == 1: attribute_name = pmc.channelBox("mainChannelBox", q=True, sma=True)[ 0 ] else: logger.log( level="error", message="more then one selection " "in the channelBox not supported", func=move_attribute_in_channel_box, logger=_LOGGER, ) return if exchange_attr_name: step_up = None step_down = None usd_attr = get_usd_attributes(node=node, index=True) for attr_ in usd_attr: name = attr_["usd_attr"].split(".")[1] if name == exchange_attr_name: new_index = attr_["index"] usd_attr = re_arrange_usd_attributes_by_name( node=node, attribute_name=attribute_name, new_index=new_index, step_up=step_up, step_down=step_down, ) def re_create_attr(): """ Executes the rebuild of the attributes. """ if usd_attr: for x in usd_attr: x["usd_attr"].disconnect() x["usd_attr"].set(lock=False) x["usd_attr"].delete() if x["attrType"] == "string": node.addAttr( x["usd_attr"].split(".")[1], dt=x["attrType"], hidden=x["hidden"], keyable=x["keyable"], en=x["enums"], ) else: node.addAttr( x["usd_attr"].split(".")[1], at=x["attrType"], hidden=x["hidden"], keyable=x["keyable"], en=x["enums"], ) node.attr(x["usd_attr"].split(".")[1]).set( x["value"], lock=x["lock"], keyable=x["keyable"], channelBox=x["channelBox"], ) if x["input"]: x["input"][0].connect(x["usd_attr"]) if x["output"]: for out in x["output"]: x["usd_attr"].connect(out) logger.log( level="info", message=attribute_name + " reordered in channelBox", logger=_LOGGER, ) re_create_attr()
def cbinfo(flag): return pm.channelBox('mainChannelBox', q=True, **{flag:True})
def syncChannelBox(graphInfo=None, perfectSync=False, useSelectedCurves=True, usePartialCurveSelection=True): ''' Syncs the attributes selected in the graphEditor to those in the channelBox. Attributes selected in the graphEditor will be modified to so that every node has the same attributes selected - this "trues" up the channelbox selection with the graph editor. ''' graphInfo = graphInfo or selectedAttributes.GraphEditorInfo.detect() if not graphInfo.isValid(): return # Get selected nodes and attributes selected = selectedAttributes.getGraphEditor( graphInfo, expandObjects=False, useSelectedCurves=useSelectedCurves, usePartialCurveSelection=usePartialCurveSelection) nodes = cmd.ls(sl=1, l=1) # Process attributes # Get the attribute part of node.attribute and separate out # selected objects. objs = [] attributes = set() for nodeOrAttr in selected: if '.' in nodeOrAttr: # This works for compound attributes too. Trust me. attributes.add(selectedAttributes.splitAttr(nodeOrAttr)[1]) else: objs.append(nodeOrAttr) attributes = list(attributes) objAttrs = ["%s.%s" % (node, attr) for attr in attributes for node in nodes] try: # I hear that the select flag was added in Maya 2016 Extension 2 pm.channelBox( pm.melGlobals['gChannelBoxName'], select=objAttrs, edit=True) except TypeError: # Legacy behavior before channelBox -select flag was created # Does not actually sync with channel box, because that was impossible. # instead it just selected the same attributes on all graph nodes. if perfectSync: # Clear graph editor attributes selectionConnection = selectedAttributes.selectionConnectionFromPanel( graphInfo.panelName) cmd.selectionConnection(selectionConnection, edit=True, clr=True) # Select the attributes on every node selected for attr in attributes: for node in nodes: try: cmd.selectionConnection(selectionConnection, edit=True, select='%s.%s' % (node, attr)) except RuntimeError: # That attribute probably didn't exist on that node. pass # reselect objects for obj in objs: cmd.selectionConnection(selectionConnection, edit=True, select=obj) else: if perfectSync: syncGraphEditor(graphInfo=graphInfo)
import pymel.core as pm import random fromCB = True attrs = ['translateX'] if fromCB: attrs_cb = pm.channelBox('mainChannelBox', q=True, selectedMainAttributes=True) if attrs_cb: attrs = attrs_cb else: pm.error('Nothing selected in the channel box to wiggle') sel = pm.ls(sl=True) circ = pm.circle(n='noisy_thing')[0] circ.addAttr('global_amplitude_multiplier', at='double', dv=1, k=True) circ.addAttr('global_frequency_multiplier', at='double', dv=1, k=True) for obj in sel: for attr in attrs: # Creating an add node for the seed value to mix in add = pm.createNode('addDoubleLinear') # Creating generic noise that's soft noise = pm.createNode('noise') noise.noiseType.set(0) noise.ratio.set(0) # Adding a multiplier to create an amplitude effect as well as global multipliers
if window('TheRiggersToolkitX',ex=True): deleteUI('TheRiggersToolkitX') if window('ExamplaeWindow',ex=True): deleteUI('ExamplaeWindow') if cmds.windowPref('TheRiggersToolkitX', exists=True ): cmds.windowPref( 'TheRiggersToolkitX', r=1 ) template = uiTemplate('TheRiggersToolkitXtemplate', force=True) template.define(formLayout) wind = pm.window( 'TheRiggersToolkitX',t = 'RigToolkitX',w=300,h=330,s=1,bgc = [(.17),(.18),(.19)]) Tab = tabLayout('Tabs',p='TheRiggersToolkitX',tc =1,stb=1,snt=1,ntc = 'NewTab()') ToolsSc = pm.scrollLayout('Controls',p='Tabs',w=300,h=330) channelbox = pm.channelBox('ChannelBox',p = 'Tabs',ac = [(.8),(.9),(1)],bc = [(.3),(.3),(.3)],ekf =1,fw=150,hlc=[(.2),(.6),(.4)],hol =1,ln=1,nn=0,m=1,pre = 5,) out = pm.formLayout('Outliner',p='Tabs',w=300,h=330) outpanel = pm.outlinerPanel(p = 'Outliner') ToolsSc = pm.scrollLayout('Tools',p='Tabs') SkinSc= pm.scrollLayout('Skin',p='Tabs') ScriptEdt = pm.scrollLayout('MelCmd',p='Tabs') MiscSc = pm.scrollLayout('Misc',p='Tabs') cmdShll = cmds.cmdShell(p='MelCmd',w=290,h=260 , bgc = [(.17),(.18),(.19)]) clearBtn = pm.symbolButton('minusBtn',p = 'MelCmd',i = 'clearAll.png',w = 285,h=43,ebg =1 , bgc = [(.1),(.11),(.11)],en = 1,command=('cmds.cmdShell(\"' + cmdShll + '\", edit=True, clear=True)' )) ControlsForm = pm.formLayout( 'ControlsForm',p='Controls')
def changeAttrName(): attr_text = cmds.textField(attr_tx, q=True, tx=True) objs = pm.ls(sl=True) for obj in objs: sl_attr = pm.channelBox("mainChannelBox", q=True, sma=True) print sl_attr, attr_text