コード例 #1
0
    def load_rig_settings(self, currentDirectory, customName):
        animModAttrSettings = []
        endFrame = []
        
        fileName = (currentDirectory + customName + "_rigSettings.csv")

        if cmds.file(fileName, q=True, exists=True):
            animModAttr = self.readAnimAttrs(fileName)
            """ Add the character name to the attribute """
            
            for each in animModAttr:

                if each[0] != 'endFrame':
                    attribute = (self.characterInfo['characterName'] + each[0])
                    animModAttrSettings.append([attribute, each[1]])              
                else:          
                    animModAttrSettings.append([each[0], each[1]])
            
            missingControls = self.missingControls(animModAttrSettings)
            #self.installAnimModFromCsv(missingControls)

            self.setAttrsFromModInfo(animModAttrSettings)                
            return missingControls
        
        else:
            cmds.headsUpMessage (fileName + " Not on disk")
コード例 #2
0
    def installProc(self, characterName, *args):
        # Return the directory names from setupDirs
        projectDirs = turbineUtils.setupDirs(self.characterName, create=False)       
        setupDir = projectDirs[1]
        xmlDir = projectDirs[2]
        rigDir = projectDirs[3]
        characterFileName = projectDirs[5]   
        setupFileName = projectDirs[6]        
        xmlFileName = projectDirs[7]
        meshDir = projectDirs[8]
        characterName = self.characterName
      
        """ use turbineUtils to find out the namespaces. """
        namespaces = turbineUtils.getCharacterNamespace(self.characterName)    
        characterNamespace = namespaces[0]        
        characterNameString = (characterNamespace + ":")
       
        """ Import the rig """
        # Return the directory names from setupDirs
        projectDirs = turbineUtils.setupDirs(self.characterName, create=False) 
        characterFileName = projectDirs[5]

        if cmds.namespace(exists=characterNamespace):
            print "Rig Installed"
        else:
            cmds.file(characterFileName, i=True, namespace=characterNamespace)
            cmds.namespace(set=characterNamespace)   
            
        cmds.namespace(setNamespace=":")  

        """ Unlock the character container """
        characterContainer = (characterNamespace + ":character_container")
        cmds.lockNode(characterContainer, lock=False, lockUnpublished=False)
        
        setupContainer = self.setupGameJoints(characterName, namespaces)

        """ Import the mesh if it exists """
        self.setupMesh(characterName, setupContainer)
        
        
        """ Lock the containers """
        cmds.lockNode(characterContainer, lock=True, lockUnpublished=True)
        cmds.lockNode(setupContainer, lock=True, lockUnpublished=True)
        
        """ Set namespace back to default """
        cmds.namespace(set=":")

        cmds.deleteUI(self.UIElements["window"])
        
                    
        """ Create all the necessary character directories if they do not exist """  
        import System.directoryExtension as directoryExtension
        dirExt = directoryExtension.DirectoryExtension()  
        dirExt.createAllDirs()
        dirExt.createBakDirs()
        
        """ Get the user name and inform of operation completion """       
        currentUser = getUser()        
        niceName = (currentUser)[1]
        cmds.headsUpMessage(self.characterName+ " has been installed " + niceName)
コード例 #3
0
ファイル: skinning.py プロジェクト: griffinanimator/MPR
    def processInitialSelection(self):
        selection = cmds.ls(selection=True)
        
        setupContents = []
        
        geometry = self.findGeometry(selection)
        
        characterContainer = turbineUtils.getCharacterInfo()[1]
        characterName = turbineUtils.getCharacterInfo()[0]
        # exportName will define the name of the export node and can also be used 
        # for the namespace the export node resides in
        
        setupNode = turbineUtils.getCharacterInfo()[3]

        # Use the joint class to identify the joints in the scene
        import System.jointUtils as jntUtils
        
        joint = jntUtils.gameJoint_Utils()
        gameJoints = joint.getGameJoints()
        
        geoNode = ("Geometry")
        
        if geometry == None:
            cmds.headsUpMessage("please select the geometry you wish to attach to the specified blueprint joint.")
        else:      
            self.doSkin(geometry, gameJoints, geoNode, setupNode) 
       
        return (geometry, characterContainer, characterName, gameJoints, geoNode, setupNode)
コード例 #4
0
ファイル: gameJointData.py プロジェクト: griffinanimator/MPR
    def storeJointVars(self, gameJointNames, parentJointNames, jointPositionX, jointPositionY, jointPositionZ, jointRotateOrder, blueprintJointNames, jointOrientX, jointOrientY, jointOrientZ, containerName):  
        # Define the file name and path        
        userName = userUtils.getUser()[0]
        outFileSuffix = '_gameJntInfo.csv'
        outFile = (userName + outFileSuffix )
        

        """ Define the artPath """
        import System.directoryExtension as directoryExtension
        dirExt = directoryExtension.DirectoryExtension()
        artPath = dirExt.artPath
            
        filePath = artPath + "/character/GEPPETTO/Data/" 
        
        finalPath = (filePath  + outFile)
             
        for index in range(len(gameJointNames)):
            int = str(index)

            value = (gameJointNames[index], parentJointNames[index], jointPositionX[index], jointPositionY[index], jointPositionZ[index], jointRotateOrder[index], blueprintJointNames[index], jointOrientX[index], jointOrientY[index], jointOrientZ[index])  
        
            writer = csv.writer(open(finalPath, "a"))                
            writer.writerow(value)

        """ I need to make sure the file closes here """            
        # Close the file
        #file.close(finalPath)
        
        cmds.headsUpMessage("The temp data file has been saved to " + finalPath)       
コード例 #5
0
def mtt_log(msg, add_tag=None, msg_type=None, verbose=True):
    """ Format output message '[TAG][add_tag] Message content'

    :param msg: (string) message content
    :param add_tag: (string or list) add extra tag to output
    :param msg_type: define message type. Accept : None, 'warning', 'error'
    :param verbose: (bool) enable headsUpMessage output
    """
    # define tags
    tag_str = '[MTT]'

    # append custom tags
    if add_tag:
        if not isinstance(add_tag, list):
            add_tag = [add_tag]

        for tag in add_tag:
            tag_str += '[%s]' % tag.upper()

    # output message the right way
    if msg_type == 'warning':
        cmds.warning('%s %s' % (tag_str, msg))
    elif msg_type == 'error':
        cmds.error('%s %s' % (tag_str, msg))
    else:
        print '%s %s\n' % (tag_str, msg),

    if verbose and MTTSettings.value('showHeadsUp'):
        cmds.headsUpMessage(msg)
コード例 #6
0
 def importAnim(self, *args):
     characterNamespace = self.animMods.characterInfo['characterName']
     print "charNameSpace"
     print characterNamespace
     
     animName = cmds.textScrollList(self.animLibUIElements["animationList"], q=True, si=True)[0]
     animMaName = (animName + ".ma")
     finalPath = (self.animDir + animMaName)
     
     animFile = cmds.file(finalPath, i=True, dns=True)
     
     """ Connect the animation curves to the controls """
     self.animLib.animConnectCurves(characterNamespace)
     
     """ Load the settings """
     loadSettings = self.animMods.load_rig_settings(animName)
     
     if loadSettings == None:
         cmds.headsUpMessage(animName+ " has been loaded")
         print (animName+ " has been loaded")
     else:
         print "---------Missing animation modules----------"
         for setting in loadSettings:
             print setting
         cmds.headsUpMessage(animName+ " has been loaded with --ERROR. /n Open the script editor for details")
コード例 #7
0
	def selectBlueprintJoint_callback(self):
		selection = cmds.ls(selection=True)
		self.blueprintJoints = self.findBlueprintJoints(selection)
		if self.blueprintJoints == None:
			cmds.confirmDialog(title='Attach Geometry to blueprint', message='Blueprint joint selection invalid, terminating tool.', button=['Accept'],defaultButton='Accept')
		elif self.geometry == None:
			cmds.headsUpMessage('Please  select the Geometry you wish to attach to the specified blueprint joint(s).')
			cmds.scriptJob(event=['SelectionChanged',self.selectGeometry_callback], runOnce=True)
		else:
			self.attachGeoToBlueprint_attachment()
