def remove_failed_edits(self,ref_nodes): for ref_node in ref_nodes: #unload reference node first file_ref = pm.system.FileReference(ref_node) unload = False # if reference file is not load if not file_ref.isLoaded() : self.Log.warning('%s has not been loaded' % ref_node.name()) unload = True else: file_ref.unload() # remove edits import maya.cmds as cmds try: cmds.referenceEdit(ref_node.name(),removeEdits=True,\ successfulEdits=False,failedEdits=True) except: self.Log.error('%s remove reference edits error' % ref_node.name()) else: self.Log.debug('%s remove reference edits success' % ref_node.name()) if not unload: file_ref.load()
def remove_failed_edits(self, ref_nodes): for ref_node in ref_nodes: #unload reference node first file_ref = pm.system.FileReference(ref_node) unload = False # if reference file is not load if not file_ref.isLoaded(): self.Log.warning('%s has not been loaded' % ref_node.name()) unload = True else: file_ref.unload() # remove edits import maya.cmds as cmds try: cmds.referenceEdit(ref_node.name(),removeEdits=True,\ successfulEdits=False,failedEdits=True) except: self.Log.error('%s remove reference edits error' % ref_node.name()) else: self.Log.debug('%s remove reference edits success' % ref_node.name()) if not unload: file_ref.load()
def process(self, context, plugin): from maya import cmds self.log.info("Finding bad nodes..") # Get the errored instances errored_instances = [] for result in context.data["results"]: if result["error"] is not None and result["instance"] is not None: if result["error"]: instance = result["instance"] errored_instances.append(instance) # Apply pyblish.logic to get the instances for the plug-in instances = pyblish.api.instances_by_plugin(errored_instances, plugin) # Get the nodes from the all instances that ran through this plug-in invalid = [] for instance in instances: invalid_nodes = plugin.get_invalid(instance) invalid.extend(invalid_nodes) if not invalid: self.log.info("No invalid nodes found.") return for ref in invalid: self.log.info("Remove failed edits for: {0}".format(ref)) cmds.referenceEdit(ref, removeEdits=True, failedEdits=True, successfulEdits=False) self.log.info("Removed failed edits")
def repair(cls, instance): invalid = cls.get_invalid(instance) # Group invalid nodes by reference node references = defaultdict(set) for node in invalid: ref = cmds.referenceQuery(node, referenceNode=True) references[ref].add(node) # Remove the reference edits on the nodes per reference node for ref, nodes in references.items(): for node in nodes: # Somehow this only works if you run the the removal # per edit command. for command in [ "addAttr", "connectAttr", "deleteAttr", "disconnectAttr", "setAttr" ]: cmds.referenceEdit("{}.cbId".format(node), removeEdits=True, successfulEdits=True, failedEdits=True, editCommand=command, onReferenceNode=ref)
def removeEdits(rfn, editStrings): """ Remove edits strings. """ rfn = type(rfn) is list and str(rfn[0]) or str(rfn) editStrings = type(editStrings) is list and editStrings or [editStrings] unloadReference(rfn) filename = cmds.referenceQuery(rfn, filename=True) m_isdeferred = cmds.file(filename, query=True, deferReference=True) #Remove edits. for i in range(0, len(editStrings)): string = str(editStrings[i]) buffer = string.split(" ") #Edit command. m_command = buffer[0] #Edit node. if m_command == "addAttr": node = buffer[-1] + "." + buffer[2] elif m_command == "deleteAttr": node = buffer[1] elif m_command == "connectAttr": node = buffer[1] elif m_command == "disconnectAttr": if m_isdeferred: node = buffer[-2] else: node = buffer[-1] elif m_command == "setAttr": node = buffer[1] elif m_command == "relationship": node = buffer[2] elif m_command == "parent": if buffer[-2] == "-w": node = buffer[-1] else: node = buffer[-2] if "\"" in node: node = node.split("\"")[1] cmds.referenceEdit(node, failedEdits=True, successfulEdits=True, editCommand=m_command, removeEdits=True) cmds.file(loadReference=rfn)
def kRefClean(self, *args): editCommandList = [] if mc.checkBox(self.setAttrBTN, value=1, q=1): editCommandList.append("setAttr") if mc.checkBox(self.addAttrBTN, value=1, q=1): editCommandList.append("addAttr") if mc.checkBox(self.connectAttrBTN, value=1, q=1): editCommandList.append("connectAttr") if mc.checkBox(self.deleteAttrBTN, value=1, q=1): editCommandList.append("deleteAttr") if mc.checkBox(self.disconnectAttrBTN, value=1, q=1): editCommandList.append("disconnectAttr") if mc.checkBox(self.parentBTN, value=1, q=1): editCommandList.append("parent") if mc.checkBox(self.lockBTN, value=1, q=1): editCommandList.append("lock") if mc.checkBox(self.unlockBTN, value=1, q=1): editCommandList.append("unlock") print editCommandList refListSelect = mc.textScrollList(self.refListScroll, selectItem=1, q=True) print refListSelect for ref in refListSelect: nodes = mc.referenceQuery(ref, editNodes=True) attrTypes = mc.referenceQuery(ref, editAttrs=True) for node in nodes: for attrType in attrTypes: for commandd in editCommandList: mc.referenceEdit( node + '.' + attrType, failedEdits=mc.checkBox(self.failedEditsBTN, value=1, q=1), successfulEdits=mc.checkBox( self.successfulEditsBTN, value=1, q=1), removeEdits=True, editCommand=commandd) print ">> Ref Edit Clean !!" '''
def main(path, pathout=None): cmds.file(path, o=True, loadReferenceDepth='none') references = cmds.ls(references=True) or list() for ref in references: for cmd, patterns in removing.iteritems(): edits = cmds.referenceQuery(ref, editStrings=True, editCommand=cmd, showDagPath=False) for edit in edits: if any(p in edit for p in patterns)\ and not any(p in edit for p in preserving.get(cmd)): print 'Removing:', edit cmds.referenceEdit(edit.split()[1], failedEdits=True, successfulEdits=True, editCommand=cmd, removeEdits=True) pathout = pathout or '.fixed'.join(os.path.splitext(path)) print 'Saving file to', pathout cmds.file(rename=pathout) cmds.file(save=True)
def removeEdits( rfn, editStrings ): """ Remove edits strings. """ rfn = type( rfn ) is list and str( rfn[0] ) or str( rfn ) editStrings = type( editStrings ) is list and editStrings or [ editStrings ] unloadReference( rfn ) filename = cmds.referenceQuery( rfn, filename=True ) m_isdeferred = cmds.file( filename, query=True, deferReference=True ) #Remove edits. for i in range( 0, len( editStrings )): string = str( editStrings[i] ) buffer = string.split( " " ) #Edit command. m_command = buffer[0] #Edit node. if m_command == "addAttr": node = buffer[-1] + "." + buffer[2] elif m_command == "deleteAttr": node = buffer[1] elif m_command == "connectAttr": node = buffer[1] elif m_command == "disconnectAttr": if m_isdeferred: node = buffer[-2] else: node = buffer[-1] elif m_command == "setAttr": node = buffer[1] elif m_command == "relationship": node = buffer[2] elif m_command == "parent": if buffer[-2] == "-w": node = buffer[-1] else: node = buffer[-2] if "\"" in node: node = node.split( "\"" )[1] cmds.referenceEdit( node, failedEdits=True, successfulEdits=True, editCommand=m_command, removeEdits=True ) cmds.file( loadReference=rfn )
def remove_shading_edits(): """ removes shading reference edits on selected objects """ sel = cmds.ls(sl=1, long=1) shapes = [] ref_nodes = set() for obj in sel: if cmds.referenceQuery(obj, inr=1): obj_shapes = cmds.listRelatives(obj, f=1, s=1) if obj_shapes: shapes.extend(obj_shapes) else: shapes.extend(obj) ref_node = cmds.referenceQuery(obj, referenceNode=1) ref_nodes.add(ref_node) if ref_nodes: for ref_node in ref_nodes: cmds.file(unloadReference=ref_node) for shape in shapes: cmds.referenceEdit(shape + '.instObjGroups', removeEdits=1, failedEdits=1, successfulEdits=1, editCommand='connectAttr') cmds.referenceEdit(shape + '.instObjGroups', removeEdits=1, failedEdits=1, successfulEdits=1, editCommand='disconnectAttr') for ref_node in ref_nodes: cmds.file(loadReference=ref_node) print 'Done remove shading edits!'
def cleanREF_SG(): print('Running %s...' % 'cleanREF_SG') allRef = mc.ls(references=True) #remove unloaded reference from the list for ref in allRef: if not mc.referenceQuery(ref, isLoaded=1): allRef.remove(ref) print('****COULDN\'T FIND: %s' % ref) print('Found:') for ref in allRef: print(' %s' % ref) #unloading all references print('\nUnloading references...') for ref in allRef: mc.file(unloadReference=ref) #remove Shading group reference edits print('Removing Shading Group reference edits...') for ref in allRef: sgEdits = [ sge for sge in mc.referenceQuery(ref, editNodes=True) if 'SG' in sge ] for sge in sgEdits: mc.referenceEdit(sge + '.dagSetMembers', failedEdits=True, successfulEdits=True, removeEdits=True) #reload reference print('Reloading...') for ref in allRef: print(' %s' % ref) mc.file(loadReference=ref) print('')
def checkReferenceShaderReset(self, configType=0, assetType=0): from idmt.maya.commonCore.core_mayaCommon import sk_infoConfig reload(sk_infoConfig) shotInfo = sk_infoConfig.sk_infoConfig().checkShotInfo() # 获取文件内参考信息 refInfos = self.checkReferenceListInfo() refNodes = refInfos[0][0] if refNodes: checkTypes = [ 'setAttr', 'connectAttr', 'disconnectAttr', 'addAttr', 'parent' ] for checkType in checkTypes: # 更改过的属性信息 modifyInfos = [] for refNode in refNodes: if 'CAM' not in refNode: #print refNode if configType == 1: modifyInfos = modifyInfos + mc.referenceQuery( refNode, failedEdits=0, successfulEdits=1, editCommand=checkType, editStrings=1) if configType == 0: if refNode.split('_')[1][0] in ['s', 'S']: modifyInfos = modifyInfos + mc.referenceQuery( refNode, failedEdits=0, successfulEdits=1, editCommand=checkType, editStrings=1) if modifyInfos: # 需要欢迎的SG相关信息 resetShaderInfo = [] resetUVInfo = [] resetAttrInfo = [] for info in modifyInfos: if 'SG' in info and shotInfo[0] != 'cl': if '\"' in info: needInfo = info.split('\"')[1] #print needInfo resetShaderInfo.append(needInfo) if '.uv' in info: #print '-----------' #print info needInfo = info.split(' ')[1] #print needInfo resetUVInfo.append(needInfo) if 'initialShadingGroup.dagSetMembers' in info: #print info needInfo = info.split('\"')[1] #print needInfo resetShaderInfo.append(needInfo) if '.transparency' in info: print info needInfo = info.split('\"')[1] resetAttrInfo.append(needInfo) # 开始欢迎 if resetShaderInfo: for info in resetShaderInfo: mc.referenceEdit(info, failedEdits=1, successfulEdits=1, editCommand=checkType, removeEdits=1) if resetUVInfo: for info in resetUVInfo: mc.referenceEdit(info, failedEdits=1, successfulEdits=1, editCommand=checkType, removeEdits=1) if resetAttrInfo: for info in resetAttrInfo: mc.referenceEdit(info, failedEdits=1, successfulEdits=1, editCommand=checkType, removeEdits=1)
elif command == "connectAttr": connectAttr = True remove_attr = "%s,%s" % (buffer[1], buffer[2]) else: remove_attr = remove_dict[command](buffer) remove_attr = remove_attr.replace('"', '') dagPath = remove_attr.split('.')[0].replace( '"', '') if connectAttr == True else remove_attr.split('.')[0].replace( '"', '') # NOTE 如果物体不存在则跳过处理 if not cmds.objExists(dagPath): continue objectType = cmds.objectType(dagPath) # NOTE 过滤 transform 节点 和 动画曲线的处理 if objectType != 'transform' and 'animCurve' not in objectType: if connectAttr: cmds.referenceEdit(*remove_attr.split(","), editCommand=command, failedEdits=True, successfulEdits=True, removeEdits=True) else: cmds.referenceEdit(remove_attr, editCommand=command, failedEdits=True, successfulEdits=True, removeEdits=True)
def propagateWeightChangesToReference(meshes): ''' Given a list of meshes to act on, this function will store the skin weights, remove any edits from the skin clusters that affect them, open the scene file the meshes come from and apply the weights to the geometry in that scene. This makes it possible to fix skinning problems while animating with minimal workflow changes ''' curFile = cmds.file(q=True, sn=True) #failsafe for untitled file if curFile == '': cmds.warning( 'Current file is not saved. Please save file and try again!') return #getting skin cluster nodes from meshes skinClusters = [] for mesh in meshes: sc = mel.eval('findRelatedSkinCluster("%s");' % mesh) skinClusters.append(sc) referencedSkins = getRefFilepathDictForNodes(skinClusters) for refFilepath, refNodeMeshDict in referencedSkins.iteritems(): referencesToUnload = [] #make sure we don't visit any of the meshes more than once meshesToUpdateWeightsOn = [] meshesToUpdateWeightsOn_withNS = [] for refNode, refMeshes in refNodeMeshDict.iteritems(): #get the maya filepath for the reference (with the "copy number") mayaFilepathForRef = cmds.referenceQuery(refNode, f=True) #get the namespace for this reference refNodeNamespace = cmds.file(mayaFilepathForRef, q=True, namespace=True) #check to see if there are any meshes in this reference that we need to store weights for for mesh_withNS in refMeshes: mesh = stripNamespaceFromNamePath(mesh_withNS, refNodeNamespace) if mesh in meshesToUpdateWeightsOn: continue meshesToUpdateWeightsOn.append(mesh) meshesToUpdateWeightsOn_withNS.append( (mesh_withNS, refNodeNamespace)) #append the file to the list of reference files that we need to unload referencesToUnload.append(mayaFilepathForRef) #get a list of skin cluster nodes - its actually the skin cluster nodes we want to remove edits from... nodesToCleanRefEditsFrom = [] #now we want to store out the weighting from the referenced meshes weightFiles = [] for mesh, meshNamespace in meshesToUpdateWeightsOn_withNS: nodesToCleanRefEditsFrom.append(mesh) m = cmds.listConnections(mesh + '.outputGeometry')[0] mStrip = stripNamespaceFromNamePath(m, meshNamespace) #export dora skin tempDir = tempfile.gettempdir() filepath = tempDir.replace('\\', '/') + '/' + mStrip.replace( ':', '_-_') + '.dsw' weightFiles.append(filepath) sourceDora() cmds.select(m) mel.eval('DoraSkinWeightExport_mod("%s")' % filepath) #modify dora skin f = open(filepath, 'r') data = f.readlines() jntData = '' for jnt in data[1].split(','): jnt = jnt.replace('\n', '') jnt = stripNamespaceFromNamePath(jnt, meshNamespace) jntData += jnt + ',' jntData = jntData[0:-1] + '\n' data[1] = jntData newData = '' for line in data: newData += line f.close() #writing new dora skin f = open(filepath, 'w') f.write(newData) f.close() #also lets remove any ref edits from the mesh and all of its shape nodes - this isn't strictly nessecary, but I can't think of a reason to make edits to these nodes outside of their native file nodesToCleanRefEditsFrom.append(m) nodesToCleanRefEditsFrom += cmds.listRelatives(m, s=True, pa=True) #remove the skinweights reference edits from the meshes in the current scene for f in referencesToUnload: cmds.file(f, unloadReference=True) #remove ref edits from the shape node as well - this isn't strictly nessecary but there probably shouldn't be changes to the shape node anyway for node in nodesToCleanRefEditsFrom: cmds.referenceEdit(node, removeEdits=True, successfulEdits=True, failedEdits=True) #re-load references for f in referencesToUnload: cmds.file(f, loadReference=True) #save this scene now that we've removed ref edits cmds.file(save=True, f=True) #load up the referenced file and apply the weighting to the meshes in that scene cmds.file(refFilepath, open=True, f=True) for f in weightFiles: mesh = f.split('/')[-1].replace('_-_', ':').split('.')[0] cmds.select(mesh) mel.eval('DoraSkinWeightImport_mod("%s",0,0,1,0.001);' % f) os.remove(f) #save the referenced scene now that we've applied the weights to it cmds.file(save=True, f=True) #reload the original file cmds.file(curFile, o=True, f=True) #informing user of edited files and printing cmd = '\nFiles updated:\n' for f in referencedSkins: cmd += f + '\n' cmds.confirmDialog(title='Skin Propagation complete!', message=cmd) print cmd
for shape in shapes: mc.setAttr(shape + ".lev", lock=False) mc.setAttr(shape + ".lev", 0) mc.setAttr(shape + ".lev", lock=True) # "addAttr", "connectAttr", "deleteAttr", "disconnectAttr", "parent", "setAttr", "lock" and "unlock" objName = "*barrel01RN" objList = mc.ls(objName) mc.select(objName) for obj in objList: editcmd = [x for x in cmds.referenceQuery(obj, es=True) if 'setAttr' in x] if editcmd: filename = cmds.referenceQuery(obj, filename=True) mc.file(filename, ur=True) mc.referenceEdit(obj, removeEdits=True, editCommand="setAttr", successfulEdits=True) mc.file(filename, lr=True) # Remove all edits ref = 'myrefRN' nodes = cmds.referenceQuery( ref, editNodes=True ) attr_types = cmds.referenceQuery( ref, editAttrs=True ) for node in nodes: for attr_type in attr_types: for edit_command in ['addAttr', 'connectAttr', 'deleteAttr', 'disconnectAttr', 'parent', 'setAttr', 'lock', 'unlock']: cmds.referenceEdit( node+'.'+attr_type, failedEdits=True, successfulEdits=True, removeEdits=True, editCommand=edit_command) ## import de tous les buildings building = ("001", "002", "003", "004", "005", "006", "007", "008", "009", "010", "011", "012", "012b", "013", "014", "015", "015a", "016", "017", "018") ep = "666" for b in building :
cmds.progressWindow(e=1, status='%s' % ref) edit_list = cmds.referenceQuery(ref, editStrings=True, showDagPath=1) count = len(edit_list) # NOTE 获取当前引用节点的编辑信息 for i, edit in enumerate(edit_list): if cmds.progressWindow(query=True, isCancelled=True): cmds.progressWindow(endProgress=1) break amount = float(i) / count * 100 cmds.progressWindow(e=1, progress=amount) buffer = edit.split() command, attr = buffer[:2] if command != "setAttr": continue attr = buffer[1] if '[' in attr: print attr cmds.referenceEdit(attr, editCommand=command, failedEdits=True, successfulEdits=True, removeEdits=True) if i > 2: break cmds.progressWindow(ep=1)
def remove_edit(attr): cmds.referenceEdit(attr, failedEdits=True, successfulEdits=True, editCommand="setAttr", removeEdits=True)
def propagateWeightChangesToReference( meshes ): ''' Given a list of meshes to act on, this function will store the skin weights, remove any edits from the skin clusters that affect them, open the scene file the meshes come from and apply the weights to the geometry in that scene. This makes it possible to fix skinning problems while animating with minimal workflow changes ''' curFile = cmds.file( q=True, sn=True ) #failsafe for untitled file if curFile=='': cmds.warning('Current file is not saved. Please save file and try again!') return #getting skin cluster nodes from meshes skinClusters=[] for mesh in meshes: sc=mel.eval('findRelatedSkinCluster("%s");' % mesh) skinClusters.append(sc) referencedSkins=getRefFilepathDictForNodes(skinClusters) for refFilepath, refNodeMeshDict in referencedSkins.iteritems(): referencesToUnload = [] #make sure we don't visit any of the meshes more than once meshesToUpdateWeightsOn = [] meshesToUpdateWeightsOn_withNS = [] for refNode, refMeshes in refNodeMeshDict.iteritems(): #get the maya filepath for the reference (with the "copy number") mayaFilepathForRef = cmds.referenceQuery( refNode, f=True ) #get the namespace for this reference refNodeNamespace = cmds.file( mayaFilepathForRef, q=True, namespace=True ) #check to see if there are any meshes in this reference that we need to store weights for for mesh_withNS in refMeshes: mesh = stripNamespaceFromNamePath( mesh_withNS, refNodeNamespace ) if mesh in meshesToUpdateWeightsOn: continue meshesToUpdateWeightsOn.append( mesh ) meshesToUpdateWeightsOn_withNS.append( (mesh_withNS, refNodeNamespace) ) #append the file to the list of reference files that we need to unload referencesToUnload.append( mayaFilepathForRef ) #get a list of skin cluster nodes - its actually the skin cluster nodes we want to remove edits from... nodesToCleanRefEditsFrom = [] #now we want to store out the weighting from the referenced meshes weightFiles = [] for mesh, meshNamespace in meshesToUpdateWeightsOn_withNS: nodesToCleanRefEditsFrom.append(mesh) m=cmds.listConnections(mesh+'.outputGeometry')[0] mStrip=stripNamespaceFromNamePath(m,meshNamespace) #export dora skin tempDir=tempfile.gettempdir() filepath=tempDir.replace('\\','/')+'/'+mStrip.replace(':','_-_')+'.dsw' weightFiles.append(filepath) sourceDora() cmds.select(m) mel.eval('DoraSkinWeightExport_mod("%s")' % filepath) #modify dora skin f=open(filepath,'r') data=f.readlines() jntData='' for jnt in data[1].split(','): jnt=jnt.replace('\n','') jnt=stripNamespaceFromNamePath(jnt,meshNamespace) jntData+=jnt+',' jntData=jntData[0:-1]+'\n' data[1]=jntData newData='' for line in data: newData+=line f.close() #writing new dora skin f=open(filepath,'w') f.write(newData) f.close() #also lets remove any ref edits from the mesh and all of its shape nodes - this isn't strictly nessecary, but I can't think of a reason to make edits to these nodes outside of their native file nodesToCleanRefEditsFrom.append( m ) nodesToCleanRefEditsFrom += cmds.listRelatives( m, s=True, pa=True ) #remove the skinweights reference edits from the meshes in the current scene for f in referencesToUnload: cmds.file( f, unloadReference=True ) #remove ref edits from the shape node as well - this isn't strictly nessecary but there probably shouldn't be changes to the shape node anyway for node in nodesToCleanRefEditsFrom: cmds.referenceEdit( node, removeEdits=True, successfulEdits=True, failedEdits=True ) #re-load references for f in referencesToUnload: cmds.file( f, loadReference=True ) #save this scene now that we've removed ref edits cmds.file( save=True, f=True ) #load up the referenced file and apply the weighting to the meshes in that scene cmds.file( refFilepath, open=True, f=True ) for f in weightFiles: mesh=f.split('/')[-1].replace('_-_',':').split('.')[0] cmds.select(mesh) mel.eval('DoraSkinWeightImport_mod("%s",0,0,1,0.001);' % f) os.remove(f) #save the referenced scene now that we've applied the weights to it cmds.file( save=True, f=True ) #reload the original file cmds.file( curFile, o=True, f=True ) #informing user of edited files and printing cmd='\nFiles updated:\n' for f in referencedSkins: cmd+=f+'\n' cmds.confirmDialog(title='Skin Propagation complete!',message=cmd) print cmd