def __preCreateUI(self): self.grp = cmds.createNode('transform', name="CURVE_TOOLS_NULL", ss=True) self.ns = 'curve_tools' try: self.ns = cmds.namespace(add=self.ns) except: pass cmds.lockNode(self.grp, l=True) tmp = cmds.ls(sl=True) self.viewport_cam = cmds.camera( name="Curve_Tools_CAM", p=[-15, 15, 21], wci=[0,0,0] )[0] cmds.parent(self.viewport_cam, self.grp) if tmp: cmds.select(tmp) else: cmds.select(clear=True)
def rehook(self, newHookObject): oldHookObject = self.findHookObject() self.hookObject = (self.moduleNamespace + ':unhookedTarget') if newHookObject != None: if newHookObject.find('_translation_control') != -1: splitString = newHookObject.split('_translation_control') if splitString[1] == '': if utils.stripLeadingNamespace(newHookObject)[0] != self.moduleNamespace: self.hookObject = newHookObject if self.hookObject == oldHookObject: return self.unconstrainRootFromHook() cmds.lockNode(self.containerName, lock=False, lockUnpublished=False) hookConstraint = (self.moduleNamespace + ':hook_pointConstraint') cmds.connectAttr((self.hookObject + '.parentMatrix[0]'), (hookConstraint + '.target[0].targetParentMatrix'), force=True) cmds.connectAttr((self.hookObject + '.translate'), (hookConstraint + '.target[0].targetTranslate'), force=True) cmds.connectAttr((self.hookObject + '.rotatePivot'), (hookConstraint + '.target[0].targetRotatePivot'), force=True) cmds.connectAttr((self.hookObject + '.rotatePivotTranslate'), (hookConstraint + '.target[0].targetRotateTranslate'), force=True) cmds.lockNode(self.containerName, lock=True, lockUnpublished=True)
def lock_phase3(self, hook_obj): module_container = self.module_namespace + ":module_container" if hook_obj != None: hook_obj_module_node = utils.strip_leading_namespace(hook_obj) hook_obj_module = hook_obj_module_node[0] hook_obj_joint = hook_obj_module_node[1].split( "_translation_control")[0] hook_obj = hook_obj_module + ":blueprint_" + hook_obj_joint parent_con = cmds.parentConstraint( hook_obj, self.module_namespace + ":HOOK_IN", maintainOffset=True, name=self.module_namespace + ":hook_parent_constraint")[0] scale_con = cmds.scaleConstraint( hook_obj, self.module_namespace + ":HOOK_IN", maintainOffset=True, name=self.module_namespace + ":hook_scale_constraint")[0] module_container = self.module_namespace + ":module_container" utils.add_node_to_container(module_container, [parent_con, scale_con]) cmds.lockNode(module_container, lock=True, lockUnpublished=True)
def constrain_root_to_hook(self): root_control = self.get_trans_ctrl(self.module_namespace + ":" + self.joint_info[0][0]) hook_obj = self.find_hook_obj() if hook_obj == self.module_namespace + ":unhookedTarget": return cmds.lockNode(self.container_name, lock=False, lockUnpublished=False) cmds.pointConstraint(hook_obj, root_control, maintainOffset=False, name=root_control + "_hookConstraint") cmds.setAttr(root_control + ".translate", l=True) cmds.setAttr(root_control + ".visibility", l=False) cmds.setAttr(root_control + ".visibility", 0) cmds.setAttr(root_control + ".visibility", l=True) cmds.select(clear=True) cmds.lockNode(self.container_name, lock=True, lockUnpublished=True)
def equal_namespace(): """ 检查文件中存在相同namespace """ _rf_nodes = cmds.ls(rf=True) _rf_ns_node = {} _error_rf_nodes = [] for _rf_node in _rf_nodes: _inr = cmds.referenceQuery(_rf_node, inr=True) if not _inr: try: _namespace = cmds.referenceQuery(_rf_node, namespace=True) if _namespace not in _rf_ns_node.keys(): _rf_ns_node[_namespace] = _rf_node else: _error_rf_nodes.append((_rf_node, _rf_ns_node[_namespace])) except: try: cmds.lockNode(_rf_node, lock=False) cmds.delete(_rf_node) except: pass # return _error_rf_nodes if _error_rf_nodes: info = "场景存在namespace相同参考\n" for _error_rf_node in _error_rf_nodes: info += "{} - {}\n".format(_error_rf_node[0], _error_rf_node[1]) return False, info return True, None
def remove_unknown_nodes(): removed_count = 0 unknown_nodes = cmds.ls(type="unknown") for node in unknown_nodes: if cmds.objExists(node): sys.stdout.write("Remove unknown node '{}'.\n".format(node)) cmds.lockNode(node, lock=False) cmds.delete(node) removed_count += 1 if cmds.pluginInfo("Turtle.mll", q=True, loaded=True): cmds.pluginInfo("Turtle.mll", e=True, autoload=False) cmds.unloadPlugin("Turtle.mll", force=True) turtle_nodes = ["TurtleDefaultBakeLayer", "TurtleBakeLayerManager", "TurtleRenderOptions", "TurtleUIOptions"] for node in turtle_nodes: if cmds.objExists(node): sys.stdout.write("Remove Turtle node '{}'.\n".format(node)) cmds.lockNode(node, lock=False) cmds.delete(node) removed_count += 1 sys.stdout.write(str(removed_count) + " unknown nodes removed.\n")
def copyMap(self): ws = self.wb[self.wb.sheetnames[0]] count = 0 for row in ws.values: if row[0] is None: #file end break count += 1 self.ProgressDialog = QProgressDialog("Copying Map", "Cancel", 0, count) self.ProgressDialog.setWindowTitle("Copy Progress") table = tuple(ws.values) for i in range(0, count): if self.ProgressDialog.wasCanceled(): #copy canceled break #generate authorStr authorStr = table[i][0] + table[i][1] # 1.add author to attribute # #create author node and set hidden # authorNode = mc.group(em = 1, name = "AuthorNode") # mc.setAttr("AuthorNode.hiddenInOutliner", True) # #add attr and lock it # mc.addAttr("AuthorNode", longName = "Author", dataType = "string") # mc.setAttr("AuthorNode.Author", authorStr, type = "string") # mc.setAttr("AuthorNode.Author", lock = 1) # 2.add author(number) to group name # create author node and set hidden groupName = "Author_" + table[i][0] print groupName authorNode = mc.group(em = 1, name = groupName) mc.setAttr(groupName + ".hiddenInOutliner", True) #lock node mc.lockNode(authorNode, lock = 1) #fresh outliner mc.outlinerEditor("outlinerPanel1", edit = 1, refresh = 1) #save and copy map mel.eval("file -save") originMapName = "origin.mb" targetMapName = authorStr originMap = workRootDir + "scenes/" + originMapName targetMap = workRootDir + "scenes/" + targetMapName + ".mb" shutil.copy(originMap, targetMap) #unlock and delete node mc.lockNode(authorNode, lock = 0) mc.delete(authorNode) count += 1 # set progress self.ProgressDialog.setValue(count) self.copyCount = str(count) self.copyDone()
def deleteIt(self): coral.Node.deleteIt(self) if self._mayaNode: cmds.lockNode(self._mayaNode, lock = False) cmds.delete(self._mayaNode) self._mayaNode = ""
def unknownNodeClear(): allunknows = mc.ls(et="unknown") for unknows in allunknows: if mc.objExists(unknows): if mc.lockNode(unknows, q=True): mc.lockNode(unknows, l=False) mc.delete(unknows)
def _unload_useless_nodes(cls, source_rig, dest_rig, source_ctrls, binder_namespace): source_namespace = source_rig.nameSpaceFull() # rig_file_path = dest_rig.referencePath() # remove source reference cls._unload_reference(source_rig) # remove the binder file's node and rename source namespace nodes nodes_with_namespace = [node for node in mc.ls(recursive=True)] for i in reversed(range(len(nodes_with_namespace))): node = nodes_with_namespace[i] if mc.objExists(node): if node.startswith(binder_namespace): if mc.nodeType(node) == 'reference': continue try: mc.lockNode(node, lock=False) mc.delete(node) except: pass elif node.startswith(source_namespace): try: mc.lockNode(node, lock=False) mc.rename( node, node.replace(source_namespace + ':', source_namespace + '__')) except: pass
def lock_phase1(self): #109 moduleInfo=hingeJoint.HingeJoint.lock_phase1(self) jointPositions=moduleInfo[0] jointOrientationValues=moduleInfo[1][0] jointRotationOrders=moduleInfo[2] joints=self.getJoints() for i in range(3, 5): joint=joints[i] jointPositions.append(cmds.xform(joint, q=True, worldSpace=True, translation=True)) jointRotationOrders.append(cmds.getAttr(joint+".rotateOrder")) cmds.lockNode(self.containerName, lock=False, lockUnpublished=False) jointNameInfo=utils.stripAllNamespaces(joints[1]) cleanParent=jointNameInfo[0]+":IK_"+jointNameInfo[1] deleteJoints=[] for i in range(2,4): orientationInfo=self.orientationControlledJoint_getOrientation(joints[i], cleanParent) jointOrientationValues.append(orientationInfo[0]) cleanParent=orientationInfo[1] deleteJoints.append(cleanParent) cmds.delete(deleteJoints) cmds.lockNode(self.containerName, lock=True, lockUnpublished=True) return moduleInfo
def editPivotHandle(self): qt_maya_window.installEventFilter(self.keypressFilter) #create transform self.pivotHandle = mc.group(em=True, name='Adjust_Pivot') mc.setAttr(self.pivotHandle+'.rotate', lock=True) mc.setAttr(self.pivotHandle+'.rx', keyable=False) mc.setAttr(self.pivotHandle+'.ry', keyable=False) mc.setAttr(self.pivotHandle+'.rz', keyable=False) mc.setAttr(self.pivotHandle+'.scale', lock=True) mc.setAttr(self.pivotHandle+'.sx', keyable=False) mc.setAttr(self.pivotHandle+'.sy', keyable=False) mc.setAttr(self.pivotHandle+'.sz', keyable=False) mc.setAttr(self.pivotHandle+'.visibility', lock=True, keyable=False) mc.setAttr(self.pivotHandle+'.displayHandle', True) self.pivotHandle = mc.parent(self.pivotHandle, self.node)[0] mc.addAttr(self.pivotHandle, ln='ml_pivot_handle', at='bool', keyable=False) #set initial position mc.setAttr(self.pivotHandle+'.translate', *mc.getAttr(self.node+'.rotatePivot')[0]) #lock it so you don't delete it or something. mc.lockNode(self.pivotHandle, lock=True) self.scriptJob = mc.scriptJob(event=['SelectionChanged', self.cleanup], runOnce=True) mc.setToolTo('Move') mc.inViewMessage( amg='After moving the pivot, press <hl>Return</hl> to bake or <hl>Esc</hl> to cancel.', pos='midCenterTop', fade=True, fadeStayTime=4000, dragKill=True)
def createPublishSet(setName): cmds.sets(name=setName) cmds.addAttr(setName, longName="active", attributeType="bool", defaultValue=1) cmds.addAttr(setName, longName="exportMaya", attributeType="bool", defaultValue=1) cmds.addAttr(setName, longName="exportAlembic", attributeType="bool", defaultValue=0) cmds.addAttr(setName, longName="exportFBX", attributeType="bool", defaultValue=0) cmds.addAttr(setName, longName="exportOBJ", attributeType="bool", defaultValue=0) cmds.addAttr(setName, longName="exportArchive", attributeType="bool", defaultValue=0) cmds.lockNode(setName, lock=True)
def acceptWindow(self, targetObject, enumIndex, *args): spaceName = cmds.textField(self.UIElements["spaceName"], q=True, text=True) maintainOffset = cmds.checkBox( self.UIElements["maintainOffset_checkBox"], q=True, value=True) setKeyframes = cmds.checkBox(self.UIElements["setKeyframes_checkBox"], q=True, value=True) cmds.deleteUI(self.UIElements["window"]) animModuleNamespace = utils.stripAllNamespaces(self.controlObject)[0] blueprintModuleNamespace = utils.stripAllNamespaces( animModuleNamespace)[0] characterNamespace = utils.stripAllNamespaces( blueprintModuleNamespace)[0] containers = (characterNamespace + ":character_container", blueprintModuleNamespace + ":module_container", animModuleNamespace + ":module_container") for c in containers: cmds.lockNode(c, lock=False, lockUnpublished=False) self.switchSpace(targetObject, spaceName, index=enumIndex, maintainOffset=maintainOffset, setKeyframes=setKeyframes) for c in containers: cmds.lockNode(c, lock=True, lockUnpublished=True) cmds.select(self.controlObject, replace=True)
def importAllReference() : # Import all reference. # Input : None # Output : Name of imported reference node. rfns = mc.ls( type='reference' ) impRfns = [] for rfn in rfns : if not rfn == 'sharedReferenceNode' : try : fn = mc.referenceQuery( rfn , filename=True ) mc.file( fn , importReference=True ) print '%s has been imported.' % rfn impRfns.append( rfn ) except RuntimeError : print '%s is not connected to reference file.' % rfn mc.lockNode( rfn , l=0 ) mc.delete( rfn ) return impRfns
def _ls(nodeType = '', topTransform = True, stringFilter = '', unlockNode = False): if nodeType: nodes = cmds.ls(type = nodeType) if nodes: final_nodes = [] for each in nodes: each = cmds.ls(each, long = True)[0] top_transform = cmds.listRelatives(each, parent = True, fullPath = True) if topTransform else None final_node = top_transform[0] if top_transform else each if unlockNode: try: cmds.lockNode(final_node, lock = False) except: mel.eval('warning "Failed to unlock %s, skipping...";' % final_node) if stringFilter: if stringFilter in final_node: if final_node not in final_nodes: final_nodes.append(final_node) else: if final_node not in final_nodes: final_nodes.append(final_node) return final_nodes return []
def ensure_unlock_target(self): if self.imported_nodes: for node in self.imported_nodes: if not cmds.ls(node): continue cmds.lockNode(self.imported_nodes, lock=False)
def SetParent(child, parent): if cmds.lockNode(parent, q=True): cmds.lockNode(parent, l=False) cmds.parent(child, parent) cmds.lockNode(parent, l=True) else: cmds.parent(child, parent)
def delete_base_template(self, e=False): if not self.target_name: return cmds.lockNode(self.imported_nodes, lock=False) cmds.delete(self.imported_nodes) self.target_name = None
def deleteUnknown(): allunknows = mc.ls(type="unknown") for unknows in allunknows: if mc.objExists(unknows): if mc.lockNode(unknows, q=True): mc.lockNode(unknows, l=False) mc.delete(unknows)
def main(log=None): if not log: import logging log = logging.getLogger() # use ' ' as a fill char and center aligned log.debug('{0:-<40}'.format('delete_unknow_node')) allUnknow = cmds.ls(dep=True) if allUnknow: for n in allUnknow: try: node_type = cmds.nodeType(n) # TODO: No object matches name: rmanFinalGlobals # so use try and except to catch this except: pass else: if (node_type == 'unknown'): try: cmds.lockNode(n, l=False) cmds.delete(n) except: log.error('can not delete%s' % n) log.error(traceback.format_exc()) else: log.warning('delete %s success' % n)
def lock_phase1(self): jointPositions=[] jointOrientationValues=[] jointRotationOrders=[] jointPreferredAngles=[] cmds.lockNode(self.containerName, lock=False, lockUnpublished=False) ikHandle=self.moduleNamespace+":IK_"+self.jointInfo[0][0]+"_ikHandle" cmds.delete(ikHandle) for i in range(3): jointName=self.jointInfo[i][0] ikJointName=self.moduleNamespace+":IK_"+jointName cmds.makeIdentity(ikJointName, rotate=True, translate=False, scale=False, apply=True) jointPositions.append(cmds.xform(ikJointName, q=True, worldSpace=True, translation=True)) jointRotationOrders.append(cmds.getAttr(self.moduleNamespace+":"+jointName+".rotateOrder")) if i<2: jointOrientX=cmds.getAttr(ikJointName+".jointOrientX") jointOrientY=cmds.getAttr(ikJointName+".jointOrientY") jointOrientZ=cmds.getAttr(ikJointName+".jointOrientZ") jointOrientationValues.append( (jointOrientX, jointOrientY, jointOrientZ ) ) joint_paX=cmds.getAttr(ikJointName+".preferredAngleX") joint_paY=cmds.getAttr(ikJointName+".preferredAngleY") joint_paZ=cmds.getAttr(ikJointName+".preferredAngleZ") jointPreferredAngles.append((joint_paX,joint_paY,joint_paZ)) jointOrientations=(jointOrientationValues, None) hookObject=self.findHookObjectForLock() rootTransform=False moduleInfo=(jointPositions, jointOrientations, jointRotationOrders, jointPreferredAngles, hookObject, rootTransform) return moduleInfo
def renameReference(reference, name): cmds.file(reference, edit=True, namespace=name) refNode = cmds.file(reference, query=True, referenceNode=True) cmds.lockNode(refNode, lock=False) result = cmds.rename(refNode, name + 'RN') cmds.lockNode(result, lock=True) return result
def match(self, *args): # Unlock all the containers characterContainer = self.characterNamespaceOnly + ":character_container" blueprintContainer = self.blueprintNamespace + ":module_container" moduleContainer = self.blueprintNamespace + ":" + self.moduleNamespace +":module_container" containers = [characterContainer, blueprintContainer, moduleContainer] for c in containers: cmds.lockNode(c, lock=False, lockUnpublished=False) joints = utils.findJointChain(self.blueprintNamespace+":"+self.moduleNamespace+":joints_grp") blueprintJoints = utils.findJointChain(self.blueprintNamespace+":blueprint_joints_grp") ikHandleControl = self.blueprintNamespace + ":" + self.moduleNamespace + ":ikHandleControl" cmds.setAttr(ikHandleControl+".stretchiness", 1) endPos = cmds.xform(blueprintJoints[ len(blueprintJoints)-1], q=True, ws=True, t=True) cmds.xform(ikHandleControl, ws=True, a=True, t=endPos) joints.pop(0) blueprintJoints.pop(0) utils.matchTwistAngle(ikHandleControl+".twist", joints, blueprintJoints) for c in containers: cmds.lockNode(c, lock=True, lockUnpublished=True)
def clean_nodes_console(): remove_namespace("*:*AVATAR") for node in BAKE_KW["UNLOCK_NODES"]: if cmds.objExists(node): cmds.lockNode(node, lock=False) cmds.delete(node)
def clean_up_scene (self, *args): delete_names = ['ikSystem', 'Turtle', 'xgen', 'xgm'] delete_types = ['mentalray', 'container'] delete_list = [] all_nodes = cmds.ls() # Append all the nodes that specified in deletion_names for node in all_nodes: for node_name in delete_names: if node.startswith(node_name): delete_list.append(node) for node_type in delete_types: if cmds.nodeType(node).startswith(node_type): delete_list.append(node) for node in delete_list: print node do_delete = cmds.confirmDialog( title='Confirm Deletion', message='Do you want to delete nodes listed in the console?', button=['Yes','No'], defaultButton='Yes', cancelButton='No', dismissString='No' ) if do_delete == 'Yes': # Delete node tha in delete_list for node in delete_list: try: cmds.lockNode(node, lock=False) cmds.delete(node) print node, 'Deleted' except: print node, 'Can not be deleted' pass else: print 'Operation canceled.'
def cleanCacheNodes(): historySwitches = cmds.ls(type='historySwitch') for switch in historySwitches: his = cmds.listHistory(switch) for h in his: if cmds.objExists(h): if cmds.nodeType(h) != 'time': cmds.delete(h) OpenMaya.MGlobal.displayInfo('== %s has been deleted ==' % h) # begin the dumbest f*****g hack ever # maya will delete any sets that connected to the orig node. The connection # only becomes visible when the Relationship Editor is open. Locking the nodes # prevents their deletion sets = cmds.ls(type='objectSet') for s in sets: # lock-em up...dumb as shitty way of doing things cmds.lockNode(s, l=True) nodes = cmds.ls(type='mesh') for node in nodes: if cmds.getAttr(node + '.intermediateObject'): cmds.delete(node) OpenMaya.MGlobal.displayInfo('== %s has been deleted ==' % node) # end the dumbest f*****g hack ever for s in sets: # unlock the nodes cmds.lockNode(s, l=False)
def removeAllNodeInNamespace( ns='' ) : # Remove every nodes that belong to the given namespace. # Input : namespace # Output : Nonde nodes = mc.ls( '%s:*' % ns ) mc.namespace( set=':' ) if nodes : # If current namespace contains nodes, # delete them. for node in nodes : if mc.objExists( node ) : lockState = mc.lockNode( node , q=True )[0] if lockState : mc.lockNode( node , l=False ) try : newName = mc.rename( node , node.split( ':' )[-1] ) print '%s has been renamed to %s' % ( node , newName ) except : pass mc.lockNode( newName , l=lockState )
def setSgxmlAttr(attrName, selection=None, value=None, attrType='bool'): if selection is None: selection = cmds.ls(selection=True) if selection is not None: for curItem in selection: # create the attribute if it doesn't already exist if not cmds.listAttr(curItem, st=[attrName]): if not cmds.referenceQuery(curItem, isNodeReferenced=True): cmds.lockNode(curItem, lock=False) if attrType is 'bool': cmds.addAttr(curItem, ln=attrName, at='bool') elif attrType == 'float': cmds.addAttr(curItem, ln=attrName, at='double') cmds.setAttr(curItem + "." + attrName, keyable=True) elif attrType == 'string': cmds.addAttr(curItem, ln=attrName, dt='string') else: raise ValueError, 'unsupported attrType' # set the value of the attribute if value is not None: if attrType is None or attrType == 'float' or attrType == 'bool': cmds.setAttr(curItem + "." + attrName, value) elif attrType == 'string': cmds.setAttr(curItem + "." + attrName, value, type='string') else: raise ValueError, 'unsupported attrType'
def rehook(self, new_hook_obj): old_hook_obj = self.find_hook_obj() self.hook_obj =self.module_namespace+":unhookedTarget" if new_hook_obj != None: if new_hook_obj.find("_translation_control") != -1: split_string = new_hook_obj.split("_translation_control") if split_string[1] == "": if utils.strip_leading_namespace(new_hook_obj)[0] != self.module_namespace: self.hook_obj = new_hook_obj if self.hook_obj == old_hook_obj: return self.unconstrain_root_from_hook() cmds.lockNode(self.container_name, lock=False, lockUnpublished=False) hook_constraint = self.module_namespace+":hook_pointConstraint" cmds.connectAttr(self.hook_obj+".parentMatrix[0]", hook_constraint+".target[0].targetParentMatrix", force=True) cmds.connectAttr(self.hook_obj+".translate", hook_constraint+".target[0].targetTranslate", force=True) cmds.connectAttr(self.hook_obj+".rotatePivot", hook_constraint+".target[0].targetRotatePivot", force=True) cmds.connectAttr(self.hook_obj+".rotatePivotTranslate", hook_constraint+".target[0].targetRotateTranslate", force=True) cmds.lockNode(self.container_name, lock=True, lockUnpublished=True)
def lock_phase3(self, hook_obj): module_container = self.module_namespace+":module_container" if hook_obj != None: hook_obj_module_node = utils.strip_leading_namespace(hook_obj) hook_obj_module = hook_obj_module_node[0] hook_obj_joint = hook_obj_module_node[1].split("_translation_control")[0] hook_obj = hook_obj_module+":blueprint_"+hook_obj_joint parent_con = cmds.parentConstraint( hook_obj, self.module_namespace+":HOOK_IN", maintainOffset=True, name=self.module_namespace+":hook_parent_constraint" )[0] scale_con = cmds.scaleConstraint( hook_obj, self.module_namespace+":HOOK_IN", maintainOffset=True, name=self.module_namespace+":hook_scale_constraint" )[0] module_container = self.module_namespace+":module_container" utils.add_node_to_container(module_container, [parent_con, scale_con]) cmds.lockNode(module_container, lock=True, lockUnpublished=True)
def rename_module_instance(self, new_name): if new_name == self.user_specified_name: return True if utils.does_blueprint_user_specified_name_exist(new_name): cmds.confirmDialog( title="Name Confilct", message="Name \""+new_name+"\" already exists, aborting rename", button=["Accept"], defaultButton="Accept" ) return False else: new_namespace = self.module_name+"__"+new_name cmds.lockNode(self.container_name, lock=False, lockUnpublished=False) cmds.namespace(setNamespace=":") cmds.namespace(add=new_namespace) cmds.namespace(setNamespace=":") cmds.namespace(moveNamespace=[self.module_namespace, new_namespace]) cmds.namespace(removeNamespace=self.module_namespace) self.module_namespace = new_namespace self.container_name = self.module_namespace+"::module_container" cmds.lockNode(self.container_name, lock=True, lockUnpublished=True) return True
def exportSetup(self): altCharacterName = cmds.textField(self.UIElements['nameTxt'], q=True, tx=True) if altCharacterName == self.characterName: exportPath =(self.dirExt.paths['setupPath'] + self.characterName + '.ma') else: exportPath =(self.dirExt.paths['setupPath'] + altCharacterName + '.ma') # Remove the setup_grp and geometry group from it's container. cmds.lockNode(self.exportContainer, l=False, lu=False) self.removeConstraints() cmds.select(cl=True) cmds.select(self.exportContainer) self.dirExt.verifyDirectory(self.dirExt.paths['setupPath']) if cmds.file(exportPath, q=True, exists=True): turbineUtils.archiveFile(exportPath) cmds.file(exportPath, exportSelected=True, con=True, type="mayaAscii", f=True) wipPath = self.exportWip() try: cmds.file(wipPath, open=True, f=True) except:pass cmds.lockNode(self.exportContainer, l=True, lu=True)
def renameAllNodeInNamespace( ns='' ) : # Remove every nodes that belong to the given namespace. # Input : Namespace # Output : Empty namespace nodes = mc.ls( '%s:*' % ns , l=True ) mc.namespace( set=':' ) if nodes : # If current namespace contains nodes, # delete them. for node in nodes : if mc.objExists( node ) : lockState = mc.lockNode( node , q=True )[0] if lockState : mc.lockNode( node , l=False ) newName = addElementToName( node.split( ':' )[-1] , ns ) print newName try : mc.rename( node , newName ) except : pass
def _fix(self, bookmark): """ :param str bookmark: """ # connected data hyperPositionStored = {} hyperPosition = "{0}.hyperPosition".format(bookmark) try: # get connections with lock state if cmds.objExists(hyperPosition): connections = cmds.listConnections(hyperPosition) or [] connections = list(set(connections)) for connection in connections: state = cmds.lockNode(connection, query=True, lock=True)[0] cmds.lockNode(connection, lock=True) hyperPositionStored[connection] = state # delete bookmark cmds.delete(bookmark) except: pass finally: # reset connections locked state for node, state in hyperPositionStored.iteritems(): cmds.lockNode(node, lock=state)
def match(self, *args): characterContainer = self.characterNamespaceOnly + ':character_container' blueprintContainer = self.blueprintNamespace + ':module_container' moduleContainer = self.blueprintNamespace + ':' + self.moduleNamespace + ':module_container' containers = [characterContainer, blueprintContainer, moduleContainer] for c in containers: cmds.lockNode(c, lock=False, lockUnpublished=False) joints = utils.findJointChain(self.blueprintNamespace+':' + self.moduleNamespace+':joints_grp') blueprintJoints = utils.findJointChain(self.blueprintNamespace+':blueprint_joints_grp') ikHandleControl = self.blueprintNamespace + ':' + self.moduleNamespace + ':ikHandleControl' cmds.setAttr(ikHandleControl + '.stretchiness',1) endPos = cmds.xform(blueprintJoints[len(blueprintJoints)-1], q=1, worldSpace=True, translation=True) cmds.xform(ikHandleControl, worldSpace=True, absolute=True, translation=endPos) joints.pop(0) blueprintJoints.pop(0) utils.matchTwistAngle(ikHandleControl + '.twist', joints, blueprintJoints) for c in containers: cmds.lockNode(c, lock=True, lockUnpublished=True)
def unlocked(nodes): # Get node state by Maya's uuid nodes = cmds.ls(nodes, long=True) uuids = cmds.ls(nodes, uuid=True) states = cmds.lockNode(nodes, query=True, lock=True) states = {uuid: state for uuid, state in zip(uuids, states)} originals = {uuid: node for uuid, node in zip(uuids, nodes)} try: cmds.lockNode(nodes, lock=False) yield finally: # Reapply original states for uuid, state in states.iteritems(): nodes_from_id = cmds.ls(uuid, long=True) if nodes_from_id: node = nodes_from_id[0] else: log.debug("Falling back to node name: %s", node) node = originals[uuid] if not cmds.objExists(node): log.warning("Unable to find: %s", node) continue cmds.lockNode(node, lock=state)
def __init__(self): character = self.findSelectedCharacter() if character == None: return niceName = character.partition('__')[2] result = cmds.confirmDialog(title='Delete Character',message='Are you sure you want to delete the character \'' + niceName + '\'?\nCharacter deletion cannot be undone.',button=['Yes','Cancel'],defaultButton='Yes',cancelButton='Cancel',dismissString='Cancel') if result == 'Cancel': return characterContainer = character + ':character_container' cmds.lockNode(characterContainer, lock=False, lockUnpublished=False) cmds.delete(characterContainer) cmds.namespace(setNamespace=character) blueprintNamespaces = cmds.namespaceInfo(listOnlyNamespaces=True) for blueprintNamespace in blueprintNamespaces: cmds.namespace(setNamespace=':') cmds.namespace(setNamespace=blueprintNamespace) moduleNamespaces = cmds.namespaceInfo(listOnlyNamespaces=True) cmds.namespace(setNamespace=':') if moduleNamespaces != None: for moduleNamespace in moduleNamespaces: cmds.namespace(removeNamespace=moduleNamespace) cmds.namespace(removeNamespace=blueprintNamespace) cmds.namespace(removeNamespace=character)
def _deleteTurtleNodes(*args): pluginName = 'Turtle' dn = cmds.pluginInfo(pluginName,q=True,dn=True) turtleNodes = cmds.ls(type=dn) cmds.lockNode(turtleNodes,l=False) cmds.delete(turtleNodes) return 0
def runFix(self): # counts the number of unknown nodes that get deleted deletedNodes = 0 # try the fix try: # for all the unknown nodes, unlock and delete them for node in self.unknownNodes: cmds.lockNode(node, lock=False) cmds.delete(node) deletedNodes += 1 # determine if there "was an unknown node" or "were unknown nodes" if deletedNodes > 1: pluralOrSingular = "nodes" else: pluralOrSingular = "node" # return the result return str( deletedNodes) + " unknown " + pluralOrSingular + " deleted." # if the fix doesn't work, return an error message except: return "There was a problem deleteing the unknown nodes."
def lock(self, state): """Locks or unlocks the metanode :param state: True to lock the node else False :type state: bool """ cmds.lockNode(self.fullPathName(), lock=state)
def clear_ref_nodes(): referencedNodes = cmds.ls(type='reference') for node in referencedNodes: cmds.lockNode(node, lock=False) cmds.delete(node) print 'Deleted: %s' % node return
def match(self, *args): characterContainer = self.characterNamespaceOnly + ":character_container" blueprintContainer = self.blueprintNamespace + ":module_container" moduleContainer = self.blueprintNamespace + ":" + self.moduleNamespace +":module_container" containers = [characterContainer, blueprintContainer, moduleContainer] for c in containers: cmds.lockNode(c, lock=False, lockUnpublished=False) ikJointsAll = utils.findJointChain(self.blueprintNamespace + ":" + self.moduleNamespace + ":joints_grp") blueprintJointsAll = utils.findJointChain(self.blueprintNamespace + ":blueprint_joints_grp") ikJoints = [ikJointsAll[1], ikJointsAll[2], ikJointsAll[3]] blueprintJoints = [blueprintJointsAll[1], blueprintJointsAll[2], blueprintJointsAll[3]] ikHandleControl = self.blueprintNamespace + ":" + self.moduleNamespace + ":ikHandleControl" if cmds.objExists(ikHandleControl): cmds.setAttr(ikHandleControl+".stretchiness", 1) endPos = cmds.xform(blueprintJoints[2], q=True, worldSpace=True, translation=True) cmds.xform(ikHandleControl, worldSpace=True, absolute=True, translation=endPos) twistControl = self.blueprintNamespace + ":" + self.moduleNamespace + ":twistControl" utils.matchTwistAngle(twistControl+".rotateZ", ikJoints, blueprintJoints) for c in containers: cmds.lockNode(c, lock=True, lockUnpublished=True)
def deleteIt(self): coral.Node.deleteIt(self) if self._mayaNode: cmds.lockNode(self._mayaNode, lock=False) cmds.delete(self._mayaNode) self._mayaNode = ""
def killNode(self,type='unknown',xform=1,force=1,*args): """ blow up a type of node. if xform is on, search for xforms and kill that too. """ deathCount = [] for node in cmds.ls(type=type): if xform==1: death = cmds.listRelatives(node,p=1) if force==1: cmds.lockNode(death,lock=0) try: deathCount.extend(death) cmds.delete(death) except TypeError: # there isn't actually an xform here, so delete the original node. deathCount.append(node) cmds.delete(node) else: if force==1: cmds.lockNode(node,lock=0) deathCount.append(node) cmds.delete(node) # some nodes can't be deleted. let's try not to return bullshit values. try: deathCount.remove('persp') deathCount.remove('top') deathCount.remove('front') deathCount.remove('side') except: pass return deathCount
def main(log=None): if not log: import logging log = logging.getLogger() # use ' ' as a fill char and center aligned log.debug('{0:-<40}'.format('delete_unknow_node')) allUnknow = cmds.ls(dep=True) if allUnknow: for n in allUnknow: try: node_type = cmds.nodeType(n) # TODO: No object matches name: rmanFinalGlobals # so use try and except to catch this except: pass else: if( node_type == 'unknown' ): try: cmds.lockNode(n, l=False) cmds.delete(n) except: log.error('can not delete%s' % n) log.error(traceback.format_exc()) else: log.warning('delete %s success' % n)
def __init__(self, name, parent): coral.Node.__init__(self, name, parent) self.setClassName("MayaContext") self._mayaNode = "" if self.className() in parent.classNames(): self._setIsInvalid( True, self.className() + " can only be created under the root!") return associateCoralNetworkNode = coralMayaApp.FiberMayaAppData._associateCoralNetworkNode if associateCoralNetworkNode: # this var is set from coralMayaApp self._mayaNode = str(associateCoralNetworkNode) else: self._mayaNode = str( cmds.createNode("coralNetworkNode", name="coralNetworkNode")) cmds.lockNode(self._mayaNode, lock=True) cmds.setAttr(self._mayaNode + ".coralNodeId", self.id()) cmds.scriptJob(nodeNameChanged=[ self._mayaNode, NodeChangedNameCallback(self._mayaNode, self._mayaNodeChangedName) ])
def removeTFNodeformTFGrp(objects): '''{'del_path':'TfCtrl/Remove/removeTFNodeformTFGrp(cmds.ls(sl=True,exactType="transform", l=True))', 'usage':'\ Delete attributes and follicle Node ect.\\n\ Put these objects to newPapa\\n\ $fun( cmds.ls(sl=True,exactType="transfororm", l=True) )', } ''' if isinstance(objects, (str, unicode)): objects = [objects] cmds.lockNode(objects, l=False) for tfNode in objects: tSource = cmds.connectionInfo(tfNode + '.t', sfd=True) if tSource: cmds.disconnectAttr(tSource, tfNode + '.t') rSource = cmds.connectionInfo(tfNode + '.r', sfd=True) if rSource: cmds.disconnectAttr(rSource, tfNode + '.r') if cmds.attributeQuery('follicleNodeState', n=tfNode, exists=True): folObj = cmds.listConnections(tfNode + '.follicleNodeState') if folObj: cmds.delete(folObj) delAttr(objects, [ 'pBNode', 'follicleNodeState', 'atU', 'atV', 'pBNode1', 'pBWeight', 'pBInT2', 'pBInR2' ]) if not cmds.objExists('newPapa'): cmds.group(n='newPapa', em=True) cmds.parent(objects, 'newPapa')
def createNode(*args): node = cmds.createNode('network', name='sceneNote0') cmds.addAttr(node, ln='type', dt='string') cmds.setAttr('{}.type'.format(node), 'note', type='string', lock=True) cmds.addAttr(node, ln='notes', dt='string') cmds.lockNode(node, lock=True) return node
def nuke(): ilrNodeTypes = [ u"ilrAshikhminShader", u"ilrBakeLayer", u"ilrBakeLayerManager", u"ilrBasicPhotonShader", u"ilrBssrdfShader", u"ilrDielectricPhotonShader", u"ilrDielectricShader", u"ilrHwBakeVisualizer", u"ilrLuaNode", u"ilrNormalMap", u"ilrOccData", u"ilrOccSampler", u"ilrOptionsNode", u"ilrOrenNayarShader", u"ilrOutputShaderBackendNode", u"ilrPhysicPhotonShader", u"ilrPointCloudShape", u"ilrPolyColorPerVertex", u"ilrRaySampler", u"ilrShadowMask", u"ilrSurfaceThickness", u"ilrUIOptionsNode", u"ilrUVMappingVisualizer", ] nodes = mc.ls(type=ilrNodeTypes) if nodes: mc.lockNode(nodes, l=False) mc.delete(nodes) mc.flushUndo() mc.unloadPlugin("Turtle.mll") else: mc.warning("No Turtle nodes found.")
def _check(s): if not cmds.objExists(s.node): sel = cmds.ls(sl=True) cmds.group(n=s.node, em=True) cmds.select(sel, r=True) if not cmds.attributeQuery("notes", n=s.node, ex=True): cmds.addAttr(s.node, ln="notes", sn="nts", dt="string", s=True) cmds.lockNode(s.node)
def unlockHierarchy(list): print "Unlocking Hierarchy ----------------------------" for item in list: cmds.select(item, hi=True) relatives = cmds.ls(sl=True, long=True) for child in relatives: cmds.lockNode(child, l=0)
def lock_phase1(self): # GAther and return all required information from this modules control objects. # Joint Positions = list of joint positions from the root down the hierarchy # Joint orientations = a list of orientations, or a list of axis information ( orient joint and secondaryAxisOrient from # # These are passed in the following tuple: ( orientations, None) or ( NOne, axis info) # JointRotationOrders = a list of joint rotation orders ( integer values gathered with getAttr) # jointPreferred Angles = a list of joint preferred angles, optional (can pass None) # hookObjedct = self.findHookObjectForLock() # rootTransform = a bool, either True or False. True = R, T, and S on root joint. False = R only. # # moduleInfo = (jointPositions , jointOrientations, jointRotationOrders, jointPreferredAngles, hookObject, rootTransform # Return moduleInfo jointPositions = [] jointOrientationValues = [] jointRotationOrders =[] jointPreferredAngles = [] # Unlock container and delete ik handle. cmds.lockNode(self.containerName, lock=False, lockUnpublished=False) ikHandle = self.moduleNamespace+":IK_"+self.jointInfo[0][0]+"_ikHandle" cmds.delete(ikHandle) # Freeze transforms on the joints before lock for i in range(3): jointName = self.jointInfo[i][0] ikJointName = self.moduleNamespace+":IK_"+jointName cmds.makeIdentity(ikJointName, rotate=True, translate=False, scale=False, apply=True) jointPositions.append(cmds.xform(ikJointName, q=True, ws=True, t=True)) jointRotationOrders.append(cmds.getAttr(self.moduleNamespace+":"+jointName+".rotateOrder")) if i < 2: jointOrientX = cmds.getAttr(ikJointName+".jointOrientX") jointOrientY = cmds.getAttr(ikJointName+".jointOrientY") jointOrientZ = cmds.getAttr(ikJointName+".jointOrientZ") jointOrientationValues.append( (jointOrientX, jointOrientY, jointOrientZ) ) joint_paX = cmds.getAttr(ikJointName+".preferredAngleX") joint_paY = cmds.getAttr(ikJointName+".preferredAngleY") joint_paZ = cmds.getAttr(ikJointName+".preferredAngleZ") jointPreferredAngles.append( (joint_paX, joint_paY, joint_paZ) ) jointOrientations= (jointOrientationValues, None) hookObject = self.findHookObjectForLock() rootTransform = False moduleNamespace = self.moduleNamespace moduleInfo = (jointPositions, jointOrientations, jointRotationOrders, jointPreferredAngles, hookObject, rootTransform, moduleNamespace) return moduleInfo
def do(): unknownNodes = cmds.ls(type="unknown") or [] for unknownNode in unknownNodes: if not cmds.objExists(unknownNode): continue if cmds.lockNode(unknownNode, query=True, lock=True): cmds.lockNode(unknownNode, lock=False) cmds.delete(unknownNode) sys.stdout.write("Deleted %s.\n" % unknownNode)
def fix(self): """@brief rename shape """ # for i in self.errorNodes: NoFiles = self.errorNodes for a in NoFiles: cmds.lockNode(a, l = False) cmds.delete(a) self.run()
def installDuplicate(self,duplicatePath, selection, *args): cmds.file(duplicatePath, i=True, namespace='TEMPLATE_1') moduleNames = self.resolveNamespaceClashes('TEMPLATE_1') groupNames = self.resolveGroupNameClashes('TEMPLATE_1') groups = [] for name in groupNames: groups.append(name[1]) if len(groups) > 0: sceneGroupContainer = 'Group_container' cmds.lockNode(sceneGroupContainer, lock=False, lockUnpublished=False) utils.addNodeToContainer(sceneGroupContainer, groups, includeShapes=True, force=True) for group in groups: groupNiceName = group.partition('__')[2] cmds.container(sceneGroupContainer, edit=True, publishAndBind=[group+'.translate',groupNiceName+'_t']) cmds.container(sceneGroupContainer, edit=True, publishAndBind=[group+'.rotate',groupNiceName+'_r']) cmds.container(sceneGroupContainer, edit=True, publishAndBind=[group+'.globalScale',groupNiceName+'_globalScale']) cmds.lockNode(sceneGroupContainer, lock=True, lockUnpublished=True) cmds.namespace(setNamespace=':') cmds.namespace(moveNamespace=('TEMPLATE_1',':'),force=True) cmds.namespace(removeNamespace='TEMPLATE_1') newSelection = [] for node in selection: found = False for group in groupNames: oldName = group[0].partition('TEMPLATE_1:')[2] newName = group[1] if node == oldName: newSelection.append(newName) found = True break if not found: nodeNamespaceInfo = utils.stripLeadingNamespace(node) if nodeNamespaceInfo != None: nodeNamespace = nodeNamespaceInfo[0] nodeName = nodeNamespaceInfo[1] searchName = 'TEMPLATE_1:' + nodeNamespace for module in moduleNames: if module[0] == searchName: newSelection.append(module[1] + ':' + nodeName) if len(newSelection) > 0: cmds.select(newSelection, replace=True)
def install_init(self): cmds.namespace(setNamespace=self.blueprintNamespace) cmds.namespace(add=self.moduleNamespace) cmds.namespace(setNamespace=":") characterContainer = self.characterNamespaceOnly+":character_container" blueprintContainer = self.blueprintNamespace+":module_container" containers = [characterContainer, blueprintContainer] for c in containers: cmds.lockNode(c, lock=False, lockUnpublished=False) # Duplicate creation pose joints to create new instance. Stored in external method. self.joints = self.duplicateAndRenameCreationPose() moduleJointsGrp = self.joints[0] # Group everything for animation module and parent to "Hook_IN_Grp" moduleGrp = cmds.group(empty=True, name=self.blueprintNamespace+":"+self.moduleNamespace+":module_grp") hookIn = self.blueprintNamespace+":HOOK_IN" cmds.parent(moduleGrp, hookIn, relative=True) cmds.parent(moduleJointsGrp, moduleGrp, absolute=True) # Attr to define icon size. cmds.select(moduleGrp) cmds.addAttr(at="float", ln="iconScale", min=0.001, softMaxValue=10.0, defaultValue=1, k=True) cmds.setAttr(moduleGrp+".overrideEnabled", 1) cmds.setAttr(moduleGrp+".overrideColor", 6) utilityNodes = self.setupBlueprintWeightBasedBlending() self.setupModuleVisibility(moduleGrp) containedNodes = list(self.joints) containedNodes.append(moduleGrp) containedNodes.extend(utilityNodes) self.moduleContainer = cmds.container(n=self.moduleContainer) utils.addNodeToContainer(self.moduleContainer, containedNodes, ihb=True) utils.addNodeToContainer(blueprintContainer, self.moduleContainer) #151 index = 0 publishToOuterContainers=False for joint in self.joints: if index > 0: niceJointName = utils.stripAllNamespaces(joint)[1] self.publishNameToModuleContainer(joint+".rotate", niceJointName+"_R", publishToOuterContainers=False) publishToOuterContainers=False index += 1 self.publishNameToModuleContainer(moduleGrp+".lod", "Control_LOD") self.publishNameToModuleContainer(moduleGrp+".iconScale", "Icon_Scale") self.publishNameToModuleContainer(moduleGrp+".overrideColor", "Icon_Color") self.publishNameToModuleContainer(moduleGrp+".visibility", "Vis") self.publishNameToModuleContainer(moduleGrp+".visibility", "Vis", publishToOuterContainers=False) return (self.joints, moduleGrp, self.moduleContainer)