コード例 #8
0
ファイル: JR_tool_class.py プロジェクト: jricker/JR_Maya
	def flattenVertex(self):
		mousePos = cmds.autoPlace(um=True)
		sl = cmds.ls(selection=True, flatten=True)
		######################################################################################################## 
		x = []
		y = []
		z = []
		######################################################################################################## 
		for i in sl:
		    location = cmds.xform(i, query=True, translation=True, worldSpace=True)
		    x.append(location[0])
		    y.append(location[1])
		    z.append(location[2])
		avgX = sum(x)/len(x)
		avgY = sum(y)/len(y)
		avgZ = sum(z)/len(z)
		xyzPos = [avgX,avgY,avgZ]
		message = ['X', 'Y', 'Z']
		largestValue = mousePos[0] - xyzPos[0]
		positionToUse = 0
		for i in range(len(mousePos)):
		    if mousePos[i] == 0:
		        pass
		    else:
		        temp = abs(mousePos[i]) - abs(xyzPos[0])
		        if temp > largestValue:
		            largestValue = temp
		            positionToUse = i
		if mousePos[positionToUse] - xyzPos[positionToUse] > 0:
		    direction = '+'
		elif  mousePos[positionToUse] - xyzPos[positionToUse] < 0:
		    direction = '-'
		######################################################################################################## 
		if direction == '+':
		    if positionToUse == 0:
		        for i in range(len(sl)):
		            cmds.xform(sl[i], translation=[max(x), y[i], z[i]], worldSpace=True)
		    if positionToUse == 1:
		        for i in range(len(sl)):
		            cmds.xform(sl[i], translation=[x[i], max(y), z[i]], worldSpace=True)
		    if positionToUse == 2:
		        for i in range(len(sl)):
		            cmds.xform(sl[i], translation=[x[i], y[i], max(z)], worldSpace=True)
		if direction == '-':
		    if positionToUse == 0:
		        for i in range(len(sl)):
		            cmds.xform(sl[i], translation=[min(x), y[i], z[i]], worldSpace=True)
		    if positionToUse == 1:
		        for i in range(len(sl)):
		            cmds.xform(sl[i], translation=[x[i], min(y), z[i]], worldSpace=True)
		    if positionToUse == 2:
		        for i in range(len(sl)):
		            cmds.xform(sl[i], translation=[x[i], y[i], min(z)], worldSpace=True)
		######################################################################################################## 
		cmds.headsUpMessage( 'FLATTENED IN THE ' + direction +' '+ message[positionToUse], verticalOffset=100, horizontalOffset=200 )
 def Position_Fn(self):
     if self.Check_Selection():
         Base_Curve = self.MainWindow.Cam_Item_Widget.Attr["Add_Crv_LE"]
         CamGrp = self.Add_CamGrp_LE.text()
         cmds.xform( CamGrp,cp=1 )
         setAttr -keyable false -channelBox false "sc02_cam|Path.tx";
         cmds.delete(cmds.parentConstraint( Base_Curve,CamGrp ))
         cmds.headsUpMessage(u"位置匹配完成")
     else:
         cmds.warning(u"请完成镜头组的选择")
         cmds.headsUpMessage(u"请完成镜头组的选择")
コード例 #10
0
    def Add_CamGrp_Pick_Fun(self):
        if len(cmds.ls(sl=True)) > 0:
            Selection = cmds.ls(sl=True,l=1)[0] 
            # SelectionShape = cmds.listRelatives(Selection)[0]
            SelectionType = cmds.nodeType( Selection )
            if SelectionType == "transform":
                self.Add_CamGrp_LE.setText(Selection)
                self.Current_Item.Cam_LE.setText(Selection)
                self.Cam_Name_Label.setText(u"<center> - %s - </center>" % Selection)
                try :
                    self.Add_CamGrp_Get.clicked.disconnect()
                except:
                    pass
                self.Add_CamGrp_Get.clicked.connect(partial(self.Select_OBJ_Fun,Selection))

                # Note 自动获取相关的物体
                TypeList =[
                    "motionPath",
                    "nurbsCurve",
                    "locator",
                ]

                FnList = [
                    self.Add_Motion_Path_Pick_Fun,
                    self.Add_Crv_Pick_Fun,
                    self.Add_Loc_Pick_Fun,
                ]

                SelectionList = cmds.listRelatives(Selection,f=1)
                for sel in SelectionList:
                    SelectionShape = cmds.listRelatives(sel,f=1)
                    SelectionType = cmds.nodeType( SelectionShape[0] )
                    for i,Type in enumerate(TypeList):
                        if SelectionType == Type:
                            cmds.select(sel)
                            FnList[i]()
                            break

                self.Current_Item.Attr["Add_CamGrp_LE"] = self.Add_CamGrp_LE.text()
            else:
                cmds.warning(u"请选择组进行获取")
                cmds.headsUpMessage(u"请选择组进行获取")
        else :
            self.Add_CamGrp_LE.setText("")
        
        if self.Add_CamGrp_LE.text() != "":
            self.Current_Item.Attr["Add_CamGrp_LE"] = self.Add_CamGrp_LE.text()
            self.Add_CamGrp_Label.setVisible(False)
            self.Add_CamGrp_Get.setVisible(True)
        else:
            self.Add_CamGrp_Label.setVisible(True)
            self.Add_CamGrp_Get.setVisible(False)
        
        self.MainWindow.Save_Json_Fun()
コード例 #11
0
def function_to_process(data):
    """
    Maya function
    :param data: incoming data to process
    :return:
    """

    logging.info("Debug Server, Process Function: {}".format(data))
    cmds.headsUpMessage("Processing incoming data: {}".format(data), time=3.0)

    exec(data)
コード例 #12
0
    def findCharacterNames(self, *args):
        characterNamespace = utils.findInstalledCharacters()
        if len(characterNamespace) != 0:
            characterNamespace = characterNamespace[0]
    
            characterName = (characterNamespace)
        else:
            cmds.headsUpMessage("No valid character in the scene")
            return

        return (characterNamespace, characterName)   
コード例 #13
0
    def findCharacterNames(self, *args):
        characterNamespace = utils.findInstalledCharacters()
        if len(characterNamespace) != 0:
            characterNamespace = characterNamespace[0]
    
            characterName = (characterNamespace)
        else:
            cmds.headsUpMessage("No valid character in the scene")
            return

        return (characterNamespace, characterName)   
コード例 #14
0
def SundayLocatorToolCreate(locatorType):
    objects = cmds.ls(selection = True)
    locators = []
    locatorUp = '0 0 0'
    if cmds.radioButton('LocatorDirectionXUpRadioButton', query = True, select = True):
        locatorUp = '0 0 90'
    
    if cmds.radioButton('LocatorDirectionYUpRadioButton', query = True, select = True):
        locatorUp = '0 90 0'
    
    if cmds.radioButton('LocatorDirectionZUpRadioButton', query = True, select = True):
        locatorUp = '90 0 0'
    
    if cmds.checkBox('SundayLocatorToolMakeControllerForSelectedCheckBox', query = True, value = True):
        if len(objects) != 0:
            for curObj in objects:
                mel.eval(SundayLocatorToolPy.SundayLocatorToolGetLocator(curObj + '_CTRL', locatorType, locatorUp))
                curLocator = cmds.ls(selection = True)[0]
                locators.append(curLocator)
                cmds.setAttr(curLocator + '.overrideEnabled', 1)
                cmds.setAttr(curLocator + '.overrideColor', int(cmds.iconTextRadioCollection('SundayLocatorToolColorCollection', query = True, select = True).split('_')[1]))
                cmds.select(curObj, curLocator)
                cmds.pointConstraint(name = curLocator + '_tempJOINTPointConstraint')
                cmds.orientConstraint(name = curLocator + '_tempJOINTOrientConstraint')
                cmds.delete(curLocator + '_tempJOINTPointConstraint*')
                cmds.delete(curLocator + '_tempJOINTOrientConstraint*')
            
        else:
            SundayDialogPy.SundayDialogConfirm('Error                                        ', 'No objects selected', 'OK')
            return None
        (len(objects) != 0).select(locators)
        cmds.headsUpMessage('Transform the locator(s) as you like and deselect to make it an controller')
        cmds.scriptJob(event = [
            'SelectionChanged',
            'SundayLocatorToolPy\nreload(SundayLocatorToolPy)\nSundayLocatorToolPy.SundayLocatorToolMoveSelectedToLocator(' + str(locators) + ', ' + str(objects) + ')'], runOnce = True)
    elif len(objects) != 0:
        for curObj in objects:
            mel.eval(SundayLocatorToolPy.SundayLocatorToolGetLocator(curObj + '_CTRL', locatorType, locatorUp))
            curLocator = cmds.ls(selection = True)[0]
            cmds.setAttr(curLocator + '.overrideEnabled', 1)
            cmds.setAttr(curLocator + '.overrideColor', int(cmds.iconTextRadioCollection('SundayLocatorToolColorCollection', query = True, select = True).split('_')[1]))
            locators.append(curLocator)
            cmds.select(curObj, curLocator)
            cmds.pointConstraint(name = curLocator + '_tempJOINTPointConstraint')
            cmds.orientConstraint(name = curLocator + '_tempJOINTOrientConstraint')
            cmds.delete(curLocator + '_tempJOINTPointConstraint*')
            cmds.delete(curLocator + '_tempJOINTOrientConstraint*')
            cmds.select(locators)
        
    else:
        mel.eval(SundayLocatorToolPy.SundayLocatorToolGetLocator('SundayLocator', locatorType, locatorUp))
        curLocator = cmds.ls(selection = True)[0]
        cmds.setAttr(curLocator + '.overrideEnabled', 1)
        cmds.setAttr(curLocator + '.overrideColor', int(cmds.iconTextRadioCollection('SundayLocatorToolColorCollection', query = True, select = True).split('_')[1]))
