def setMirrorObject( fromList, toList ): for i in range( len( fromList ) ): fromCtl = fromList[i] toCtl = toList[i] isTransMirror = False isZRotMirror = False for transMirrorName in CtlInfo.xTransMirrorTargetNames: if fromCtl.find( transMirrorName ) != -1: isTransMirror = True for zRotMirror in CtlInfo.zRotMirrorTargetNames: if fromCtl.find( zRotMirror ) != -1 and fromCtl.find( 'wing_big4_CTL' ) == -1: isZRotMirror = True try: if isTransMirror: trValue = cmds.getAttr( fromCtl + '.t' )[0] cmds.setAttr( toCtl+'.t', -trValue[0], trValue[1], trValue[2] ) elif isZRotMirror: rotValue = cmds.getAttr( fromCtl + '.r' )[0] cmds.setAttr( toCtl + '.r', -rotValue[0], -rotValue[1], rotValue[2] ) else: keys = cmds.listAttr( fromCtl, k=1 ) for key in keys: value = cmds.getAttr( fromCtl+'.'+key ) cmds.setAttr( toCtl + '.' + key, value ) except: pass listAttr = cmds.listAttr( fromCtl, ud=1, k=1 ) if not listAttr: continue for attr in listAttr: cmds.setAttr( toCtl+'.'+attr, cmds.getAttr( fromCtl+'.'+attr ) )
def getNonAnimatableAttributes(obj): '''Returns non-keyable attributes on an object. Always returns a list. If this fails to work again, I recommend disabling it in filterSelectedToAttributes''' attrs = [] # Get scalar keyable attributes. I believe only scalar attributes appear in the channel box # Though I have been known to be mistaken about these things before. allKeyable = cmd.listAttr(obj, k=1, s=1) if allKeyable: for attr in allKeyable: try: # Get non-multi attributes if cmd.getAttr('%s.%s' % (obj, attr), size=1) == 1: attrs.append(attr) except ValueError: # Most likely failed because of a multi attribute not yet set # For some reason listAttr includes these. And listAttr -multi does not # so I can't filter them out. Yaaaaaaaay Autodesk. pass # Grab non-keyable attributes in channel box. nonKeyable = cmd.listAttr(obj, cb=1) if nonKeyable: attrs.extend(nonKeyable) # Homogonize names. attrs = [homogonizeName('%s.%s' % (obj, attr)) for attr in attrs] removeUnderworldFromPath(attrs) return attrs
def getAttribute(self): # if lattice point is selected, returning list is 'attr.attr' keyable = cmds.listAttr(self.name, k=True, s=True) if keyable: for attr in keyable: if attr not in self.attributesDriven: # hacky -- if attr.attr format, remove first attr hack = False if '.' in attr: attr = attr.split('.')[1] hack = True try: a = Attribute(self.name, attr, poseOnly=self.poseOnly) a.get() self.attributes.append(a) except: message('Hack fail: ' + attr) else: a = Attribute(self.name, attr, poseOnly=self.poseOnly) a.get() self.attributes.append(a) settable = cmds.listAttr(self.name, cb=True) # future fix, make part of one pass, current code copied from above if settable: for attr in settable: if attr not in self.attributesDriven: # hacky -- if attr.attr format, remove first attr if '.' in attr: attr = attr.split('.')[1] a = Attribute(self.name, attr, poseOnly=self.poseOnly, settable=True) a.get() self.attributes.append(a)
def updateInputOutputs(self): """ finds attributes on module with "input_" & "output_" prefix then populates dicts """ # Get input attrs inputsAttrs = cmds.listAttr( self.container, st='input_*') # Get output attrs outputsAttrs = cmds.listAttr( self.container, st='output_*') if inputsAttrs: for attr in inputsAttrs: # get attr key key = Util.getSuffix(attr) if key != "data": # get connected obj objs = Util.getConnectedObjects( (self.container + "." + attr) ) # store obj self.inputs[key] = Util.getFirst(objs) if outputsAttrs: for attr in outputsAttrs: # get attr key key = Util.getSuffix(attr) if key != "data": # get connected obj objs = Util.getConnectedObjects( (self.container + "." + attr) ) # store obj self.outputs[key] = Util.getFirst(objs)
def channelBox_Filter_Items(box): with sysCmd.Undo(0): filters = [] names = [] for f in box.filter_items: if f == "attr_userDefined": user_cb = cmds.listAttr(ud=1, cb=1) user_kv = cmds.listAttr(ud=1, k=1, v=1) if user_cb: names += user_cb if user_kv: names += user_kv elif f == "attr_translate": names.append("translateX") names.append("translateY") names.append("translateZ") elif f == "attr_rotate": names.append("rotateX") names.append("rotateY") names.append("rotateZ") elif f == "attr_scale": names.append("scaleX") names.append("scaleY") names.append("scaleZ") else: filters.append(f.split("_")[-1]) if len(filters) == 0 and len(names) == 0: cmds.channelBox(box.channelbox, e=1, update=1) return _f = [] # create the actual filters if "animCurve" in filters: _f.append(cmds.itemFilterAttr(hasCurve=1)) if "expression" in filters: _f.append(cmds.itemFilterAttr(hasExpression=1)) if "drivenKey" in filters: _f.append(cmds.itemFilterAttr(hasDrivenKey=1)) if "scaleRotateTranslate" in filters: _f.append(cmds.itemFilterAttr(scaleRotateTranslate=1)) if names: _f.append(cmds.itemFilterAttr(byNameString=names)) destination = _f[0] odd = len(_f) % 2 # determines odd/even number loops = len(_f) / 2 + (1 if odd else 0) for i in range(loops): # create union filters index_1 = i * 2 index_2 = i * 2 + 1 use_last = odd and i + 1 == loops destination = cmds.itemFilterAttr(union=(_f[index_1], _f[index_2] if not use_last else destination)) box.filter = destination cmds.itemFilterAttr(box.filter, e=1, negate=box.saved_states["invertShown"][0]) cmds.channelBox(box.channelbox, e=1, attrFilter=box.filter, update=1) for f in _f: cmds.delete(f)
def utilChannelBoxAttributes(source): attributes = cmds.listAttr(source, k=True) #extend non-keyable in channel box nonKeyable = cmds.listAttr(source, cb=True) if nonKeyable: attributes.extend(nonKeyable) return attributes
def attrReset( ): ''' This function will reset the attributes on the selected objects in the scene. ''' selected = cmds.ls(sl=True) # selCB = cmds.channelBox( "mainChannelBox", q=True, sma=True) for sel in selected: # Gathering all the attributes from the object. selCB = cmds.listAttr(sel, k=True) # Duplicating list because removing from the list your are looping through causes problems. newAttrs = selCB[:] try: [selCB.remove(x) for x in newAttrs if x in cmds.listAttr( selected , k=True, l=True )] except TypeError: print( "None of the attributes are locked.") for attr in selCB: attrName = "%s.%s" %(sel,attr) print(attrName) # Check to see if keyable if( cmds.getAttr( attrName, k=True) ): # Get default value # cmds.attributeQuery( "sx", node="nurbsCircle1", listDefault=True ) attrDV = cmds.attributeQuery( attr, node=sel, listDefault=True)[0] print( "Object: %s Setting to Default: %s" %(attrName, attrDV)) cmds.setAttr( attrName, attrDV )
def setMirrorObjectOnce( target ): otherTarget = '' if target in CtlInfo.leftCtls: otherTarget = target.replace( 'L_', 'R_' ) elif target in CtlInfo.rightCtls: otherTarget = target.replace( 'R_', 'L_' ) if not otherTarget: return None isTransMirror = False isZRotMirror = False for transMirrorName in CtlInfo.xTransMirrorTargetNames: if target.find( transMirrorName ) != -1: isTransMirror = True for zRotMirror in CtlInfo.zRotMirrorTargetNames: if target.find( zRotMirror ) != -1 and target.find( 'wing_big4_CTL' ) == -1: isZRotMirror = True if isTransMirror: trValue = cmds.getAttr( target + '.t' )[0] cmds.setAttr( otherTarget+'.t', -trValue[0], trValue[1], trValue[2] ) elif isZRotMirror: rotValue = cmds.getAttr( target + '.r' )[0] cmds.setAttr( otherTarget + '.r', -rotValue[0], -rotValue[1], rotValue[2] ) else: keys = cmds.listAttr( target, k=1 ) for key in keys: value = cmds.getAttr( target+'.'+key ) cmds.setAttr( otherTarget + '.' + key, value ) listAttr = cmds.listAttr( target, ud=1, k=1 ) if not listAttr: return None for attr in listAttr: cmds.setAttr( otherTarget+'.'+attr, cmds.getAttr( target+'.'+attr ) )
def importAssetCache(self, cacheXmlLt, cacheErrorCheck = False): """ cacheXmlLt = "R:/data/cache/sq001/sh001/light/char/ben00c_ben/ben00c_ben.xml" """ if os.path.exists(cacheXmlLt): cacheChannels = mc.cacheFile(fileName=cacheXmlLt,q=1,channelName=1) cacheGeos = self.getCacheGeos() cacheGeoDict, cacheChannelsTmp = {}, [] for chn in cacheChannels: for geo in cacheGeos: baseChn = utils.stripNames(utils.convertName(chn, "texture")) baseGeo = utils.stripNames(utils.stripNames(geo, ":"), "|") if baseChn in baseGeo: cacheGeoDict[chn] = geo cacheChannelsTmp.append(chn) continue else: utils.msgWin("Error", "File does not exist : %s"%cacheXmlLt, self.silent) return False if cacheErrorCheck: missedChannels = list(set(cacheChannels).difference(set(cacheGeoDict.keys()))) if len(missedChannels) > 0: msg = "Cache geometry missing\n" msg += "\n".join(missedChannels) utils.msgWin("Error", msg, self.silent) return missedChannels else: return False for chNode in self.getCacheNodes(): mc.delete(chNode) for chn in cacheGeoDict.keys(): deformShp = cacheGeoDict[chn] try: shpSwitch = mc.deformer(deformShp, type="historySwitch") except: continue shpHist = mc.listHistory(deformShp, pdo=1) if shpHist: for hist in shpHist: if mc.nodeType(hist) == "tweak": dblList = mc.listAttr("%s.plist"%hist, m= 1) fltList = mc.listAttr("%s.vlist"%hist, m= 1) dbCon, flCon = False, False if dblList: if len(dblList) > 1: dbCon = True if fltList: if len(fltList) > 1: flCon = True if not(dbCon or flCon): mc.delete(hist) break conns = mc.listConnections("%s.ip[0].ig"%shpSwitch[0], p=1) mc.connectAttr(conns[0], "%s.ug[0]"%shpSwitch[0]) mc.setAttr("%s.playFromCache"%shpSwitch[0], 1) mc.getAttr("%s.op[0]"%shpSwitch[0], sl = 1) mc.setAttr("%s.playFromCache"%shpSwitch[0], 0) mc.disconnectAttr(conns[0], "%s.ug[0]"%shpSwitch[0]) switch = mc.rename(shpSwitch[0],'cacheSwitch#') mc.setAttr(switch+'.ihi',0) cacheNode = mc.cacheFile(f = cacheXmlLt, attachFile = True, ia = '%s.inp[0]'%switch, cnm = chn) mc.connectAttr(cacheNode+".inRange", switch + '.playFromCache') utils.msgWin("Message", "Cache loaded successfully for %s"%self.namespace, self.silent) return True
def getattributes(self): for key, nodes in self.oldNodes.iteritems(): if key == 'expression': expression = True else: expression = False for oldNode in nodes: listAttr = cmds.listAttr(oldNode) if listAttr: self.attributes[nodes[oldNode]] = {} for attr in listAttr: try: self.attributes[nodes[oldNode]].update({attr: {'value': cmds.getAttr(oldNode + '.' + attr)}}) self.attributes[nodes[oldNode]][attr].update({'type': cmds.getAttr(oldNode + '.' + attr, type=True)}) if expression and attr == 'expression': self.expressions.update({nodes[oldNode]: self.attributes[nodes[oldNode]][attr]['value']}) except RuntimeError as e: pass except ValueError as e: pass listAttrCustom = cmds.listAttr(oldNode, userDefined=True) if listAttrCustom: self.newAttributes[nodes[oldNode]] = {} for attr in listAttrCustom: try: self.newAttributes[nodes[oldNode]].update({attr: {'type': cmds.getAttr(oldNode + '.' + attr, type=True)}}) if cmds.attributeQuery(attr, node=oldNode, minExists=True): self.newAttributes[nodes[oldNode]][attr].update({'min': cmds.attributeQuery(attr, node=oldNode, min=True)}) if cmds.attributeQuery(attr, node=oldNode, maxExists=True): self.newAttributes[nodes[oldNode]][attr].update({'max': cmds.attributeQuery(attr, node=oldNode, max=True)}) except RuntimeError as e: pass except ValueError as e: pass
def copyAttribute( firstAttr, second ): first, attr = firstAttr.split( '.' ) keyAttrs = cmds.listAttr( firstAttr, k=1 ) cbAttrs = cmds.listAttr( firstAttr, k=1 ) if not cmds.attributeQuery( attr, node=second, ex=1 ): attrType = cmds.attributeQuery( attr, node=first, at=1 ) if attrType == 'enum': enumList = cmds.attributeQuery( attr, node=first, le=1 ) cmds.addAttr( second, ln=attr, at=attrType, en= ':'.join( enumList ) + ':' ) else: minValue = None maxValue = None if cmds.attributeQuery( attr, node=first, mne=1 ): minValue = cmds.attributeQuery( attr, node=first, min=1 )[0] if cmds.attributeQuery( attr, node=first, mxe=1 ): maxValue = cmds.attributeQuery( attr, node=first, max=1 )[0] if minValue != None and maxValue == None: cmds.addAttr( second, ln=attr, at=attrType, min=minValue ) elif minValue == None and maxValue != None : cmds.addAttr( second, ln=attr, at=attrType, max=maxValue ) elif minValue != None and maxValue != None : cmds.addAttr( second, ln=attr, at=attrType, min=minValue, max=maxValue ) else: cmds.addAttr( second, ln=attr, at=attrType ) if attr in keyAttrs: cmds.setAttr( second+'.'+attr, e=1, k=1 ) elif attr in cbAttrs: cmds.setAttr( second+'.'+attr, e=1, cb=1 )
def userAttrCheck(objList=[], includeShapes=False): """ Return a list of user defined attributes for a specified list of nodes (and shapes). @param objList: List of objects to check for user defined attributes. @type objList: list @param includeShapes: Also check shapes for user defined attributes. @type includeShapes: bool """ # Initialize Return List result = [] # Check objList if not objList: objList = cmds.ls() # For each node for obj in objList: userAttrs = cmds.listAttr(obj, ud=True) if not userAttrs: userAttrs = [] for attr in userAttrs: result.append(obj + '.' + attr) # Check Shapes if includeShapes: shapes = cmds.listRelatives(obj, s=True) if not shapes: shapes = [] for shape in shapes: userAttrs = cmds.listAttr(shape, ud=True) if not userAttrs: userAttrs = [] for attr in userAttrs: result.append(shape + '.' + attr) # Return Result return result
def writeCtrlAttr( ctrls = [] , fn = '' ) : fid = open( fn , 'w' ) ctrlDct = {} for ctrl in ctrls : currCtrl = pc.Dag( ctrl ) currShape = pc.Dag( currCtrl.shape ) for each in ( currCtrl , currShape ) : if mc.objExists( each ) : attrs = mc.listAttr( each , ud=True ) keyableAttrs = mc.listAttr( each , k=True ) lockAttrs = mc.listAttr( each , l=True ) if attrs : for attr in attrs : currCtrlAttr = '%s.%s' % ( each , attr ) ctrlDct[ currCtrlAttr ] = [ False , False ] if lockAttrs and ( attr in lockAttrs ) : ctrlDct[ currCtrlAttr ][0] = True if keyableAttrs and ( attr in keyableAttrs ) : ctrlDct[ currCtrlAttr ][1] = True pickle.dump( ctrlDct , fid ) fid.close()
def setAttributeState(lock=None, hide=None): sel = mc.ls(sl=True) if not sel: OpenMaya.MGlobal.displayWarning('Please make a selection.') return channels = utl.getSelectedChannels() doAll = not bool(channels) kwargs = dict() for obj in sel: attrs = channels[:] #we unhide first, so hidden attributes can get unlocked. if hide is False and doAll: attrs = ['tx','ty','tz','rx','ry','rz','sx','sy','sz','v'] ud = mc.listAttr(obj, userDefined=True) if ud: attrs+=ud elif doAll: attrs = mc.listAttr(obj, keyable=True) if lock is not None: kwargs['lock'] = lock if hide is not None: kwargs['keyable'] = not hide if attrs: for attr in attrs: try: mc.setAttr(obj+'.'+attr, **kwargs) except StandardError: pass
def listNodeConnections(*args,**keywords): s=True d=True sn=False sel=[] if len(args)==0: sel=mc.ls(sl=True) for a in args: if isIterable(a): sel.extend(a) else: sel.append(a) for k in keywords: if k=='s' or k=='source': s=keywords[k] if k=='d' or k=='destination': d=keywords[k] if k=='sn' or k=='shortName': sn=keywords[k] elif k in locals(): exec(k+'=keywords[k]') connections=[] for conn in removeDuplicates(mc.listConnections(sel[0],s=s,d=d,p=True)): if len(sel)==1 or mc.ls(conn,o=True)[0]==sel[1]: if mc.connectionInfo(conn,isSource=True): for dfs in mc.connectionInfo(conn,dfs=True): if mc.ls(dfs,o=True)[0]==sel[0]: if sn: connections.append\ ( [ mc.ls(conn,o=True)[0]+'.'+mc.listAttr(conn,sn=True)[0], mc.ls(dfs,o=True)[0]+'.'+mc.listAttr(dfs,sn=True)[0] ] ) else: connections.append([conn,dfs]) if mc.connectionInfo(conn,id=True): sfd=mc.connectionInfo(conn,sfd=True) if mc.ls(sfd,o=True)[0]==sel[0]: if sn: connections.append\ ( [ mc.ls(sfd,o=True)[0]+'.'+mc.listAttr(sfd,sn=True)[0], mc.ls(conn,o=True)[0]+'.'+mc.listAttr(conn,sn=True)[0] ] ) else: connections.append([sfd,conn]) return removeDuplicates(connections)
def addObjectID(): ''' add object id to selected objects. check for existing object ID and add new one if there are existing. ''' nodeList = cmds.ls(selection = True, dag=True, lf=True, type = 'mesh') # find shape nodes of current selection allNodes = cmds.ls(type = 'mesh') # look for meshes only in the scene existingIDs = [0] for node in allNodes: # go through and check for existing object IDs here attrList = cmds.listAttr(node) if 'vrayObjectID' in attrList: existingIDs.append (cmds.getAttr ('%s.vrayObjectID' % node)) newObjectID = 1 existingIDs.sort() # this is just for cleanliness. not required. for id in range(max(existingIDs)+2): # look through the list and let's find an unused number if that exists we need to go one beyond the current values so we can add it if needed if id not in existingIDs: newObjectID = id existingIDs.append(newObjectID) break for node in nodeList: attrList = cmds.listAttr(node) if 'vrayObjectID' not in attrList: print newObjectID mel.eval ('vray addAttributesFromGroup %s vray_objectID 1' % node) cmds.setAttr('%s.vrayObjectID' % node ,newObjectID) renderElements = cmds.ls (type = 'VRayRenderElement') addedID = False # clear the slate here attrsToSearch = ['vray_redid_multimatte','vray_greenid_multimatte','vray_blueid_multimatte'] # just looking for these attrs multiMatteElements = [] # nice and tidy here for element in renderElements: #go through and find multi matte elements and add them to our list if cmds.getAttr('%s.vrayClassType' % element) == 'MultiMatteElement': multiMatteElements.append(element) if len(multiMatteElements) < int(math.modf((newObjectID+2)/3)[1]) : # check amount of multi matte elements against how many we can fit in a render element newMMate = mel.eval('vrayAddRenderElement MultiMatteElement') # add the element cmds.setAttr('%s.vray_considerforaa_multimatte' % newMMate, 1) #make sure it has AA on it... multiMatteElements.append(newMMate) for element in multiMatteElements: # go through the multimatte list for multimatte in attrsToSearch: # we are looking only through the id attributes if cmds.getAttr('%s.%s' % (element, multimatte)) == newObjectID : # if we find the ID already just try to skip the rest of the testing addedID = True if cmds.getAttr('%s.%s' % (element, multimatte)) == 0 and addedID == False : # didn't find anything eh? good. we add the id to the multimatte. cmds.setAttr('%s.%s' % (element, multimatte), newObjectID) addedID = True
def constrainAttributeNaming( cnstrs ) : for cnstr in cnstrs : cnstrType = mc.nodeType( cnstr ) dummyAttr = 'targetTranslate' if cnstrType == 'parentConstraint' : dummyAttr = 'target[000].targetTranslate' elif cnstrType == 'pointConstraint' : dummyAttr = 'target[000].targetTranslate' elif cnstrType == 'orientConstraint' : dummyAttr = 'target[000].targetRotate' elif cnstrType == 'scaleConstraint' : dummyAttr = 'target[000].targetScale' elif cnstrType == 'aimConstraint' : dummyAttr = 'target[000].targetTranslate' elif cnstrType == 'poleVectorConstraint' : dummyAttr = 'constraintRotatePivot' if mc.listAttr( cnstr , ud=True ) : udAttrs = sorted( mc.listAttr( cnstr , ud=True ) ) for ix in range( len( udAttrs ) ) : currNodeAttrName = '%s.%s' % ( cnstr , udAttrs[ix] ) outAttr = dummyAttr.replace( '000' , str( ix ) ) target = mc.listConnections( '%s.%s' % ( cnstr , outAttr ) , s=True )[0] newAttrName = '%sW%s' % ( target , str( ix ) ) print '%s -- %s' % ( udAttrs[ix] , newAttrName ) lock = False if mc.getAttr( currNodeAttrName , l=True ) : lock = True mc.setAttr( currNodeAttrName , l=False ) if not udAttrs[ix] == newAttrName : mc.renameAttr( currNodeAttrName , newAttrName ) if lock : mc.setAttr( '%s.%s' % ( cnstr , newAttrName ) , l=True )
def _syncUI(self): # Since _syncUI is called in response to events that invalidate/clear # the selections in the views, disable the buttons until something is # selected again. self.removeExportedAttrButton.setEnabled(False) self.addExportedAttrButton.setEnabled(False) selectedNodeNames = cmds.ls(selection=True, long=True) if not selectedNodeNames: self.addAttrsModel.setStringList([]) self.exportedAttrsModel.exportedAttributes = [] self.exportedAttrsView.resizeColumnsToContents() return # Collect the export attributes common to all selected nodes. If the # same attribute is configured differently on multiple objects (e.g. # different usdAttrName), then do not include that attribute. allExportedAttributeNames = set() commonExportedAttributeNames = set() commonExportedAttrs = {} for exportedAttr in ExportedAttribute.GetExportedAttributesFromNode(selectedNodeNames[0]): mayaAttrName = exportedAttr.mayaAttrName allExportedAttributeNames.add(mayaAttrName) commonExportedAttributeNames.add(mayaAttrName) commonExportedAttrs[mayaAttrName] = exportedAttr for selectedNodeName in selectedNodeNames[1:]: exportedAttrNames = set() for exportedAttr in ExportedAttribute.GetExportedAttributesFromNode(selectedNodeName): mayaAttrName = exportedAttr.mayaAttrName allExportedAttributeNames.add(mayaAttrName) if (mayaAttrName in commonExportedAttrs and commonExportedAttrs[mayaAttrName] == exportedAttr): exportedAttrNames.add(mayaAttrName) commonExportedAttributeNames.intersection_update(exportedAttrNames) commonExportedAttrs = [commonExportedAttrs[x] for x in commonExportedAttributeNames] commonExportedAttrs.sort(key=lambda x: x.mayaAttrName) self.exportedAttrsModel.exportedAttributes = commonExportedAttrs self.exportedAttrsView.resizeColumnsToContents() # Collect the attributes common to all selected nodes. cmdOptions = {'read': True} if self.userDefinedCheckBox.isChecked(): cmdOptions['userDefined'] = True commonAttrNames = set(cmds.listAttr(selectedNodeNames[0], **cmdOptions) or []) for selectedNodeName in selectedNodeNames[1:]: attrNames = set(cmds.listAttr(selectedNodeName, **cmdOptions) or []) commonAttrNames.intersection_update(attrNames) # Subtract out reserved attribute names and attributes already being # exported by ANY node. commonAttrNames -= RESERVED_ATTRIBUTES commonAttrNames -= allExportedAttributeNames self.addAttrsModel.setStringList(sorted(list(commonAttrNames)))
def isolate(option): sel = mc.ls(sl=True) if not sel: return graphVis = mc.selectionConnection('graphEditor1FromOutliner', query=True, obj=True) channels = list() wildCard = str() alreadyIsolated = True if graphVis: for c in graphVis: if not '.' in c and mc.objExists(c): attrs = mc.listAttr(c, keyable=True, unlocked=True) if attrs: channels.extend([c+'.'+a for a in attrs]) else: attr = c.split('.')[-1] if attr.startswith(option): channels.append(c) if not wildCard: wildCard = option+'*' elif attr.endswith(option): channels.append(c) if not wildCard: wildCard = '*'+option elif attr == option: channels.append(c) if not wildCard: wildCard = option else: #found a curve that is outside our search parameters alreadyIsolated = False if channels and alreadyIsolated: #if the option is already the only thing being displayed, then show everything that matches the option for obj in sel: attrs = mc.listAttr(obj, keyable=True, unlocked=True, string=wildCard) if attrs: channels.extend([obj+'.'+a for a in attrs]) if not channels: for obj in sel: attrs = mc.listAttr(obj, keyable=True, unlocked=True) for a in attrs: if a==option or a.startswith(option) or a.endswith(option): channels.append(obj+'.'+a) clear() for c in channels: mc.selectionConnection('graphEditor1FromOutliner', edit=True, select=c)
def __cleanup(self): if self._lockGroups: attr = ['shearXY', 'shearXZ', 'shearYZ', 'rotateOrder', 'rotateAxisX', 'rotateAxisY', 'rotateAxisZ', 'inheritsTransform'] if self.offsets: #--- lock offsets for i in self.offsets: attrs = cmds.listAttr(i, keyable=True) if attrs: for j in attr: attrs.append(j) for a in attrs: cmds.setAttr(i + '.' + a, lock=True, keyable=False) attribute.lock_n_hide(i, ['t', 'r'], True) #--- lock group attrs = cmds.listAttr(self.group, keyable=True) for i in attr: attrs.append(i) if attrs: for a in attrs: cmds.setAttr(self.group + '.' + a, lock=True, keyable=False) #--- lock transform attrs = ['sx', 'sy', 'sz', 'v'] for i in attr: attrs.append(i) for a in attrs: cmds.setAttr(self.transform + '.' + a, lock=True, keyable=False) cmds.setAttr(self.shape + '.ihi', 0) #--- lock shape attrs = cmds.listAttr(self.shape, channelBox=True) if attrs: for a in attrs: cmds.setAttr(self.shape + '.' + a, lock=True, keyable=False) cmds.setAttr(self.shape + '.' + a, channelBox=False) cmds.setAttr(self.shape + '.ihi', 0) if self._withGimbal: #--- lock gimbal attrs = ['sx', 'sy', 'sz', 'v'] for i in attr: attrs.append(i) for a in attrs: cmds.setAttr(self.gimbal + '.' + a, lock=True, keyable=False) cmds.setAttr(self._gshape + '.ihi', 0) #--- lock gimbal shape attrs = cmds.listAttr(self._gshape, channelBox=True) if attrs: for a in attrs: cmds.setAttr(self._gshape + '.' + a, lock=True, keyable=False) cmds.setAttr(self._gshape + '.' + a, channelBox=False) cmds.setAttr(self._gshape + '.ihi', 0) cmds.select(clear=True)
def complete_node_with_attr( node, attr ): #print "noe_with_attr", node, attr long_attrs = cmds.listAttr( node ) short_attrs = cmds.listAttr( node , shortNames=1) # if node is a plug ( 'persp.t' ), the first result will be the passed plug if '.' in node: attrs = long_attrs[1:] + short_attrs[1:] else: attrs = long_attrs + short_attrs return [ u'%s.%s' % ( node, a) for a in attrs if a.startswith(attr) ]
def listStorableAttrs(self , node, shortName=True, noCompound=True): """ @brief List every attributes of a node who can go trough the pipeline and whose value will be stored. @return : List @param node - String - Node to get the attributes of. @param shortName - Bool - If True, return attributes short name. @param noCompound - Bool - If True, exclude compound attributes. """ def __getShortName(node, attr, shortName): result = attr if shortName: names = attr.split('.') snames = [] for name in names: if name.endswith(']'): snames.append(name) else: snames.append(mc.attributeQuery(name, node=node, shortName=True)) result = ".".join(snames) return result result = [] nodeType = mc.nodeType(node) if not mc.listAnimatable(node): return result for s in mc.listAnimatable(node): if noCompound: if len(s.split('.')) > 2: continue nodeName = s.split('.')[0] attr = ".".join(s.split('.')[1:]) ## Remove attributes on the shapes (listAnimatable return them) if mc.nodeType(node) == mc.nodeType(nodeName): attr = __getShortName(node, attr, shortName) result.append(str(attr)) attrs = mc.listAttr(node, cb=True) if attrs: for attr in attrs: attr = __getShortName(node, attr, shortName) result.append(str(attr)) if mc.listAttr(node, userDefined=True): extra = [str(x) for x in mc.listAttr(node, userDefined=True) if mc.getAttr("%s.%s" % (node, x), type=True) == 'string' if not x.startswith("rnkInit_") if not mc.getAttr("%s.%s" % (node, x), lock=True)] if extra: result.extend(extra) return result
def outputDict (self, *args): for item in self.selection: self.getKeyableAttr = cmds.listAttr(item,k = True) #defines list of keyable attributes self.lockedAttr = cmds.listAttr(item, l = True) #gets locked attributes for key in self.getKeyableAttr: rar = cmds.connectionInfo((item +'.' +key), isDestination = True) #grabs attributes with incoming connections if rar == False: #if attribute doesn't have an incoming connection, continues if not self.lockedAttr: #if there are no locked attributes, defines as empty self.lockedAttr = ['empty'] elif key not in self.lockedAttr: #if it's not in locked attributes, self.infoDict[item+"."+key] = cmds.getAttr(item+"."+key) #adds attributes to dictionary with their values
def attributes(self): """ Construct and return attribute list that belongs to node. :rtype: ``set`` """ if self._attributes is None: attributes = set(cmds.listAttr(self.fullpath, shortNames=True)) attributes.update(set(cmds.listAttr(self.fullpath))) self._attributes = attributes return self._attributes
def getAttrs(self): """ Stores the dictionary of userAttrs of an object.""" self.userAttrsDict = attributes.returnUserAttrsToDict(self.nameLong) or {} self.userAttrs = mc.listAttr(self.nameLong, userDefined = True) or [] self.attrs = mc.listAttr(self.nameLong) or [] self.keyableAttrs = mc.listAttr(self.nameLong, keyable = True) or [] self.transformAttrs = [] for attr in 'translate','translateX','translateY','translateZ','rotate','rotateX','rotateY','rotateZ','scaleX','scale','scaleY','scaleZ','visibility','rotateOrder': if mc.objExists(self.nameLong+'.'+attr): self.transformAttrs.append(attr)
def attributeExists(attr,node): """ Check if attribute exists on node """ if (attr and node): if not cmds.objExists(node): return 0 if attr in cmds.listAttr(node,shortNames= True): return 1 if attr in cmds.listAttr(node): return 1 return 0
def attrsAtDefault(obj, attrList=None, tol=0.000001): """ Check object attributes are at default values. @param tol: @param obj: Object to check default attribute values on. @type obj: str @param attrList: List of attributes to check. @type attrList: list or None """ # Check Object if not cmds.objExists(obj): print('Object "' + obj + '" does not exist! Returning False...') return False # Check Attribute List if not attrList: attrList = [] attrList += cmds.listAttr(obj, k=True) or [] attrList += cmds.listAttr(obj, cb=True) or [] # Get List of User Defined Attributes udAttrList = [cmds.attributeName(obj + '.' + at, s=True) for at in cmds.listAttr(obj, ud=True) or []] # Check Attribute Values for at in attrList: # Check Attribute Exists if not cmds.attributeQuery(at, n=obj, ex=True): print('Object attribute "' + obj + '.' + at + '" not found!') continue # Check Value attr = cmds.attributeName(obj + '.' + at, s=True) if attr in ['tx', 'ty', 'tz', 'rx', 'ry', 'rz']: # Translate / Rotate if abs(cmds.getAttr(obj + '.' + attr)) > tol: return False elif attr in ['sx', 'sy', 'sz']: # Scale if abs(1.0 - cmds.getAttr(obj + '.' + attr)) > tol: return False else: # User Defined if attr in udAttrList: defVal = cmds.addAttr(obj + '.' + attr, q=True, dv=True) if abs(defVal - cmds.getAttr(obj + '.' + attr)) > tol: return False # ================= # - Return Result - # ================= return True
def list_connectable_attributes(node): '''Lists the possible connectable attributes for a node. Parameters: node [str] : The name of the node in the scene. On Exit: Returns a list of the attributes that can be connected to and/or from the node. ''' return cmds.listAttr(node, connectable=True, multi=True) + \ cmds.listAttr(node, connectable=True, shortNames=True, multi=True)
def copy_attributes(src_name, dst_name, include=None, prefix=None, connect=False, copy_values=False): include = set(include) if include else None src_obj = mobject_from_name(src_name) src_dep = om.MFnDependencyNode(src_obj) dst_obj = mobject_from_name(dst_name) dst_dep = om.MFnDependencyNode(dst_obj) existing_attrs = set(cmds.listAttr(dst_name)) with context.selection(): cmds.select([dst_name], replace=True) for attr_name in cmds.listAttr(src_name): if include and attr_name not in include: continue if prefix and not attr_name.startswith(prefix): continue # Skip any attributes which are part of a multi-attribute unless # specifically requested. if not include and cmds.attributeQuery(attr_name, node=src_name, listParent=True): continue attr_obj = src_dep.attribute(attr_name) attr_plug = om.MPlug(src_obj, attr_obj) # Create the attribute on the destination of it doesn't exist. if attr_name not in existing_attrs: dst_dep.addAttribute(attr_obj) if connect: src_attr = src_name + '.' + attr_name dst_attr = dst_name + '.' + attr_name existing_conn = cmds.connectionInfo(dst_attr, sourceFromDestination=True) if existing_conn and existing_conn != src_attr: cmds.warning('Replacing connection from %r to %r' % (existing_conn, dst_attr)) if not existing_conn or existing_conn != src_attr: cmds.connectAttr(src_attr, dst_attr) elif copy_values: # Evaluate the mel required to copy the values. for mel_chunk in attr_plug.getSetAttrCmds(): mel.eval(mel_chunk)
def _data(self, mode="save"): """ Handles gathering all of the needed overlap data. @param: mode: Can either be "save" or "load". """ overlap_data = dict() dy_attrs = dict() if mode == "save": current_rig = self.rig_box.currentText() meta_nodes = self.overlap_obj.find_meta_attribute("metaNode") controls = self.overlap_obj.find_meta_attribute("dynamicControl") meta_node = None for node in meta_nodes: if node.startswith(current_rig): meta_node = node if meta_node: # data attributes = cmds.listAttr(meta_node, ud=True) for attribute in attributes: value = cmds.getAttr("{0}.{1}".format(meta_node, attribute)) overlap_data[attribute] = value # attributes for control in controls: if control.startswith(current_rig): attributes = cmds.listAttr(control, ud=True) for attribute in attributes: value = cmds.getAttr("{0}.{1}".format(control, attribute)) dy_attrs[attribute] = value overlap_data["dynamicAttributes"] = dy_attrs path = self.overlap_obj._json_save(overlap_data) return path return overlap_data elif mode == "load": # data self.overlap_data = self.overlap_obj._json_load() # cancel if not self.overlap_data: return # new loaded data self.root_group = self.overlap_data["rootGroup"] self.rig_name = self.overlap_data["rigName"] self.parent_control = self.overlap_data["parentControl"] self.controls = self.overlap_data["controls"] self.point_lock = int(self.overlap_data["pointLock"]) self.start_frame = int(self.overlap_data["startFrame"]) self.end_frame = int(self.overlap_data["endFrame"]) self.dynamic_control = self.overlap_data["dynamicControl"]
def getGJNames(self, containerName, moduleInfo, jointInfo, userSpecifiedName): """ Get all the attributes we need into a list """ """ I am changing the way we get the parent joint and game joint names. I do not need a new attr because the info is already contained in the module via the "gameJntNames and hookObject """ blueprintJointNames = [] gameJointNames = [] parentJointNames = [] jointRotateOrder = [] jointOrient = [] jointOrientX = [] jointOrientY = [] jointOrientZ = [] jointPositionX = [] jointPositionY = [] jointPositionZ = [] """ Get the namespace from the module container """ nameSpace = containerName.replace("module_container", "") moduleNamespace = moduleInfo[6] """ Get game joint names """ for index in range(len(jointInfo)): instPrefix = self.pruneUSpecName(userSpecifiedName)[0] instSuffix = self.pruneUSpecName(userSpecifiedName)[1] jointNum = str(index + 1) joint = (instPrefix + jointNum + "_" + instSuffix + "_gjnt") gameJointNames.append(joint) """ Get blueprint joint names """ for info in jointInfo: bpSufix = info[0] bpJointName = (nameSpace + "blueprint_" + bpSufix) blueprintJointNames.append(bpJointName) """ Get the position """ jointPosition = (moduleInfo)[0] for pos in jointPosition: jointPositionX.append(pos[0]) jointPositionY.append(pos[1]) jointPositionZ.append(pos[2]) """ get the joint orientations """ jointOrientations = moduleInfo[1] """ Determine how the joint is oriented """ orientWithAxis = False pureOrientations = False if jointOrientations[0] == None: orientWithAxis = True jointOrientations = jointOrientations[1] else: pureOrientations = True jointOrientations = jointOrientations[0] numOrientations = len(jointOrientations) numJoints = len(jointInfo) for i in range(numJoints): if orientWithAxis: # Spine breaking because jointOrient passed without a value. Adding this for testing jointOrientation = [0.0, 0.0, 0.0] if i != 0: offsetIndex = i - 1 if offsetIndex < numOrientations: jointOrientation = (jointOrientations[offsetIndex][0]) else: jointOrientation = [0.0, 0.0, 0.0] if i < numOrientations: jointOrientation = [ jointOrientations[i][0], jointOrientations[i][1], jointOrientations[i][2] ] jointOrient.append(jointOrientation) """ Split the vars into axis """ for orient in jointOrient: jointOrientX.append(orient[0]) jointOrientY.append(orient[1]) jointOrientZ.append(orient[2]) """ Retrieve the parent joint """ hookObject = moduleInfo[4] if hookObject == None: parentJointNames.append("None") if hookObject != None: userSpecFromHook = self.getUserSpecNameFromHook(hookObject) parentName = (userSpecFromHook + "_gjnt") parentJointNames.append(parentName) for index in range(len(gameJointNames)): current = gameJointNames[index] if current == gameJointNames[0]: pass else: parent = (gameJointNames[index - 1]) if parent not in parentJointNames: parentJointNames.append(parent) """ Get the rotateOrder from the translation control """ attrs = cmds.listAttr(containerName) for attr in attrs: roSuffix = "rotateOrder" result = attr.endswith(roSuffix) if result == True: roAttr = cmds.getAttr(containerName + "." + attr) jointRotateOrder.append(roAttr) else: """ This breaking on select modules """ jointRotateOrder.append(0) self.storeJointVars(gameJointNames, parentJointNames, jointPositionX, jointPositionY, jointPositionZ, jointRotateOrder, blueprintJointNames, jointOrientX, jointOrientY, jointOrientZ, containerName)
def generate(self, objects, startFrame=None, endFrame=None): ''' generates an anim dictionary - its basically just dict with node names for keys. key values are lists of tuples with the form: (keyTime, attrDict) where attrDict is a dictionary with attribute name keys and attribute value keys ''' defaultWeightedTangentOpt = bool( cmd.keyTangent(q=True, g=True, wt=True)) self.clear() if startFrame is None: startFrame = cmd.playbackOptions(q=True, min=True) if endFrame is None: endFrame = cmd.playbackOptions(q=True, max=True) startFrame, endFrame = list(sorted([startFrame, endFrame])) self.offset = startFrame #list all keys on the objects - so we can determine the start frame, and range. all times are stored relative to this time allKeys = cmd.keyframe(objects, q=True) or [] allKeys.sort() allKeys = [k for k in allKeys if startFrame <= k <= endFrame] self.offset = offset = allKeys[0] self.__range = allKeys[-1] - offset for obj in objects: attrs = cmd.listAttr(obj, keyable=True, visible=True, scalar=True) if attrs is None: continue objDict = {} self[obj] = objDict for attr in attrs: timeTuple = startFrame, endFrame #so the attr value dict contains a big fat list containing tuples of the form: #(time, value, itt, ott, ita, ota, iw, ow, isLockedTangents, isWeightLock) attrpath = '%s.%s' % (obj, attr) times = cmd.keyframe(attrpath, q=True, t=timeTuple) weightedTangents = defaultWeightedTangentOpt #if there is an animCurve this will return its "weighted tangent" state - otherwise it will return None and a TypeError will be raised try: weightedTangents = bool( cmd.keyTangent(attrpath, q=True, weightedTangents=True)[0]) except TypeError: pass if times is None: #in this case the attr has no animation, so simply record the pose for this attr objDict[attr] = (False, [(None, cmd.getAttr(attrpath), None, None, None, None, None, None, None, None)]) continue else: times = [t - offset for t in times] values = cmd.keyframe(attrpath, q=True, t=timeTuple, vc=True) itts = cmd.keyTangent(attrpath, q=True, t=timeTuple, itt=True) otts = cmd.keyTangent(attrpath, q=True, t=timeTuple, ott=True) ixs = cmd.keyTangent(attrpath, q=True, t=timeTuple, ix=True) iys = cmd.keyTangent(attrpath, q=True, t=timeTuple, iy=True) oxs = cmd.keyTangent(attrpath, q=True, t=timeTuple, ox=True) oys = cmd.keyTangent(attrpath, q=True, t=timeTuple, oy=True) isLocked = cmd.keyTangent(attrpath, q=True, t=timeTuple, weightLock=True) isWeighted = cmd.keyTangent(attrpath, q=True, t=timeTuple, weightLock=True) objDict[attr] = weightedTangents, zip(times, values, itts, otts, ixs, iys, oxs, oys, isLocked, isWeighted)
def exportBlendShapes(): """Exports sparse blendShape data from the scene for each mesh with a blendShape deformer in its history. This is accomplished by duplicating the mesh and tagging vertices in the duplicate using vertex colors. The duplicate then stores all of the data as user properties.""" # find all of the potential models in the scene models = om.MSelectionList() for model in cmds.ls(transforms=True): models.add(model) # store a dictionary mapping models whose shapes have a blendShape upstream to all of their blendShape nodes modelsWithBlendShapeDeformers = {} dagPath = om.MDagPath() iter = om.MItSelectionList(models) while not iter.isDone(): iter.getDagPath(dagPath) model = om.MDagPath(dagPath) try: # ensure the current transform has a shape node dagPath.extendToShape() # search upstream from shape for all blendShape nodes dg = om.MItDependencyGraph(dagPath.node(), om.MFn.kBlendShape, om.MItDependencyGraph.kUpstream) while not dg.isDone(): # add the blendShape nodes to a list in the dictionary if not modelsWithBlendShapeDeformers.has_key(model): modelsWithBlendShapeDeformers[model] = [] modelsWithBlendShapeDeformers[model].append(dg.currentItem()) dg.next() except: pass iter.next() # create tagged duplicates for each model with blendShapes and its targets for model in modelsWithBlendShapeDeformers.keys(): # delete non-deformer history on the model in order to collapse intermediate nodes # model will come into Unity wrong, but at least not with ugly error cmds.select(model.partialPathName()) mel.eval('doBakeNonDefHistory( 1, {"prePost" });') cmds.select(cl=True) # zero all blendShape target weights on the model for blendNode in modelsWithBlendShapeDeformers[model]: fn = om.MFnDependencyNode(blendNode) aliases = cmds.aliasAttr(fn.name(), q=True) for alias in aliases: # skip non-weight attributes if not re.match('weight\[[0-9]+\]', alias): continue dest = '%s.%s'%(fn.name(), alias) source = cmds.listConnections(dest, p=True) if source: cmds.disconnectAttr(source[0], dest) cmds.setAttr(dest, 0.0) # duplicate the base mesh and indicate that it is the base index map taggedBaseMesh = cmds.duplicate(model.partialPathName())[0] taggedBaseMesh = cmds.rename(taggedBaseMesh, model.partialPathName()+'__blendShapeIndexMap') customAttrs = cmds.listAttr(taggedBaseMesh, ud=True) if (customAttrs): for attr in customAttrs: try: cmds.deleteAttr(taggedBaseMesh, at=attr) except: pass cmds.addAttr(taggedBaseMesh, ln='isBlendShapeMapFor', dt='string') cmds.setAttr('%s.isBlendShapeMapFor'%taggedBaseMesh, model.partialPathName(), type='string') # tag each vertex in the base shape duplicate dagPath = om.MDagPath() sel = om.MSelectionList() sel.add(taggedBaseMesh) sel.getDagPath(0, dagPath) dagPath.extendToShape() tagMesh(dagPath) # duplicate the tagged base mesh to create the seamless base mesh seamlessBaseMesh = cmds.duplicate(taggedBaseMesh)[0] seamlessBaseMesh = cmds.rename(seamlessBaseMesh, model.partialPathName()+'__seamlessBaseMesh') for attr in cmds.listAttr(seamlessBaseMesh, ud=True): try: cmds.deleteAttr(seamlessBaseMesh, at=attr) except: pass makeSeamless(seamlessBaseMesh) # link seamless mesh to tagged base shape cmds.addAttr(seamlessBaseMesh, ln='isSeamlessBaseMeshFor', dt='string') cmds.setAttr('%s.isSeamlessBaseMeshFor'%seamlessBaseMesh, taggedBaseMesh, type='string') # make the seamless base mesh a child of the tagged base mesh, in order to avoid creating additional roots cmds.parent(seamlessBaseMesh, taggedBaseMesh) # create a color-tagged copy of each target, linked back to the tagged base shape via user properties for blendNode in modelsWithBlendShapeDeformers[model]: fn = om.MFnDependencyNode(blendNode) aliases = cmds.aliasAttr(fn.name(), q=True) for alias in aliases: # skip weight attributes if re.match('weight\[[0-9]+\]', alias): continue # create a duplicate of the composite shape and convert it into a seamless mesh cmds.setAttr('%s.%s'%(fn.name(), alias), 1.0) taggedTarget = cmds.duplicate(model.partialPathName())[0] attrs = cmds.listAttr(taggedTarget, ud=True) if (attrs): for attr in attrs: try: cmds.deleteAttr(taggedTarget, at=attr) except: pass taggedTarget = cmds.rename(taggedTarget, '%s__blendShapeTarget__%s'%(model.partialPathName(), alias)) makeSeamless(taggedTarget) cmds.setAttr('%s.%s'%(fn.name(), alias), 0.0) # tag the duplicated target dagPath = om.MDagPath() sel = om.MSelectionList() sel.add(taggedTarget) sel.getDagPath(0, dagPath) dagPath.extendToShape() tagMesh(dagPath) # link target to tagged base shape cmds.addAttr(taggedTarget, ln='isBlendShapeTargetFor', dt='string') cmds.setAttr('%s.isBlendShapeTargetFor'%taggedTarget, taggedBaseMesh, type='string') # make the tagged mesh a child of the tagged base mesh, in order to avoid creating additional roots cmds.parent(taggedTarget, taggedBaseMesh) # make the tagged mesh a child of the original, in order to avoid creating additional roots cmds.parent(taggedBaseMesh, model.partialPathName())
def CreateLoc(oObj, ver): if ver == 0: Order = cmds.optionMenu('Order_List', q=True, sl=True) - 1 BakeAll = cmds.checkBox("FrameLock", q=True, value=True) else: Order = cmds.optionMenu('Check_Order_List', q=True, sl=True) - 1 BakeAll = cmds.checkBox("Check_FrameLock", q=True, value=True) timeIn = cmds.playbackOptions(q=True, min=True) timeout = cmds.playbackOptions(q=True, max=True) inframe = [] outframe = [] Flag = 0 plotObj = [] plotDummy = [] obj_tmp = [] delConst = [] for i in oObj: obj_tmp.append(i) #キー、オーダー、アトリビュート取得 Original_Orders = cmds.listAttr(i, r=True, string="Original_Order*") oObj_Order = cmds.getAttr(i + ".rotateOrder") oKey_Rot = [] if cmds.findKeyframe(i, c=True, at='rotateX') != None: oKey_Rot.append(cmds.findKeyframe(i, c=True, at='rotateX')) if cmds.findKeyframe(i, c=True, at='rotateY') != None: oKey_Rot.append(cmds.findKeyframe(i, c=True, at='rotateY')) if cmds.findKeyframe(i, c=True, at='rotateZ') != None: oKey_Rot.append(cmds.findKeyframe(i, c=True, at='rotateZ')) if len(oKey_Rot) > 1: keys = cmds.keyframe(oKey_Rot[0], query=True) if len(keys) > 1: #ここからが実行文 #アトリビュートの設定とオリジナルのキーを保存しておく if not cmds.objExists(i + ".Original_Order"): cmds.addAttr(i, sn="Ori", ln="Original_Order", dt="string") cmds.setAttr(i + ".Original_Order", oObj_Order, type="string") if not cmds.objExists(i + ".Original_Order_RotX"): cmds.addAttr(i, sn="RotX", ln="Original_Order_RotX", at="double") cmds.setAttr(i + ".Original_Order_RotX", e=True, k=True, cb=False) cmds.copyKey(i, at="rotateX", o="curve") cmds.pasteKey(i + '.Original_Order_RotX') if not cmds.objExists(i + ".Original_Order_RotY"): cmds.addAttr(i, sn="RotY", ln="Original_Order_RotY", at="double") cmds.setAttr(i + ".Original_Order_RotY", e=True, k=True, cb=False) cmds.copyKey(i, at="rotateY", o="curve") cmds.pasteKey(i + '.Original_Order_RotY') if not cmds.objExists(i + ".Original_Order_RotZ"): cmds.addAttr(i, sn="RotZ", ln="Original_Order_RotZ", at="double") cmds.setAttr(i + ".Original_Order_RotZ", e=True, k=True, cb=False) cmds.copyKey(i, at="rotateZ", o="curve") cmds.pasteKey(i + '.Original_Order_RotZ') #ロケータを作ってオーダーを変えてプロット oLoc = cmds.spaceLocator(n=i + "_TempObj") inframe.append(keys[0]) outframe.append(keys[-1]) PointCons = cmds.pointConstraint(i, oLoc, n="Dummy_point") OrientCons = cmds.orientConstraint(i, oLoc, n="Dummy_orient") cmds.setAttr(i + ".rotateOrder", Order) Connections = cmds.listRelatives(oLoc, c=True, typ="constraint", fullPath=True) delConst.append(Connections) if BakeAll == True: plotObj.append(i + ".rotateX") plotObj.append(i + ".rotateY") plotObj.append(i + ".rotateZ") dummy = oLoc[0] plotDummy.append(dummy + ".rotateX") plotDummy.append(dummy + ".rotateY") plotDummy.append(dummy + ".rotateZ") else: cmds.bakeResults([ oLoc[0] + ".rotateX", oLoc[0] + ".rotateY", oLoc[0] + ".rotateZ" ], sm=False, t=(keys[0], keys[-1]), pok=True) for d in Connections: cmds.select(d) cmds.delete() To_OrientCons = cmds.orientConstraint(oLoc, i, n="Dummy_orient") cmds.delete(i + "_rotateX") cmds.delete(i + "_rotateY") cmds.delete(i + "_rotateZ") cmds.bakeResults( [i + ".rotateX", i + ".rotateY", i + ".rotateZ"], sm=False, t=(keys[0], keys[-1]), pok=True) Connections = cmds.listRelatives(i, c=True, typ="constraint", fullPath=True) for c in Connections: cmds.select(c) cmds.delete() cmds.delete(oLoc) if len(plotDummy) > 0: #配列済なので、sortedでソート実行 S_in = sorted(inframe) S_out = sorted(outframe) Sort_in = set(S_in) Sort_out = set(S_out) Min_Frame = list(Sort_in)[0] Max_Frame = list(Sort_out)[-1] #Plot cmds.bakeResults(plotDummy, sm=False, t=(Min_Frame, Max_Frame), pok=True) for d in delConst: cmds.select(d) cmds.delete() if len(obj_tmp) != []: delConst = [] for tmp in obj_tmp: OrientCons = cmds.orientConstraint( tmp + "_TempObj", tmp, n="Dummy_orient") Connections = cmds.listRelatives( tmp, c=True, typ="constraint", fullPath=True) delConst.append(Connections) cmds.bakeResults(plotObj, sm=False, t=(Min_Frame, Max_Frame), pok=True) for d in delConst: cmds.select(d) cmds.delete() for tmp in obj_tmp: cmds.delete(tmp + "_TempObj") else: cmds.warning(u'キーが2つ以上打たれていません。') DirectChange = cmds.confirmDialog( title='ChangeOrder', m=u'キーが2つ以上打たれていません。そのままオーダーが変えますがよろしいでしょうか?', button=['Yes', 'No'], defaultButton='Yes', cancelButton='No', dismissString='No') if DirectChange == "Yes": cmds.setAttr(i + ".rotateOrder", Order) else: cmds.warning(u'終了しました。') else: cmds.warning(u'回転XYZの2つ以上キー設定がされてません') cmds.confirmDialog(title='ChangeOrder', m=u'回転XYZの2つ以上キー設定がされてません', icon='warning') if BakeAll == True: delConect = [] Min_Frame = sorted(inframe)[0] Max_Frame = sorted(outframe)[-1] cmds.bakeResults(plotDummy, sm=False, t=(Min_Frame, Max_Frame), pok=True) for d in Connections: cmds.select(d) cmds.delete() for i in oObj: To_OrientCons = cmds.orientConstraint(i + "_TempObj", i, n="Dummy_orient") cmds.delete(i + "_rotateX") cmds.delete(i + "_rotateY") cmds.delete(i + "_rotateZ") delConect.append( cmds.listRelatives(i, c=True, typ="constraint", fullPath=True)) cmds.bakeResults(plotObj, sm=False, t=(Min_Frame, Max_Frame), pok=True) for dc in delConect: cmds.select(dc) cmds.delete() delConect = [] for tmp in oObj: OrientCons = cmds.orientConstraint(tmp + "_TempObj", tmp, n="Dummy_orient") Connections = cmds.listRelatives(tmp, c=True, typ="constraint", fullPath=True) delConect.append(Connections) cmds.bakeResults(plotObj, sm=False, t=(Min_Frame, Max_Frame), pok=True) for d in delConect: cmds.select(d) cmds.delete() for tmp in oObj: cmds.delete(tmp + "_TempObj")
def copyChannels(src, dst, transform=True, joint=True, userDefined=True): ''' ''' # Check source and destination objects if not mc.objExists(src): raise Exception('Source object "' + src + '" does not exist!!') if not mc.objExists(dst): raise Exception('Destination object "' + dst + '" does not exist!!') # ----------------------- # - Copy channel values - # ----------------------- # Transform if transform: tAttrs = ['tx', 'ty', 'tz', 'rx', 'ry', 'rz', 'sx', 'sy', 'sz'] for attr in tAttrs: # Get source attribute value attrVal = mc.getAttr(src + '.' + attr) # Set destination attribute value if not mc.objExists(dst + '.' + attr): raise Exception('Destination attribute "' + dst + '.' + attr + '" does not exist!!') mc.setAttr(dst + '.' + attr, l=False) mc.setAttr(dst + '.' + attr, attrVal) # Joint if joint: jAttrs = [ 'radius', 'stx', 'sty', 'stz', 'pax', 'pay', 'paz', 'jox', 'joy', 'joz' ] for attr in jAttrs: # Check source attribute if not mc.objExists(src + '.' + attr): continue # Get source attribute value attrVal = mc.getAttr(src + '.' + attr) # Set destination attribute value if not mc.objExists(dst + '.' + attr): raise Exception('Destination attribute "' + dst + '.' + attr + '" does not exist!!') mc.setAttr(dst + '.' + attr, l=False) mc.setAttr(dst + '.' + attr, attrVal) # User Defined if userDefined: uAttrs = mc.listAttr(src, ud=True) for attr in tAttrs: # Get source attribute value attrVal = mc.getAttr(src + '.' + attr) # Check destination attribute if not mc.objExists(dst + '.' + attr): print('Destination attribute "' + dst + '.' + attr + '" does not exist!! Skipping attribute...') continue # Set destination attribute value mc.setAttr(dst + '.' + attr, l=False) mc.setAttr(dst + '.' + attr, attrVal)
def getAllNodes(nodes, shaderNetwork): for node in nodes: history = cmds.listHistory(node) for n in history: if not n in shaderNetwork["nodes"]: #print(cmds.objectType(n)) shaderNetwork["nodes"][n] = {} shaderNetwork["nodes"][n]["type"] = cmds.objectType(n) shaderNetwork["nodes"][n]["data"] = {} nodeAttributes = cmds.listAttr(n) tempNode = cmds.createNode(cmds.objectType(n), n="tempNode") for a in nodeAttributes: # print("__________________________________") # print(cmds.getAttr(n + "." + a, type=True)) # print("__________________________________") try: type = cmds.getAttr(n + "." + a, type=True) if type != "TdataCompound": try: nodeAttr = cmds.getAttr(n + '.' + str(a)) tempAttr = cmds.getAttr(tempNode + '.' + str(a)) if nodeAttr != tempAttr: shaderNetwork["nodes"][n]["data"][a] = {} shaderNetwork["nodes"][n]["data"][a][ "value"] = nodeAttr shaderNetwork["nodes"][n]["data"][a][ "type"] = cmds.getAttr(n + "." + a, type=True) except: pass else: #print("COMPOUND") #print(a) looping = True attrIndex = 0 compounds = [] while looping: #print(a) try: compound = cmds.getAttr( str(n) + '.' + str(a) + "[" + str(attrIndex) + "]") #print(compound[0][2]) if (compound[0][2] == 0.0): #print("empty") pass else: compounds.append(compound[0]) attrIndex += 1 if (attrIndex == 100): looping = False except: loop = false #print(compounds) if (compounds[0]): #print("not empty") shaderNetwork["nodes"][n]["data"][a] = {} shaderNetwork["nodes"][n]["data"][a][ "value"] = compounds shaderNetwork["nodes"][n]["data"][a][ "type"] = "TdataCompound" except: pass cmds.delete(tempNode) attributes = cmds.listAttr(n) for attr in attributes: try: connection = cmds.connectionInfo(n + '.' + str(attr), sfd=1) if connection: try: shaderNetwork["connections"].append({ "from": cmds.listHistory(connection)[0], "to": n, "fromAttribute": connection, "toAttributeComplete": n + '.' + str(attr), "toAttribute": str(attr) }) except: pass except: pass # for attr in attributes: # try: # connections = cmds.listConnections(node + '.' + attr, d=False, s=True) # # links = cmds.connectionInfo(node + '.' + atr, sfd=1) # except: # pass # if connections: # getAllNodes(connections) return shaderNetwork
def overlap(self): NotUseFirstCtrl = self.First_CB.isChecked() CycleCheckBox = self.Cycle_CB.isChecked() TRANSLATEmode = self.Translate_CB.isChecked() OnLayerSwitch = self.Bake_CB.isChecked() WindSwitch = self.Wind_CB.isChecked() windScaleValue = self.Wind_Scale_SP.value() windSpeedValue = self.Wind_Speed_SP.value() overlapIntensity = self.Scale_SP.value() timeShift = self.Softness_SP.value() timeStart = cmds.playbackOptions(q=1, min=1) timeEnd = cmds.playbackOptions(q=1, max=1) controller_list = cmds.ls(sl=1) # NOTE 生成骨骼 | 调整轴向 cmds.select(cl=1) jnt_list = [] _jnt = None for controller in controller_list: pos = cmds.xform(controller, q=1, rp=1, ws=1) jnt = cmds.joint(p=pos, rad=1, n="%s_OverlapJoint" % controller) if _jnt: cmds.joint(_jnt, e=1, zso=1, oj="xyz", sao="yup") jnt_list.append(jnt) _jnt = jnt else: last_jnt = cmds.duplicate(jnt, rr=1, n="%s_LastOrientJoint" % controller)[0] cmds.move(2, 0, 0, r=1, ls=1, wd=1) cmds.parent(last_jnt, jnt) jnt_list.append(last_jnt) cmds.joint(jnt, e=1, zso=1, oj="xyz", sao="yup") sumLenghtJoints = sum( [cmds.getAttr("%s.tx" % jnt) for jnt in jnt_list]) averageLenghtJoints = (sumLenghtJoints - 2) / len(jnt_list) cmds.setAttr(last_jnt + ".tx", averageLenghtJoints) constraint_list = [] for controller, jnt in zip(controller_list, jnt_list): constraint_list.extend(cmds.parentConstraint(controller, jnt, mo=1)) # NOTE 烘焙骨骼跟随控制器的关键帧 cmds.bakeResults( jnt_list, simulation=1, # NOTE 开启模拟 解决卡顿问题 t=(timeStart, timeEnd), sampleBy=1, oversamplingRate=1, disableImplicitControl=1, preserveOutsideKeys=1, sparseAnimCurveBake=0, removeBakedAttributeFromLayer=0, removeBakedAnimFromLayer=0, bakeOnOverrideLayer=0, minimizeRotation=1, at=['tx', 'ty', 'tz', 'rx', 'ry', 'rz']) cmds.delete(constraint_list) if CycleCheckBox: # NOTE 将骨骼关键帧复制多几份 for i, jnt in enumerate(jnt_list): cmds.selectKey(cmds.listConnections(jnt + ".tx", type="animCurve"), cmds.listConnections(jnt + ".ty", type="animCurve"), cmds.listConnections(jnt + ".tz", type="animCurve"), cmds.listConnections(jnt + ".rx", type="animCurve"), cmds.listConnections(jnt + ".ry", type="animCurve"), cmds.listConnections(jnt + ".rz", type="animCurve"), r=1, k=1, t=(timeStart, timeEnd)) cmds.copyKey() cmds.pasteKey(time=(timeEnd, timeEnd), float=(timeEnd, timeEnd), option="insert", copies=2, connect=0, timeOffset=0, floatOffset=0, valueOffset=0) cycleLenghts = timeEnd - timeStart timeEnd = timeEnd + 2 * cycleLenghts # NOTE 进行 overlap overlapIntensityMult = averageLenghtJoints / overlapIntensity * 5 timeShiftNeg = -timeShift timeShiftCurrent = 1 + timeShift gc_list = [] aim_data = {} for i, jnt in enumerate(jnt_list): offset_loc = cmds.spaceLocator(n="overlapOffsetLocator%s" % i)[0] cmds.delete(cmds.parentConstraint(jnt, offset_loc, w=1)) cmds.move(overlapIntensityMult, 0, 0, r=1, os=1, ls=1) con = cmds.parentConstraint(jnt, offset_loc, mo=1) cmds.bakeResults(offset_loc, simulation=0, t=(timeStart, timeEnd), sampleBy=1, disableImplicitControl=1, preserveOutsideKeys=1, minimizeRotation=1, at=['tx', 'ty', 'tz', 'rx', 'ry', 'rz']) cmds.delete(con) wind_loc = cmds.spaceLocator(n="overlapOffsetLocatorWind%s" % i)[0] gc_list.append(wind_loc) cmds.parent(wind_loc, offset_loc) cmds.makeIdentity(wind_loc, a=0, t=1, r=1, s=1, n=0, pn=1) animCurve_list = [ (offset_loc + "_translateX"), (offset_loc + "_translateY"), (offset_loc + "_translateZ"), (offset_loc + "_rotateX"), (offset_loc + "_rotateY"), (offset_loc + "_rotateZ"), ] for animCurve in animCurve_list: cmds.keyframe(animCurve, e=1, iub=1, r=1, o="over", tc=timeShift) cmds.keyframe(animCurve, t=(timeShiftCurrent, timeShiftCurrent), option="over", relative=1, timeChange=timeShiftNeg) aim_loc = cmds.spaceLocator(n="overlapInLocator_aim_%s" % i)[0] aim_grp = cmds.group(aim_loc, n=aim_loc + "_grp") cmds.pointConstraint(jnt, aim_grp) aim_data[aim_loc] = aim_grp cmds.aimConstraint(wind_loc, aim_grp, aimVector=[1, 0, 0], upVector=[0, 1, 0], worldUpType="object", worldUpObject=wind_loc) cmds.orientConstraint(wind_loc, aim_loc, mo=1, skip=["y", "z"], w=1) # NOTE 添加控制器 translate 坐标位移 if TRANSLATEmode and i != len(jnt_list) - 1: IK_loc = cmds.spaceLocator(n="overlapOffsetIKLocator%s" % i)[0] cmds.pointConstraint(jnt, IK_loc) cmds.bakeResults(IK_loc, simulation=0, t=(timeStart, timeEnd), sampleBy=1, disableImplicitControl=1, preserveOutsideKeys=1, minimizeRotation=1, at=['tx', 'ty', 'tz']) animCurve_list = [ (IK_loc + "_translateX"), (IK_loc + "_translateY"), (IK_loc + "_translateZ"), ] for animCurve in animCurve_list: cmds.keyframe(animCurve, e=1, iub=1, r=1, o="over", tc=timeShift) cmds.keyframe(animCurve, t=(timeShiftCurrent, timeShiftCurrent), option="over", relative=1, timeChange=timeShiftNeg) cmds.pointConstraint(IK_loc, aim_loc) gc_list.append(IK_loc) # NOTE 添加随机风向控制 if WindSwitch: windMultiply = 0.07 * overlapIntensityMult * windScaleValue speedMultiply = 20 / windSpeedValue cmds.setKeyframe(wind_loc, attribute=['translateY', 'translateZ'], t=[timeStart, timeStart]) cmds.bakeResults(wind_loc, simulation=0, t=(timeStart, timeEnd + speedMultiply), sampleBy=speedMultiply, oversamplingRate=1, disableImplicitControl=1, preserveOutsideKeys=1, at=['ty', 'tz']) for attr in cmds.listAttr(wind_loc, k=1): animCurve = cmds.listConnections("%s.%s" % (wind_loc, attr), type="animCurve") if not animCurve: continue for animCurveCurrent in animCurve: for animCurveCurrentKeysTime in cmds.keyframe( animCurveCurrent, q=1, t=(timeStart, timeEnd), tc=1): t = (animCurveCurrentKeysTime, animCurveCurrentKeysTime) animCurveCurrentKeysTimeArray = cmds.keyframe( animCurveCurrent, q=1, time=t, vc=1) RandomizerValue = random.random() * 2 - 1 animCurveCurrentKeysValueArrayAddRandom = animCurveCurrentKeysTimeArray[ 0] + windMultiply * RandomizerValue cmds.keyframe( animCurveCurrent, e=1, iub=1, r=1, o="over", vc=animCurveCurrentKeysValueArrayAddRandom, t=t) attr = (wind_loc + "_translateY") cmds.keyframe(attr, e=1, iub=1, r=1, o="over", tc=speedMultiply / 2) t = (speedMultiply / 2) + 1 cmds.selectKey(attr, add=1, k=1, t=(t, t)) cmds.keyframe(attr, animation="keys", r=1, o="over", tc=speedMultiply / -2) cmds.bakeResults(aim_grp, aim_loc, simulation=0, t=(timeStart, timeEnd), sampleBy=1, disableImplicitControl=1, preserveOutsideKeys=1, minimizeRotation=1, at=['tx', 'ty', 'tz', 'rx', 'ry', 'rz']) cmds.parentConstraint(aim_loc, jnt, mo=1) gc_list.append(offset_loc) gc_list.append(aim_grp) # NOTE 动画循环控制 if CycleCheckBox: timeStart = cmds.playbackOptions(q=1, min=1) timeEnd = cmds.playbackOptions(q=1, max=1) cycleLenghts = timeEnd - timeStart # NOTE 将关键帧挪动回去两个时间范围 for aim_loc, aim_grp in aim_data.items(): cmds.keyframe(cmds.listConnections(aim_loc + ".tx", type="animCurve"), cmds.listConnections(aim_loc + ".ty", type="animCurve"), cmds.listConnections(aim_loc + ".tz", type="animCurve"), cmds.listConnections(aim_loc + ".rx", type="animCurve"), cmds.listConnections(aim_loc + ".ry", type="animCurve"), cmds.listConnections(aim_loc + ".rz", type="animCurve"), cmds.listConnections(aim_grp + ".tx", type="animCurve"), cmds.listConnections(aim_grp + ".ty", type="animCurve"), cmds.listConnections(aim_grp + ".tz", type="animCurve"), cmds.listConnections(aim_grp + ".rx", type="animCurve"), cmds.listConnections(aim_grp + ".ry", type="animCurve"), cmds.listConnections(aim_grp + ".rz", type="animCurve"), e=1, iub=1, r=1, o="over", tc=cycleLenghts * -2) constraint_list = [] for i, [controller, jnt] in enumerate(zip(controller_list, jnt_list)): if NotUseFirstCtrl and i == 0: continue if cmds.getAttr(controller+".tx",k=1) and not cmds.getAttr(controller+".tx",l=1) and \ cmds.getAttr(controller+".ty",k=1) and not cmds.getAttr(controller+".ty",l=1) and \ cmds.getAttr(controller+".tz",k=1) and not cmds.getAttr(controller+".tz",l=1): constraint_list.extend( cmds.pointConstraint(jnt, controller, mo=1)) if cmds.getAttr(controller+".rx",k=1) and not cmds.getAttr(controller+".rx",l=1) and \ cmds.getAttr(controller+".ry",k=1) and not cmds.getAttr(controller+".ry",l=1) and \ cmds.getAttr(controller+".rz",k=1) and not cmds.getAttr(controller+".rz",l=1): constraint_list.extend( cmds.orientConstraint(jnt, controller, mo=1)) if NotUseFirstCtrl: controller_list = controller_list[1:] # NOTE 输出到控制器上 cmds.bakeResults( controller_list, simulation=1, # NOTE 开启模拟 解决卡顿问题 t=(timeStart, timeEnd), sampleBy=1, disableImplicitControl=1, bakeOnOverrideLayer=OnLayerSwitch, preserveOutsideKeys=1, minimizeRotation=1, at=['tx', 'ty', 'tz', 'rx', 'ry', 'rz']) cmds.delete(constraint_list) cmds.delete(jnt_list) cmds.delete(gc_list)
def k_checkTexfiles(self): texfiles=cc.ls(type='file') for texfile in texfiles: #判断有无自定义属性 userAttrs=cc.listAttr(texfile,ud=1) if userAttrs: #获取有无UDIM模式 ktexmode=cc.getAttr(texfile+'.uvTilingMode') #如果无: if not ktexmode: for userAttr in userAttrs: #判断自定义内容是否 Tex 开头 if userAttr[:3]=='Tex': #获取自定义属性的 内容 userTex=cc.getAttr(texfile+"."+userAttr) ##########设置节点内容 及 加入到节点数据############# ktemp={'path':userTex,'port':('.'+userAttr)} if self.kNodedate.has_key('kmayaTex_userTex'): if self.kNodedate['kmayaTex_userTex'].has_key(texfile): self.kNodedate['kmayaTex_userTex'][texfile].append(ktemp) else: self.kNodedate['kmayaTex_userTex'].update({texfile:[ktemp]}) else:self.kNodedate['kmayaTex_userTex']={texfile:[ktemp]} #################################################### #添加入总数组 if userTex and not userTex in self.kmayaTex: if os.path.exists(userTex): #print texfile self.kmayaTex.append(userTex) #print userTex userTex_tx=os.path.splitext(userTex)[0]+'.tx' if os.path.exists(userTex_tx) and not userTex_tx in self.kmayaTex: self.kmayaTex.append(userTex_tx) #print userTex_tx #有UDIM模式 else: for userAttr in userAttrs: #判断自定义内容是否 Tex 开头 if userAttr[:3]=='Tex': userTex=cc.getAttr(texfile+"."+userAttr) ##########设置节点内容 及 加入到节点数据############# ktemp={'path':userTex,'port':('.'+userAttr)} if self.kNodedate.has_key('kmayaTex_userTex'): if self.kNodedate['kmayaTex_userTex'].has_key(texfile): self.kNodedate['kmayaTex_userTex'][texfile].append(ktemp) else: self.kNodedate['kmayaTex_userTex'].update({texfile:[ktemp]}) else:self.kNodedate['kmayaTex_userTex']={texfile:[ktemp]} ##################################################### #获取自定义内容 的UDIM贴图 k_getUDIMp=k.getFilePatternString(userTex, False, ktexmode) k_exudims=k.findAllFilesForPattern(k_getUDIMp,None) #添加贴图入总数组 for k_exudim in k_exudims: if k_exudim and not k_exudim in self.kmayaTex: #print texfile self.kmayaTex.append(k_exudim) #print k_exudim k_exudim_tx=os.path.splitext(k_exudim)[0]+'.tx' if os.path.exists(k_exudim_tx) and not k_exudim_tx in self.kmayaTex: self.kmayaTex.append(k_exudim_tx) #print k_exudim_tx else: ktexfile=cc.getAttr(texfile+'.fileTextureName') ktexmode=cc.getAttr(texfile+'.uvTilingMode') ##########设置节点内容 及 加入到节点数据############# ktemp={'path':ktexfile,'port':'.fileTextureName'} if self.kNodedate.has_key('kmayaTex_default'): self.kNodedate['kmayaTex_default'].update({texfile:[ktemp]}) else:self.kNodedate['kmayaTex_default']={texfile:[ktemp]} ##################################################### if not ktexmode: if ktexfile and not os.path.isabs(ktexfile): ktexfile=self.projectDir+ktexfile ktexfile=ktexfile.replace('\\','/') if ktexfile and not ktexfile in self.kmayaTex: if os.path.exists(ktexfile): #print texfile self.kmayaTex.append(ktexfile) #print ktexfile ktexfile_tx=os.path.splitext(ktexfile)[0]+'.tx' if os.path.exists(ktexfile_tx) and not ktexfile_tx in self.kmayaTex: self.kmayaTex.append(ktexfile_tx) #print ktexfile_tx else: if ktexfile and not os.path.isabs(ktexfile): ktexfile=self.projectDir+ktexfile ktexfile=ktexfile.replace('\\','/') #maya内部UDIM命令 k_getUDIMp=k.getFilePatternString(ktexfile, False, ktexmode) k_exudim=k.findAllFilesForPattern(k_getUDIMp,None) for ktexfile in k_exudim: if ktexfile and not ktexfile in self.kmayaTex: #print texfile self.kmayaTex.append(ktexfile) #print ktexfile ktexfile_tx=os.path.splitext(ktexfile)[0]+'.tx' if os.path.exists(ktexfile_tx) and not ktexfile_tx in self.kmayaTex: self.kmayaTex.append(ktexfile_tx) #print ktexfile_tx #先判断插件有没开,防止找不到节点类型 if cc.pluginInfo("mtoa",q=1,l=1): aiTexfiles=cc.ls(type='aiImage') if aiTexfiles: for aiTexfile in aiTexfiles: #返回文件路径 aiTexfilesname = cc.getAttr(aiTexfile+'.filename') #判断是否为空 及 在总数组有无重复 及 文件是否存在 if aiTexfilesname and not aiTexfilesname in self.kaiTex: if os.path.exists(aiTexfilesname): #print aiTexfilesname self.kaiTex.append(aiTexfilesname) #判断此文件有无tx版本的路径 aiTexfilesname_tx=os.path.splitext(aiTexfilesname)[0]+'.tx' #判断文件是否存在 及 在总数组有无重复 if os.path.exists(aiTexfilesname_tx) and not aiTexfilesname_tx in self.kaiTex: self.kaiTex.append(aiTexfilesname_tx) #print aiTexfilesname_tx #先判断插件有没开,防止找不到节点类型 if cc.pluginInfo("vrayformaya",q=1,l=1): Vptexfiles=cc.ls(type='VRayPtex') if Vptexfiles: for Vptexfile in Vptexfiles: #返回文件路径 Vptexfilename = cc.getAttr(Vptexfile+'.ptexFile') #判断是否为空 及 在总数组有无重复 及 文件是否存在 if Vptexfilename and not Vptexfilename in self.kVpTex: if os.path.exists(Vptexfilename): #print Vptexfilename self.kaiTex.append(Vptexfilename) #判断此文件有无tx版本的路径 Vptexfilename_tx=os.path.splitext(Vptexfilename)[0]+'.tx' #判断文件是否存在 及 在总数组有无重复 if os.path.exists(Vptexfilename_tx) and not Vptexfilename_tx in self.kaiTex: self.kaiTex.append(Vptexfilename_tx) #print Vptexfilename_tx self.kTexture=list(set(self.kmayaTex+self.kaiTex+self.kVpTex))
def _refresh(self, node): #print('InputButtons._refresh: ' + node) try: lastParentLayout = cmds.setParent(q=True) cmds.setParent(self.path) with UITemplate('DefaultTemplate'): node_i = node + '.i' attrs = cmds.listAttr(node_i, m=True) or [] conn = cmds.listConnections( node_i, s=True, d=False, c=True, p=True) or [] conn = dict(zip(conn[::2], conn[1::2])) lyt_ = self.path + '|' children = [ (lyt_ + x) for x in (cmds.layout(self.path, q=True, ca=True) or []) ] nChildren = len(children) i = 0 node_ = node + '.' for attr in attrs: if i < nChildren: row = children[i] cmds.text(row + '|name', e=True, l=attr) upstream = row + '|upstream' trash = row + '|trash' else: row = cmds.rowLayout(nc=3, h=20, cw=[(2, 30), (3, 30)]) cmds.text('name', l=attr) upstream = cmds.symbolButton('upstream', i='hsUpStreamCon.png', h=20) trash = cmds.symbolButton('trash', i='smallTrash.png', h=20) cmds.setParent('..') plug = node_ + attr src = conn.get(plug) if src: cmds.symbolButton(upstream, e=True, en=True, c=_partial(_showUpstream, plug)) else: cmds.symbolButton(upstream, e=True, en=False) cmds.symbolButton(trash, e=True, c=_callback( cmds.evalEcho, 'removeMultiInstance -b 1 ' + plug)) i += 1 for i in range(i, nChildren): cmds.deleteUI(children[i]) finally: if lastParentLayout: cmds.setParent(lastParentLayout)
def checkObjectSetKey(self): ''' 驱动过的物体是否锁定并设置成了不可K帧。 ''' geoName = self.getGeoGroup() notGroup = ['hair_G' , 'arnold_loc' , 'yeti_G' , 'cloth_G'] if not geoName: OpenMaya.MGlobal_displayWarning('not geo group') else: notGroup.append(geoName[0]) notTransList = [] for n in notGroup: if pm.objExists(n): notTransList += self.notCkeck(pm.PyNode(n)) jointSel = cmds.ls( type = 'joint') if jointSel: for jnt in jointSel: attr = cmds.listAttr(jnt , k = True) if attr: for a in attr: value = cmds.getAttr(jnt+'.'+a , k = True) if value: if jnt not in self.keyjointList: self.keyjointList.append(jnt) continue all = cmds.ls(dag= True , type = 'transform' ) if not all: OpenMaya.MGlobal_displayInfo('file not object') return conList = cmds.ls( type =['constraint','joint']) ctrlList = [ cmds.listRelatives(s , p = True)[0] for s in cmds.ls(type = ['nurbsCurve' ,'camera'])] transList = [t for t in all if t not in conList+ctrlList+notTransList] attrs = ['t' , 'r' , 's' ] for t in transList: attr = cmds.listAttr(t , k = True ,sn = True) if attr: for at in attr: if at not in self.setKeyDict.keys(): continue value1 = cmds.getAttr(t +'.'+ at , l = True) if not value1: value = cmds.getAttr(t +'.'+ at) if value != self.setKeyDict[at] : if t not in self.keyOverName: self.keyOverName.append(t) continue if cmds.listConnections(t +'.'+ at , s = True , d = False): if t not in self.keyOverName: self.keyOverName.append(t) for at in attrs: valueX = cmds.getAttr(t +'.'+ at +'x' , l = True) valueY = cmds.getAttr(t +'.'+ at +'y' , l = True) valueZ = cmds.getAttr(t +'.'+ at +'z' , l = True) if valueX == True and valueX == True and valueX == True: continue if cmds.listConnections(t +'.'+ at , s = True , d = False): if t not in self.keyOverName: self.keyOverName.append(t) continue return self.keyOverName+self.keyjointList
def dpCreateRivet(self, geoToAttach, uvSetName, itemList, attachTranslate, attachRotate, addFatherGrp, addInvert, invT, invR, rivetGrpName='Rivet_Grp', askComponent=False, *args): """ Create the Rivet setup. """ # declaring variables self.shapeToAttachList = None self.shapeToAttach = None self.cpNode = None self.tempNoce = None attrList = ['tx', 'ty', 'tz', 'rx', 'ry', 'rz', 'sx', 'sy', 'sz'] self.rivetList, togetherList = [], [] isComponent = None # integrate to dpAutoRigSystem: self.masterGrp = None self.masterCtrl = None self.scalableGrp = None allList = cmds.ls(selection=False, type="transform") if allList: for node in allList: if cmds.objExists(node+"."+MASTER_GRP) and cmds.getAttr(node+"."+MASTER_GRP) == 1: self.masterGrp = node if self.masterGrp: masterCtrlList = cmds.listConnections(self.masterGrp+".masterCtrl") scalableGrpList = cmds.listConnections(self.masterGrp+".scalableGrp") if masterCtrlList: self.masterCtrl = masterCtrlList[0] if scalableGrpList: self.scalableGrp = scalableGrpList[0] # create Rivet_Grp in order to organize hierarchy: createdRivetGrp = False self.rivetGrp = rivetGrpName if not cmds.objExists(rivetGrpName): createdRivetGrp = True self.rivetGrp = cmds.group(name=rivetGrpName, empty=True) for attr in attrList: cmds.setAttr(self.rivetGrp+"."+attr, lock=True, keyable=False, channelBox=False) cmds.addAttr(self.rivetGrp, longName="dpRivetGrp", attributeType='bool') cmds.setAttr(self.rivetGrp+".dpRivetGrp", 1) if self.scalableGrp: cmds.parent(self.rivetGrp, self.scalableGrp) # get shape to attach: if cmds.objExists(geoToAttach): self.shapeToAttachList = cmds.ls(geoToAttach, dag=True, shapes=True) if self.shapeToAttachList: self.shapeToAttach = self.shapeToAttachList[0] # get shape type: self.shapeType = cmds.objectType(self.shapeToAttach) # verify if there are vertices, cv's or lattice points in our itemList: if itemList: asked = False for i, item in enumerate(itemList): if ".vtx" in item or ".cv" in item or ".pt" in item: if askComponent: if not asked: isComponent = cmds.confirmDialog(title="dpRivet on Components", message="How do you want attach vertices, cv's or lattice points?", button=("Individually", "Together", "Ignore"), defaultButton="Individually", dismissString="Ignore", cancelButton="Ignore") asked = True if isComponent == "Individually": cls = cmds.cluster(item, name=item[:item.rfind(".")]+"_"+str(i)+"_Cls")[0]+"Handle" clsToRivet = cmds.parent(cls, self.rivetGrp)[0] self.rivetList.append(clsToRivet) elif isComponent == "Together": togetherList.append(item) elif isComponent == "Ignore": itemList.remove(item) elif isComponent == "Ignore": itemList.remove(item) elif isComponent == "Together": togetherList.append(item) else: #Individually cls = cmds.cluster(item, name=item[:item.rfind(".")]+"_"+str(i)+"_Cls")[0]+"Handle" clsToRivet = cmds.parent(cls, self.rivetGrp)[0] self.rivetList.append(clsToRivet) else: #Individually cls = cmds.cluster(item, name=item[:item.rfind(".")]+"_"+str(i)+"_Cls")[0]+"Handle" clsToRivet = cmds.parent(cls, self.rivetGrp)[0] self.rivetList.append(clsToRivet) elif cmds.objExists(item): self.rivetList.append(item) else: mel.eval("error \"Select and add at least one item to be attached as a Rivet, please.\";") if isComponent == "Together": cls = cmds.cluster(togetherList, name="dpRivet_Cls")[0]+"Handle" clsToRivet = cmds.parent(cls, self.rivetGrp)[0] self.rivetList.append(clsToRivet) # check about locked or animated attributes on items: if not addFatherGrp: cancelProcess = False for rivet in self.rivetList: # locked: if cmds.listAttr(rivet, locked=True): cancelProcess = True break # animated: for attr in attrList: if cmds.listConnections(rivet+"."+attr, source=True, destination=False): cancelProcess = True break if cancelProcess: if createdRivetGrp: cmds.delete(self.rivetGrp) else: for rivet in self.rivetList: if not rivet in itemList: # clear created clusters: cmds.delete(rivet) mel.eval("error \"Canceled process: items to be Rivet can't be animated or have locked attributes, sorry.\";") return # workarount to avoid closestPoint node ignores transformations. # then we need to duplicate, unlock attributes and freezeTransformation: dupGeo = cmds.duplicate(geoToAttach, name=geoToAttach+"_dpRivet_TEMP_Geo")[0] # unlock attr: for attr in attrList: cmds.setAttr(dupGeo+"."+attr, lock=False) # parent to world: if cmds.listRelatives(dupGeo, allParents=True): cmds.parent(dupGeo, world=True) # freezeTransformation: cmds.makeIdentity(dupGeo, apply=True) dupShape = cmds.ls(dupGeo, dag=True, shapes=True)[0] # temporary transform node to store object's location: self.tempNode = cmds.createNode("transform", name=geoToAttach+"_dpRivet_TEMP_Transf", skipSelect=True) # working with mesh: if self.shapeType == "mesh": # working with uvSet: uvSetList = cmds.polyUVSet(dupShape, query=True, allUVSets=True) if len(uvSetList) > 1: if not uvSetList[0] == uvSetName: # change uvSet order because closestPointOnMesh uses the default uv set cmds.polyUVSet(dupShape, copy=True, uvSet=uvSetName, newUVSet=uvSetList[0]) # closest point on mesh node: self.cpNode = cmds.createNode("closestPointOnMesh", name=geoToAttach+"_dpRivet_TEMP_CP", skipSelect=True) cmds.connectAttr(dupShape+".outMesh", self.cpNode+".inMesh", force=True) # move tempNode to cpNode position: cmds.connectAttr(self.tempNode+".translate", self.cpNode+".inPosition", force=True) else: #nurbsSurface uRange = cmds.getAttr(dupShape+".minMaxRangeU")[0] vRange = cmds.getAttr(dupShape+".minMaxRangeV")[0] # closest point on mesh node: self.cpNode = cmds.createNode("closestPointOnSurface", name=geoToAttach+"_dpRivet_TEMP_CP", skipSelect=True) cmds.connectAttr(dupShape+".local", self.cpNode+".inputSurface", force=True) # working with follicles and attaches for rivet in self.rivetList: rivetPos = cmds.xform(rivet, query=True, worldSpace=True, rotatePivot=True) if addFatherGrp: rivet = cmds.group(rivet, name=rivet+"_Rivet_Grp") cmds.xform(rivet, worldSpace=True, rotatePivot=(rivetPos[0], rivetPos[1], rivetPos[2])) # move temp tranform to rivet location: cmds.xform(self.tempNode, worldSpace=True, translation=(rivetPos[0], rivetPos[1], rivetPos[2])) # get uv coords from closestPoint node fu = cmds.getAttr(self.cpNode+".u") fv = cmds.getAttr(self.cpNode+".v") if self.shapeType == "nurbsSurface": # normalize UVs: fu = abs((fu - uRange[0])/(uRange[1] - uRange[0])) fv = abs((fv - vRange[0])/(vRange[1] - vRange[0])) # create follicle: folTransf = cmds.createNode("transform", name=rivet+"_Fol", parent=self.rivetGrp, skipSelect=True) folShape = cmds.createNode("follicle", name=rivet+"_FolShape", parent=folTransf, skipSelect=True) # connect geometry shape and follicle: if self.shapeType == "mesh": cmds.connectAttr(self.shapeToAttach+".worldMesh[0]", folShape+".inputMesh", force=True) cmds.setAttr(folShape+".mapSetName", uvSetName, type="string") else: #nurbsSurface: cmds.connectAttr(self.shapeToAttach+".local", folShape+".inputSurface", force=True) cmds.connectAttr(self.shapeToAttach+".worldMatrix[0]", folShape+".inputWorldMatrix", force=True) cmds.connectAttr(folShape+".outRotate", folTransf+".rotate", force=True) cmds.connectAttr(folShape+".outTranslate", folTransf+".translate", force=True) # put follicle in the correct place: cmds.setAttr(folShape+".parameterU", fu) cmds.setAttr(folShape+".parameterV", fv) # attach follicle and rivet using constraint: if attachTranslate and attachRotate: cmds.parentConstraint(folTransf, rivet, maintainOffset=True, name=rivet+"_ParentConstraint") elif attachTranslate: cmds.parentConstraint(folTransf, rivet, maintainOffset=True, name=rivet+"_ParentConstraint" , skipRotate=("x", "y", "z")) elif attachRotate: cmds.parentConstraint(folTransf, rivet, maintainOffset=True, name=rivet+"_ParentConstraint" , skipTranslate=("x", "y", "z")) # try to integrate to dpAutoRigSystem in order to keep the Rig as scalable: if self.masterCtrl: cmds.scaleConstraint(self.masterCtrl, folTransf, maintainOffset=True, name=folTransf+"_ScaleConstraint") # check invert group (back) in order to avoide double transformations: if addInvert: for rivet in self.rivetList: self.dpInvertAttrTranformation(rivet, invT, invR) # clean-up temporary nodes: cmds.delete(dupGeo, self.cpNode, self.tempNode) else: mel.eval("error \"Load one geometry to attach Rivets on it, please.\";") cmds.select(clear=True)
def connectToConn(replace, iterExec, curNode, curNode2, repPattern, mode, newKeyNode, origBW): ''' Connect the newKeyNode based on the search/replace parameters specified. ''' errorCheck = False if replace.count('%s'): currentRep = replace exec (iterExec) in locals() currentRep = currentRep % feeder newConn = curNode2.split('.')[0].replace(repPattern, currentRep) else: newConn = curNode2.split('.')[0].replace(repPattern, replace) if mc.objExists(newConn) and \ mc.attributeQuery( '.'.join(curNode2.split('.')[1:]), node=newConn, ex=True) and \ mode: mc.connectAttr( '%s.%s' % (newConn, '.'.join(curNode2.split('.')[1:])), '%s.input' % newKeyNode, f=True) # In driver mode, check for blendWeighted nodes. If the target # has a blendWeighted node, check to see if it has the same number # of input multi attrs, otherwise make a new one. elif mc.objExists(newConn) and ( mc.attributeQuery( '.'.join(curNode2.split('.')[1:]), node=newConn, ex=True) or mc.attributeQuery( curNode2.split('.')[1].split('[')[0], node=newConn, ex=True)) \ and not mode: targetCon = mc.listConnections( '%s.%s' % (newConn, '.'.join(curNode2.split('.')[1:])), s=True, d=False, p=True, scn=True) makeNewBW = False if targetCon: nodeType = mc.ls(targetCon[0].split('.')[0], st=True)[1] if nodeType == 'blendWeighted': targetBWInSize = len(mc.listAttr( '%s.input' % targetCon[0].split('.')[0], multi=True)) origBWInSize = len(mc.listAttr( '%s.input' % origBW.split('.')[0], multi=True)) if targetBWInSize == origBWInSize: mc.connectAttr('%s.output' % newKeyNode, '%s.%s' % (targetCon[0].split('.')[0], '.'.join(curNode.split('.')[1:])), f=True) else: makeNewBW = True else: makeNewBW = True else: makeNewBW = True if makeNewBW and origBW: newBW = mc.duplicate(origBW.split('.')[0])[0] mc.connectAttr('%s.output' % newKeyNode, '%s.%s' % (newBW, '.'.join(curNode.split('.')[1:])), f=True) mc.connectAttr('%s.output' % newBW, '%s.%s' % (newConn, '.'.join(curNode2.split('.')[1:])), f=True) else: mc.connectAttr('%s.output' % newKeyNode, '%s.%s' % (newConn, '.'.join(curNode2.split('.')[1:])), f=True) elif mode and mc.objExists(newConn) and \ not mc.attributeQuery( '.'.join(curNode2.split('.')[1:]), node=newConn, ex=True): print ('\nDriver node %s does not have the attribute %s .' % (newConn, '.'.join(curNode2.split('.')[1:]))) mc.delete(newKeyNode) else: errorCheck = True return errorCheck, newConn
def copySDK(curAttrs=[], mirrorAttrs=[], source='', targets=[], search='', replace='', specialIter=[], sort=False, mode='driven', drAttrSearch='', drAttrReplace='', createDriverAttr=False): '''This definition is used to copy SDK setups from one node to another node/s in Maya. With no declarations, the script works by getting the selection list. The first selected object is the source, everything else is a target. The script will copy SDKs from the source and replicate it on the targets. SDKs will be linked to the original source driver by default. Node and attribute options curAttrs - string or string list - is for explicitly declaring which attributes to copy SDKs from. If you don't declare it, the script will search for SDKs on all keyable attributes of the source. mirrorAttrs - string or string list - is to tell the script which attributes on the source object will receive a negative value in their keyframes. source - string - is to explicitly declare the source node to copy. If this is declared, targets must also be declared. If not declared, the selection list is used and the first selected object is the source. - if mode is set to driven, source represents the source driven node, when mode is set to driver, source represents the source driver node. targets - string or string list - is to explicitly declare target nodes to apply SDKs to. If this is declared, source must also be declared. If not declared, the selection list is used and all other objects other than the first comprise the targets list. - if mode is set to driven, targets represents the destination driven node/s, when mode is set to driver, targets represents the destination driver node/s. String search options for driver nodes: search - string - when mode is set to Driven, is used for pattern searching in Driver names. search and replace both have to be declared. If not declared, the SDK's are connected to the original driver node attributes. This attribute accepts regex search strings. - when mode is set to Driver, this is used instead to search for Driven object names. search and replace MUST be declared in case of Driver-centric operations. replace - string - when mode is set to Driven, is used for pattern searching in Driver names, to look for alternate Driver nodes. This provides the replace string to use when looking for Driver nodes. The replace string can use the special %s character to provide more flexibility with choosing different Drivers for multiple Driven nodes. - when mode is set to Driver, this is used instead to search for Driven object names. search and replace MUST be declared in case of Driver-centric operations. specialIter - int or string list or list of lists - is used when you want to provide a list or an iteratable object to use when you want more flexibility in naming your driver object. Your replace variable must contain a replace string with %s, and that will get swapped by what you enter here. - You can use a single list ['a', 'b', 'c'], lists within lists for multiple %s's [['a', 'b', 'c'], [1, 2, 3]], or python techniques such as range e.g., range(0,12). - The only rule is that the lists have to be as long as the number of targets. sort - boolean - Sort the target list alphabetically. Helps to reorganize the targets list if you're using the specialIter function. mode - string 'driver', 'driven' or 'guess' - Decides whether the script operates via selecting a driven node, or a driver node. Default is set to driven, meaning you have to select the driven object you want to mirror over as your first selection. Options are either 'driver', 'driven', or 'guess' (if set to guess, will find whether it has more outgoing or incomming sdk keyframes), and the default is driven. - In driven mode, script wil find the original driver from the driven node and seek out alternate driver names via the search and replace variables if declared, else it will use the original driver/s. - In driver mode, script will seek out all driven nodes and search for the alternate driven node names based off the search and replace variables. In driver mode, search and replace declaration is required. drAttrSearch - string - If declared, search for this string component in a source driver attribute, for the purpose of replacing this string in a target driver attribute. drAttrReplace - string - If declared, use this string to replace a found attrSearch component in a source driver attr when looking for a target driver attr. createDriverAttr - boolean - Create the driver attribute on a found target node if it did not already exist, Default is False. This only works in 'driver' mode. Mirror SDK curves example: sys.path.append('//ml-store-smb.magicleap.ds/fl/Users/MAGICLEAP/tcoleman/code') # DEV import rigUtils.utils.setDrivenKey as sdk reload(sdk) # Mirror SDK curves src = 'Rt_elbow_jnt_outerTransRot_helper_jnt' tgts = ['Lf_elbow_jnt_outerTransRot_helper_jnt'] attrs = ['offsetX', 'offsetY'] sdk.copySDK(curAttrs=attrs, mirrorAttrs=attrs, source=src, targets=tgts, search='', replace='', specialIter=[], sort=False, mode='driven', drAttrSearch='', drAttrReplace='', createDriverAttr=False) ''' # Make sure all variables are correct if not source.strip() or not targets: curlist = mc.ls(sl=True, ap=True) if not curlist or len(curlist) < 2: print ('\nPlease select at least two objects.') return 1 source = curlist[0] targets = curlist[1:] elif isinstance(targets, str) and targets.strip(): targets = [targets] if sort: targets.sort() 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) if mirrorAttrs: if isinstance(mirrorAttrs, str): mirrorAttrs = [mirrorAttrs] tempMirrorAttrs = [] for attr in mirrorAttrs: if not mc.attributeQuery(attr, node=source, ex=True): continue tempMirrorAttrs.append(mc.attributeQuery(attr, node=source, ln=True)) tempMirrorAttrs = list(set(tempMirrorAttrs)) if tempMirrorAttrs: mirrorAttrs = tempMirrorAttrs else: print ('Specified attributes to be mirrored %s, do not exist ' 'on source node %s .' % (', '.join(mirrorAttrs), source)) mirrorAttrs = [] if mode.strip().lower() == 'driven': mode = True elif mode.strip().lower() == 'driver': mode = False elif mode.lower() == 'guess': driverNodes = [] drivenNodes = [] drivenNodes, blendWeightedNodes = \ findSDKNodes(mirrorAttrs, source, attrs, True) if blendWeightedNodes: for node in blendWeightedNodes: SDKN2, SKN, ON = searchBWNodes(node) if SDKN2: a = set(drivenNodes + SDKN2) drivenNodes = list(a) driverNodes, blendWeightedNodes = \ findSDKNodes(mirrorAttrs, source, attrs, False) if len(drivenNodes) >= len(driverNodes): mode = True else: mode = False else: print ('\nUnrecognized mode argument: "' + str(mode) + '", use either "driver", "driven", or "guess".') return 1 # Determine special iteration parameters if there is a %s in the replace # variable. Used for complex Driver name searching, if each of your targets # has a different driver object. SDKResults = [] BWNResults = [] iterExec = None if (not search or not replace) and mode: search = None replace = None elif (not search or not replace) and not mode: print ('\nPlease "declare" search and "replace" variables ' 'when in driver mode.') return 1 elif replace.count('%s') and not specialIter: print ('\nWhen using the "%s" character, you must declare ' 'a specialIter list') return 1 elif replace.count('%s'): if (isinstance(specialIter[0], list) or isinstance(specialIter[0], tuple)): numArgs = len(specialIter) iterExec = 'feeder = (' iterScratch = [] for x in range(0, numArgs): if len(specialIter[x]) != len(targets): print ('\nspecialIter item ' + str(x) + ' length (' + str(len(specialIter[x])) + ') must be the same as target' ' length (' + str(len(targets)) + ') .') return 1 iterScratch.append('specialIter[%s][i]' % str(x)) iterExec += ', '.join(iterScratch) + ' )' else: if len(specialIter) != len(targets): print ('\nspecialIter length (' + str(len(specialIter)) + ') must be the same as target length (' + str(len(targets)) + ') .') return 1 iterExec = 'feeder = specialIter[i]' # Acquire SDK and blendweighted nodes from source SDKnodes, blendWeightedNodes = \ findSDKNodes(mirrorAttrs, source, attrs, mode) # Go through all the targets and mirror SDK nodes and # blendWeighted nodes with SDK from source. i = 0 for target in targets: if SDKnodes: doSDKs(SDKnodes, target, search, replace, i, iterExec, specialIter, SDKResults, BWNResults, mode, createDriverAttr, drAttrSearch, drAttrReplace) if blendWeightedNodes and mode: for node in blendWeightedNodes: SDKnodes2, SKnodes, otherNodes = searchBWNodes(node) if SDKnodes2: newBlendNode = mc.duplicate(node[0])[0] doSDKs(SDKnodes2, newBlendNode, search, replace, i, iterExec, specialIter, SDKResults, BWNResults, True, createDriverAttr, drAttrSearch, drAttrReplace) if SKnodes: for node2 in SKnodes: newKeyNode = mc.duplicate(node2[0])[0] if node2[2]: mirrorKeys(newKeyNode) mc.connectAttr('%s.output' % newKeyNode, '%s.%s' % (newBlendNode, node2[1]), f=True) mc.connectAttr('%s.output' % newBlendNode, '%s.%s' % (target, node[1]), f=True) BWNResults.append('Connected Blend Weighted node ' '%s.output to Driven node %s.%s' % (newBlendNode, target, node[1])) else: print ('\nNo SDK nodes connected to blendWeighted node ' + node[0] + ', skipping...') i += 1 return 0
def listAttr_(sNode): return listForNone(mc.listAttr(sNode, k=True, ud=True))
#print 'Skipping ' + nodeType + ' from nodeTypes...' pass else: nodeTypesFiltered.append(nodeType) #with open("c:/filepathDebug.txt", "a") as myfile: # myfile.truncate() #for nodeType in nodeTypes: for nodeType in nodeTypesFiltered: #with open("c:/filepathDebug.txt", "a") as myfile: # myfile.write(str(nodeType) + '\n') #print nodeType # USE THIS TO IDENTIFY ERROROUS QUERIES nodes = cmds.ls(type=nodeType) for node in nodes: attributes = cmds.listAttr(node, write=True, hasData=True) for attribute in attributes: try: if findFirstMatchInString(['C:', 'R:', 'X:'], cmds.getAttr(node + '.' + attribute)): print 'Found invalid drive letter in : ' + cmds.getAttr( node + '.' + attribute) errors += 1 except: pass print '\n-------Summary -------' print 'Found ' + str(len(nodeTypes)) + ' possible node types.' print 'Found ' + str(len(nodes)) + ' nodes in scene.' print 'Found ' + str(errors) + ' invalid filepaths.'
def _get_all_attributes(self): selection = cmds.ls(sl=True, l=True) return [str(c) for c in cmds.listAttr(selection, keyable=True)]
if '.vtx' in objects[0]: #*********** Get parent name ****************** ObjectParent = cmds.listRelatives(objects[1], p=True) #*********** Get object position ****************** position = cmds.xform(objects[0], q=True, ws=True, t=True) #******* Create a group driven by pointOnPolyContraint ********** groupName = cmds.group(em=True, name=("grp_ptc_" + objects[1])) cmds.parent(groupName, ObjectParent[0]) #******* Get the UV map relationed with the vtx ********** mapList = cmds.polyListComponentConversion(objects[0], fv=- True, tuv=True) #******* Create a pointOnPolyContraint ********** contraintNames = cmds.pointOnPolyConstraint(objects[0], groupName, mo=False, o=[0, 0, 0], w=1) #************* Disconnect rotation chanel **************************************** mel.eval("CBdeleteConnection " + groupName + ".rotateX;") mel.eval("CBdeleteConnection " + groupName + ".rotateY;") mel.eval("CBdeleteConnection " + groupName + ".rotateZ;") #******* Get U and V values from map array ********** uvvalues = cmds.polyEditUV(mapList, q=True) contraintAttr = cmds.listAttr(contraintNames[0], k=True) #******* Assign the U and V values respectively from maplist ********** cmds.setAttr((contraintNames[0] + "." + contraintAttr[10]), uvvalues[0]) cmds.setAttr((contraintNames[0] + "." + contraintAttr[11]), uvvalues[1]) groupDrv = _2GrpUp(objects[1]) cmds.parent(groupDrv, groupName) GrpSubsTrans(objects[1])
def mirrorAnimation(): mirrorPose() l = mc.ls(sl=True, o=True) or [] for n in l: if not n.endswith("_ctrl"): continue side = "_lf" side2 = "_rt" if "_rt" in n: side = "_rt" side2 = "_lf" n2 = n.replace(side, side2) if not mc.objExists(n2): continue # delete existing anim curves attached to the node on the "other" side l2 = mc.listAttr(n2, k=True) or [] for a in l2: l3 = mc.listConnections( n2 + "." + a, s=True, d=False, scn=True, t="animCurve") or [] for n3 in l3: try: mc.delete(n3) except: pass # copy existing anim curves from the node on "this" onto the node on the "other" side l2 = mc.listAttr(n, k=True, sn=True) or [] for a in l2: try: n3 = mc.listConnections(n + "." + a, s=True, d=False, scn=True, t="animCurve")[0] except: continue n3 = mc.duplicate(n3)[0] try: mc.connectAttr(n3 + ".output", n2 + "." + a) except: mc.delete(n3) continue # mirror keyframes if needed if "_ik_" in n and a in ["tx", "ry", "rz"]: if "shoulder_" in n and a in ["ry", "rz"]: continue mc.select(n3) mc.selectKey(n3, k=True, t=(-999999999, 999999999)) mc.scaleKey(iub=False, ts=1, tp=0, fs=1, fp=0, vs=-1, vp=0, an="keys") elif "_fk" in n and "head_eye_" in n and a == "ry": mc.select(n3) mc.selectKey(n3, k=True, t=(-999999999, 999999999)) mc.scaleKey(iub=False, ts=1, tp=0, fs=1, fp=0, vs=-1, vp=0, an="keys") elif n.plit(":")[-1].startswith("finger_") and a in [ "ty", "rx", "rz" ]: mc.select(n3) mc.selectKey(n3, k=True, t=(-999999999, 999999999)) mc.scaleKey(iub=False, ts=1, tp=0, fs=1, fp=0, vs=-1, vp=0, an="keys") elif "_pv_" in n and a in ["tx", "ty", "tz"]: mc.select(n3) mc.selectKey(n3, k=True, t=(-999999999, 999999999)) mc.scaleKey(iub=False, ts=1, tp=0, fs=1, fp=0, vs=-1, vp=0, an="keys") if len(l) > 0: mc.select(l)
def shaders_to_json(objA=None, file_path=None): if not objA: return if not file_path: return #shaders = [] for i in objA: allChildren = cmds.listRelatives(i, ad=1) for eachChild in allChildren: # Get the shader groups attached to this particular object shaderGroups = cmds.listConnections(cmds.listHistory(eachChild)) print(shaderGroups) if shaderGroups is not None: # Get the material attached to the shader group for shader in shaderGroups: type = cmds.objectType(shader) if (type == "shadingEngine"): shaders = [] materials = [ x for x in cmds. ls(cmds.listConnections(shaderGroups), materials=1) ] if materials: # If its an AlSurface material add it to the list #if cmds.nodeType(materials[0]) == 'alSurface': if materials not in shaders: shaders.append(materials[0]) network = {"nodes": {}, "connections": []} nodeNetwork = getAllNodes(shaders, network) objects[shader] = nodeNetwork #print shaderNetwork["nodes"] for shader_name in shaders: attributes = cmds.listAttr(shader_name, visible=True) atrA = {'name': shader_name, 'data': []} # for i in attributes: # value = cmds.getAttr(shader_name + '.' + "baseColor") # print value # remap = cmds.listConnections(shader_name + '.' + 'baseColor', d=False, s=True) # remapConnenction = cmds.connectionInfo(shader_name + '.' + 'baseColor', sfd=1) # print remap # print remapConnenction # print cmds.listHistory(remapConnenction)[0] # remapAttributes = cmds.listAttr(remap, visible=True) # print remapAttributes # file1 = cmds.listConnections(remap[0] + '.' + 'color', d=False, s=True) # file1Connection = cmds.connectionInfo(remap[0] + '.' + 'color', sfd=1) # print file1 # print file1Connection # print cmds.listHistory(file1Connection)[0] # print cmds.listAttr(file1, visible=True) # texture = cmds.listConnections(file1[0] + '.' + 'uvCoord', d=False, s=True) # textureConnection = cmds.connectionInfo(file1[0] + '.' + 'uvCoord', sfd=1) # print texture # print texture[0] # print textureConnection # value = cmds.getAttr(shader_name + '.' + str(i)) # if value: # if isinstance(value, list): # value = value[0] # # Check if output plug has a file node connection # output_conn_node = cmds.listConnections(shader_name + '.' + str(i), d=False, s=True) # # for clar_id, arnold_id in clarisse_arnold_pairs.iteritems(): # # if i == arnold_id: # attr = {i: value} # atrA['data'].append(attr) # # break # if atrA: # shaderA.append(atrA) # if shaderA: with open(file_path, 'w') as fp: json.dump(objects, fp, sort_keys=False, indent=4) print '[Info]Finished exporting material data...'
def tween(percentage, obj=None, attrs=None, selection=True): # if obj is not given and selection is set to False, error early if not obj and not selection: raise ValueError("No object given to tween") # if no obj is specified, get it from the first selection if not obj: obj = cmds.ls(selection=True)[0] # if no attrs specified, use all if not attrs: attrs = cmds.listAttr(obj, keyable=True) currentTime = cmds.currentTime(query=True) for attr in attrs: # construct the full name of the attribute with its objects attrFull = '%s.%s' % (obj, attr) keyframes = cmds.keyframe(attrFull, query=True) # if there are no keyframs continue if not keyframes: continue previousKeyframes = [] for k in keyframes: if k < currentTime: previousKeyframes.append(k) laterKeyframes = [frame for frame in keyframes if frame > currentTime] # if no keyframes before after continue if not previousKeyframes and not laterKeyframes: continue if previousKeyframes: previousFrame = max(previousKeyframes) else: previousFrame = None nextFrame = min(laterKeyframes) if laterKeyframes else None print previousFrame print nextFrame if not previousFrame or not nextFrame: continue previousValue = cmds.getAttr(attrFull, time=previousFrame) nextValue = cmds.getAttr(attrFull, time=nextFrame) print previousValue print nextValue difference = nextValue - previousValue weightedDifference = (difference * percentage) / 100.0 currentValue = previousValue + weightedDifference cmds.setKeyframe(attrFull, time=currentTime, value=currentValue)
def process(self, context): from maya import cmds from avalon import maya, api def render_global(attr): return cmds.getAttr("defaultRenderGlobals." + attr) for layer in cmds.ls(type="renderLayer"): if layer.endswith("defaultRenderLayer"): continue data = { "family": "Render Layers", "families": ["mindbender.renderlayer"], "publish": cmds.getAttr(layer + ".renderable"), "startFrame": render_global("startFrame"), "endFrame": render_global("endFrame"), "byFrameStep": render_global("byFrameStep"), "renderer": render_global("currentRenderer"), "time": context.data["time"], "author": context.data["user"], "source": context.data["currentFile"].replace(api.registered_root(), "{root}").replace( "\\", "/"), } # Apply each user defined attribute as data for attr in cmds.listAttr(layer, userDefined=True) or list(): try: value = cmds.getAttr(layer + "." + attr) except Exception: # Some attributes cannot be read directly, # such as mesh and color attributes. These # are considered non-essential to this # particular publishing pipeline. value = None data[attr] = value # Include (optional) global settings # TODO(marcus): Take into account layer overrides try: avalon_globals = maya.lsattr("id", "avalon.renderglobals")[0] except IndexError: pass else: avalon_globals = maya.read(avalon_globals) data["renderGlobals"] = { key: value for key, value in { "Pool": avalon_globals["pool"], "Group": avalon_globals["group"], "Frames": avalon_globals["frames"], "Priority": avalon_globals["priority"], }.items() # Here's the kicker. These globals override defaults # in the submission integrator, but an empty value # means no overriding is made. Otherwise, Frames # would override the default frames set under globals. if value } instance = context.create_instance(layer) instance.data.update(data)
def end(): global meshes global origin global mesh_skins_dict global bones_list # Then attach skins, fix, etc cmds.select(clear=True) meshes_LO_GRP = 'meshes_LO' if not cmds.objExists(meshes_LO_GRP): meshes_LO_GRP = cmds.group(name=meshes_LO_GRP, empty=True) # Dupe and clean all meshes kwargs = { # Settings for the skin bind 'toSelectedBones': False, 'bindMethod': 0, 'skinMethod': 0, 'normalizeWeights': 1, 'maximumInfluences': 5, } meshes_LO = [] for mesh in meshes: mesh_LO = cmds.duplicate(mesh, name=mesh + '_LO')[0] cmds.parent(mesh_LO, meshes_LO_GRP) for attr in cmds.listAttr(mesh_LO, locked = True) or []: cmds.setAttr(mesh_LO + "." + attr, lock = False) # Delete those pesky unconnected Orig nodes hero_shape = cmds.listRelatives(\ mesh_LO, shapes = True, noIntermediate = True)[0] mesh_LO_shapes = cmds.listRelatives(\ mesh_LO, shapes = True, noIntermediate = False) for shape in mesh_LO_shapes: if not shape == hero_shape: cmds.delete(shape) # bones = skins_bones_dict[mesh_skins_dict[mesh]] # bones.append(origin) skin_LO = cmds.skinCluster(origin, mesh_LO, **kwargs)[0] skinFn = _getClusterName(mesh_skins_dict[mesh]) newSkinFn = _getClusterName(skin_LO) # get the MDagPath for all influence infDags = OpenMaya.MDagPathArray() skinFn.influenceObjects(infDags) newInfDags = OpenMaya.MDagPathArray() newSkinFn.influenceObjects(newInfDags) infIds, infs, boneNamesIDs = _infIDsDict(infDags, skinFn) newinfIds, newInfs, newBoneNamesIDs = _infIDsDict(newInfDags, newSkinFn) # get the MPlug for the weightList and weights attributes wlPlug = skinFn.findPlug('weightList') wPlug = skinFn.findPlug('weights') wlAttr = wlPlug.attribute() wAttr = wPlug.attribute() wInfIds = OpenMaya.MIntArray() # the weights are stored in dictionary, the key is the vertId, # the value is another dictionary whose key is the influence id and # value is the weight for that influence weights = {} for vId in xrange(wlPlug.numElements()): vWeights = {} # tell the weights attribute which vertex id it represents wPlug.selectAncestorLogicalIndex(vId, wlAttr) # get the indice of all non-zero weights for this vert wPlug.getExistingArrayAttributeIndices(wInfIds) # create a copy of the current wPlug infPlug = OpenMaya.MPlug(wPlug) for infId in wInfIds: # tell the infPlug it represents the current influence id infPlug.selectAncestorLogicalIndex(infId, wAttr) # add this influence and its weight to this verts weights try: vWeights[infIds[infId]] = infPlug.asDouble() except KeyError: # assumes a removed influence pass weights[vId] = vWeights # The following removes all weighting so only non-zero weights need applied: # unlock influences used by skincluster # for inf in infs: # cmds.setAttr('%s.liw' % inf) for inf in newInfs: cmds.setAttr('%s.liw' % inf) _normWeights(skin_LO, mesh_LO) # Fix normalization before applying weights! # Now to set the weights using the weights variable you would use something like this: for vertId, weightData in weights.items(): wlAttr = '%s.weightList[%s]' % (skin_LO, vertId) for infId, infValue in weightData.items(): bone = boneNamesIDs[infId] newID = newBoneNamesIDs.keys()[newBoneNamesIDs.values().index(bone + '_LO')] wAttr = '.weights[%s]' % newID # if not cmds.skinPercent(newClusterName, newShapeName + '.vtx[%d]' % vertId, transform=bone + '_LO', q=True) == 0: cmds.setAttr(wlAttr + wAttr, infValue) #print cmds.skinPercent(newClusterName, newShapeName + '.vtx[%d]' % vertId, transform=bone + '_LO', q=True) # Parent Constrain new Skeleton with Original (based on names) for bone in bones_list: cmds.parentConstraint(bone, bone + '_LO', mo=False)
def copy_bake_camera(cam, replace_cam=False): # camName = cam camShape = cmds.listRelatives(cam, typ='camera')[0] garbages = [] keyables = cmds.listAttr(cam, camShape, keyable=True) keyables += cmds.listAttr(cam, st=['rotateOrder', '*Pivot*']) # roMapping = ('xyz', 'yzx', 'zxy', 'xzy', 'yxz', 'zyx') # roCurrent = roMapping[cmds.getAttr(cam + '.rotateOrder')] # roIndex = roMapping.index(roGiven) parents = cmds.listRelatives(cam, parent=True, fullPath=True) # copy camera and cleanup children dup_cam = cmds.duplicate(cam, name=cam + '_baked', returnRootsOnly=True)[0] childs = cmds.listRelatives(dup_cam, children=True, typ='transform', fullPath=True) if childs: cmds.delete(childs) # unlock new camera for attr in keyables: cmds.setAttr(dup_cam + '.' + attr, lock=False) # parent attrs may also have been locked somehow... for attr in 'trs': cmds.setAttr(dup_cam + '.' + attr, lock=False) # unparent and cleanup pivots if parents: dup_cam = cmds.parent(dup_cam, w=True)[0] cmds.xform(dup_cam, zeroTransformPivots=True) cmds.makeIdentity(dup_cam, apply=True, translate=True, rotate=True, scale=True) # contraint new camera to original one and set rotateOrder garbages.extend(cmds.parentConstraint(cam, dup_cam, maintainOffset=True)) # cmds.setAttr(dup_cam + '.rotateOrder', roIndex) # connect imagePlane to dup_cam imagePlane = cmds.imagePlane(cam, q=True, name=True) if imagePlane: imagePlane = imagePlane[0] cmds.imagePlane(imagePlane, detach=True, edit=True) cmds.imagePlane(camera=dup_cam, edit=True) # copy focal animation if exist if cmds.copyKey(cam, at='fl'): cmds.pasteKey(dup_cam, at='fl') # cleanup old camera if replace_cam: # check existence existing = cmds.ls(cam) if existing: # if cmds.confirmDialog(message='%s already exists, do you want to replace it?' % # cam, button=['Yes', 'No'], defaultButton='Yes', cancelButton='No', dismissString='No') == 'Yes': garbages.extend(existing) # unlock camera for attr in keyables: cmds.setAttr(dup_cam + '.' + attr, lock=False) # make sure the curves on camera continue on for motion blur time_range = get_time_range_in_slider() cmds.bakeResults(dup_cam, t=time_range) cmds.delete(dup_cam, staticChannels=True) cmds.filterCurve(dup_cam) cmds.keyTangent(dup_cam, itt='spline', ott='spline') # master.extendKeyframes([dup_cam]) # cleanup garbages if garbages: cmds.delete(garbages) while parents: if not cmds.listConnections(parents[0]) \ and not cmds.listRelatives(parents[0], children=True): parent = parents[0] parents = cmds.listRelatives(parent, parent=True, fullPath=True) cmds.delete(parent) else: break # set key at startFrame if attr has no animation for attr in cmds.listAttr(dup_cam, camShape, keyable=True, st=['translate*', 'rotate*', 'focalLength']): if not cmds.listConnections(dup_cam + '.' + attr, destination=False): cmds.setKeyframe(dup_cam, itt='spline', ott='spline', attribute=attr, t=time_range[0]) # set scale and visibility for attr in cmds.listAttr(dup_cam, keyable=True, st=['scale*', 'visibility']): cmds.delete(dup_cam + '.' + attr, icn=True) cmds.setAttr(dup_cam + '.' + attr, 1) # set camera clip range l_objs = cmds.ls(typ='mesh') l_objs.append(dup_cam) l_bbox = cmds.exactWorldBoundingBox(l_objs) maxDist = math.sqrt((l_bbox[3] - l_bbox[0])**2 + (l_bbox[4] - l_bbox[1])**2 + (l_bbox[5] - l_bbox[2])**2) farClip = math.ceil(maxDist) * 2 nearClip = 0.1 cmds.setAttr(dup_cam + '.farClipPlane', farClip) cmds.setAttr(dup_cam + '.nearClipPlane', nearClip) # lock attributes for attr in keyables: cmds.setAttr(dup_cam + '.' + attr, lock=True) # look through cam and rename # pane = cmds.playblast(activeEditor=True) # pane = pane if not pane.count('|') else pane.split('|')[-1] # cmds.modelPanel(pane, e=True, camera=dup_cam) # camName = cmds.rename(cam, camName) # # create motion trail # if cmds.menuItem(master.ui['mtrailCB'], q=True, checkBox=True): # if not cmds.listConnections(camName, t='snapshot', d=True): # l_cameraPath = cmds.snapshot(camName, # ch=True, # st=master.getStartFrame(), # et=master.getEndFrame(), # motionTrail=True) # camPath = cmds.rename(l_cameraPath[0], camName + '_path') # if cmds.objExists('|layout|misc'): # cmds.parent(camPath, '|layout|misc') # # cleanup horizon line # curves = cmds.ls('horizon*', exactType='transform') # for c in curves: # if cmds.attributeQuery('camera', node=c, exists=True) and not cmds.listConnections(c + '.camera'): # cmds.delete(c) # # create horizon line # plugs = cmds.listConnections(camName + '.message', plugs=True, d=True) # if not plugs or not any(i.endswith('.camera') for i in plugs): # if cmds.menuItem(master.ui['horizonRenderCB'], query=True, checkBox=True): # horizon = cmds.polyCylinder(radius=1, height=1, # name='horizon_mesh1', # subdivisionsX=50, subdivisionsY=5, subdivisionsZ=0, # axis=(0, 1, 0), createUVs=False, constructionHistory=False)[0] # cmds.delete(horizon + '.f[250:251]') # cmds.addAttr(horizon, longName='depth', attributeType='double', minValue=0.1, defaultValue=1) # cmds.setAttr(horizon + '.depth', keyable=True) # cmds.expression(o=horizon, name=horizon + '_expr', # string=('sx = sz = depth;' # 'sy = (20/defaultResolution.height)' # '* (%s.verticalFilmAperture*depth/%s.focalLength);' % (camName, camName))) # setupHorizon(horizon, camName) # if cmds.menuItem(master.ui['horizonCB'], query=True, checkBox=True): # horizon = cmds.circle(normal=(0, 1, 0), # name='horizon_curve1', # constructionHistory=False)[0] # setupHorizon(horizon, camName) return dup_cam
def Custom_2Const(oSel,sConstName, iMo = False, aSkipTrans = [], aSkipRot = []): aAxis = ['tx','ty','tz','rx','ry','rz'] for i in range(0,6): v = cmds.getAttr(str(oSel[0])+'.%s'%aAxis[i], l = True) if v: if i < 3: if not aAxis[i][-1] in aSkipTrans: aSkipTrans.append(aAxis[i][-1]) else: if not aAxis[i][-1] in aSkipRot: aSkipRot.append(aAxis[i][-1]) cmds.parentConstraint(oSel[-1], oSel[0], st = aSkipTrans, sr = aSkipRot, n = sConstName, mo = iMo) # Returns Non Locked Axis aAdj = ['z','y','x'] for i in range(0,3): if aSkipRot: if aAdj[i] in aSkipRot: aAxis.remove('r%s'%aAdj[i]) if aSkipTrans: if aAdj[i] in aSkipTrans: aAxis.remove('t%s'%aAdj[i]) return aAxis # List files and directories aSceneFiles = os.listdir(sFullPath) # Find keyable attributes print cmds.listAttr(oSel[0], keyable = True) # Check if path exists import os def CreateTxtFilePath(sPath = '/net/homes/dyabu/Personal/TimeStamp/TimeStamp.txt'): if os.path.exists(sPath): print 'yes' # Get Local Transform Values aTrans = cmds.xform(oSel, q = True, translation = True) aRot = cmds.xform(oSel, q = True, ro = True, os = True) ### To get Scene File Path cmds.file( q = True, sn = True) ### In view Message self.PrintOnScreen = ['a7a8af', 'Playblast done [%s]'%sView, 0x6b6c75] cmds.inViewMessage(amg = '<text style="color:#%s";>%s</text>'%(aPrint[0], aPrint[1]), pos = 'topCenter', fade = True, fts = 10, ft = 'arial', bkc = aPrint[2]) ### Display Message Box def MessageBox(Message): '''Displaying Entered Message as Popup ''' oWindow = cmds.window(title = 'Message Box', s = False) if cmds.windowPref(oWindow, exists = True): cmds.windowPref(oWindow, remove = True) cmds.columnLayout(adjustableColumn = True) cmds.text('\n\t%s\t\n' % Message, bgc = (.25,.25,.25),enableBackground = False) cmds.button(label = 'Close', command = ('cmds.deleteUI(\"'+oWindow+'\",window = True)'), bgc = (.2,.2,.2),enableBackground = False) cmds.setParent('..') cmds.showWindow(oWindow) # Print Methods import maya.mel as mel dir(mel) # To Get the creation time of a file from datetime import datetime import os tCreateTime = os.path.getmtime('/job/nysm2/film/bt163/bt163_0485/work/dyabu/maya/scenes/bt163_0485_DY.v001.01.Ohoh.0002.mb') print datetime.fromtimestamp(tCreateTime).strftime('%Y-%m-%d %H:%M:%S') ### Modifiers K = cmds.getModifiers() sMenu = ''' ----- ALT [8] ----- CTL [4] ----- SFT [1] ----- CTL + SFT [5] ----- ALT + SFT [9] ----- CTL + ALT [12] ----- CTL + ALT + SFT [13]''' ### fill with 0 in a string. ex "003" '1'.zfill(3) ### Prompt Dialog Box o = cmds.confirmDialog( title='Confirm', message='Are you sure?', button=['Yes','No','Maybe','Not Sure'], defaultButton='Yes', cancelButton='No', dismissString='No' , bgc = [1.2,1.2,1.2]) ### Prompt Enter Box def EnterBox(): oResult = cmds.promptDialog( title='Rename Object', message='Enter Name:', button=['OK', 'Cancel'], defaultButton='OK', cancelButton='Cancel', dismissString='Cancel') if oResult == 'OK': sText = cmds.promptDialog(query=True, text=True) return sText else: return None ### Change all non alpha numeric to '_' def Underscore(sString): if sString[0].isdigit(): sString = '_'+sString sNewString ='' for s in sString: if s.isalnum(): sNewString += s else: sNewString += '_' print sNewString Underscore('a#$^fgg1') ### Current Frame iFrame = int(cmds.currentTime(q = True)) ### In/Out Range iIn = int(cmds.playbackOptions(q = True, minTime = True)) iOut = int(cmds.playbackOptions(q = True, maxTime = True)) # Get List of Audios in the scene. aAudio = [str(a) for a in cmds.ls(typ = 'audio')] # Get Currently Active Sound aPlayBackSlider = mel.eval('$tmpVar=$gPlayBackSlider') sAudio = cmds.timeControl(aPlayBackSlider, q = True, s = True) ### Date Examples from datetime import datetime from datetime import timedelta # String to daytime def MondayFinder(sYear, sMonth, sDate): #date_object = datetime.strptime('05 12 2015 1:33PM', '%b %d %Y %I:%M%p') oEntered = datetime.strptime('%s %s %s'%(sMonth, sD), '%m %d %Y') #print date_object.weekday() oMonday = date_object - timedelta(days = date_object.weekday()) print newDate.weekday() ### Get Current SoundTrack aPlayBackSliderPython = maya.mel.eval('$tmpVar=$gPlayBackSlider') sSound = cmds.timeControl( aPlayBackSliderPython, q = True, sound = True) print sSound if sSound: iOffset = cmds.getAttr(sSound+'.offset') print cmds.sound( sSound, q = True, f = True ) print iOffset ### Open Folder cmd1 ='nautilus /net/homes/dyabu/Desktop/Shots/tu125250/Rv' os.system(cmd1) ### User Define Enter Box oClick = cmds.promptDialog( title='Rename Object', message='Enter Shot : ( ex. fs150 )', button=['OK', 'Cancel'], defaultButton='OK', cancelButton='Cancel', dismissString='Cancel') if oClick == 'OK': sShot = cmds.promptDialog(query=True, text=True) ### Get Current Camera ### def getCamera(): oCamera = '' oPanel = cmds.getPanel(wf = True) if 'modelPanel' in oPanel: oCamera = cmds.modelEditor(oPanel, q = True, camera = True) return str(oCamera) ### Warning Message cmds.warning( 'Enter something here' ) ### Rename objects cmds.rename(o, sName) ### Get User Name import getpass print getpass.getuser() ### Write File oRvFile = open(sPath, 'w') oRvFile.write(sContent) oRvFile.close() ### Read File oRvFile = open(sPath, 'r') aLines = oRvFile.readlines() oRvFile.close() for line in aLines: sLine = line.strip() ### Get Active Panel sCurrentPanel = cmds.getPanel(underPointer = True) if sCurrentPanel == None: sCurrentPanel = cmds.getPanel(withFocus = True) tCurrentPanel = cmds.getPanel(typeOf = sCurrentPanel) if tCurrentPanel == 'modelPanel': print tCurrentPanel # Execute Python File #import sys #sys.path.append('/home/ericb/GIT_DEV/ebLabs-workshop/whisKEY2') import ebLabs_whisKEY reload(ebLabs_whisKEY) ebLabs_whisKEY.window.load() # Execute External Python file import sys import os def ExecuteExternal(Mod): sFile = os.path.basename( Mod ) aFiles = sFile.split( '.' ) sDir = os.path.dirname( Mod ) if( os.path.exists( sDir ) ): aPaths = sys.path iCheck = 0 for p in aPaths: if(sDir == p): iCheck = 1 if not iCheck: print iCheck sys.path.append( sDir ) exec( 'import ' + aFiles[0] ) in globals() exec( 'reload( ' + aFiles[0] + ' )' ) in globals() ExecuteExternal('/net/homes/dyabu/maya/2013.5-x64/scripts/HelloWorld.py') ### Linux Run Command def Execute(cmd2): global aMainPath if cmd2: if aMainPath[2] == 'homes': MessageBox('Please open your scene first.') else: cmd1 ='go %s'%aMainPath[2] os.system(cmd1) os.system(cmd2) ### Partial Usage ### from functools import partial cmds.button( .... command = partial(defFunction, arg1, arg2) ...) # in a button # and/or oCMD = cmds.optionMenu( "CustomOptionMenu", label = "Version ", w = fWidth, cc = partial(self.defFunction)) def defFunction(arg1, arg2, *args): print 1 ### Create Hotkey ### def createHotkey(command, name, description=''): ''' Open up the hotkey editor to create a hotkey from the specified command ''' mel.eval('hotkeyEditor') cmds.textScrollList('HotkeyEditorCategoryTextScrollList', edit=True, selectItem='User') mel.eval('hotkeyEditorCategoryTextScrollListSelect') mel.eval('hotkeyEditorCreateCommand') cmds.textField('HotkeyEditorNameField', edit=True, text=name) cmds.textField('HotkeyEditorDescriptionField', edit=True, text=description) cmds.scrollField('HotkeyEditorCommandField', edit=True, text=command) mel.eval('hotkeyEditorAcceptCommand') mel.eval('hotkeyEditorSave') ### Create Shaders and assign to an object. def Colour_The_Balls(): # Create Shaders aColourList = [ [0 ,[ 0.39 , 0.86 , 1.0 ]], [1 ,[ 0.26 , 1.0 , 0.64 ]], [2 ,[ 1.0 , 0.69 , 0.69 ]], [3 ,[ 0.19 , 0.63 , 0.63 ]], [4 ,[ 0.89 , 0.67 , 0.47 ]], [5 ,[ 0.41 , 0.63 , 0.19 ]], [6 ,[ 0 , 0.6 , 0.33 ]], [7 ,[ 1.0 , 0 , 0 ]], [8 ,[ 0 , 1.0 , 0 ]], [9 ,[ 0 , 0 , 0 ]], ] for colour in aColourList: oMaterial = 'PivotColour_%s' % colour[0] oShader = oMaterial+'_SDR' if not cmds.objExists(oMaterial): cmds.shadingNode('lambert', n = oMaterial, asShader = 1, ) cmds.sets(oMaterial, renderable = True, noSurfaceShader = True, empty = True, name = oShader) cmds.connectAttr(oMaterial+'.outColor', oShader+'.surfaceShader', f = True) cmds.setAttr( "%s.color"%oMaterial, type = 'double3', *colour[1]) cmds.setAttr( "%s.incandescence"%oMaterial, type = 'double3', *colour[1]) cmds.setAttr( "%s.ambientColor"%oMaterial, type = 'double3', *colour[1]) # Change the color of the Spheres. for i in range(0,len(GetExistingPivots())): sBall = 'PivotSphere_%s_Pivot' % i # Object Name print sBall cmds.sets( sBall, fe = 'PivotColour_%s_SDR' % i, e = True) ### Copy files in Python from shutil import copyfile copyfile(src, dst) ### Bake Animation ### import maya.mel as mel def SpeedUpBake_1_Store(sName): # store a temporary panel configuration. layout = cmds.panelConfiguration(l=sName, sc=0) evalStr = 'updatePanelLayoutFromCurrent "'+name+'"' mel.eval(evalStr) # switch to fast "hidden" layout evalStr = 'setNamedPanelLayout "Single Perspective View"' mel.eval(evalStr) perspPane = cmds.getPanel(vis=1) cmds.scriptedPanel('graphEditor1',e=1,rp=perspPane[0]) return sName def SpeedUpBake_2_Restore(sName): # restore the layout returned from makeHiddenLayout. evalStr = 'setNamedPanelLayout "'+sName+'"' mel.eval(evalStr) # now delete the old layout. killMe = cmds.getPanel(cwl=sName) cmds.deleteUI(killMe,pc=1) SpeedUpBake_1_Store('tempLayout') try: print 'do something' cmds.bakeResults(aFirst, t = (aRange[0],aRange[1]), simulation = True ) finally: SpeedUpBake_2_Restore('tempLayout') #ScriptJob example (ScriptJob : script must fishish executing completely in order for maya to respond.) def CB(callback): trans = set(cmds.ls(sl = True, type = 'transform')) if trans: cb = cmds.channelBox('mainChannelBox', q = True, sma = True) or [] if cb: callback([a+'.' +b for a in trans for b in cb]) else: objs = set(cmds.ls(sl = True)) - trans if objs: cmds.select(list(objs)) def temp(): res = [a+'.'+b for a in objs for b in cmds.channelBox('mainChannelBox', q = True, sma = True)or[]] cmds.select(list(trans)) callback(res) cmds.scriptJob(e = ('idle', temp), ro = True) def main(): def p(val): print val CB(p) print 'test'
def buildData(self, nodeList=None, chanList=None): ''' Build ChannelData class. @param nodeList: List of nodes to store channel values and connections for. @type nodeList: list ''' # ========== # - Checks - # ========== # Node List if not nodeList: print('ChannelData: Empty node list! Unable to build channelData!') return # Channel List if not chanList: chanList = self.userChannelList if not chanList: chanList = [] # ============== # - Build Data - # ============== # Start timer timer = mc.timerX() # Reset Data --- ? self.reset() # Build Node Channel Data self._data['channelDataNodes'] = [] for node in nodeList: # Initialize Node Data self._channelData[node] = {} self._data['channelDataNodes'].append(node) # Build Node.Channel List nodeChanList = [ node + '.' + i for i in chanList if mc.objExists(node + '.' + i) ] # Get Value Channel List valChanList = [] if chanList: valChanList = chanList else: valChanList = mc.listAttr(node, se=True, r=True, w=True, m=True, v=True) # Get Source Connection Channel List srcChanList = [] if nodeChanList: srcChanList = mc.listConnections( nodeChanList, s=True, d=False, p=True, c=True, sh=True) or [] else: srcChanList = mc.listConnections( node, s=True, d=False, p=True, c=True, sh=True) or [] # Get Destination Connection Channel List dstChanList = [] if nodeChanList: dstChanList = mc.listConnections( nodeChanList, s=False, d=True, p=True, c=True, sh=True) or [] else: dstChanList = mc.listConnections( node, s=False, d=True, p=True, c=True, sh=True) or [] # Add Channel Value Data for chan in valChanList: # Check Attribute #if not mc.attributeQuery(chan,n=node,ex=True): if not mc.objExists(node + '.' + chan): if self.verbosity > 0: print('ChannelData: Node "' + node + '" has no attribute "' + chan + '"! Skipping...') continue # Check Settable if not mc.getAttr(node + '.' + chan, se=True): if not mc.listConnections( node + '.' + chan, s=True, d=False): if self.verbosity > 0: print('ChannelData: Attribute "' + node + '.' + chan + '" is not settable! Skipping...') continue # Get Channel Value chanVal = None try: chanVal = mc.getAttr(node + '.' + chan) except Exception, e: if self.verbosity > 0: print('ChannelData: Error getting channel value "' + node + '.' + chan + '"! Skipping...') if self.verbosity > 1: print('ChannelData: Exception message: ' + str(e)) else: # Create Channel Entry if not self._channelData[node].has_key(chan): self._channelData[node][chan] = {} # Store Channel Value if not chanVal == None: if type(chanVal) == list: if type(chanVal[0]) == tuple: chanVal = list(chanVal[0]) self._channelData[node][chan]['value'] = chanVal # Add Channel Source Data for i in range(0, len(srcChanList), 2): # Get Channel Name chan = str(srcChanList[i].replace(node + '.', '')) # Create Channel Entry if not self._channelData[node].has_key(chan): self._channelData[node][chan] = {} # Store Channel Source Data self._channelData[node][chan]['source'] = srcChanList[i + 1] # Store Channel Value Data try: chanVal = mc.getAttr(srcChanList[i]) except Exception, e: if self.verbosity > 0: print('ChannelData: Error getting channel value "' + node + '.' + chan + '"! Skipping...') if self.verbosity > 1: print('ChannelData: Exception message: ' + str(e)) else: self._channelData[node][chan]['value'] = chanVal
def checkObjectSetKey(self): ''' 驱动过的物体是否锁定并设置成了不可K帧。 ''' geoName = self.getGeoGroup() transList = [] if geoName: allChild = [c for c in geoName[0].getChildren(ad = True , type = 'transform') if c.nodeType() == 'transform'] allChild.append(geoName[0]) transList = [chi for chi in allChild if not chi.getShape()] for t in transList: attrlist = t.listAttr(k = True) for a in attrlist: a.setLocked(0) transList = [t.name() for t in allChild] jointSel = cmds.ls( type = 'joint') if jointSel: for jnt in jointSel: attr = cmds.listAttr(jnt , k = True) if attr: for a in attr: value = cmds.getAttr(jnt+'.'+a , k = True) if value: if jnt not in self.keyjointList: self.keyjointList.append(jnt) continue all = cmds.ls(dag= True , type = 'transform' ) notMesh = [t.name() for t in pm.ls(dag= True , type = 'transform') if 'cloth_G' in t.getAllParents()] conList = cmds.ls( type =['constraint','joint']) ctrlList = [ cmds.listRelatives(s , p = True)[0] for s in cmds.ls(type = ['nurbsCurve' ,'camera'])] transList = [t for t in all if t not in conList+ctrlList+notMesh+transList] attrs = ['t' , 'r' , 's' ] for t in transList: attr = cmds.listAttr(t , k = True ,sn = True) if attr: for at in attr: if at not in self.setKeyDict.keys(): continue value1 = cmds.getAttr(t +'.'+ at , l = True) if not value1: value = cmds.getAttr(t +'.'+ at) if value != self.setKeyDict[at] : if t not in self.keyOverName: self.keyOverName.append(t) continue if cmds.listConnections(t +'.'+ at , s = True , d = False): if t not in self.keyOverName: self.keyOverName.append(t) for at in attrs: valueX = cmds.getAttr(t +'.'+ at +'x' , l = True) valueY = cmds.getAttr(t +'.'+ at +'y' , l = True) valueZ = cmds.getAttr(t +'.'+ at +'z' , l = True) if valueX == True and valueX == True and valueX == True: continue if cmds.listConnections(t +'.'+ at , s = True , d = False): if t not in self.keyOverName: self.keyOverName.append(t) continue return self.keyOverName+self.keyjointList
def register(controlObject = None,#(mObject - None) -- The object to use as a control typeModifier = None,#(string - None) -- Tag for cgmTypeModifier for naming copyTransform = None,#(mObject - None) -- Object to copy the transform of for our control object copyPivot = None,#(mObject - None) -- Object to copy the pivot of for our control object shapeParentTo = None, #'(mObject - None) -- Object to shape parent our control curve to to use that transform useShape = None, #'(mObject - None) -- Object to use the curve shape of for our control setRotateOrder = None,#'(rotateOrder - None) -- Argument for a rotate order to set autoLockNHide = None,#'(bool - None) -- Try to set lock and hide mirrorAxis = None,#'(string - None) -- Mirror axis to set - using red9's setup terms mirrorSide = None,#'(string/int - None) -- Mirror side - using red9's setup terms makeMirrorable = True,#'(bool - True) -- Setup for mirrorability (using red9) -- implied by other mirror args addDynParentGroup = False,#'(False) -- Add a dynParent group setup addExtraGroups = False,#'(int - False) -- Number of nested extra groups desired addConstraintGroup = False,#'(bool - False) -- If a group just above the control is desired for consraining freezeAll = False,#'(bool - False) -- Freeze all transforms on the control object noFreeze = False, addSpacePivots = False,#'(int - False) -- Number of space pivots to generate and connect controlType = None,#'(string - None) -- Tag for cgmType aim = None,#'(string/int - None) -- aim axis to use up = None,#'(string/int - None) -- up axis to use out = None,#'(string/int - None) -- out axis to use makeAimable = None,#'(mObject - False) -- Make object aimable -- implied by aim/up/out): **kws): _str_func = 'register' """ [{'step':'validate','call':self._validate}, {'step':'Copy Transform','call':self._copyTransform}, {'step':'Shape Parent','call':self._shapeParent}, {'step':'Copy Pivot','call':self._copyPivot}, {'step':'Naming','call':self._naming}, {'step':'Aim Setup','call':self._aimSetup}, {'step':'Rotate Order','call':self._rotateOrder}, {'step':'Initial Freeze','call':self._initialFreeze}, {'step':'Groups Setup','call':self._groupsSetup}, {'step':'Space Pivot','call':self._spacePivots}, {'step':'Mirror Setup','call':self._mirrorSetup}, {'step':'Freeze','call':self._freeze}, {'step':'Mirror Attribute Bridges','call':self._mirrorAttributeBridges_}, {'step':'lock N Hide','call':self._lockNHide}, {'step':'Return build','call':self._returnBuild}] """ try: #Validate ================================================================================================ mi_control = cgmMeta.validateObjArg(controlObject,'cgmControl', setClass=True) str_mirrorAxis = VALID.stringArg(mirrorAxis,calledFrom = _str_func) str_mirrorSide = cgmGeneral.verify_mirrorSideArg(mirrorSide)#VALID.stringArg(mirrorSide,calledFrom = _str_func) b_makeMirrorable = VALID.boolArg(makeMirrorable,calledFrom = _str_func) _addMirrorAttributeBridges = kws.get('addMirrorAttributeBridges',False) addForwardBack = kws.get('addForwardBack',False) if _addMirrorAttributeBridges : if type(_addMirrorAttributeBridges ) not in [list,tuple]: raise ValueError,"[Bad addMirrorAttributeBridge arg]{arg: %s}"%_addMirrorAttributeBridge for i,l in enumerate(_addMirrorAttributeBridges): if type(l) not in [list,tuple]: raise ValueError,"[Bad addMirrorAttributeBridge arg: %s]{arg: %s}"%(i,l) # Running lists ------------------------------------------------------------------------------------------ ml_groups = []#Holder for groups ml_constraintGroups = [] ml_spacePivots = [] #Copy Transform ================================================================================================ if copyTransform is not None: mTarget = cgmMeta.validateObjArg(copyTransform,'cgmObject',noneValid=True) if not mTarget: raise StandardError,"Failed to find suitable copyTransform object: '%s"%copyTransform #Need to move this to default cgmNode stuff mBuffer = mi_control i_newTransform = cgmMeta.cgmObject( rigging.groupMeObject(mTarget.mNode,False) ) for a in mc.listAttr(mi_control.mNode, userDefined = True): ATTR.copy_to(mi_control.mNode,a,i_newTransform.mNode) curves.parentShapeInPlace(i_newTransform.mNode,mi_control.mNode)#Parent shape i_newTransform.parent = mi_control.parent#Copy parent mi_control = cgmMeta.asMeta(i_newTransform,'cgmControl', setClass=True) mc.delete(mBuffer.mNode) #ShapeParent ================================================================================================ if shapeParentTo: i_target = cgmMeta.validateObjArg(shapeParentTo,'cgmObject') CORERIG.shapeParent_in_place(i_target.mNode,mi_control.mNode) i_target = cgmMeta.asMeta(i_target,'cgmControl',setClass = True) #mi_control.delete() mi_control = i_target#replace the control with the joint if useShape is not None: i_shape = cgmMeta.validateObjArg(useShape,cgmMeta.cgmObject,mayaType='nurbsCurve') curves.parentShapeInPlace(mi_control.mNode,i_shape.mNode) #Copy Pivot ============================================================================================ if copyPivot is not None: if issubclass(type(copyPivot),cgmMeta.cgmNode): i_target = copyPivot elif mc.objExists(copyPivot): i_target = cgmMeta.cgmObject(copyPivot) else: raise StandardError,"Failed to find suitable copyTransform object: '%s"%copyPivot #Need to move this to default cgmNode stuff mi_control.doCopyPivot(i_target.mNode) #Naming ============================================================================================ mi_control.addAttr('cgmType','controlAnim',lock=True) if typeModifier is not None: mi_control.addAttr('cgmTypeModifier',str(typeModifier),lock=True) mi_control.doName()#mi_control.doName(nameShapes=True) #Rotate Order ============================================================================================ _rotateOrder = False if setRotateOrder is not None: _rotateOrder = setRotateOrder elif controlType in __d_rotateOrderDefaults__.keys(): _rotateOrder = __d_rotateOrderDefaults__[controlType] elif mi_control.getAttr('cgmName') in __d_rotateOrderDefaults__.keys(): _rotateOrder = __d_rotateOrderDefaults__[mi_control.getAttr('cgmName')] else: log.debug("|{0}| >> Rotate order not set on: {1}".format(_str_func,mi_control.p_nameShort)) #Set it --------------------------------------------------------------- if _rotateOrder: mRotateOrder = VALID.simpleOrientation(_rotateOrder) #dictionary.validateRotateOrderString(_rotateOrder) mc.xform(mi_control.mNode, rotateOrder = mRotateOrder.p_string) #Initial Freeze ============================================================================================ if freezeAll: mc.makeIdentity(mi_control.mNode, apply=True,t=1,r=1,s=1,n=0) #Groups ============================================================================================ if addDynParentGroup or addSpacePivots or mi_control.getAttr('cgmName') == 'cog' or _addMirrorAttributeBridges: mi_control.addAttr('________________',attrType = 'int',keyable = False,hidden = False,lock=True) ATTR.reorder(mi_control.mNode, '________________',top=True ) #Aim Setup ============================================================================================ if aim is not None or up is not None or makeAimable: mi_control._verifyAimable() #First our master group: i_masterGroup = (cgmMeta.asMeta(mi_control.doGroup(True), 'cgmObject', setClass=True)) i_masterGroup.doStore('cgmName',mi_control) i_masterGroup.addAttr('cgmTypeModifier','master',lock=True) i_masterGroup.doName() mi_control.connectChildNode(i_masterGroup,'masterGroup','groupChild') if addDynParentGroup: i_dynGroup = (cgmMeta.cgmObject(mi_control.doGroup(True))) i_dynGroup = cgmRigMeta.cgmDynParentGroup(dynChild=mi_control,dynGroup=i_dynGroup) i_dynGroup.doName() """ i_zeroGroup = (cgmMeta.cgmObject(mi_control.doGroup(True))) i_zeroGroup.addAttr('cgmTypeModifier','zero',lock=True) i_zeroGroup.doName() mi_control.connectChildNode(i_zeroGroup,'zeroGroup','groupChild')""" if addExtraGroups: for i in range(addExtraGroups): i_group = (cgmMeta.asMeta(mi_control.doGroup(True),'cgmObject',setClass=True)) if type(addExtraGroups)==int and addExtraGroups>1:#Add iterator if necessary i_group.addAttr('cgmIterator',str(i+1),lock=True) i_group.doName() ml_groups.append(i_group) mi_control.msgList_connect("extraGroups",ml_groups,'groupChild') if addConstraintGroup:#ConstraintGroups i_constraintGroup = (cgmMeta.asMeta(mi_control.doGroup(True),'cgmObject',setClass=True)) i_constraintGroup.addAttr('cgmTypeModifier','constraint',lock=True) i_constraintGroup.doName() ml_constraintGroups.append(i_constraintGroup) mi_control.connectChildNode(i_constraintGroup,'constraintGroup','groupChild') #Space Pivot ============================================================================================ if addSpacePivots: parent = mi_control.getMessage('masterGroup')[0] for i in range(int(addSpacePivots)): #i_pivot = rUtils.create_spaceLocatorForObject(mi_control.mNode,parent) i_pivot = SPACEPIVOTS.create(mi_control.mNode,parent) ml_spacePivots.append(i_pivot) #log.info("spacePivot created: {0}".format(i_pivot.p_nameShort)) #Mirror Setup ============================================================================================ if str_mirrorSide is not None or b_makeMirrorable: for mObj in [mi_control] + ml_spacePivots: mi_control._verifyMirrorable() l_enum = cgmMeta.cgmAttr(mi_control,'mirrorSide').p_enum if str_mirrorSide in l_enum: #log.debug("|{0}| >> Rotate order not set on: {1}".format(_str_func,mi_control.p_nameShort)) #log.debug("%s >> %s >> found in : %s"%(_str_funcCombined, "mirrorSetup", l_enum)) mi_control.mirrorSide = l_enum.index(str_mirrorSide) if str_mirrorAxis: mi_control.mirrorAxis = str_mirrorAxis for mObj in mi_control.msgList_get('spacePivots'): mObj._verifyMirrorable() mi_control.doConnectOut('mirrorAxis',mObj.mNode + '.mirrorAxis') mi_control.doConnectOut('mirrorSide',mObj.mNode + '.mirrorSide') #cgmMeta.cgmAttr(mObj,'mirrorSide').doConnectIn(mi_control,'mirrorSide') #cgmMeta.cgmAttr(mi_control,'mirrorAxis').doCopyTo(mObj,connectTargetToSource = 1) #ATTR.connect(mObj.mNode + '.mirrorAxis',"{0}.mirrorAxis".format(mi_control.mNode)) #ATTR.connect(mObj.mNode + 'mirrorSide',"{0}.mirrorSide".format(mi_control.mNode)) #Freeze ============================================================================================ if not shapeParentTo and noFreeze is not True: if not freezeAll: if mi_control.getAttr('cgmName') == 'cog' or controlType in __l_fullFreezeTypes__: mc.makeIdentity(mi_control.mNode, apply=True,t=1,r=1,s=1,n=0) else: mc.makeIdentity(mi_control.mNode, apply=True,t=1,r=0,s=1,n=0) else: mc.makeIdentity(mi_control.mNode, apply=True,t=1,r=1,s=1,n=0) #Mirror attriubte Bridges ============================================================================================ if addForwardBack: mPlug_forwardBackDriver = cgmMeta.cgmAttr(mi_control,"forwardBack",attrType = 'float',keyable=True) try: mPlug_forwardBackDriven = cgmMeta.validateAttrArg([mi_control,addForwardBack])['mi_plug'] except Exception,error:raise StandardError,"push pull driver | %s"%(error) if str_mirrorSide.lower() == 'right': arg_forwardBack = "%s = -%s"%(mPlug_forwardBackDriven.p_combinedShortName, mPlug_forwardBackDriver.p_combinedShortName) else: arg_forwardBack = "%s = %s"%(mPlug_forwardBackDriven.p_combinedShortName, mPlug_forwardBackDriver.p_combinedShortName) mPlug_forwardBackDriven.p_locked = True mPlug_forwardBackDriven.p_hidden = True mPlug_forwardBackDriven.p_keyable = False NodeF.argsToNodes(arg_forwardBack).doBuild() if _addMirrorAttributeBridges: for l_bridge in _addMirrorAttributeBridges: _attrName = VALID.stringArg(l_bridge[0]) _attrToBridge = VALID.stringArg(l_bridge[1]) if not mi_control.hasAttr(_attrToBridge): raise StandardError,"['%s' lacks the bridge attr '%s']"%(mi_control.p_nameShort,_attrToBridge) mPlug_attrBridgeDriver = cgmMeta.cgmAttr(mi_control,_attrName,attrType = 'float',keyable=True) try: mPlug_attrBridgeDriven = cgmMeta.validateAttrArg([mi_control,_attrToBridge])['mi_plug'] except Exception,error:raise StandardError,"[validate control attribute bridge attr]{%s}"%(error) if str_mirrorSide.lower() == 'right': arg_attributeBridge = "%s = -%s"%(mPlug_attrBridgeDriven.p_combinedShortName, mPlug_attrBridgeDriver.p_combinedShortName) else: arg_attributeBridge = "%s = %s"%(mPlug_attrBridgeDriven.p_combinedShortName, mPlug_attrBridgeDriver.p_combinedShortName) mPlug_attrBridgeDriven.p_locked = True mPlug_attrBridgeDriven.p_hidden = True mPlug_attrBridgeDriven.p_keyable = False NodeF.argsToNodes(arg_attributeBridge).doBuild() #lock N Hide ============================================================================================ if mi_control.hasAttr('visibility'): mi_control.visibility = True if autoLockNHide: if mi_control.hasAttr('cgmTypeModifier'): if mi_control.cgmTypeModifier.lower() == 'fk': ATTR.set_standardFlags(mi_control.mNode,attrs=['tx','ty','tz','sx','sy','sz']) if mi_control.cgmName.lower() == 'cog': ATTR.set_standardFlags(mi_control.mNode,attrs=['sx','sy','sz']) cgmMeta.cgmAttr(mi_control,'visibility',lock=True,hidden=True) if mi_control.hasAttr('cgmIterator'): ATTR.set_standardFlags(mi_control.mNode,attrs=['cgmIterator']) str_base = mi_control.p_nameBase for i,mShape in enumerate(mi_control.getShapes(asMeta=True)): mShape.rename("{0}_shape_{1}".format(str_base,i)) #mShape.doName() #return ============================================================================================ #pprint.pprint(vars()) return {'mObj':mi_control,'instance':mi_control,'ml_groups':ml_groups,'ml_constraintGroups':ml_constraintGroups} except Exception,err: cgmGeneral.cgmExceptCB(Exception,err)
def _syncUI(self): # Since _syncUI is called in response to events that invalidate/clear # the selections in the views, disable the buttons until something is # selected again. self.removeExportedAttrButton.setEnabled(False) self.addExportedAttrButton.setEnabled(False) selectedNodeNames = cmds.ls(selection=True, long=True) if not selectedNodeNames: self.addAttrsModel.setStringList([]) self.exportedAttrsModel.exportedAttributes = [] self.exportedAttrsView.resizeColumnsToContents() return # Collect the export attributes common to all selected nodes. If the # same attribute is configured differently on multiple objects (e.g. # different usdAttrName), then do not include that attribute. allExportedAttributeNames = set() commonExportedAttributeNames = set() commonExportedAttrs = {} for exportedAttr in ExportedAttribute.GetExportedAttributesFromNode(selectedNodeNames[0]): mayaAttrName = exportedAttr.mayaAttrName allExportedAttributeNames.add(mayaAttrName) commonExportedAttributeNames.add(mayaAttrName) commonExportedAttrs[mayaAttrName] = exportedAttr for selectedNodeName in selectedNodeNames[1:]: exportedAttrNames = set() for exportedAttr in ExportedAttribute.GetExportedAttributesFromNode(selectedNodeName): mayaAttrName = exportedAttr.mayaAttrName allExportedAttributeNames.add(mayaAttrName) if (mayaAttrName in commonExportedAttrs and commonExportedAttrs[mayaAttrName] == exportedAttr): exportedAttrNames.add(mayaAttrName) commonExportedAttributeNames.intersection_update(exportedAttrNames) commonExportedAttrs = [commonExportedAttrs[x] for x in commonExportedAttributeNames] commonExportedAttrs.sort(key=lambda x: x.mayaAttrName) self.exportedAttrsModel.exportedAttributes = commonExportedAttrs # Normally, the combo boxes for selecting usdAttrType and # primvarInterpolation would only appear when the table cell is put into # edit mode. Instead, we want the combo boxes to always be visible, so # we tell the view to open them as persistent editors. for row in xrange(self.exportedAttrsModel.rowCount()): usdAttrTypeIndex = self.exportedAttrsModel.index(row, ExportedAttributesModel.USD_ATTR_TYPE_COLUMN) self.exportedAttrsView.openPersistentEditor(usdAttrTypeIndex) # Only open the interpolation editor if this is a primvar. if self.exportedAttrsModel.data(usdAttrTypeIndex) == USD_ATTR_TYPE_PRIMVAR: primvarInterpolationIndex = self.exportedAttrsModel.index(row, ExportedAttributesModel.PRIMVAR_INTERPOLATION_COLUMN) self.exportedAttrsView.openPersistentEditor(primvarInterpolationIndex) # Only open the double-to-single precision editor if the Maya # attribute is double-based. mayaAttrNameIndex = self.exportedAttrsModel.index(row, ExportedAttributesModel.MAYA_ATTR_NAME_COLUMN) mayaAttrName = self.exportedAttrsModel.data(mayaAttrNameIndex) if _ShouldEnableDoublePrecisionEditor(mayaAttrName): doublePrecisionIndex = self.exportedAttrsModel.index(row, ExportedAttributesModel.DOUBLE_PRECISION_COLUMN) self.exportedAttrsView.openPersistentEditor(doublePrecisionIndex) self.exportedAttrsView.resizeColumnsToContents() # Collect the attributes common to all selected nodes. cmdOptions = {'read': True} if self.userDefinedCheckBox.isChecked(): cmdOptions['userDefined'] = True commonAttrNames = set(cmds.listAttr(selectedNodeNames[0], **cmdOptions) or []) for selectedNodeName in selectedNodeNames[1:]: attrNames = set(cmds.listAttr(selectedNodeName, **cmdOptions) or []) commonAttrNames.intersection_update(attrNames) # Subtract out reserved attribute names and attributes already being # exported by ANY node. commonAttrNames -= RESERVED_ATTRIBUTES commonAttrNames -= allExportedAttributeNames self.addAttrsModel.setStringList(sorted(list(commonAttrNames)))
if not cmds.objExists('shotMaster'): cmds.confirmDialog(icon='warning', title='Message', message='No shot_master within the maya scene!', button=['Ok'], defaultButton='Ok') cmds.error('NO SHOT MASTER WITHIN THE MAYA SCENE!') SHOTDURATIONlis = [] SHOTNAMElis = [] #Preliminary Scene Data PRJSRSvar = cmds.getAttr('sceneInfo.projName', asString=True) PRJCDEvar = cmds.getAttr('sceneInfo.projCode', asString=True) PRJEPSvar = cmds.getAttr('sceneInfo.episodeName', asString=True) PRJSEQvar = cmds.getAttr('sceneInfo.sequenceName', asString=True) SHOTLISTATTRvar = cmds.listAttr('sceneInfo') for chk in SHOTLISTATTRvar: if chk.find('SH') >= 0: TEMPvar = cmds.getAttr('sceneInfo.' + chk, asString=True) SHOTNAMElis.append(chk) SHOTDURATIONlis.append(TEMPvar) class SCENEINFOVIEWER: def __init__(self): win = cmds.window(t='Scene Information', s=False, w=200, h=300) cmds.renameUI(win, 'mncToolsLaySceneInfoViewer') cmas = cmds.columnLayout(adj=True) f1 = cmds.frameLayout(l='Sequence Credential', w=200) fc1 = cmds.columnLayout(adj=True, p=f1) cmds.rowColumnLayout(nc=2, columnWidth=[(1, 80), (2, 120)], p=fc1)
def isolate(option): sel = mc.ls(sl=True) if not sel: return graphVis = mc.selectionConnection('graphEditor1FromOutliner', query=True, obj=True) channels = list() wildCard = str() alreadyIsolated = True if graphVis: for c in graphVis: if not '.' in c and mc.objExists(c): attrs = mc.listAttr(c, keyable=True, unlocked=True) if attrs: channels.extend([c + '.' + a for a in attrs]) else: attr = c.split('.')[-1] if attr.startswith(option): channels.append(c) if not wildCard: wildCard = option + '*' elif attr.endswith(option): channels.append(c) if not wildCard: wildCard = '*' + option elif attr == option: channels.append(c) if not wildCard: wildCard = option else: #found a curve that is outside our search parameters alreadyIsolated = False if channels and alreadyIsolated: #if the option is already the only thing being displayed, then show everything that matches the option for obj in sel: attrs = mc.listAttr(obj, keyable=True, unlocked=True, string=wildCard) if attrs: channels.extend([obj + '.' + a for a in attrs]) if not channels: for obj in sel: attrs = mc.listAttr(obj, keyable=True, unlocked=True) for a in attrs: if a == option or a.startswith(option) or a.endswith(option): channels.append(obj + '.' + a) clear() for c in channels: mc.selectionConnection('graphEditor1FromOutliner', edit=True, select=c)