コード例 #15
0
ファイル: animFilters.py プロジェクト: saphilli/AnimFiltersV2
 def addControllerCurve(self):
     if self.controllingCurve is not None:
         return
     curve = cmds.keyframe(q=True,name=True,sl=True)
     if len(curve)>1:
         cmds.headsUpMessage("Please select only one animation curve to control the scale of any other animation curves.")
         return
     elif curve is None:
         cmds.headsUpMessage("Please select the keys of the animation curve you want to add as a controller curve in the graph editor.")
         return
     self.controllingCurve = curve[0]
     self.MainWindowUI.controllingCurveList.addItem(curve[0])
    def Batch_Position_Fn(self):
        ChildrenList = self.Item_Layout.children()
        for i,child in enumerate(ChildrenList):
            if i != 0:
                Base_Curve = self.Attr["Add_Crv_LE"]
                CamGrp = self.Attr["Add_Crv_LE"]
                if cmds.setObjectName(Base_Curve) : 
                cmds.xform( CamGrp,cp=1 )
                cmds.delete(cmds.parentConstraint( Base_Curve,CamGrp ))
                Target_Curve = self.Add_Crv_LE.text()
                # Note 解除曲线的锁定
                cmds.setAttr("%s.tx" % Target_Curve,lock=False)
                cmds.setAttr("%s.ty" % Target_Curve,lock=False)
                cmds.setAttr("%s.tz" % Target_Curve,lock=False)
                cmds.setAttr("%s.rx" % Target_Curve,lock=False)
                cmds.setAttr("%s.ry" % Target_Curve,lock=False)
                cmds.setAttr("%s.rz" % Target_Curve,lock=False)
                cmds.delete(cmds.parentConstraint( Base_Curve,Target_Curve ))
                cmds.headsUpMessage(u"位置匹配完成")

    def Batch_Keyframe_Fn(self):
        ChildrenList = self.Item_Layout.children()
        for i,child in enumerate(ChildrenList):
            if i != 0:
                Path = child.Attr["Add_Motion_Path_LE"]
                if cmds.objExists(Path):
                    offset = cmds.keyframe(Path,q=1)[0] 
                    cmds.keyframe("%s.uValue"% Path,e=1,iub=1,r=1,o="over",tc=-offset)

    def Select_Path_Fn(self):
        cmds.select(cl=1)
        ChildrenList = self.Item_Layout.children()
        for i,child in enumerate(ChildrenList):
            if i != 0:
                if cmds.objExists(child.Attr["Add_Motion_Path_LE"]):
                    cmds.select(child.Attr["Add_Motion_Path_LE"],add=1)

        
    def Item_Add_Fn(self):
        self.Cam_Item_Num += 1
        return Cam_Item(self,self.MainWindow)
        
    def Item_Clear_Fn(self):
        self.Attr["Add_Crv_LE"] = ""
        self.Attr["Add_Motion_Path_LE"] = ""
        self.Attr["Name"] = ""
        for i,child in enumerate(self.Item_Layout.children()):
            if i != 0:
                child.deleteLater()

    def Scroll_Fn(self):
        self.Scroll_Offset = self.Cam_Item_Scroll.verticalScrollBar().value()
コード例 #17
0
 def initializeInitVars(self, *args):
     namespaces = cmds.namespaceInfo(listOnlyNamespaces=True)
     for name in namespaces:
         var = 'Character'
         result = name.startswith(var)
         if result == True:
             self.characterInfo['characterNamespace'] = self.findCharacterNames()[0]
             self.characterInfo['characterName'] = self.findCharacterNames()[1]
             self.getCurrentReferences()
             return True
         else:
             cmds.headsUpMessage("No valid character in the scene")
             return False
コード例 #18
0
ファイル: ddxml-dump.py プロジェクト: MORTAL2000/dangerdeep
 def doIt(self, argList):
     self.filename = None
     self.filenamePrompt()
     if None == self.filename:
         return
     self.output = ddxmlWriter()
     self.output.createDefaultMaterial()
     try:
         self.walk()
     except Exception, e:
         log(e.message)
         cmds.headsUpMessage("ERROR: " + str(e.message))
         raise
コード例 #19
0
	def rehookModule_setup(self, *args):
		selectedNodes = cmds.ls(selection=True, transforms=True)
		if len(selectedNodes) == 2:
			newHook = self.findHookObjectFromSelection()
			self.moduleInstance.rehook(newHook)
		else:
			self.deleteScriptJob()
			
			currentSelection = cmds.ls(selection=True)
			
			cmds.headsUpMessage("Please select the joint you wish to rehook to. Clear selection to un-hook")
			
			cmds.scriptJob(event=["SelectionChanged", partial(self.rehookModule_callback, currentSelection)], runOnce=True )
コード例 #20
0
 def doIt(self, argList):
     self.filename = None
     self.filenamePrompt()
     if None == self.filename:
         return
     self.output = ddxmlWriter()
     self.output.createDefaultMaterial()
     try:
         self.walk()
     except Exception, e:
         log(e.message)
         cmds.headsUpMessage("ERROR: " + str(e.message))
         raise
 def Keyframe_Fn(self):
     if self.Check_Selection():
         Path = self.Add_Motion_Path_LE.text()
         offset = cmds.keyframe(Path, q=1)[0]
         cmds.keyframe("%s_uValue" % Path,
                       e=1,
                       iub=1,
                       r=1,
                       o="over",
                       tc=-offset)
     else:
         cmds.warning(u"请完成镜头组的选择")
         cmds.headsUpMessage(u"请完成镜头组的选择")
コード例 #22
0
	def rehookModule_setup(self, *args):
		selectedNodes = cmds.ls(selection=True, transforms=True)
		if len(selectedNodes) == 2:
			newHook = self.findHookObjectFromSelection()
			self.moduleInstance.rehook(newHook)
		else:
			self.deleteScriptJob()
			
			currentSelection = cmds.ls(selection=True)
			
			cmds.headsUpMessage('Please select the joint you wish to re-hook to. Clear selection to un-hook')
			
			cmds.scriptJob(event=['SelectionChanged',partial(self.rehookModule_callback, currentSelection)], runOnce=True)
コード例 #23
0
def cCreateSpeedometer(*args):
    grp = 'speed_lc_grp'
    lc = '_SLC'
    decimals = cmds.intField('iDecimals', v=1, q=1)

    sceneScale = cmds.floatField('fSceneScale', v=1, q=1)
    objs = cmds.ls(sl=1, l=1)

    for obj in objs:
        if not cmds.objExists('speed_lc_grp'):
            grp = cmds.group(empty=1, n='speed_lc_grp')
            cmds.setAttr(grp + '.visibility', 0)

            cmds.addAttr(grp, ln='sceneScale', at='double', dv=0)
            cmds.setAttr(grp + '.sceneScale', e=1, k=1)
            cmds.setAttr(grp + '.sceneScale', sceneScale)

            cmds.addAttr(grp, ln='decimals', at='long', dv=1)
            cmds.setAttr(grp + '.decimals', e=1, k=1)
            cmds.setAttr(grp + '.decimals', decimals)

        if not cmds.objExists(obj + '_SLC') and len(objs) > 0:
            objShort = obj.split('|')[-1]
            if not cmds.objExists(objShort + '_SLC'):
                lc = cmds.spaceLocator(n=objShort + '_SLC', p=(0, 0, 0))

                matrix = cmds.createNode('pointMatrixMult')
                cmds.connectAttr(obj + '.parentMatrix[0]',
                                 matrix + '.inMatrix')
                cmds.connectAttr(obj + '.translate', matrix + '.inPoint')
                cmds.connectAttr(matrix + '.output', lc[0] + '.translate')

                cmds.parent(lc, grp)

                cmds.addAttr(lc, ln='kmPerHour', at='double', dv=0)
                cmds.setAttr(lc[0] + '.kmPerHour', e=1, k=1)
                cmds.addAttr(lc, ln='milesPerHour', at='double', dv=0)
                cmds.setAttr(lc[0] + '.milesPerHour', e=1, k=1)

                exString = cExString(matrix, lc, sceneScale)

                cmds.expression(n="ex" + lc[0],
                                s=exString,
                                o="",
                                ae=1,
                                uc='all')

                cmds.headsUpMessage('speedometer created!')

                cmds.select(clear=1)
                cSpeedHud(1)
コード例 #24
0
    def installProc(self, characterName, *args):
        # Return the directory names from setupDirs
        projectDirs = turbineUtils.setupDirs(self.characterName, create=False)
        setupDir = projectDirs[1]
        xmlDir = projectDirs[2]
        rigDir = projectDirs[3]
        characterFileName = projectDirs[5]
        setupFileName = projectDirs[6]
        xmlFileName = projectDirs[7]
        meshDir = projectDirs[8]
        characterName = self.characterName
        """ use turbineUtils to find out the namespaces. """
        namespaces = turbineUtils.getCharacterNamespace(self.characterName)
        characterNamespace = namespaces[0]
        characterNameString = (characterNamespace + ":")
        """ Import the rig """
        # Return the directory names from setupDirs
        projectDirs = turbineUtils.setupDirs(self.characterName, create=False)
        characterFileName = projectDirs[5]

        if cmds.namespace(exists=characterNamespace):
            print "Rig Installed"
        else:
            cmds.file(characterFileName, i=True, namespace=characterNamespace)
            cmds.namespace(set=characterNamespace)

        cmds.namespace(setNamespace=":")
        """ Unlock the character container """
        characterContainer = (characterNamespace + ":character_container")
        cmds.lockNode(characterContainer, lock=False, lockUnpublished=False)

        setupContainer = self.setupGameJoints(characterName, namespaces)
        """ Import the mesh if it exists """
        self.setupMesh(characterName, setupContainer)
        """ Lock the containers """
        cmds.lockNode(characterContainer, lock=True, lockUnpublished=True)
        cmds.lockNode(setupContainer, lock=True, lockUnpublished=True)
        """ Set namespace back to default """
        cmds.namespace(set=":")

        cmds.deleteUI(self.UIElements["window"])
        """ Create all the necessary character directories if they do not exist """
        import System.directoryExtension as directoryExtension
        dirExt = directoryExtension.DirectoryExtension()
        dirExt.createAllDirs()
        dirExt.createBakDirs()
        """ Get the user name and inform of operation completion """
        currentUser = getUser()
        niceName = (currentUser)[1]
        cmds.headsUpMessage(self.characterName + " has been installed " +
                            niceName)
コード例 #25
0
    def editBind(self, *args):

        selection = self.unBindSkin()
        if selection == None:

            return(mc.headsUpMessage("skin detached"))




        sknCluster = self.getSelectionSkinClusters(selection)

        delSkin = self.detachSkin()

        if delSkin == None:
            return(mc.headsUpMessage("Skin Detached"))

        if sknCluster != False:

            print "skin information exists"




        #query active item in drop Down
        ddVal2 = mc.optionMenu(self.UIElements['DropDownMenu2'], q=True, v=True)

        print ddVal2

        if ddVal2 == 'detach w/ Hist.':
            try:
                mc.skinCluster(edit=True, unbindKeepHistory=True)
            except:

                return (mc.headsUpMessage("Skin is Detached with History"))

        if ddVal2 == "Detach w/o Hist.":
            #unbinds joints in edit mode, can move joints without effecting skinCluster
            try:
                mc.skinCluster(edit =True, ubk= True)

            except:
                return (mc.headsUpMessage("Skin Detached Without History"))

            if ddVal2 == 'Normalize Weight':
                try:
                    mc.skinCluster(edit = True, normalizeWeights = 2)
                except:
            #Normalize in post = default
                    return (mc.headsUpMessage("Weights normalized"))
コード例 #26
0
    def saveSkinWeights(self, *args):
        ''' This next block is used to define the path where the weights will be saved.
        I plan on putting this in the __init__ once I am done testing '''
        print "saving weights"
        #import tsapi.core.maya.animation as annie
        #reload(annie)

        try:
            character = cmds.ls(sl=True)[0]
        except:
            cmds.headsUpMessage("Please Select Valid Geometry")
            return
        annie = annie.animation()

        # Define the file name and path
        characterName = self.characterName
        skinPath = turbineUtils.setupDirs(characterName, create=False)[4]
        outFileSuffix = '_skinWeight.csv'
        outFile = (character + outFileSuffix)
        finalPath = (skinPath + outFile)
        """ Delete the skin file if one already exists """
        if cmds.file(finalPath, q=True, ex=True):
            os.remove(finalPath)

        # Select the character here, then use GetValidSkinWeights to grab vert info.
        print " Annie used here"
        for char in annie.GetValidSkinWeights():
            vert = char[0]

            jointInfo = char[1]
            for each in jointInfo:
                joint = each[0]
                tmpWeight = each[1]

                weight = str("%.2f" % tmpWeight)
                weight = float(weight)

                value = (vert, joint, weight)

                writer = csv.writer(open(finalPath, "a"))
                writer.writerow(value)
        """ I need to make sure the file closes here """
        # Close the file
        #file.close(finalPath)

        # Get the user name and inform the user the weights have been saved
        currentUser = getUser()
        niceName = (currentUser)[1]
        cmds.headsUpMessage("The weight file has been saved to " + finalPath)
コード例 #27
0
ファイル: skinning.py プロジェクト: griffinanimator/MPR
    def saveSkinWeights(self, *args):
        ''' This next block is used to define the path where the weights will be saved.
        I plan on putting this in the __init__ once I am done testing '''
        print "saving weights"
        
        try:
            character = cmds.ls(sl=True)[0]
        except:
            cmds.headsUpMessage("Please Select Valid Geometry")
            return
        weights = animation.Weights()
        

        # Define the file name and path
        characterName = self.characterName 
        skinPath = turbineUtils.setupDirs(characterName, create=False)[4]
        outFileSuffix = '_skinWeight.csv'
        outFile = (character + outFileSuffix )
        finalPath = (skinPath + outFile)
        
        """ Delete the skin file if one already exists """
        if cmds.file(finalPath, q=True, ex=True):
            os.remove(finalPath)
                
        # Select the character here, then use GetValidSkinWeights to grab vert info.

        for char in Weights.getValidSkinWeights():
            vert = char[0]
        
            jointInfo = char[1]
            for each in jointInfo:
                joint = each[0]
                tmpWeight = each[1]

                weight = str("%.2f" % tmpWeight)
                weight = float(weight)

                value = (vert, joint, weight)
                   
                writer = csv.writer(open(finalPath, "a"))                
                writer.writerow(value)
        """ I need to make sure the file closes here """            
        # Close the file
        #file.close(finalPath)
        
         # Get the user name and inform the user the weights have been saved        
        currentUser = getUser()        
        niceName = (currentUser)[1]
        cmds.headsUpMessage("The weight file has been saved to " + finalPath)
コード例 #28
0
def gameStart(*args):
    #create the mash network
    game()
    #add the code to the MASH Python node
    cmds.select(pfx + "test")
    cmds.addAttr(longName="code", dataType="string")
    cmds.connectAttr(pfx + "test.code", pfx + "tower_Python.pyScript")
    endStr = "\n\nmd.setData()"
    s = "import openMASH\n\nmd = openMASH.MASHData(thisNode)"
    pyStr = s + endStr
    cmds.setAttr(pfx + "test.code", str(pyStr), type="string")
    myList = []
    cmds.hide(pfx + "test")
    #new game message
    cmds.headsUpMessage('New Game')
コード例 #29
0
 def Batch_Position_Fn(self):
     Base_Curve = self.MainWindow.Cam_Item_Widget.Attr["Add_Crv_LE"]
     CamGrp = self.Add_CamGrp_LE.text()
     cmds.xform(CamGrp, cp=1)
     cmds.delete(cmds.parentConstraint(Base_Curve, CamGrp))
     Target_Curve = self.Add_Crv_LE.text()
     # Note 解除曲线的锁定
     cmds.setAttr("%s.tx" % Target_Curve, lock=False)
     cmds.setAttr("%s.ty" % Target_Curve, lock=False)
     cmds.setAttr("%s.tz" % Target_Curve, lock=False)
     cmds.setAttr("%s.rx" % Target_Curve, lock=False)
     cmds.setAttr("%s.ry" % Target_Curve, lock=False)
     cmds.setAttr("%s.rz" % Target_Curve, lock=False)
     cmds.delete(cmds.parentConstraint(Base_Curve, Target_Curve))
     cmds.headsUpMessage(u"位置匹配完成")
コード例 #30
0
ファイル: WhiteBoxTool.py プロジェクト: octvision/oct
def storeTarget():

    global sourceObject

    sourceObject = mc.ls(sl=True)

    #error check variable, checks to make sure only one object is being sourced
    sourceCheck = len(sourceObject)
    if (sourceCheck != 1):
        mc.warning(
            '1 source object should be stored at a time.  Please select one object.'
        )
        sourceObject = 'empty[]'
    elif (sourceCheck == 1):
        mc.headsUpMessage('Source Object Stored!')
コード例 #31
0
ファイル: pickWalker.py プロジェクト: crisosphinx/SampleCode
    def print_sel_and_info(self):
        _info = '{}{} has selected {}. This is mesh {} of {}.'.format(
            self.scriptName,
            self.pickWalkVersion,
            self.dictOfSceneObjects[self.indexed],
            self.indexed + 1,
            len(self.dictOfSceneObjects),
        )
        _umvs = '{} unmerged verts.'.format(self.umv)

        # Print the info
        print(_info)

        # Heads up message for user to visibly always see information
        cm.headsUpMessage(_info + '    ' + _umvs)
コード例 #32
0
def Keyframe_Match(MotionPathText,LocText):
    MotionPath = cmds.textField(MotionPathText,q=1,tx=1)
    Locator = cmds.textField(LocText,q=1,tx=1)
    Selection = cmds.ls(sl=1)[0]
    cmds.cutKey("%s.uValue"%MotionPath,clear=True)

    AnimCurve = cmds.listConnections( "%s.uValue"%Locator, d=False, s=True )[0]

    StartTime = cmds.findKeyframe(Locator,w="first")
    EndTime = cmds.findKeyframe(Locator,w="last")

    cmds.copyKey( "%s.uValue" % Locator, time=(StartTime,EndTime))
    cmds.pasteKey("%s.uValue" % MotionPath)

    cmds.headsUpMessage(u"关键帧匹配完成")
 def Add_CamGrp_Pick_Fun(self):
     if len(cmds.ls(sl=True)) > 0:
         Selection = cmds.ls(sl=True,l=1)[0] 
         # SelectionShape = cmds.listRelatives(Selection)[0]
         SelectionType = cmds.nodeType( Selection )
         if SelectionType == "transform":
             self.Add_CamGrp_LE.setText(Selection)
             try :
                 self.Add_CamGrp_Get.clicked.disconnect()
             except:
                 pass
             self.Add_CamGrp_Get.clicked.connect(partial(self.Select_OBJ_Fun,Selection))
         self.Current_Item.Attr["Add_CamGrp_LE"] = self.Add_CamGrp_LE.text()
         else:
             cmds.warning(u"请选择组进行获取")
             cmds.headsUpMessage(u"请选择组进行获取")
コード例 #34
0
	def processInitialSelection(self):
		selection = cmds.ls(selection=True)
		self.blueprintJoints = []
		self.geometry = []
		
		self.blueprintJoints = self.findBlueprintJoints(selection)
		self.geometry = self.findGeometry(selection)
		
		if self.blueprintJoints == None:
			cmds.headsUpMessage('pleade select the blueprint joint(s) you wish to attach geometry to.')
			cmds.scriptJob( event=['SelectionChanged', self.selectBlueprintJoint_callback],runOnce=True)
		elif self.geometry == None:
			cmds.headsUpMessage('Please  select the Geometry you wish to attach to the specified blueprint joint(s).')
			cmds.scriptJob(event=['SelectionChanged',self.selectGeometry_callback], runOnce=True)
		else:
			self.attachGeoToBlueprint_attachment()
コード例 #35
0
def target_listManager(list):
    missing_elements = False
    print("#" * 32 + " Target Objects " + "#" * 32)
    for obj in list:
        if cmds.objExists(obj):
            print(obj)
        else:
            print(obj + " no longer exists!")
            missing_elements = True
    print("#" * 80)
    if missing_elements:
        cmds.headsUpMessage( 'It looks like you are missing some target elements! Open script editor for more information', verticalOffset=150 , time=5.0)
    else:
        cmds.headsUpMessage( 'Target elements selected (Open script editor to see a list of your loaded elements)', verticalOffset=150 , time=5.0)
    if settings.get("target_list") != [] and missing_elements == False:
        cmds.select(settings.get("target_list"))
コード例 #36
0
    def popInfluenceList(self, *args):
        selection = self.getSelectedMesh()

        if selection == None:
            return(mc.headsUpMessage("Select Geometry"))
        
        # Doing this to verify we have a skin cluster
        sknCluster = self.getSelectionSkinClusters(selection)

        if sknCluster == None:
            return(mc.headsUpMessage('skinCluster Not Found'))
        
        # Get the list of verts   
        vertList = self.listVertices(selection)
        print vertList
        mc.textScrollList(self.UIElements['influenceList'], edit=True, append=vertList)
コード例 #37
0
def Keyframe_Match(text):
    target = cmds.textField(text,q=1,tx=1)
    selList = cmds.ls(sl=1)
    for sel in selList:
        StartTime = cmds.getAttr("%s.start"%sel)
        EndTime = cmds.getAttr("%s.end"%sel)

        if StartTime == EndTime:
            StartTime = cmds.findKeyframe(sel,w="first")
            EndTime = cmds.findKeyframe(sel,w="last")

        cmds.copyKey( sel, time=(StartTime,EndTime), option="curve" ,at="translate")
        targetEndTime = cmds.findKeyframe(target,w="last")
        cmds.pasteKey( target, time=(targetEndTime,targetEndTime) )

    cmds.headsUpMessage(u"关键帧匹配完成")
コード例 #38
0
ファイル: WW_Leg_Rig.py プロジェクト: winsi3d/Art-Tools
	def Leg_Lyt_Check(self, *args):
		locatorInfo = []
		rootLoc = cmds.ls(sl=True)
		print rootLoc
		print rootLoc[0]

		rootCheck = rootLoc[0].rpartition("_")[2]
		print rootCheck

		if rootCheck == "root":
			print "Root is selected"

			rootChildren = cmds.listRelatives(rootLoc, allDescendents = True, type = "transform")
			print rootChildren

			for each in rootChildren:
				pos = cmds.xform(each, q=True, ws=True, t=True)
				locatorInfo.append([each, pos])


			locatorInfo.reverse()

			self.Leg_Rig(locatorInfo, rootLoc)

		else:
			return cmds.headsUpMessage("Please Select A Root")
コード例 #39
0
    def Add_CamGrp_Pick_Fun(self):
        if len(cmds.ls(sl=True)) > 0:
            Selection = cmds.ls(sl=True,l=1)[0] 
            # SelectionShape = cmds.listRelatives(Selection)[0]
            SelectionType = cmds.nodeType( Selection )
            if SelectionType == "transform":
                self.Add_CamGrp_LE.setText(Selection)
                try :
                    self.Add_CamGrp_Get.clicked.disconnect()
                except:
                    pass
                self.Add_CamGrp_Get.clicked.connect(partial(self.Select_OBJ_Fun,Selection))

                TypeList =[
                    "motionPath",
                    "nurbsCurve",
                    "locator",
                ]

                FnList = [
                    self.Add_Motion_Path_Pick_Fun,
                    self.Add_Crv_Pick_Fun,
                    self.Add_Loc_Pick_Fun,
                ]

                SelectionList = cmds.listRelatives(Selection)
                for sel in SelectionList:
                    SelectionType = cmds.nodeType( sel )
                    for Type in TypeList:
                        if 
                    cmds.select(sel)
                self.Current_Item.Attr["Add_CamGrp_LE"] = self.Add_CamGrp_LE.text()
            else:
                cmds.warning(u"请选择组进行获取")
                cmds.headsUpMessage(u"请选择组进行获取")
        else :
            self.Add_CamGrp_LE.setText("")
        
        if self.Add_CamGrp_LE.text() != "":
            self.Add_CamGrp_Label.setVisible(False)
            self.Add_CamGrp_Get.setVisible(True)
            self.Current_Item.Attr["Add_CamGrp_LE"] = self.Add_CamGrp_LE.text()
        else:
            self.Add_CamGrp_Label.setVisible(True)
            self.Add_CamGrp_Get.setVisible(False)
        
        self.MainWindow.Save_Json_Fun()
コード例 #40
0
ファイル: JR_tool_class.py プロジェクト: jricker/JR_Maya
	def vertexMergeTool(self):
		length = len( self.getSelection() )
		if self.getSelection() == 'None': # set tool to the merge vertex tool if no verts are selected
			cmds.setToolTo('polyMergeVertexContext')
		else: # if verts are already selected, then run the commands below
			if self.getType(0) == 'vertex': # check to see if the selection is of the vertex type, in case the mask is set to vert but the sel is edge etc.
				if length == 2:
					cmds.polyMergeVertex(alwaysMergeTwoVertices = True)
				elif length  > 2:
					cmds.polyMergeVertex(distance = 0.001)
					newLength = len(self.getSelection())
					if newLength == length: # Nothing was merged because the before and after are the same, state so
						cmds.headsUpMessage( str(length) + ' Verts Selected - 0 Merged', verticalOffset=-100, horizontalOffset=-200 )
					else: # means a merge did happen, so tell how many were merged and how many are left now
						cmds.headsUpMessage( 'FROM ' + str(length) + ' TO ' + str(newLength), verticalOffset=-100, horizontalOffset=-200 )
			else:
				cmds.warning('Vertex not selected')
コード例 #41
0
	def rehook_module_setup(self, *args):

		selected_nodes = cmds.ls(sl=True, transforms=True)

		if len(selected_nodes) == 2:

			new_hook = self.find_hook_obj_from_selection()
			self.module_instance.rehook(new_hook)

		else:
			self.delete_script_job()

			current_selection = cmds.ls(sl=True)

			cmds.headsUpMessage("Please select the joint you wish to re-hook to. Clear selection to un-hook")

			cmds.scriptJob(event=["SelectionChanged", partial(self.rehook_module_callback, current_selection)], runOnce=True)
コード例 #42
0
ファイル: IShatterCTX.py プロジェクト: jeffhong21/scripts
 def initSetup(self):
     ''' 
     Initialize all data relative to IShatter Context.
     '''
     iMinTime = cmds.playbackOptions(query = True, minTime = True)
     cmds.currentTime(iMinTime, edit = True)
     
     self.setFractureFX()
     self.getHardEdges()
     self.setObjectToDisplay()        
     self.createImpactHelper()        
     self._mView.getCamera(self._mCamera)
     
     if self._mInViewMessage:
         cmds.inViewMessage(amg = 'Estimated Fragments : <hl>' + str(self._mVoroPoints.length()) + '</hl>', dragKill = True, pos = 'topCenter')
     else:                     
         cmds.headsUpMessage('Estimated Fragments : ' + str(self._mVoroPoints.length()), verticalOffset = (cmds.control('modelPanel4', q = True, h = True) / 2.5))    
コード例 #43
0
    def createFootLyt(self, *args):
        if cmds.objExists('lyt_ankle') == True:
            cmds.headsUpMessage('A lyt already exists')
            return
        al = cmds.spaceLocator(n='lyt_ankle')
        cmds.xform(al, ws=True, t=[0.0, 2.0, 0.0])
        bl = cmds.spaceLocator(n='lyt_ball')
        cmds.xform(bl, ws=True, t=[0.0, 0.5, 1.0])
        tl = cmds.spaceLocator(n='lyt_toe')
        cmds.xform(tl, ws=True, t=[0.0, 0.0, 2.0])
        hl = cmds.spaceLocator(n='lyt_heel')
        cmds.xform(hl, ws=True, t=[0.0, 0.0, -1.0])
        rbl = cmds.spaceLocator(n='lyt_rbank')
        cmds.xform(rbl, ws=True, t=[-0.5, 0.0, 1.0])
        lbl = cmds.spaceLocator(n='lyt_lbank')
        cmds.xform(lbl, ws=True, t=[0.5, 0.0, 1.0])

        cmds.parent(bl, tl, hl, rbl, lbl, al)
コード例 #44
0
def get_raw_curves():
    result_curves = {}
    anim_curves = cmds.keyframe(q=True, sl=True, name=True)
    if anim_curves is None:
        cmds.headsUpMessage(
            "No animation keys/curve selected! Select keys to filter, please!")
        return None
    for anim_curve in anim_curves:
        anim_keys = cmds.keyframe(q=True, sl=True, timeChange=True)
        start, end = int(anim_keys[0]), int(anim_keys[len(anim_keys) - 1])
        anim_dict = {}
        for i in range(start, end + 1):
            anim_dict[i] = cmds.keyframe(anim_curve,
                                         q=True,
                                         time=(i, i),
                                         ev=True)[0]
        result_curves[anim_curve] = anim_dict
    return result_curves
コード例 #45
0
ファイル: animFilters.py プロジェクト: saphilli/AnimFiltersV2
def copy_original_curves():
    # type: () -> tuple
    """
    Copy selected animation curves to clipboard and return their names with start and end frames
    so we can paste them back later

    :return: list of anim curve names, start frame, end frame
    :rtype: list, float, float
    """
    anim_curves = cmds.keyframe(q=True, sl=True, name=True)
    if anim_curves is None:
        cmds.headsUpMessage("No animation keys/curve selected! Select keys to filter, please!")
        cmds.warning("No animation keys/curve selected! Select keys to filter, please!")
        return None, None, None
    anim_keys = cmds.keyframe(q=True, sl=True, timeChange=True)
    start, end = int(anim_keys[0]), int(anim_keys[len(anim_keys) - 1])
    cmds.copyKey(anim_curves, t=(start, end)) 
    return anim_curves, start, end
 def Batch_Position_Fn(self):
     ChildrenList = self.Item_Layout.children()
     for i,child in enumerate(ChildrenList):
         if i != 0:
             Base_Curve = self..Attr["Add_Crv_LE"]
             CamGrp = self.Add_CamGrp_LE.text()
             cmds.xform( CamGrp,cp=1 )
             cmds.delete(cmds.parentConstraint( Base_Curve,CamGrp ))
             Target_Curve = self.Add_Crv_LE.text()
             # Note 解除曲线的锁定
             cmds.setAttr("%s.tx" % Target_Curve,lock=False)
             cmds.setAttr("%s.ty" % Target_Curve,lock=False)
             cmds.setAttr("%s.tz" % Target_Curve,lock=False)
             cmds.setAttr("%s.rx" % Target_Curve,lock=False)
             cmds.setAttr("%s.ry" % Target_Curve,lock=False)
             cmds.setAttr("%s.rz" % Target_Curve,lock=False)
             cmds.delete(cmds.parentConstraint( Base_Curve,Target_Curve ))
             cmds.headsUpMessage(u"位置匹配完成")
コード例 #47
0
ファイル: QuadLeg.py プロジェクト: griffinanimator/GTOOLS
    def getSelHipHierarchy(self, selJnt, *args):
        """ Create some empty arrays to store information """
        legJntSets = []
        """ Use the getBindJoints function"""
        selJnt = cmds.ls(sl=True)
        """ Find the hip bone and it's children """
        for jnt in selJnt:
            suffix = "hip"
            result = jnt.endswith(suffix)
            if result == True:
                jntChildren = cmds.listRelatives(jnt, ad=True, type='joint')
                jntChildren.append(jnt)
                legJntSets.append(jntChildren)

        else:
            cmds.headsUpMessage("Please select a jnt_*_hip")

        return legJntSets
コード例 #48
0
def stored_list_manager(list):
    missing_elements = False
    found_elements = []
    print("#" * 32 + " Objects List " + "#" * 32)
    for obj in list:
        if cmds.objExists(obj):
            print(obj)
            found_elements.append(obj)
        else:
            print(obj + " no longer exists!")
            missing_elements = True
    print("#" * 80)
    if missing_elements:
        cmds.headsUpMessage( 'It looks like you are missing some elements! Open script editor for more information', verticalOffset=150 , time=5.0)
    else:
        cmds.headsUpMessage( 'Stored elements selected (Open script editor to see a list)', verticalOffset=150 , time=5.0)
    if list != []:
        cmds.select(found_elements)
コード例 #49
0
    def createFootLyt(self, *args):
        if cmds.objExists('lyt_ankle') == True:
            cmds.headsUpMessage('A lyt already exists')
            return
        al = cmds.spaceLocator(n='lyt_ankle')
        cmds.xform(al, ws=True, t=[0.0, 2.0, 0.0])
        bl = cmds.spaceLocator(n='lyt_ball')
        cmds.xform(bl, ws=True, t=[0.0, 0.5, 1.0])
        tl = cmds.spaceLocator(n='lyt_toe')
        cmds.xform(tl, ws=True, t=[0.0, 0.0, 2.0])
        hl = cmds.spaceLocator(n='lyt_heel')
        cmds.xform(hl, ws=True, t=[0.0, 0.0, -1.0])
        rbl = cmds.spaceLocator(n='lyt_rbank')
        cmds.xform(rbl, ws=True, t=[-0.5, 0.0, 1.0])
        lbl = cmds.spaceLocator(n='lyt_lbank')
        cmds.xform(lbl, ws=True, t=[0.5, 0.0, 1.0])

        cmds.parent(bl, tl, hl, rbl, lbl, al)
コード例 #50
0
ファイル: QuadLeg.py プロジェクト: griffinanimator/GTOOLS
    def getSelHipHierarchy(self, selJnt, *args):
        """ Create some empty arrays to store information """
        legJntSets = []
        
        """ Use the getBindJoints function"""
        selJnt = cmds.ls(sl=True)
        """ Find the hip bone and it's children """
        for jnt in selJnt:
            suffix = "hip" 
            result = jnt.endswith(suffix)
            if result == True:
                jntChildren = cmds.listRelatives(jnt, ad=True, type='joint')
                jntChildren.append(jnt)
                legJntSets.append(jntChildren)

        else: 
            cmds.headsUpMessage("Please select a jnt_*_hip")

        return legJntSets
コード例 #51
0
ファイル: minime.py プロジェクト: sanfx/pythonScripts
 def savePlus(self,*args):
         """
         Save as a new file with incremented number.
         """
         # Get the current scene name.
         curName, curExt = os.path.splitext(cmds.file(query=True,sceneName=True))
         # Determine the file type.
         if curExt == ".ma":
                 curType = "mayaAscii"
         elif curExt == ".mb":
                 curType = "mayaBinary"
         else:
                 api.MGlobal.displayWarning("Unknown file type.")
                 # Abort.
                 return
         # Compute the new scene name.
         underscorePos = curName.rfind("_")
         if underscorePos == -1:
                 # No underscore found, so we append the number.
                 newName = curName + "_001"
         else:
                 try:
                         curNum = int(curName[underscorePos+1:])
                 except ValueError:
                         # The part of the current name after the last underscore is not
                         # a decimal number, so we ignore it and append "_001" instead.
                         newName = curName + "_001"
                 else:
                         # Get the right padding from the length of the number.
                         padding = len(curName[underscorePos+1:])
                         formatstring = "_%%0%dd" % padding
                         newName = curName[:underscorePos] + formatstring % (curNum + 1)
         newName += curExt
         # Save the file.
         result = cmds.file(rename=newName)
         cmds.file(f=True, type=curType, save=True)
         newName=newName.split("/")[-1]
         cmds.textScrollList('fileLister',edit=True,append=newName)
         cmds.headsUpMessage("Scene saved as `%s'." % result, time=3.0)
         self.setThumbnail
         self.isAutoUpload
コード例 #52
0
 def checkBlendshapeChildren(self):
     if not cmds.listRelatives('blendshapes_hrc', children = True):
         cmds.warning('NO BLENDSHAPES FOUND ATTEMPTING AN UNDO....')
         cmds.undo()
         if not cmds.listRelatives('blendshapes_hrc', children = True):
             cmds.warning('NO BLENDSHAPES FOUND ATTEMPTING AN UNDO....')
             cmds.undo()
             if not cmds.listRelatives('blendshapes_hrc', children = True):
                 cmds.warning('NO BLENDSHAPES FOUND ATTEMPTING AN UNDO....')
                 cmds.undo()
                 if not cmds.listRelatives('blendshapes_hrc', children = True):
                     cmds.warning('FAILED TO RESTORE BLENDSHAPES GROUP!!')
                     cmds.headsUpMessage('FAILED TO RESTORE BLENDSHAPES GROUP!!', time = 3)
                 else:
                     return True
             else:
                 return True
         else:
             return True
     else:
         return True
コード例 #53
0
ファイル: IShatterCTX.py プロジェクト: jeffhong21/scripts
    def finalizeCtx(self):
        '''
        called when we exit the context
        '''
        if cmds.objExists(self._mVoroImpactTrs):
            cmds.delete(self._mVoroImpactTrs) ; self._mVoroImpactTrs = None
        
        if cmds.objExists(self._mVoroDisplay[0]):
            cmds.delete(self._mVoroDisplay) ; self._mVoroDisplay = None
        
        if cmds.objExists(self._mVoroObject):
            cmds.setAttr(self._mVoroObject + '.visibility', True)
            mBreakNode = cmds.listConnections(self._mVoroObject, sh = True, type = 'fxBreakGeometry')
            if len(mBreakNode) > 0:
                if self._mVoroPoints.length() > 0:
                    cmds.setAttr(mBreakNode[0] + '.numPoints', self._mVoroPoints.length())       
        
        if len(self._mObjectsToHide):
            cmds.showHidden(self._mObjectsToHide)
        
        self._mVoroPoints.clear() ; self._mVoroPoints = None
        self._mObjectsToHide = None            
            
        cmds.select(clear = True)
        mel.eval('hyperShadePanelMenuCommand("hyperShadePanel1", "deleteUnusedNodes")')
        cmds.scriptEditorInfo (clearHistory = True)
            
        if self._mInViewMessage:
            cmds.inViewMessage(amg = '<hl> IShatter Completed </hl>', dragKill = True, fade = True, pos = 'topCenter')
        else:                     
            cmds.headsUpMessage('IShatter Completed', verticalOffset = (cmds.control('modelPanel4', q = True, h = True) / 2.5))        
        
        cmds.scriptJob(event = ("idle", self.deleteIShatterCtx), runOnce = True)                        

#****************************************************************************************************************************************************************************************#
#****************************************************************************************************************************************************************************************#
# 													    	                     CLASS END DEFINITION                                                                                    #
#****************************************************************************************************************************************************************************************#
#****************************************************************************************************************************************************************************************#
コード例 #54
0
ファイル: gameJointData.py プロジェクト: griffinanimator/MPR
    def saveDelCharFile(self, characterName):
        """ This process happens at character publish.  The temp .csv file will be saved to a new directory with the character name as prefix """
        self.characterName = characterName
        """ Write the csv with all the character info """                
        """ Define the artPath """
        import System.directoryExtension as directoryExtension
        dirExt = directoryExtension.DirectoryExtension()
        artPath = dirExt.artPath

        # Define the file name and path        
        userName = userUtils.getUser()[0]
        
        outFileSuffix = '_gameJntInfo.csv'
        outFileSuffixBU = '_gameJntInfo_BU.csv'
        
        outFileD = (userName + outFileSuffix )# Delete this
        outFileS = (self.characterName + outFileSuffix )# Save as this
        outFileBU = (self.characterName + outFileSuffixBU )# Save as this
    
    
        filePath = artPath + "/character/GEPPETTO/Data/" 
        filePathS = artPath + "/character/GEPPETTO/Data/Character/" 
        filePathBU = artPath + "/character/GEPPETTO/Data/Character/BU/" 
        
        finalPathD = (filePath  + outFileD)
        finalPathS = (filePathS  + outFileS)
        finalPathBU = (filePathBU + outFileBU)
              
        if cmds.file(finalPathS, q=True, ex=True):
            turbineUtils.archiveFile(finalPathS)

        
        if cmds.file(finalPathD, q=True, ex=True):
            import shutil
            shutil.copy(finalPathD, finalPathS)
            os.remove(finalPathD)
        else:
            cmds.headsUpMessage("No character data file exists for publish.  Please lock a character.")
コード例 #55
0
 def _do_maya_post_publish(self, work_template, progress_cb):
     """
     Do any Maya post-publish work
     """        
     import maya.cmds as cmds
     progress_cb(0, "Post Checking scene now...")
     
     
     if cmds.objExists('CORE_ARCHIVES_hrc'):
         ## Cleanup all the namespaces now to get ready for a rebuild.
         cleanup.removeAllNS()
         
         ## Get the assembly paths from the transforms in the scene with the correct tags to load now..
         getAssemblyPaths = coreLib.getCorePaths()        
         
         ## Now load the assemblies from the paths
         coreLib.loadCoreArchives(paths = getAssemblyPaths)
         
         ## Now clean up the old archives before processing the new
         coreLib.removePreppedArchives()
         
         ## Now tag the base archives
         coreLib.tagRootArchive()
         
         ## Now clean the imported
         coreLib.cleanupCoreArchiveImports()
         
         ## Now Reconnect the duplicated cores to the originals
         coreLib.doReconnect()
         
          ## Put the maingroups and placement nodes into nice tidy places now
         coreLib.cleanupPlacements()
         coreLib._cleanupCoreArchiveRebuildGrps(parentTO = 'geo_hrc')
     
     ## Do a resave of the working file as ascii
     #cmds.file(save=True, force=True, type = 'mayaAscii')
     cmds.headsUpMessage("CORE ARCHIVES HAVE BEEN REMOVED! RELOAD YOUR SCENE NOW! DONOT SAVE!", time = 1)
     progress_cb(100,"Post complete...")
コード例 #56
0
ファイル: app.py プロジェクト: vipul-rathod/lsapipeline
    def run_app(self):
        """
        Callback from when the menu is clicked.
        """
        ## Tell the artist to be patient... eg not genY
        cmds.headsUpMessage("Building shotCam...", time = 1)
        inprogressBar = pbui.ProgressBarUI(title = 'Building Shotcam:')
        inprogressBar.show()
        ## Instantiate the API
        tk = sgtk.sgtk_from_path("T:/software/bubblebathbay")
        debug(app = self, method = 'run_app', message = 'API instanced...\n%s' % tk, verbose = False)
        debug(app = self, method = 'run_app', message = 'Fetch Shot Assets launched...', verbose = False)
               
        context = self.context ## To get the step
        debug(app = self, method = 'run_app', message = 'Context Step...\n%s' % context.step['name'], verbose = False)
        if context.step['name'] == 'Anm' or context.step['name'] == 'Blocking':
            inprogressBar.updateProgress(percent = 10, doingWhat = 'processing scene info...')
            cmds.cycleCheck(e = 1)
            ## Build an entity type to get some values from.
            entity = self.context.entity                                                                                    ## returns {'type': 'Shot', 'name': 'ep100_sh010', 'id': 1166}
            debug(app = self, method = 'run_app', message = 'entity... %s' % entity, verbose = False)

            ## Set the template to the maya publish folder
            shot_root_template = tk.templates[self.get_setting('shot_root_template')]
            debug(app = self, method = 'run_app', message = 'shot_root_template...\n%s' % shot_root_template, verbose = False)

            ## Now build the camera
            shotName = entity['name']
            cameraName = '%s_shotCam' % shotName
            if self.doesAssetAlreadyExistInScene(cameraName):
                inprogressBar.updateProgress(percent = 100, doingWhat = 'Camera found...')
                inprogressBar.close()
                cmds.warning("Scene currently has a valid shotCamera in it! Aborting ...")
                QtGui.QMessageBox.information(None, "Scene currently has a valid shotCamera in it! Aborting ...")
                raise tank.TankError("Scene currently has a valid shotCamera in it! Aborting ...")
            else:
                inprogressBar.updateProgress(percent = 50, doingWhat = 'Building camera...')
                cmds.camera()
                cmds.rename('camera1', cameraName)
                self.tagShotCam(cameraName)
                
                ## Now set the default camera stuff up
                settings._setCameraDefaults(cameraName)
                settings._createCamGate(cameraName)
                ## Now set the renderGlobals up
                width = self.get_setting('movie_width')
                height = self.get_setting('movie_height')
                inprogressBar.updateProgress(percent = 90, doingWhat = 'Setting render globals...')
                settings._setRenderGlobals(width = width, height = height, animation = True)

            inprogressBar.updateProgress(percent = 100, doingWhat = 'Finished...')
            inprogressBar.close()
            cmds.headsUpMessage("shotCam built successfully...", time = 1)
        else:
            cmds.headsUpMessage("Current context is not a valid Shot context. Please make sure you are under a valid shotgun Shot context!", time = 2)
            cmds.warning("Current context is not a valid Shot context. Please make sure you are under a valid shotgun Shot context!")
            QtGui.QMessageBox.information(None, "Current context is not a valid Shot context. Please make sure you are under a valid shotgun Shot context!")
            raise tank.TankError("Current context is not a valid Shot context. Please make sure you are under a valid shotgun Shot context!")
コード例 #57
0
    def animModInfo(self):
        """ Call on getInstalledAnimModules to get bp mod name, anim mod class
        and anim mod container name"""
        modSets = self.getModuleInformation()
        
        """ Create an empty list to store all the info retrieved from getAnimModAttrs """
        animModInfo = []

        for set in modSets: 
            animContainer = set[2]
            moduleContainer = set[3]
            moduleGroup = set[4]
            blueprintContainer = moduleContainer.replace("module_container", "blueprint_container")
            animModAttrs = self.getAnimModAttrs(moduleGroup, moduleContainer)
        
            for attr in animModAttrs:
                animModInfo.append(attr)
                
        """ If no mods exist, a character is probably not installed """
        if animModInfo == None:
            cmds.headsUpMessage ("No character in the scene ")
        
        return animModInfo
コード例 #58
0
def archiveFile(file):  
    import userUtils as userUtils
    import shutil
    
    # Define the file name and path        
    userName = userUtils.getUser()[0]
    
    """ Get the current date and time to use as the backup name """
    import datetime
    now = datetime.datetime.now()
    dateTime = now.strftime("%Y-%m-%d-%M")
    
    """ Define a suffix to add to the file path """
    fileSuffix = (userName + dateTime)
    
    """ Define a new file path """
    filePartition = file.rpartition('/')
    bakFile = ('/' + fileSuffix + '_' + filePartition[2] )
    bakFilePath = (filePartition[0] + '/Bak' + bakFile) 
            
    if cmds.file(file, q=True, ex=True):
        cmds.headsUpMessage("This file already exists" + file + ".  Backing it up.")
        shutil.copy(file, bakFilePath) 
コード例 #59
0
ファイル: altSetupTools.py プロジェクト: griffinanimator/MPR
 def publishForExport(self, *args):
     """ Let the user confirm they wish to proceed """
     confirmDialogue = cmds.confirmDialog( title='Confirm', message='Closing this file. Shall I proceed?', button=['Yes','No'], defaultButton='Yes', cancelButton='No', dismissString='No' )
     if confirmDialogue == 'No':
         return
     else:
         """ Try to move the character and setup containers into the default namespace """
         try:
             self.removeNamespaces()
         except:
             print "Failed to remove namespaces"
             return
 
         """ Export the setup and character containers to a rig file """
         """ Save the selection to a list and select """
         selection = ('character_container', 'Setup')
         cmds.select(d=True)
         for sel in selection:
             cmds.select(sel, add=True)
             
         rigFile = (self.dirExt.paths['rigPath'] +  self.characterName + '.ma')
         
         """ Export the selection to a rig file """
         cmds.file(rigFile, es=True, type='mayaAscii')  
         
         """ 
         Create a new file.
         Setup the scene.
         Define the namespace.
         Reference the character into the new file using the character namespace. 
         """
         cmds.file(new=True, force=True)
         sceneSettings.sceneSetup()
         characterNamespace = self.characterPrefix 
         cmds.file(rigFile, r=True, ns=characterNamespace)
         
         cmds.headsUpMessage( 'Save this file for export/animate with me' )
コード例 #60
0
def deleteEmptyUVSets():
    """
    Function to remove empty uv's
    """
    getMeshes = cmds.ls(type = 'mesh', l = True)
    emptyExists = False

    if getMeshes:
        for eachMesh in getMeshes:
            selectionList = om.MSelectionList()
            selectionList.add(eachMesh)
            nodeDagPath = selectionList.getDagPath(0)
            shapeFn = om.MFnMesh(nodeDagPath)
            ## Now fetch data from shapeFn
            shapeName = shapeFn.name()
            currentUVSets = shapeFn.getUVSetNames()

            validUVSets = []
            getFaceCount = shapeFn.numPolygons

            try:
                [[validUVSets.extend([eachUVset]) for eachUVset in shapeFn.getFaceUVSetNames(x) if
                  eachUVset not in validUVSets] for x in range(0, getFaceCount)]
            except:
                uvsets = None

            for eachUVSet in currentUVSets:
                if eachUVSet not in validUVSets:
                    logger.info('Removing empty UVSet %s from %s' % (eachUVSet, eachMesh))
                    cmds.select(eachMesh, r = True)
                    try:
                        cmds.polyUVSet(delete = True, uvSet = eachUVSet)
                        emptyExists = True
                    except:
                        cmds.warning('Failed to empty uv set %s of %s...' % (eachUVSet, eachMesh))
    if emptyExists:
        cmds.headsUpMessage('YOU HAD EMPTY UV SETS CLEANED UP!!', time = 3)