Ejemplo n.º 1
0
def setup():
    print ("bamboo user setup")

    mainFileMenu = mel.eval("string $f=$gMainFileMenu")
    mel.eval("buildFileMenu")
    cmds.menuItem(dividerLabel="Bamboo Tools", divider=True)
    cmds.menuItem(label="Export...", parent=mainFileMenu, command="openExporterUI()")
Ejemplo n.º 2
0
 def setup(self):
    self.addSwatch()
    
    self.beginScrollLayout()
    
    self.beginLayout("Expression", collapse=False)
    self.addCustom('expression', self.createExpression, self.replaceExpression)
    self.endLayout()
    
    self.beginLayout("Float variables", collapse=False)
    self.addCustom('fparam_name', self.createFloatVariables, self.replaceFloatVariables)
    self.suppress('fparam_value')
    self.endLayout()
    
    self.beginLayout("Vector variables", collapse=False)
    self.addCustom('vparam_name', self.createVectorVariables, self.replaceVectorVariables)
    self.suppress('vparam_value')
    self.endLayout()
    
    self.addControl('stop_on_error', label="Stop On Error")
    self.addControl('error_value', label="Error Value")
    
    mel.eval('AEdependNodeTemplate("%s")' % self.nodeName)
    self.addExtraControls()
    self.endScrollLayout()
Ejemplo n.º 3
0
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 []
Ejemplo n.º 4
0
def pupMaya2mental(mentalVersion):
        destPath = os.getenv('DEST_PATH_WIN')
        rootPath, shadersPath = {	
                3.8:('c:/Program Files/Autodesk/mrstand3.8.1-adsk2011/bin', destPath + '/mental3.8.1'),
                3.11:('c:/Program Files/Autodesk/mrstand3.11.1-adsk2014/bin', destPath + '/mental3.11.1')
                }[mentalVersion]

        os.putenv('RAY_COMMAND', '"' + rootPath + '/ray.exe"')

        os.putenv('MR_VERSION', str( mentalVersion ) )

        miModulesPaths, binModulesPaths = modulesPath.getMiBinString()
        #os.putenv('MI_RAY_INCPATH', shadersPath + '/mi;' +  miModulesPaths)
        #os.putenv('MI_LIBRARY_PATH', shadersPath + '/bin;' +  binModulesPaths)
        #os.putenv('MI_ROOT', rootPath)
        mel.eval('pup_maya_2_mental(3);')

        mc.checkBoxGrp('pup_m2mrOverrideEnv', e=True, v1=1)
        mc.textFieldGrp('pup_m2mrMiRoot', e=True, tx= rootPath )
        mc.textFieldGrp('pup_m2mrMiInclude', e=True, tx= shadersPath + '/mi;' +  miModulesPaths )
        mc.textFieldGrp('pup_m2mrMiLib', e=True, tx= shadersPath + '/bin;' +  binModulesPaths )
        mc.textFieldGrp('pup_m2mrMiDir', e=True, tx= "C:/Temp/" )
        mc.optionMenuGrp('pup_m2mrVerboseM', e=True, sl=5)
        #mc.textFieldGrp('pup_m2mrCommandLine', e=True, tx= '-finalgather_passes 0 -memory 1000000' )
        mc.textFieldGrp('pup_m2mrCommandLine', e=True, tx= '-memory 1000000' )
        mc.checkBoxGrp('pup_m2mrUniqueMI', e=True, v1=1)
        mc.optionMenuGrp('pup_m2mrPriority', e=True, sl=3)
 def makeShaderWithCreateNode(self, shaderType ):
     # pm.createNode( shaderType )   ## For some reason, the python version of this command does not work with mip shaders... i dunno why...
     ## Use mel to make MIP shaders
     try:
         mel.eval( 'createNode "' + str(shaderType) + '";' )
     except:
         print( 'cannot create shader type:' + str(shaderType)  )        
def main():
	mm.eval('selectCurveCV("all");')
	sel = mc.ls(sl=1, fl=1)
	grpname = (sel[0].split('.'))
	grpname = grpname[0]+"_grp"
	grp = mc.group(em=1, n=grpname)
	
	for i in sel:
		iname = i.replace('[', '')
		iname = iname.replace(']','')
		iname = iname.replace('.','_')
		
		locname = iname+"_loc"
		clusname = iname+"_clus"	
		
		mc.select(i, r=1)
		print "here"
		cluster = mc.cluster(n=clusname)
	
		location = mc.xform(cluster, q=1, ws=1, sp=1)
		print location
		locator = mc.spaceLocator(n=locname, p=(location[0], location[1], location[2]))
		mc.xform(locator, cp=1)
		set_vis = clusname+"Handle.visibility"
		mc.setAttr(set_vis, 0)
		mc.parent(cluster, locator)
		mc.parent(locator, grp)
		
		shape = mc.listRelatives(locator)
		mc.setAttr((shape[0]+".overrideEnabled"),1)
		mc.setAttr((shape[0]+".overrideColor"),17)
    def _publish_gpu_for_item(self, item, output, work_template, primary_publish_path, sg_task, comment, thumbnail_path, progress_cb):
        """
        Export a gpu cache for the specified item and publish it  to Shotgun.
        """
        group_name = item["name"].strip("|")
        debug(app = None, method = '_publish_gpu_for_item', message = 'group_name: %s' % group_name, verbose = False)
        tank_type = output["tank_type"]
        publish_template = output["publish_template"]        
                
        # get the current scene path and extract fields from it using the work template:
        scene_path = os.path.abspath(cmds.file(query=True, sn= True))
        fields = work_template.get_fields(scene_path)
        publish_version = fields["version"]

        # update fields with the group name:
        fields["grp_name"] = group_name

        ## create the publish path by applying the fields with the publish template:
        publish_path = publish_template.apply_fields(fields)
        #'@asset_root/publish/gpu/{name}[_{grp_name}].v{version}.abc'
        gpuFileName = os.path.splitext(publish_path)[0].split('\\')[-1] 
        fileDir = '/'.join(publish_path.split('\\')[0:-1])
        debug(app = None, method = '_publish_gpu_for_item', message = 'gpuFileName: %s' % gpuFileName, verbose = False)
        
        ## Now fix the shaders
        shd.fixDGForGPU()
        
        if cmds.objExists('CORE_ARCHIVES_hrc'):
            cmds.setAttr('CORE_ARCHIVES_hrc.visiblity', 0)
        
        if cmds.objExists('ROOT_ARCHIVES_DNT_hrc'):
            cmds.setAttr('ROOT_ARCHIVES_DNT_hrc.visiblity', 0)
                                       
        ## build and execute the gpu cache export command for this item:
        try:
            print '====================='
            print 'Exporting gpu now to %s\%s' % (fileDir, gpuFileName)
            #PUT THE FILE EXPORT COMMAND HERE
            cmds.select(clear = True)
            for geo in cmds.listRelatives(group_name, children = True):
                if 'geo_hrc' in geo:
                    geoGroup = str(group_name)
                    debug(app = None, method = '_publish_gpu_for_item', message = 'geoGroup: %s' % geoGroup, verbose = False)
                
            cmds.select(geoGroup)
            
            debug(app = None, method = '_publish_gpu_for_item', message = 'geoGroup: %s' % geoGroup, verbose = False)
            debug(app = None, method = '_publish_gpu_for_item', message = "gpuCache -startTime 1 -endTime 1 -optimize -optimizationThreshold 40000 -directory \"%s\" -fileName %s %s;" % (fileDir, gpuFileName, geoGroup), verbose = False)
            
            mel.eval("gpuCache -startTime 1 -endTime 1 -optimize -optimizationThreshold 40000 -directory \"%s\" -fileName %s %s;" % (fileDir, gpuFileName, geoGroup))

            print 'Finished gpu export...'
            print '====================='
            
            if cmds.objExists('dgSHD'):            
                ## Now reconnect the FileIn nodes
                for key, var in filesDict.items():
                    cmds.connectAttr('%s.outColor' % key, '%s.color' % var)
        except Exception, e:
            raise TankError("Failed to export gpu cache file")
Ejemplo n.º 8
0
def appendPluginPath():

    putenvStr = mel.eval( 'getenv "MAYA_PLUG_IN_PATH"' )
    
    if os.name == 'posix':
        sepChar = ':'
    else:
        sepChar = ';'
    
    pythonPathName = sepChar + os.path.dirname( __file__.replace( '\\', '/' ) ) + '/pluginRoot'
    
    version = cmds.about(version=True)[:4]
    cppPathName = sepChar + os.path.dirname( __file__.replace( '\\', '/' ) ) + '/pluginRoot/' + version
    
    putenvStr = putenvStr.replace( pythonPathName, '' )
    putenvStr += pythonPathName
    putenvStr = putenvStr.replace( cppPathName, '' )
    putenvStr += cppPathName
    
    mel.eval( 'putenv "MAYA_PLUG_IN_PATH" "%s"' % putenvStr )
    putenvStr = mel.eval( 'getenv "MAYA_PLUG_IN_PATH"' )
    
    print "MAYA_PLUG_IN_PATH : "
    for path in putenvStr.split( sepChar ):
        print "    ", path
Ejemplo n.º 9
0
def setTool_hardSkinWeightBrush( evt=0 ):

    appendPluginPath()
    _cmdStr =  """global string $tf_skinSmoothPatin_selection[];
    
    global proc tf_smoothBrush( string $context )     
    {       
     artUserPaintCtx -e -ic "tf_init_smoothBrush"
     -svc "tf_set_smoothBrushValue"
     -fc "" -gvc "" -gsc "" -gac "" -tcc "" $context;
    }
    
    global proc tf_init_smoothBrush( string $name )
    {
        string $sel[] = `ls -sl -fl`;
        string $obj[] = `ls -sl -o`;
        
        sgSmoothWeightCommand $obj;
    }
    
    global proc tf_set_smoothBrushValue( int $slot, int $index, float $val )             
    {         
        sgSmoothWeightCommand -h 1 -i $index -w $val;
    }
    
    ScriptPaintTool;     
    artUserPaintCtx -e -tsc "tf_smoothBrush" `currentCtx`;"""
    
    if not cmds.pluginInfo( 'sgSmoothWeightCommand', q=1, l=1 ):
        cmds.loadPlugin( 'sgSmoothWeightCommand' )
    mel.eval( _cmdStr )
Ejemplo n.º 10
0
def cutSkin(mesh, weightThreshold=0.25, reducePercent=None, parentShape=False):
    """
    Extract a per influence proxy mesh from a skinned mesh based on influence weights.
    @param mesh: Mesh to extract faces from
    @type mesh: str
    @param weightThreshold: Influence to use to extract faces
    @type weightThreshold: float
    @param reducePercent: Influence to use to extract faces
    @type reducePercent: int or None
    """
    # Initialize
    startTime = cmds.timerX()
    cmds.undoInfo(state=False)

    # Get Skin Info
    skin = glTools.utils.skinCluster.findRelatedSkinCluster(mesh)
    if not skin:
        print('Cut Skin: Mesh "" has no skinCluster! Skipping...')
        return None

    # Prune Weights
    glTools.utils.skinCluster.lockSkinClusterWeights(skin, lock=False, lockAttr=False)
    pruneWts = glTools.utils.mathUtils.distributeValue(10, rangeStart=0.001, rangeEnd=weightThreshold)
    cmds.select(mesh)
    for wt in pruneWts:
        try:
            mel.eval('doPruneSkinClusterWeightsArgList 1 {"' + str(wt) + '"}')
        except Exception, e:
            print('Prune weight FAILED (' + mesh + ')! ' + str(e))
            break
Ejemplo n.º 11
0
def enableUI(*args):
    # Enable viewports
    MELCommand = 'paneLayout -edit -manage true $gMainPane;'

    # Enanble only what really matters...
    UIElementNames = [
        #'Attribute Editor',
        #'Channel Box / Layer Editor',
        #'Tool Settings',
        #'Shelf',     
        'Tool Box',  
        'Time Slider',
        'Range Slider',  
        'Command Line',   
        'Help Line',
        'Status Line'                
    ]    
    
    for name in UIElementNames:
        print name
        # If not visible, toggle it's visibility
        MELCommand += """
            if (!`isUIComponentVisible("{0}")`){{
                toggleUIComponentVisibility("{0}");}}
        """.format(name)
    
    MM.eval(MELCommand)
Ejemplo n.º 12
0
def stateFromFileInfo():
    from fnmatch import fnmatch
    selInfo = m.fileInfo('onSaveSelection', q=1)
    if len(selInfo) != 0:
        sel = []
        for i in selInfo[0].split('?'):
            if m.objExists(i):
                sel.append(i)
        if len(sel):
            m.select(sel)

            hilite = []
            c1 = ['f[*','e[*','map[*','vtx[*','vtxFace[*']
            c2 = ['facet','edge','puv','vertex','pvf']
            for x in sel:
                if x.count('.'):
                    parts = x.split('.')
                    for i in range(5):
                        if fnmatch(parts[1],c1[i]) and parts[0] not in hilite:
                            hilite.append(parts[0])
                            mel.eval('doMenuComponentSelection("' + parts[0] + '", "' + c2[i] + '");')

    ctxInfo = m.fileInfo('onSaveCtx', q=1)
    if len(ctxInfo) != 0:
        print ('ctxInfo: ' + str(ctxInfo))
        try:
            m.setToolTo(ctxInfo[0])
        except:
            print 'could not set "' + ctxInfo[0] + '"!'
Ejemplo n.º 13
0
def export_static_ogre(*args):
	export_dir = get_export_dir()
	objects = get_objects()
	ogre_mesh_files = []
	if (cmds.file(q=True, sceneName=True)==''):
		print 'Not a valid scene. Try saving it.'
		return False

	if not export_dir:
		print ("Empty Scene? unable to export.")

	else:
		print ('Export Directory:\n  %s\nOgre files\n' % export_dir)
		for ob in objects:
			name = ob
			if cmds.nodeType(ob) == 'transform':
				name = cmds.listRelatives(ob)[0]
			cmds.select(ob, r=True)
			_path = os.path.abspath( export_dir + ('/%s.mesh' % name) )
			ogre_path = _path.replace(os.sep, '/')
			# print ('select %s' % ob)
			print ('     %s' % ogre_path)

			ogre_mesh_files.append(ogre_path)
					  # 'ogreExport -sel -obj -lu mm -scale 1 -mesh \"aaa.mesh\" -shared -v -n -c -t -tangents TANGENT -tangentsplitmirrored;''
			command = 'ogreExport -sel -obj -lu mm -scale 0.1 -mesh \"%s\" -shared -n -c -t -tangents TANGENT -tangentsplitmirrored;' % ogre_path
			mm.eval(command)
		
		cmds.select(objects)
		print 'fixing materials'
		fix_xml_material_names(ogre_mesh_files)
Ejemplo n.º 14
0
def getFileName():
    base = studioBase.StudioSQL()

    loadType = {'Load saved reference load state':'', 
                'Load all references':'all', 
                'Load top-level references only':'topOnly', 
                'Load no references':'none'}

    fileData = mop.OpenDialog.openFile()
    if fileData[0] and fileData[1] and fileData[2]:
        fileName = fileData[1] + '/' + fileData[2]
    else:
        return False

    ref = loadType[fileData[3]]
    selective = fileData[4]
    print('filename', fileName, ref, 'selective', selective, fileData)

    base.setAction('open', fileName)
    if selective:
        cmds.file(fileName, open=True, buildLoadSettings=True )
        num = cmds.selLoadSettings( q=True, numSettings=True)
        cmds.optionVar(sv=('preloadRefEdTopLevelFile', fileName))
        mel.eval('PreloadReferenceEditor')

    else:
        if ref:
            cmds.file(fileName, o=True, f=True, lrd=ref)
        else:
            cmds.file(fileName, o=True, f=True)

    setRecentFile(fileName)

    return True
Ejemplo n.º 15
0
def importPose(filePath):
    poseTip = u'通用pose文件夹找不到制定pose文件\n'
    try:
        """Import the pose data stored in filePath"""
        # try to open the file
        newRootControl = cmds.ls(sl=True, type='transform')[0]
        newNodeAttr = newRootControl.rpartition('_root_')[0]
        try: f = open(filePath, 'r')
        except:
            cmds.confirmDialog(
                t='Error', b=['OK'],
                m='Unable to open file: %s'%filePath
            )
            raise
        # uncPickle the data
        pose = cPickle.load(f)
        # close the file
        f.close()
        # set the attributes to the stored pose
        errAttrs = []
        for attrValue in pose:
            try: 
                cmds.setAttr('%s%s'%(newNodeAttr, attrValue[0]), attrValue[1])
            except:
                try: errAttrs.append(attrValue[0])
                except: errAttrs.append(attrValue)
        # display error message if needed
        if len(errAttrs) > 0:
            importErrorWindow(errAttrs)
            sys.stderr.write('Not all attributes could be loaded.')
    except:
        mel.eval('print "%s";'%poseTip)
Ejemplo n.º 16
0
    def __set_renderer_by_str(self, value):
        """
        This function sets the active rendere from it s string name
        @param value: str, the name of the rendere
        """
        currPanel = cmds.getPanel(withFocus = 1)
        panelType = cmds.getPanel(to = currPanel)

        if value in self.RENDERERS_SHORTCUT:
            #create the mel command to eval
            cmd = 'setRendererInModelPanel \"{r}\" {cp};'.format(
                r = self.RENDERERS_SHORTCUT[value] , 
                cp = currPanel)
            
            #make sure we have a model panel active
            if (panelType == "modelPanel"):
                mel.eval(cmd)
            else :
                OpenMaya.MGlobal.displayError("In order to set stuff" +
                " on the viewport we need an acive viewport")

        else :
            #print the error
            strSupp = [str(k) for k in self.RENDERERS_SHORTCUT.keys()]
            supp = "\n-" +"\n- ".join(strSupp)
            OpenMaya.MGlobal.displayError("You did not provide a valid " + 
                "renderer name, supported renderer names are :" + 
                " \n {r}".format(r = supp) + 
                " \n got {v}".format(v= type(value).__name__))        
Ejemplo n.º 17
0
def setRecentFile(fileName):
    attr='mayaBinary'
    if fileName.split('.')[-1] == 'ma':
        attr='mayaAscii'

    melstr = 'addRecentFile("%s", "%s")' % (fileName, attr)
    mel.eval(melstr)
Ejemplo n.º 18
0
	def MEL_b167(self):##convert mel2py prints to script editor output window only
		mel.eval('scriptEditorInfo -clearHistory')
		mel_script = str(self.ui.t005.text())
		mel2py_script = ('mel2py.mel2pyStr('+'"""'+ mel_script +'"""'+')')
		python_script = eval(mel2py_script)
		python_script = python_script.lstrip('from pymel.all import *')
		outputscrollField(python_script, "mel2py", 1.0, 1.0)
Ejemplo n.º 19
0
def exportAnim(namespace, exportFile) : 
	# ctrls
	set1 = mc.ls('%s:*_ctrl' % namespace)
	set2 = mc.ls('%s:*:*_ctrl' % namespace)
	set3 = mc.ls('%s:*:*:*_ctrl' % namespace)
	set4 = mc.ls('%s:*_Ctrl' % namespace)
	set5 = mc.ls('%s:*:*_Ctrl' % namespace)
	set6 = mc.ls('%s:*:*:*_Ctrl' % namespace)

	ctrls = set1+set2+set3+set4+set5+set6

	animFile = '%s/%s.anim' % (exportFile, namespace)

	# manage dirs 
	if not os.path.exists(exportFile) : 
		os.makedirs(exportFile)

	# export command 
	mc.select(ctrls)

	tempFile = '%s/temp.anim' % mc.internalVar(utd = True)
	mm.eval('file -force -options "precision=8;intValue=17;nodeNames=1;verboseUnits=0;whichRange=1;range=1:24;options=keys;hierarchy=none;controlPoints=0;shapes=0;helpPictures=0;useChannelBox=0;copyKeyCmd=-animation objects -option keys -hierarchy none -controlPoints 0 -shape 0 " -typ "animExport" -pr -es "%s";' % tempFile)

	fileUtils.copy(tempFile, animFile)
	os.remove(tempFile)

	# export selection controllers 
	exportFilePath = '%s/%s.txt' % (exportFile, namespace)
	fileUtils.writeFile(exportFilePath, str(ctrls))

	mc.select(cl = True)

	return True 
Ejemplo n.º 20
0
 def import_hierarchy_geo(self):
     """Import all the obj objects"""
     file_info = self.geo_file_info
     for self.current_target in file_info.keys():
         cmds.file(file_info[self.current_target],
                   rpr="PKD_Temp",
                   i=1,
                   type="OBJ",
                   loadReferenceDepth="all",
                   ra=True,
                   mergeNamespacesOnClash=False,
                   options="mo=1")
         # Delete Existing geo if it exists
         if not self.cleansing_mode:
             if pm.objExists(self.current_target):
                 pm.delete(self.current_target)
         logger.info("Importing\n%s" % file_info[self.current_target])
         if self.cleansing_mode:
             os.remove(file_info[self.current_target])
         for top in pm.ls(assemblies=True, ud=True):
             if top.getShape():
                 if top.getShape().type() == "mesh" and top.name() == "PKD_Temp_Mesh":
                     top.rename(self.current_target)
                     pm.select(self.current_target)
                     mel.eval("polySetToFaceNormal")
                     mel.eval("polySoftEdge -a 180 -ch 1 %s" % self.current_target)
                     pm.delete(self.current_target, ch=1)
                     pm.refresh()
         self.update_progress()
Ejemplo n.º 21
0
    def get(self, var, type=None):

        var = self._format_var(var)
        if type is None:
            type = self._get_var_type(var)

        if type.endswith('[]'):
            proc_name = 'mampy_get_global_' + var[1:].replace('[]', 'array')
        else:
            proc_name = 'mampy_get_global_' + type

        try:
            global_declare = self._get_declare(type, var)
            cmd = textwrap.dedent('''
                global proc {type} {proc_name}()
                {{
                    {global_declare};
                    return {var};
                }}
                {proc_name}()
            '''.format(**locals()))
            result = mel.eval(cmd)
        except RuntimeError:
            raise RuntimeError('{} is an undeclared variable.'.format(var))

        try:
            if type.endswith('[]'):
                return tuple(mel.eval(cmd))
            else:
                return self.MELTYPES[type](mel.eval(cmd))
        except RuntimeError:
            raise RuntimeError('{}'.format(cmd))
Ejemplo n.º 22
0
def main(centerCurrentTime=False):
    '''
    Replacement command for "fitPanel -selected"
    If graph editor has focus, run frameGraphEditor, otherwise default to fitPanel -selected mel command.
    '''
    if not frameGraphEditor(centerCurrentTime=centerCurrentTime):
        mm.eval("fitPanel -selected") 
Ejemplo n.º 23
0
def enableaPlugin(filename):
    extDict = {'win64':'mll','mac':'bundle','linux':'so','linux64':'so'}
    os = cmds.about(os=True)
    ext = extDict[os]
    version = cmds.about(v=True)[:4]
    pluginName = 'deltaMushToSkinCluster_%s' % version
    fileFullName = '%s.%s' % (pluginName,ext)
    rootPath = getParentPath(currentFileDirectory())
    pluginsPath = rootPath+'/plug-ins/'
    pluginFilePath = pluginsPath+fileFullName
    pluginStr = mel.eval('getenv "MAYA_PLUG_IN_PATH";')+';'+pluginsPath
    mel.eval('putenv "MAYA_PLUG_IN_PATH" "%s";' % pluginStr)
    with open(filename,'a+') as f:
        state = True
        for line in f.readlines():
            if re.findall(fileFullName,line):
                state = False
        if state:
            f.write(r'evalDeferred("autoLoadPlugin(\"\", \"%s\", \"%s\")");' % (fileFullName,pluginName))

    if not cmds.pluginInfo( pluginFilePath, query=True, autoload=True):
        cmds.pluginInfo( pluginFilePath, edit=True, autoload=True)

    if not cmds.pluginInfo(pluginFilePath,query=True,loaded=True):
        cmds.loadPlugin(pluginFilePath)
Ejemplo n.º 24
0
def sourceMelFolderContents(path):
    '''
    source all mel files in a given folder
    '''
    for script in [f for f in os.listdir(path) if f.lower().endswith('.mel')]:
        log.info('Sourcing mel script : %s' % script)
        mel.eval('source %s' % script)
Ejemplo n.º 25
0
 def test_nameTooShort(self):
     class ShortFuncCls(object):
         def go(self):
             return 'Manitoba'
     self.wrapClass(ShortFuncCls, 'myShort')
     self.assertEqual(mel.eval('''myShort -goxx'''), 'Manitoba')
     self.assertEqual(mel.eval('''myShort -g'''), 'Manitoba')
Ejemplo n.º 26
0
def load():
    '''loads animation environment'''
    print "loading animation environment presets..."
    #set autoKey
    cmds.autoKeyframe( state=True )
    #set 24fps and playback on all viewports
    cmds.playbackOptions(ps=1.0, v='all')
    #set unlimited undo's
    cmds.undoInfo( state=True, infinity=True )
    #set manipulator sizes
    if lib.checkAboveVersion(2014):
        cmds.manipOptions( r=False, hs=55, ls=4, sph=1 )
    else:
        cmds.manipOptions( r=False, hs=55, ls=4 )
    #set framerate visibility
    mel.eval("setFrameRateVisibility(1);")
    #gimbal rotation
    cmds.manipRotateContext('Rotate', e=True, mode=2)
    #world translation
    cmds.manipMoveContext('Move', e=True, mode=2)
    #time slider height
    aPlayBackSliderPython = mel.eval('$tmpVar=$gPlayBackSlider')
    cmds.timeControl(aPlayBackSliderPython, h=45, e=True);
    #special tick color
    cmds.displayRGBColor("timeSliderTickDrawSpecial", 1,0.5,0)

    #check if hotkeys have been set
    if (cmds.hotkey( 't', ctl=True, query=True, name = True)== 'CharacterAnimationEditorNameCommand'):
        print "Hotkeys have been previously loaded"
    else:
        setHotkeys('default')

    print "ENVIRONMENT SET\n", #the comma forces output on the status line
Ejemplo n.º 27
0
def setup_scene(name=sys.argv[1]):
    # imports shirt, scales to fit, converts to ncloth
    try:
        cmds.loadPlugin("objExport")
    except:
        pass
    mel.eval('file -f -options "mo=1" -ignoreVersion -typ "OBJ" -o "%s";' \
         % name)
    try:
        mel.eval('rename "Mesh" "shirt";')
    except:
        pass
    # scale shirt to fit
    create_table()
    if (fold_num == 0):
        bbx = cmds.xform("shirt", q=True, bb=True, ws=True)
        s_x_len = abs(bbx[3] - bbx[0])
        s_y_len = abs(bbx[4] - bbx[1])
        global GLOBAL_SCALE
        if (s_x_len >= s_y_len):
            GLOBAL_SCALE = s_x_len/(SHIRT_SCALE * TABLE_SIZE)
        else:
            GLOBAL_SCALE = s_y_len/(SHIRT_SCALE * TABLE_SIZE)
        cmds.select("shirt")
        cmds.move(0, 0.0001, 0, relative = True)
    cmds.scale(GLOBAL_SCALE, GLOBAL_SCALE, GLOBAL_SCALE, "table", centerPivot = True)
    shirt_to_nCloth()
    create_camera()
Ejemplo n.º 28
0
def mkIngestionDir(source,type):
	mkFile = source
	filename =source.split("/")
	filename = filename[-1]
	mkSource =source.split("/")
	mkSource = mkSource[-1]
	mkSource = mkSource.replace( type, "" )
	mkFolder =source.split("/")
	mkFolder.pop(-1)
	mkFolder = "/".join(mkFolder)
	mkFolder=mkFolder+"/"+mkSource
	if os.path.exists( mkFolder ) == False:
		os.makedirs( mkFolder )
	copycmd = 'sysFile -copy'+' '+'"'+mkFolder+'/'+ filename +'"'+' ' + '"'+ mkFile+'"'+';'
	mel.eval (copycmd)
	dst = "Q:/Tools/Nearline/ingestion/3dModels"
	delcmd = 'sysFile -delete'+' "'+mkFile+'";'
	mel.eval (delcmd)
	createdirCmd = 'sysFile -makeDir'+' '+'"'+dst+'/' +mkSource+'/"'
	mel.eval(createdirCmd)
	cpyDepotCmd = 'sysFile -mov'+' '+'"'+dst+'/' +mkSource+'/'+filename +'"'+' ' + '"'+mkFolder+'/'+ filename +'"'+';'
	mel.eval (cpyDepotCmd)
	print "copied "+filename+" to depot"
	removeEmptydir = 'sysFile -removeEmptyDir'+' '+'"'+mkFolder+'/";'
	mel.eval (removeEmptydir)
	cmds.confirmDialog(m=filename+" ready for upload", cb = "cancel")
	return mkFolder
 def rigUpdate(self):
     #disable refresh until the rig update is complete
     cmds.refresh(su=True)
     rigNodeFound = False
     try:
         rigGuiNode = self.scene.sceneNodes["Rig"]
         rigNodeFound = True
     except KeyError:
         rigNodeFound = False
     if rigNodeFound:
         #kill all script jobs created by controllers to avoid
         #an update loop which the rig is updated
         for jobNum in self.scriptJobNumbers:
             if jobNum != globals.currentScriptJobNum:
                 cmds.scriptJob(k=jobNum)
         self.scriptJobNumbers = []
         rigGuiNode.updateVersion += 0.1
         rootElem = self.recursiveGetXML(rigGuiNode)
         self.indent(rootElem)
         tree = xml.ElementTree(rootElem)
         file = open(self.updateXmlPath, 'w')
         tree.write(file)
         file.close()
         self.recursiveZeroOutControllers(rigGuiNode)
         if rigGuiNode.metaNodeName is not None and rigGuiNode.metaNodeName != "":
             self.rootNodeName = mel.eval("updateMetaDataManager -n \""+rigGuiNode.metaNodeName+"\";")
         else:
             self.rootNodeName = mel.eval("loadRig -p \""+self.updateXmlPath+"\";")
         cmds.select(cl=True)
         self.recursiveUpdateMetaNodes(rigGuiNode,self.rootNodeName)
         self.recursiveSetupScriptJobs(rigGuiNode)
     cmds.refresh(su=False)
def open_scene(*args):
    '''    
    Function to open a new scene file and reload the tool
    '''
    mel.eval('OpenScene;')
    import threeDF_script
    threeDF_script.gui()
Ejemplo n.º 31
0
def performAlignObjects():
    cmds.perform
    mel.eval("performAlignObjects 0")
Ejemplo n.º 32
0
 def buildPose_ButtonCmd(self):
     mm.eval('shuaiBuildPose;')
Ejemplo n.º 33
0
 def poseDesigner_ButtonCmd(self):
     mm.eval('asPoserDesigner;')
    def __publish_obj(self, item, output, work_template, primary_publish_path,
                      sg_task, comment, thumbnail_path, progress_cb):
        """
        Export an OBJ geo file for the scene and publish it to Shotgun.

        :param item:                    The item to publish
        :param output:                  The output definition to publish with
        :param work_template:           The work template for the current scene
        :param primary_publish_path:    The path to the primary published file
        :param sg_task:                 The Shotgun task we are publishing for
        :param comment:                 The publish comment/description
        :param thumbnail_path:          The path to the publish thumbnail
        :param progress_cb:             A callback that can be used to report progress
        """
        # determine the publish info to use
        #
        progress_cb(10, "Determining publish details")

        # get the current scene path and extract fields from it
        # using the work template:
        scene_path = os.path.abspath(cmds.file(query=True, sn=True))
        fields = work_template.get_fields(scene_path)
        publish_version = fields["version"]
        tank_type = output["tank_type"]

        # create the publish path by applying the fields
        # with the publish template:
        publish_template = output["publish_template"]
        publish_path = publish_template.apply_fields(fields)

        # ensure the publish folder exists:
        publish_folder = os.path.dirname(publish_path)
        self.parent.ensure_folder_exists(publish_folder)

        # determine the publish name:
        publish_name = fields.get("name")
        if not publish_name:
            publish_name = os.path.basename(publish_path)

        # Find additional info from the scene:
        #
        progress_cb(20, "Analysing scene")

        # build the export command.
        obj_export_cmd = "file -force -es -pr -typ \"OBJexport\""
        obj_export_cmd += " -options \"groups=1;ptgroups=1;materials=0;smoothing=1;normals=1\""
        obj_export_cmd += " \"%s\"" % (publish_path.replace("\\", "/"))

        # ...and execute it:
        progress_cb(30, "Exporting OBJ file")
        try:
            self.parent.log_debug("Executing command: %s" % obj_export_cmd)

            # make sure plugin is loaded
            if not cmds.pluginInfo('objExport', query=True, loaded=True):
                cmds.loadPlugin('objExport')

            # clear selection, select what's in the set
            sel = cmds.ls(sl=True)
            set_contents = cmds.sets('publish_SET', q=True)
            cmds.select(clear=True)
            for obj in set_contents:
                cmds.select(obj, add=True)

            # do the actual export
            mel.eval(obj_export_cmd)

            # then restore the selection
            cmds.select(clear=True)
            for obj in sel:
                cmds.select(obj, add=True)

        except Exception, e:
            raise TankError("Failed to export OBJ file: %s" % e)
        # run the command:
        progress_cb(30, "Exporting GeoCache")
        try:
            # do it
            self.parent.log_debug("Executing command: aaPCGen.doExport(%s,%s,%s)"\
                                   % ( publish_path, frame_start, frame_end ) )
            aaPCGen.doExport(publish_path, frame_start, frame_end)
        except Exception, e:
            raise TankError("Failed to export GeoCache: %s" % e)

        geo_export_cmd = 'doCreateGeometryCache 6 {{ "0", "{}", "{}", "OneFile", "0", "{}/{}", "1", "", "0", "export", "0", "1", "1", "0", "1", "mcc", "1" }} ;'.format(
            frame_start, frame_end, geo_publish_path, namespace)
        try:
            # do it
            self.parent.log_debug("Executing command: " + geo_export_cmd)
            mel.eval(geo_export_cmd)
        except Exception, e:
            raise TankError("Failed to export GeoCache: %s" % e)

        # code will be the basename of path (017)
        # register the publish:
        progress_cb(75, "Registering the publish")
        args = {
            "tk": self.parent.tank,
            "context": self.parent.context,
            "comment": comment,
            "path": publish_path,
            "name": publish_name,
            "version_number": publish_version,
            "thumbnail_path": thumbnail_path,
            "task": sg_task,
Ejemplo n.º 36
0
def searchReplaceNames():
    mel.eval("performSearchReplaceNames 1")
Ejemplo n.º 37
0
def alignTool():
    mel.eval("setToolTo alignToolCtx")
Ejemplo n.º 38
0
def Obq_EnvironmentHelpURL():
	# Add the Obq_Shader docs URL to the Attribute Editor help menu
	ObqNodeType = 'Obq_Environment'
	ObqNodeHelpURL = 'https://github.com/madesjardins/Obq_Shaders/wiki/Obq_Environment'
	ObqHelpCommand = 'addAttributeEditorNodeHelp("' + ObqNodeType + '", "showHelp -absolute \\"' +ObqNodeHelpURL +'\\"");'
	mel.eval(ObqHelpCommand)
Ejemplo n.º 39
0
def reset_channels(nodes=None,
                   selectedChannels=False,
                   transformsOnly=False,
                   excludeChannels=None,
                   keyableOnly=False):
    '''
    Modified from Morgan Loomis' great reset call to expand options...
    '''
    gChannelBoxName = mel.eval('$temp=$gChannelBoxName')
    _reset = {}
    if not nodes:
        nodes = mc.ls(sl=True)
        if not nodes:
            return

    if excludeChannels:
        if not isinstance(excludeChannels, (list, tuple)):
            excludeChannels = [excludeChannels]

    chans = None
    if selectedChannels:
        chans = mc.channelBox(gChannelBoxName, query=True, sma=True)

    l_trans = [
        'translateX', 'translateY', 'translateZ', 'rotateX', 'rotateY',
        'rotateZ', 'scaleX', 'scaleY', 'scaleZ', 'tx', 'ty', 'yz', 'rx', 'ry',
        'rz', 'sx', 'sy', 'sz'
    ]

    for obj in nodes:
        #mObj = r9Meta.MetaClass(obj)

        attrs = chans
        if not chans:
            attrs = mc.listAttr(obj, keyable=True, unlocked=True)
            if excludeChannels:
                attrs = [x for x in attrs if x not in excludeChannels]

        if transformsOnly:
            attrs = [x for x in attrs if x in l_trans]
        if keyableOnly:
            attrs = [x for x in attrs if ATTR.is_keyable(obj, x)]

        d_defaults = {}
        for plug in ['defaultValues', 'transResets']:
            if ATTR.has_attr(obj, plug):
                d_defaults = getattr(r9Meta.MetaClass(obj), plug)

        if not attrs:
            log.warning("{0} resetAttrs | no attributes offered!".format(obj))
            continue
        for a in attrs:
            try:
                if transformsOnly is not None and transformsOnly:
                    if ATTR.get_nameLong(obj, a) not in l_trans:
                        continue
                dVal = d_defaults.get(a)
                if dVal is not None:
                    default = dVal
                else:
                    default = mc.attributeQuery(a, listDefault=True,
                                                node=obj)[0]
                ATTR.set(obj, a, default)
                _reset[a] = default
            except Exception, err:
                log.error("{0}.{1} resetAttrs | error: {2}".format(
                    obj, a, err))
Ejemplo n.º 40
0
def textureToGeometryOptions():
    mel.eval("""performTextureToGeom 1""")
Ejemplo n.º 41
0
def translatorOptions(parent, action, initialSettings, resultCallback):
    defaults = {
        "activeCamera": "<Current>",
        "exportAnim": False,
        "startFrame": 1,
        "endFrame": 100,
        "stepFrame": 1
    }

    createGlobalNodes()

    if initialSettings:
        logger.debug("Parsing initial translator settings %s" %
                     initialSettings)

        opts = initialSettings.split(";")
        for opt in opts:
            opt = opt.strip()

            if opt == "":
                continue

            name, value = opt.split("=")
            if name in defaults:
                if isinstance(defaults[name], basestring):
                    defaults[name] = value
                elif isinstance(defaults[name], bool):
                    defaults[name] = bool(value)
                elif isinstance(defaults[name], int):
                    defaults[name] = int(value)
                else:
                    logger.warning("Unhandled param %s in translator options" %
                                   name)

    if action == "post":
        mc.setParent(parent)
        mc.setUITemplate("DefaultTemplate", pushTemplate=True)
        mc.columnLayout(adj=True)

        mc.optionMenuGrp("as_exportOpts_activeCamera", label="Render camera")
        mc.menuItem(label='<Current>', divider=True)
        for camera in mc.ls(type='camera'):
            if mc.getAttr(camera + '.orthographic'):
                continue
            if not mc.getAttr(camera + ".renderable"):
                continue

            mc.menuItem(label=camera)

        mc.separator(style="single")

        def exportAnimChanged(value):
            mc.intSliderGrp("as_exportOpts_startFrame",
                            edit=True,
                            enable=value)

            mc.intSliderGrp("as_exportOpts_endFrame", edit=True, enable=value)

            mc.intSliderGrp("as_exportOpts_stepFrame", edit=True, enable=value)

        exportAnim = defaults["exportAnim"]
        mc.checkBoxGrp("as_exportOpts_exportAnim",
                       numberOfCheckBoxes=1,
                       label=" ",
                       label1="Animation",
                       cc=exportAnimChanged,
                       value1=exportAnim)

        mc.intSliderGrp("as_exportOpts_startFrame",
                        label="Start:",
                        field=True,
                        min=1,
                        max=1000,
                        enable=exportAnim,
                        value=defaults["startFrame"])

        mc.intSliderGrp("as_exportOpts_endFrame",
                        label="End:",
                        field=True,
                        min=1,
                        max=1000,
                        enable=exportAnim,
                        value=defaults["endFrame"])

        mc.intSliderGrp("as_exportOpts_stepFrame",
                        label="Step:",
                        field=True,
                        min=1,
                        max=100,
                        enable=exportAnim,
                        value=defaults["stepFrame"])

    elif action == "query":
        options = ""

        value = mc.optionMenuGrp("as_exportOpts_activeCamera",
                                 query=True,
                                 value=True)

        # Replace current by the active camera.
        if value == "<Current>":
            if om.MGlobal.mayaState() == om.MGlobal.kInteractive:
                camera = om.MDagPath()
                omui.M3dView.active3dView().getCamera(camera)

                if mc.getAttr(camera.partialPathName() + ".renderable"):
                    value = camera.partialPathName()
                else:
                    logger.warning("Active camera not renderable. Ignoring.")
                    value = ""
            else:
                logger.warning("Active camera specified for maya batch.")
                value = ""

        if value:
            options += "activeCamera=" + value + ";"

        exportAnim = mc.checkBoxGrp("as_exportOpts_exportAnim",
                                    query=True,
                                    value1=True)
        if exportAnim:
            options += "exportAnim=true;"

            value = mc.intSliderGrp("as_exportOpts_startFrame",
                                    query=True,
                                    value=True)
            options += "startFrame=" + str(value) + ";"

            value = mc.intSliderGrp("as_exportOpts_endFrame",
                                    query=True,
                                    value=True)
            options += "endFrame=" + str(value) + ";"

            value = mc.intSliderGrp("as_exportOpts_stepFrame",
                                    query=True,
                                    value=True)
            options += "stepFrame=" + str(value) + ";"

        logger.debug("calling translator callback, options = %s" % options)
        mel.eval('%s "%s"' % (resultCallback, options))
Ejemplo n.º 42
0
    def accept(self, settings, item):
        """
        Method called by the publisher to determine if an item is of any
        interest to this plugin. Only items matching the filters defined via the
        item_filters property will be presented to this method.

        A publish task will be generated for each item accepted here. Returns a
        dictionary with the following booleans:

            - accepted: Indicates if the plugin is interested in this value at
                all. Required.
            - enabled: If True, the plugin will be enabled in the UI, otherwise
                it will be disabled. Optional, True by default.
            - visible: If True, the plugin will be visible in the UI, otherwise
                it will be hidden. Optional, True by default.
            - checked: If True, the plugin will be checked in the UI, otherwise
                it will be unchecked. Optional, True by default.

        :param settings: Dictionary of Settings. The keys are strings, matching
            the keys returned in the settings property. The values are `Setting`
            instances.
        :param item: Item to process

        :returns: dictionary with boolean keys accepted, required and enabled
        """

        accepted = True
        publisher = self.parent
        template_name = settings["Publish Template"].value

        # ensure a work file template is available on the parent item
        work_template = item.parent.properties.get("work_template")
        if not work_template:
            self.logger.debug(
                "A work template is required for the session item in order to "
                "publish session geometry. Not accepting session geom item.")
            accepted = False

        # ensure the publish template is defined and valid and that we also have
        publish_template = publisher.get_template_by_name(template_name)
        if not publish_template:
            self.logger.debug(
                "The valid publish template could not be determined for the "
                "session geometry item. Not accepting the item.")
            accepted = False

        # we've validated the publish template. add it to the item properties
        # for use in subsequent methods
        item.properties["publish_template"] = publish_template

        # check that the AbcExport command is available!
        if not mel.eval("exists \"AbcExport\""):
            self.logger.debug(
                "Item not accepted because alembic export command 'AbcExport' "
                "is not available. Perhaps the plugin is not enabled?")
            accepted = False

        # because a publish template is configured, disable context change. This
        # is a temporary measure until the publisher handles context switching
        # natively.
        item.context_change_allowed = False

        return {"accepted": accepted, "checked": True}
Ejemplo n.º 43
0
 def mprint(cls, *args):
     """mel print command in case the python print command doesn't cut it"""
     # print r"""print (%s\\n);""" % pythonToMel( ' '.join( map( str, args)))
     _mm.eval(r"""print (%s);""" % pythonToMel(' '.join(map(str, args))) +
              '\n')
Ejemplo n.º 44
0
    def greate_controler(self, CON_shape, CON_color, parent_list, name):

        if CON_shape == 'circle':
            circle_NUL_list = []
            circle_CON_list = []

            for x in range(len(parent_list)):
                circle_CON = (mel.eval(
                    'circle -c 0 0 0 -nr 1 0 0 -sw 360 -r 2 -d 3 -ut 0 -tol 0.01 -s 8 -ch 0 -n "tail%s_CON" '
                    % (x + 1))[0])
                circle_CONShape = cmds.listRelatives(s=1)[0]
                cmds.setAttr(circle_CONShape + '.overrideEnabled', 1)
                cmds.setAttr(circle_CONShape + '.overrideColor', CON_color)
                circle_CON_list.append(circle_CON)

                cmds.group(n='tail%s_extra_NUL' % (x + 1))
                each_circle_NUL = cmds.group(n='tail%s_NUL' % (x + 1))
                circle_NUL_list.append(each_circle_NUL)
                cmds.delete(
                    cmds.parentConstraint(parent_list[x], each_circle_NUL))

            instance_circle_NUL_list = [] + circle_NUL_list
            instance_circle_CON_list = [] + circle_CON_list

            for x in range(len(parent_list) - 1):
                cmds.parent(instance_circle_NUL_list[-1],
                            instance_circle_CON_list[-2])
                del instance_circle_NUL_list[-1], instance_circle_CON_list[-1]

            return circle_NUL_list, circle_CON_list

        elif CON_shape == 'sphere':

            sphere_NUL_list = []
            sphere_CON_list = []

            for x in range(len(parent_list)):
                sphere_CON = mel.eval(
                    '''curve -d 1 -p 0 0 1 -p 0 0.5 0.866025 -p 0 0.866025 0.5 -p 0 1 0 -p 0 0.866025 -0.5 -p 0 0.5 -0.866025 -p 0 0 -1 -p 0 -0.5 -0.866025
                                                -p 0 -0.866025 -0.5 -p 0 -1 0 -p 0 -0.866025 0.5 -p 0 -0.5 0.866025 -p 0 0 1 -p 0.707107 0 0.707107 -p 1 0 0 -p 0.707107 0 -0.707107
                                                -p 0 0 -1 -p -0.707107 0 -0.707107 -p -1 0 0 -p -0.866025 0.5 0 -p -0.5 0.866025 0 -p 0 1 0 -p 0.5 0.866025 0 -p 0.866025 0.5 0 -p 1 0 0
                                                -p 0.866025 -0.5 0 -p 0.5 -0.866025 0 -p 0 -1 0 -p -0.5 -0.866025 0 -p -0.866025 -0.5 0 -p -1 0 0 -p -0.707107 0 0.707107 -p 0 0 1
                                                -k 0 -k 1 -k 2 -k 3 -k 4 -k 5 -k 6 -k 7 -k 8 -k 9 -k 10 -k 11 -k 12 -k 13 -k 14 -k 15 -k 16 -k 17 -k 18 -k 19 -k 20 -k 21 -k 22 -k 23 -k 24
                                                -k 25 -k 26 -k 27 -k 28 -k 29 -k 30 -k 31 -k 32 -n "tail%s_move_CON" '''
                    % (x + 1))

                sphere_CONShape = cmds.listRelatives(sphere_CON, s=1)[0]
                sphere_CONShape = cmds.rename(sphere_CONShape,
                                              sphere_CON + 'Shape')
                cmds.setAttr(sphere_CONShape + '.overrideEnabled', 1)
                cmds.setAttr(sphere_CONShape + '.overrideColor', CON_color)

                sphere_CON_list.append(sphere_CON)
                cmds.group(n='tail%s_move_extra_NUL' % (x + 1))
                each_sphere_NUL = cmds.group(n='tail%s_move_NUL' % (x + 1))
                sphere_NUL_list.append(each_sphere_NUL)

                cmds.delete(
                    cmds.parentConstraint(parent_list[x], each_sphere_NUL))

            return sphere_NUL_list, sphere_CON_list
Ejemplo n.º 45
0
 def trace(msg, showLineNumber=False):
     if showLineNumber:
         flags = ' -showLineNumber true '
     else:
         flags = ''
     _mm.eval("""trace %s %s""" % (flags, pythonToMel(msg)))
Ejemplo n.º 46
0
    def _eval(cls, cmd, commandName):
        # commandName is just used for nicer formatting of error messages,
        # and is used by MelCallable

        # should return a value, like _mm.eval
        # return _mm.eval( cmd )
        # get this before installing the callback
        undoState = _mc.undoInfo(q=1, state=1)
        lineNumbers = _mc.commandEcho(q=1, lineNumbers=1)
        _mc.commandEcho(lineNumbers=1)
        global errors
        errors = []  # a list to store each error line

        def errorCallback(nativeMsg, messageType, data):
            global errors
            if messageType == _api.MCommandMessage.kError:
                if nativeMsg:
                    errors += [nativeMsg]

        # setup the callback:
        # assigning ids to a list avoids the swig memory leak warning, which would scare a lot of people even though
        # it is harmless.  hoping we get a real solution to this so that we don't have to needlessly accumulate this data
        id = _api.MCommandMessage.addCommandOutputCallback(errorCallback, None)

        try:
            res = _api.MCommandResult()
            _api.MGlobal.executeCommand(cmd, res, False, undoState)
        except Exception:
            msg = '\n'.join(errors)

            if 'Cannot find procedure' in msg:
                e = MelUnknownProcedureError
            elif 'Wrong number of arguments' in msg:
                e = MelArgumentError
                if commandName:
                    # remove the calling proc, it will be added below
                    msg = msg.split('\n', 1)[1].lstrip()
            elif 'Cannot convert data' in msg or 'Cannot cast data' in msg:
                e = MelConversionError
            elif 'Syntax error' in msg:
                e = MelSyntaxError
            else:
                e = MelError
            message = "Error during execution of MEL script: %s" % (msg)
            fmtCmd = '\n'.join(['  ' + x for x in cmd.split('\n')])

            if commandName:
                if e is not MelUnknownProcedureError:
                    file = _mm.eval('whatIs "%s"' % commandName)
                    if file.startswith('Mel procedure found in: '):
                        file = 'file "%s"' % os.path.realpath(
                            file.split(':')[1].lstrip())
                    message += '\nCalling Procedure: %s, in %s' % (commandName,
                                                                   file)
                    message += '\n' + fmtCmd
            else:
                message += '\nScript:\n%s' % fmtCmd
            raise e, message
        else:
            resType = res.resultType()

            if resType == _api.MCommandResult.kInvalid:
                return
            elif resType == _api.MCommandResult.kInt:
                result = _api.SafeApiPtr('int')
                res.getResult(result())
                return result.get()
            elif resType == _api.MCommandResult.kIntArray:
                result = _api.MIntArray()
                res.getResult(result)
                return [result[i] for i in range(result.length())]
            elif resType == _api.MCommandResult.kDouble:
                result = _api.SafeApiPtr('double')
                res.getResult(result())
                return result.get()
            elif resType == _api.MCommandResult.kDoubleArray:
                result = _api.MDoubleArray()
                res.getResult(result)
                return [result[i] for i in range(result.length())]
            elif resType == _api.MCommandResult.kString:
                return res.stringResult()
            elif resType == _api.MCommandResult.kStringArray:
                result = []
                res.getResult(result)
                return result
            elif resType == _api.MCommandResult.kVector:
                result = _api.MVector()
                res.getResult(result)
                return datatypes.Vector(result)
            elif resType == _api.MCommandResult.kVectorArray:
                result = _api.MVectorArray()
                res.getResult(result)
                return [
                    datatypes.Vector(result[i]) for i in range(result.length())
                ]
            elif resType == _api.MCommandResult.kMatrix:
                result = _api.MMatrix()
                res.getResult(result)
                return datatypes.Matrix(result)
            elif resType == _api.MCommandResult.kMatrixArray:
                result = _api.MMatrixArray()
                res.getResult(result)
                return [
                    datatypes.Matrix(result[i]) for i in range(result.length())
                ]
        finally:
            _api.MMessage.removeCallback(id)
            _mc.commandEcho(lineNumbers=lineNumbers)
            # 8.5 fix
            if hasattr(id, 'disown'):
                id.disown()
Ejemplo n.º 47
0
"""
LOCATOR DELAY SYSTEM SHELF INSTALLER
"""
from maya import cmds
from maya import mel
import os, json, sys
import datetime as dt


def formatPath(path):
    path = path.replace("/", os.sep)
    path = path.replace("\\", os.sep)
    return path


mayaAppDir = formatPath(mel.eval('getenv MAYA_APP_DIR'))
scriptsDir = formatPath(mayaAppDir + os.sep + 'scripts')
projectDir = formatPath(scriptsDir + os.sep + 'BRSLocDelay')
userFile = formatPath(projectDir + os.sep + 'user')

# print ('mayaAppDir = ' + mayaAppDir)
# print ('scriptsDir = ' + scriptsDir)
# print ('projectDir = ' + projectDir)
# print ('userSetupFile = ' + userFile)
# mayaAppDir = C:\Users\TEST\Documents\maya
# scriptsDir = C:\Users\TEST\Documents\maya\scripts
# projectDir = C:\Users\TEST\Documents\maya\scripts\BRSLocDelay
# userSetupFile = C:\Users\TEST\Documents\maya\scripts\BRSLocDelay\user

# -------------
# CREATE USER
Ejemplo n.º 48
0
 def __setitem__(self, index, value):
     _mm.eval(self._setItemCmd % (index, pythonToMel(value)))
     super(MelGlobalArray, self).__setitem__(index, value)
Ejemplo n.º 49
0
	def setupControl(self,*args):
		#Load variables
		name = cmds.textFieldGrp(self.nameField,q=True,text=True)
		control = cmds.textFieldButtonGrp(self.controlField,q=True,text=True)
		rivet = cmds.textFieldButtonGrp(self.rivetField,q=True,text=True)
		constObj = cmds.textFieldButtonGrp(self.jointField,q=True,text=True)


		#Load selection
		verts = cmds.ls(sl=True,fl=True)

		#Create Cluster
		clusterName,clusterHandle = cmds.cluster(rel=True,n=name+'_clstr')

		#Delete Rivet's aim constraint because it causes flipping if the rivets lofted nurbs plane flips.
		#Add parent constraint to object.(constObj)
		"""
		try:
			temp = cmds.listConnections(rivet)
			cmds.delete(temp[1])
		except:
			# No constraint to delete on rivet
			pass
		"""
		#Rivet WS location
		rivetLocation = cmds.xform(rivet,q=True,ws=True,t=True)

		#Snap Cluster pivots to rivetLocation
		self.move(clusterHandle, rivetLocation,t=False,sp=True,rp=True)

		#Snap Controls pivots to rivetLocation
		self.move(control, rivetLocation,t=False,sp=True,rp=True)

		#Group Cluster
		clusterGrp = cmds.group(clusterHandle)
		clusterGrp = cmds.rename(clusterGrp, name + 'Cluster_' + clusterHandle)

		#Create over ride group
		or_grp = cmds.group(em=True,name=name+"OR1") 
		or2_grp = cmds.group(em=True,name=name+"OR2") 

		#Parent override group to rivet
		cmds.parent(or_grp,or2_grp)  
		cmds.parent(or2_grp,rivet)   

		#Freeze transforms on override group
		cmds.makeIdentity(or_grp,apply=True,t=True,r=True,s=True,n=True)

		#Zero Control
		zeroNode = cmds.group(em=True,n=name + "nullGrp")

		pos = cmds.xform( control, q=1, ws=True, t=1)
		cmds.xform( zeroNode, ws=True, t=[pos[0], pos[1], pos[2]]) 

		rot = cmds.xform( control, q=1, ws=True, ro=1)
		cmds.xform( zeroNode, ws=True, ro=[rot[0], rot[1], rot[2]]) 

		scale = cmds.xform( control, q=1, r=1, s=1)
		cmds.xform( zeroNode, ws=True, s=[scale[0], scale[1], scale[2]])		

		#Snap zeroNode pivot to control
		controlLocation = cmds.xform(control,q=True,ws=True,rp=True)
		self.move(zeroNode, controlLocation, t=False, sp=True, rp=True)

		#parent control to OverRide group
		cmds.parent(control, zeroNode, a=True)		
		cmds.parent(zeroNode,or_grp)

		#Connect control t,r,s to cluster, then hide the cluster and rivet group 
		cmds.connectAttr(control + ".translate", clusterHandle + ".translate")
		cmds.connectAttr(control + ".rotate", clusterHandle + ".rotate")
		cmds.connectAttr(control + ".scale", clusterHandle + ".scale")		

		#Create utility node and negate double transform
		#by reversing the transformation of or_grp <---- Cause of double transforms
		mdNode = cmds.createNode("multiplyDivide")
		nodeName = name + "_MD"
		cmds.rename(mdNode,nodeName)
		mdNode = nodeName

		#Unparent control
		cmds.parent(zeroNode,w=True)

		#Set up the MD node
		cmds.setAttr( "%s.input2X"%mdNode, -1)
		cmds.setAttr( "%s.input2Y"%mdNode, -1)
		cmds.setAttr( "%s.input2Z"%mdNode, -1)

		#Connect the nodes
		# control ---> mdNode
		cmds.connectAttr("%s.translateX"%control,"%s.input1X"%mdNode,f=True)
		cmds.connectAttr("%s.translateY"%control,"%s.input1Y"%mdNode,f=True)
		cmds.connectAttr("%s.translateZ"%control,"%s.input1Z"%mdNode,f=True)

		#mdNode ---> or_grp
		cmds.connectAttr("%s.outputX"%mdNode,"%s.translateX"%or_grp,f=True)
		cmds.connectAttr("%s.outputY"%mdNode,"%s.translateY"%or_grp,f=True)
		cmds.connectAttr("%s.outputZ"%mdNode,"%s.translateZ"%or_grp,f=True)

		#Reparent control
		cmds.parent(zeroNode,or_grp)

		#Get mesh name 
		# ex. "meshName.vtx[35]"
		mesh = verts[0].split('.')[0]

		#Get meshDeformer
		meshDeformer = None
		try:
			meshDeformer = mel.eval('findRelatedSkinCluster("%s");'%mesh)
		except:
			pass
		"""
		history = cmds.listHistory(mesh)  
		for each in history:
			#print " History: " + each
			if("skinCluster" in str(each)):
				#Possible match for meshDeformer
				if("Group" not in str(each)):
					meshDeformer = each
			if("cMuscleSystem" in str(each)):
				if("Group" not in str(each)):
					meshDeformer = each
		"""
		#Reorder deformer nodes
		if meshDeformer:
			#Move cluster + meshDeformer to top of deformer stack
			cmds.reorderDeformers(clusterHandle,meshDeformer,mesh)

			#Move meshDeformer to top of deformer stack
			cmds.reorderDeformers(meshDeformer,clusterHandle,mesh)

		#Create final group
		topGrp = cmds.group(em=True,name=name+"_followCnt_grp")
		cmds.parent(clusterGrp,rivet,topGrp)

		#Orient constrain rivet to constrain object
		if constObj:
			cmds.orientConstraint(constObj,rivet,mo=True)

		#Hide cluster grp
		cmds.setAttr(clusterGrp + ".visibility",0) 

		#Hide the rivet
		rivetShape = cmds.listRelatives(rivet,shapes=True)
		cmds.setAttr(rivetShape[0] + ".visibility",0)
		
		# Add cluster atttribute to control
		cmds.addAttr(control,ln='cluster',min=0.0,max=1.0,dv=1.0)
		cmds.setAttr('%s.cluster'%control,l=False,k=True)
		
		# Connect it to the deformer
		cmds.connectAttr('%s.cluster'%control,'%s.envelope'%clusterName,f=True)

		#Clear selection
		cmds.select(clear=True)
Ejemplo n.º 50
0
 def warning(msg, showLineNumber=False):
     if showLineNumber:
         flags = ' -showLineNumber true '
     else:
         flags = ''
     _mm.eval("""warning %s %s""" % (flags, pythonToMel(msg)))
Ejemplo n.º 51
0
def export_animation_into_fbx(
    root_node_name,
    save_dir='./',
    save_filename='',
    start_time=0,
    end_time=240
):
    """Export animation of a node into .fbx file.

    Args:
        root_node_name: str
            Name of root joint.
        save_dir: str
            Directory to save .fbx files.
        save_filename: str
            Video filename. The full file path is : {save_dir}/{save_filename}
        start_time: int
            Start frame of animation
        end_time: int
            End frame of animation

    Returns: 
        None.
    """
    pprint("===> root_node_name: {}".format(root_node_name))
    pprint("===> save_dir: {}".format(save_dir))

    if not osp.exists(save_dir):
        os.makedirs(save_dir)

    scene_name = get_current_scene_name()
    if not save_filename:
        save_filename = '{}.animation.{}.fbx'.format(
            scene_name, root_node_name.replace(':', '-'))
    elif not save_filename.endswith('.fbx'):
        save_filename += '.fbx'

    output_filename = osp.join(save_dir, save_filename)

    pprint("===> output file: {}".format(output_filename))

    # num_frames = cmds.keyframe(root_node_name, q=True, keyframeCount=True) / 6
    # num_frames = get_keyframe_count(root_node_name)
    # pprint('===> {} keyframes in total'.format(num_frames))

    pprint('===> start_time: {}'.format(start_time))
    pprint('===> end_time: {}'.format(end_time))

    cmds.currentTime(0)
    cmds.select(root_node_name, replace=True)

    # mel.eval('FBXExportAnimationOnly -v true;')
    # mel.eval('FBXExportBakeComplexAnimation -v true;')
    # mel.eval('FBXExportBakeComplexStart -v 0;')
    # mel.eval('FBXExportBakeComplexEnd -v {};'.format(num_frames))
    # mel.eval('FBXExportBakeComplexStep -v 1;')
    # mel.eval('FBXExport -f "{}" -s;'.format(output_filename))

    # cmd_str = """
    #     FBXExportAnimationOnly -v true;
    #     FBXExportBakeComplexAnimation -v true;
    #     FBXExportBakeComplexStart -v 0;
    #     FBXExportBakeComplexEnd -v {};
    #     FBXExportBakeComplexStep -v 1;
    #     FBXExport -f "{}" -s;
    # """.format(num_frames, output_filename)

    # pprint('===> run command: ')
    # pprint(cmd_str)
    # mel.eval(cmd_str)

    cmd_str = 'FBXExportAnimationOnly -v true;'
    pprint('===> run command: ')
    pprint(cmd_str)
    mel.eval(cmd_str)

    cmd_str = 'FBXExportBakeComplexAnimation - v true;'
    pprint('===> run command: ')
    pprint(cmd_str)
    mel.eval(cmd_str)

    cmd_str = 'FBXExportBakeComplexStart - v {};'.format(start_time)
    pprint('===> run command: ')
    pprint(cmd_str)
    mel.eval(cmd_str)

    cmd_str = 'FBXExportBakeComplexEnd -v {};'.format(end_time)
    pprint('===> run command: ')
    pprint(cmd_str)
    mel.eval(cmd_str)

    cmd_str = 'FBXExportBakeComplexStep - v 1;'
    pprint('===> run command: ')
    pprint(cmd_str)
    mel.eval(cmd_str)

    cmd_str = 'FBXExport -f "{}" -s;'.format(output_filename)
    pprint('===> run command: ')
    pprint(cmd_str)
    mel.eval(cmd_str)

    output_filename = osp.abspath(output_filename)
    pprint("===> full path of output file: {}".format(output_filename))

    return output_filename
Ejemplo n.º 52
0
	def createController(self,name):
		"""
		Creates controller curve at origin.
		"""
		cnt = mel.eval('createNode transform -n "%s";\n'%name+\
		               'setAttr ".ove" yes;\n'+\
		               'setAttr ".ovc" 15;\n'+\
		               'createNode nurbsCurve -n "%sShape" -p "%s";\n'%(name,name)+\
		               'setAttr -k off ".v";\n'+\
		               'setAttr ".cc" -type "nurbsCurve" \n'+\
		               '1 52 0 no 3 \n'+\
		               '53 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 \n'+\
		               ' 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 \n'+\
		               '53 \n'+\
		               '0 0.074400512458903195 0 \n'+\
		               '0 0.068737145450531487 0.028471811309310452 \n'+\
		               '0 0.052609123163277663 0.052609123163277663 \n'+\
		               '0 0.028471811309310452 0.068737145450531487 \n'+\
		               '0 0 0.074400512458903195 \n'+\
		               '0 -0.028471811309310452 0.068737145450531487 \n'+\
		               '0 -0.052609123163277663 0.052609123163277663 \n'+\
		               '0 -0.068737145450531487 0.028471811309310452 \n'+\
		               '0 -0.074400512458903195 0 \n'+\
		               '0 -0.068737145450531487 -0.028471811309310452 \n'+\
		               '0 -0.052609123163277663 -0.052609123163277663 \n'+\
		               '0 -0.028471811309310452 -0.068737145450531487 \n'+\
		               '0 0 -0.074400512458903195 \n'+\
		               '0 0.028471811309310452 -0.068737145450531487 \n'+\
		               '0 0.052609123163277663 -0.052609123163277663 \n'+\
		               '0 0.068737145450531487 -0.028471811309310452 \n'+\
		               '0 0.074400512458903195 0 \n'+\
		               '0.028471811309310452 0.068737145450531487 0 \n'+\
		               '0.052609123163277663 0.052609123163277663 0 \n'+\
		               '0.068737145450531487 0.028471811309310452 0 \n'+\
		               '0.074400512458903195 0 0 \n'+\
		               '0.068737145450531487 -0.028471811309310452 0 \n'+\
		               '0.052609123163277663 -0.052609123163277663 0 \n'+\
		               '0.028471811309310452 -0.068737145450531487 0 \n'+\
		               '0 -0.074400512458903195 0 \n'+\
		               '-0.028471811309310452 -0.068737145450531487 0 \n'+\
		               '-0.052609123163277663 -0.052609123163277663 0 \n'+\
		               '-0.068737145450531487 -0.028471811309310452 0 \n'+\
		               '-0.074400512458903195 0 0 \n'+\
		               '-0.068737145450531487 0.028471811309310452 0 \n'+\
		               '-0.052609123163277663 0.052609123163277663 0 \n'+\
		               '-0.028471811309310452 0.068737145450531487 0 \n'+\
		               '0 0.074400512458903195 0 \n'+\
		               '0 0.068737145450531487 -0.028471811309310452 \n'+\
		               '0 0.052609123163277663 -0.052609123163277663 \n'+\
		               '0 0.028471811309310452 -0.068737145450531487 \n'+\
		               '0 0 -0.074400512458903195 \n'+\
		               '-0.028471811309310452 0 -0.068737145450531487 \n'+\
		               '-0.052609123163277663 0 -0.052609123163277663 \n'+\
		               '-0.068737145450531487 0 -0.028471811309310452 \n'+\
		               '-0.074400512458903195 0 0 \n'+\
		               '-0.068737145450531487 0 0.028471811309310452 \n'+\
		               '-0.052609123163277663 0 0.052609123163277663 \n'+\
		               '-0.028471811309310452 0 0.068737145450531487 \n'+\
		               '0 0 0.074400512458903195 \n'+\
		               '0.028471811309310452 0 0.068737145450531487 \n'+\
		               '0.052609123163277663 0 0.052609123163277663 \n'+\
		               '0.068737145450531487 0 0.028471811309310452 \n'+\
		               '0.074400512458903195 0 0 \n'+\
		               '0.068737145450531487 0 -0.028471811309310452 \n'+\
		               '0.052609123163277663 0 -0.052609123163277663 \n'+\
		               '0.028471811309310452 0 -0.068737145450531487 \n'+\
		               '0 0 -0.074400512458903195 \n'+\
		               ';')
Ejemplo n.º 53
0
                             DsAttractDeformer.MAYAVERSION)
    try:
        plugin.registerNode(DsAttractDeformer.NODENAME,
                            DsAttractDeformer.NODEID,
                            DsAttractDeformer.creator,
                            DsAttractDeformer.initialize,
                            ommpx.MPxNode.kDeformerNode)
    except RuntimeError:
        sys.stderr.write('Failed to register node: {0}'.format(
            DsAttractDeformer.NODENAME))


aeTemplate = open(
    os.path.join(DsAttractDeformer.MAYA_APP_DIR,
                 'scripts\dsNodes\dsAttractDeformer\plugins\AEtemplate.mel'),
    "r").read()
mel.eval(aeTemplate)
mel.eval("refreshEditorTemplates; refreshAE;")
mel.eval(
    'makePaintable -attrType "multiFloat" -sm "deformer" "dsAttract" "weights";'
)


def uninitializePlugin(obj):
    plugin = ommpx.MFnPlugin(obj)
    try:
        plugin.deregisterNode(DsAttractDeformer.NODEID)
    except Exception as err:
        sys.stderr.write('Failed to deregister node: {0}{1}'.format(
            (DsAttractDeformer.NODENAME, err)))
Ejemplo n.º 54
0
    def __init__(self, name, start, end, up, **kwds):

        rigGrp = ''
        if cmds.objExists('rig_GRP'):
            rigGrp = 'rig_GRP'

        parent = 'stretchyJoints_GRP'
        if not cmds.objExists(parent):
            parent = rig_transform(0, name='stretchyJoints',
                                   parent=rigGrp).object

        self.topGrp = rig_transform(0, name=name + 'Stretchy',
                                    parent=parent).object

        jntStart = rig_transform(0,
                                 name=name + 'JntStartTmp',
                                 type='joint',
                                 target=start).object
        jntEnd = rig_transform(0,
                               name=name + 'JntEndTmp',
                               type='joint',
                               target=end,
                               parent=jntStart).object
        cmds.joint(jntStart, e=True, oj='xzy', sao='zup', ch=True, zso=True)

        pm.setAttr(jntEnd + '.jointOrientX', 0)
        pm.setAttr(jntEnd + '.jointOrientY', 0)
        pm.setAttr(jntEnd + '.jointOrientZ', 0)

        self.startOffset = rig_transform(0,
                                         name=name + 'DrvStartOffset',
                                         parent=self.topGrp,
                                         target=jntStart).object
        self.start = rig_transform(0,
                                   name=name + 'DrvStart',
                                   type='locator',
                                   parent=self.startOffset,
                                   target=self.startOffset).object
        startLoc = rig_transform(0,
                                 name=name + 'StartStretchy',
                                 type='locator',
                                 parent=self.topGrp,
                                 target=jntStart).object

        self.endOffset = rig_transform(0,
                                       name=name + 'DrvEndOffset',
                                       parent=self.topGrp,
                                       target=jntEnd).object
        self.end = rig_transform(0,
                                 name=name + 'DrvEnd',
                                 type='locator',
                                 parent=self.endOffset,
                                 target=self.endOffset).object
        endLoc = rig_transform(0,
                               name=name + 'EndStretchy',
                               type='locator',
                               parent=self.topGrp,
                               target=jntEnd).object

        self.upOffset = rig_transform(0,
                                      name=name + 'DrvUpOffset',
                                      parent=self.topGrp,
                                      target=up).object

        pm.delete(jntStart, jntEnd)

        partsGrp = mm.eval('rig_makePiston("' + startLoc + '", "' + endLoc +
                           '", "' + name + 'StretchyParts");')

        pm.hide(partsGrp)

        pm.delete(pm.parentConstraint(self.upOffset, endLoc + 'Up'))
        pm.parent(endLoc + 'Up', self.upOffset)
        self.up = name + 'DrvUp_LOC'
        pm.rename(endLoc + 'Up', name + 'DrvUp_LOC')

        self.startJnt = startLoc.replace('_LOC', '_JNT')
        endJnt = endLoc.replace('_LOC', '_JNT')

        pm.parent(endJnt, self.startJnt)
        pm.parent(self.startJnt, self.topGrp)
        pm.parentConstraint(startLoc + 'Aim', self.startJnt, mo=True)
        pm.delete(startLoc + 'Up', endLoc, startLoc)

        pm.parentConstraint(self.start, startLoc + 'AimOffset', mo=True)
        pm.parentConstraint(self.end, endLoc + 'AimOffset', mo=True)
        pm.parentConstraint(self.start, self.upOffset, mo=True)

        pm.parent(partsGrp, self.topGrp)

        measure = rig_measure(name=name + 'Dist',
                              start=self.start,
                              end=self.end,
                              parent=partsGrp)

        # make pin feature

        #pm.connectAttr( measure.distance.globalOriginalPercent, self.startJnt+'.scaleX' )

        self.startJnt = pm.PyNode(self.startJnt)
        pm.addAttr(self.startJnt,
                   longName='stretch',
                   at='float',
                   k=True,
                   dv=1,
                   min=0,
                   max=1)
        #self.startJnt.stretch.set(cb=True)

        bldColor = pm.shadingNode('blendColors',
                                  asUtility=True,
                                  name=name + '_blendStretch')

        pm.connectAttr(measure.distance.globalOriginalPercent,
                       bldColor + '.color1R',
                       f=True)  # connect ik jnt to color
        pm.setAttr(bldColor + '.color2R', 1)
        pm.connectAttr(bldColor + '.outputR',
                       self.startJnt + '.scaleX',
                       f=True)  # connect bldColor output to bind jnt

        pm.connectAttr(self.startJnt.stretch, bldColor.blender)

        # bulge
        pm.addAttr(self.startJnt, longName='bulge', at='float', k=True, dv=1)
        bulge_PM = plusMinusNode(name + 'Bulge_plusMinus', 'subtract', '', 2,
                                 self.startJnt, 'scaleX')
        bldColorBulge = pm.shadingNode('blendColors',
                                       asUtility=True,
                                       name=name + '_blendBulge')
        pm.connectAttr(bulge_PM + '.output1D',
                       bldColorBulge + '.color1R',
                       f=True)
        pm.setAttr(bldColorBulge + '.color2R', 1)
        pm.connectAttr(bldColorBulge + '.outputR',
                       self.startJnt + '.scaleY',
                       f=True)
        pm.connectAttr(bldColorBulge + '.outputR',
                       self.startJnt + '.scaleZ',
                       f=True)
        pm.connectAttr(self.startJnt.bulge, bldColorBulge.blender)
Ejemplo n.º 55
0
def SetFbxParameter():
    if not pm.pluginInfo('fbxmaya', q=True, loaded=True):
        pm.loadPlugin('fbxmaya')
    mel.eval('FBXResetExport')
    mel.eval('FBXExportFileVersion -v FBX201600')
    mel.eval('FBXExportUpAxis y')
    mel.eval('FBXExportShapes  -v false')
    mel.eval('FBXExportScaleFactor 1.0')
    mel.eval('FBXExportInAscii -v true')
    mel.eval('FBXExportConstraints -v false')
    mel.eval('FBXExportLights -v false')
    mel.eval('FBXExportSkins -v false')
    mel.eval('FBXExportSmoothingGroups -v true')
    mel.eval('FBXExportSmoothMesh -v true')
    mel.eval('FBXExportEmbeddedTextures -v false')
    mel.eval('FBXExportCameras -v false')
    mel.eval('FBXExportBakeResampleAnimation -v false')
    mel.eval('FBXExportSkeletonDefinitions -v false')
Ejemplo n.º 56
0
class DsAttractDeformer(ommpx.MPxDeformerNode):

    VENDOR = 'Dmitrii Shevchenko'
    VERSION = '1.0'
    MAYAVERSION = '2020'
    NODENAME = 'dsAttract'
    NODEID = om.MTypeId(0x09113)
    MAYA_APP_DIR = mel.eval('getenv ("MAYA_APP_DIR")')

    MAX_ANGLE = 0.5 * 3.14159265  #90 degrees

    def __init__(self):
        super(DsAttractDeformer, self).__init__()

    def deform(self, pDataBlock, geoIter, worldMatrix, multiIndex):
        thisNode = self.thisMObject()

        ## GET DATA
        envelope = pDataBlock.inputValue(self.envelope).asFloat()
        if envelope == 0:
            return

        suspendWarnings = pDataBlock.inputValue(self.aWarnings).asBool()

        maxDistanceUv = om.MRampAttribute(thisNode, self.aMaxDistanceUV)
        falloff = om.MRampAttribute(thisNode, self.aFalloff)

        projectOnNormal = pDataBlock.inputValue(
            self.aProjectOnNormal).asFloat()
        if (projectOnNormal):
            # aNormalDirectionLimit
            normalDirectionLimit = pDataBlock.inputValue(
                self.aNormalDirectionLimit).asShort()
            # inputGeom
            hInput = pDataBlock.outputArrayValue(self.input)
            hInput.jumpToElement(multiIndex)
            hInputGeom = hInput.outputValue().child(self.inputGeom)
            oInputGeom = hInputGeom.asMesh()
            mfInputGeom = om.MFnMesh(oInputGeom)

        maxDistance = pDataBlock.inputValue(self.maxDistance).asFloat()
        if maxDistance == 0:
            return

        inputMatrix = pDataBlock.inputValue(self.aInputMatrix).asMatrix()
        plugInputMatrix = om.MPlug(thisNode, self.aInputMatrix)
        if not plugInputMatrix.isConnected():
            if not suspendWarnings:
                self.warning(thisNode,
                             "Missing incoming connection to InputMatrix")
            return

        dhInputShape = pDataBlock.inputValue(self.inputShape)
        dagNodeFn = self.getConnectedDagNode(self.inputShape)
        if not dagNodeFn:
            if not suspendWarnings:
                self.warning(thisNode,
                             "Missing incoming connection to InputShape")
            return

        ##GET INPUT SHAPE TYPE
        inputShapeType = None
        targetFn = None
        if dhInputShape.type() == om.MFnNurbsCurveData.kNurbsCurve:
            inputShapeType = "curve"
            targetFn = om.MFnNurbsCurve(dagNodeFn)
        elif dhInputShape.type() == om.MFnNurbsCurveData.kNurbsSurface:
            inputShapeType = "nurbs"
            targetFn = om.MFnNurbsSurface(dagNodeFn)

        ## LOOP VARIABLES
        d_util = om.MScriptUtil()
        d_util.createFromDouble(0.0)
        d_ptr = d_util.asDoublePtr()

        f_util = om.MScriptUtil()
        f_util.createFromDouble(0.0)
        f_ptr = f_util.asFloatPtr()

        f2_util = om.MScriptUtil()
        f2_util.createFromList([0.0, 0.0], 2)
        f2_util = f2_util.asFloat2Ptr()

        loopPoint = om.MPoint()
        loopVec = om.MVector()

        matrixInverse = worldMatrix.inverse()
        paAllpoints = om.MPointArray()
        geoIter.allPositions(paAllpoints)

        ## DEFORM
        count = 0
        while not geoIter.isDone():
            iterIndex = geoIter.index()
            #current point
            pt = geoIter.position()
            #get painted weight
            wPt = self.weightValue(pDataBlock, multiIndex, iterIndex)
            if (wPt == 0.0):
                count += 1
                geoIter.next()
                continue
            #set point to world space
            pt *= worldMatrix

            ## GET CLOSEST POINT
            closePt = None
            dUvalue = None
            if inputShapeType == "curve":
                closePt = targetFn.closestPoint(pt, d_ptr, 0.00001,
                                                om.MSpace.kWorld)
                dUvalue = om.MScriptUtil.getDouble(d_ptr)
            elif inputShapeType == "nurbs":
                closePt = targetFn.closestPoint(pt, d_ptr, None, False,
                                                0.00001, om.MSpace.kWorld)
                dUvalue = om.MScriptUtil.getDouble(d_ptr)

            #Make it a local vector for the vertex
            vecMove = closePt - pt
            #Adjust max distance
            maxDistanceUv.getValueAtPosition(dUvalue, f_ptr)
            maxDistLocal = maxDistance * om.MScriptUtil.getFloat(f_ptr)
            #Check if vertex is in range
            if vecMove.length() < maxDistLocal:
                #Adjust with falloff
                dPercent = vecMove.length() / maxDistLocal
                falloff.getValueAtPosition(float(1.0 - dPercent), f_ptr)
                valueFalloff = om.MScriptUtil.getFloat(f_ptr)
                vecMove *= valueFalloff
                #Adjust with vertex normal
                if projectOnNormal:
                    mfInputGeom.getVertexNormal(iterIndex, loopVec,
                                                om.MSpace.kWorld)
                    #normalize
                    loopVec.normalize()
                    #project move vector on normal
                    dVecDotProduct = vecMove * loopVec
                    loopVec *= dVecDotProduct
                    if normalDirectionLimit == 1 and dVecDotProduct <= 0:
                        #only positive
                        loopVec *= 0
                    elif normalDirectionLimit == 2 and dVecDotProduct > 0:
                        #only negative
                        loopVec *= 0
                    #blend
                    vecMove = vecMove * (
                        1 - projectOnNormal) + loopVec * projectOnNormal

                #Adjust with envelope and painted value
                vecMove *= envelope * wPt
                pt += vecMove
                #back to object space
                pt *= matrixInverse
                #save point positions
                paAllpoints.set(pt, count)

            count += 1
            geoIter.next()

        geoIter.setAllPositions(paAllpoints)

    def getConnectedDagNode(self, attrArg):
        plugArg = om.MPlug(self.thisMObject(), attrArg)
        dagPath = om.MDagPath()
        if (plugArg.isConnected()):
            plugArr = om.MPlugArray()
            plugArg.connectedTo(plugArr, True, False)
            plugDag = om.MPlug(plugArr[0])
            oDagNode = plugDag.node()
            fnDagNode = om.MFnDagNode(oDagNode)
            fnDagNode.getPath(dagPath)
            return dagPath
        else:
            return None

    def warning(self, thisNode_arg, msg_arg):
        fnThis = om.MFnDependencyNode(thisNode_arg)
        nameThis = fnThis.name()
        om.MGlobal.displayWarning("{0}: {1}".format(nameThis, msg_arg))

    def accessoryNodeSetup(self, cmd):
        thisNode = self.thisMObject()
        # aFalloff
        hFalloff = om.MRampAttribute(thisNode, self.aFalloff)

        a1 = om.MFloatArray()  # positions
        b1 = om.MFloatArray()  # values
        c1 = om.MIntArray()  # interpolations

        a1.append(float(0.0))
        a1.append(float(1.0))

        b1.append(float(0.0))
        b1.append(float(1.0))

        c1.append(om.MRampAttribute.kSmooth)
        c1.append(om.MRampAttribute.kSmooth)

        hFalloff.addEntries(a1, b1, c1)

        # aMaxDistanceUv
        hMaxDistUv = om.MRampAttribute(thisNode, self.aMaxDistanceUV)

        as1 = om.MFloatArray()  # positions
        bs1 = om.MFloatArray()  # values
        cs1 = om.MIntArray()  # interpolations

        as1.append(float(0.5))
        bs1.append(float(1.0))
        cs1.append(om.MRampAttribute.kSmooth)

        hMaxDistUv.addEntries(as1, bs1, cs1)

    @classmethod
    def creator(cls):
        return DsAttractDeformer()

    @classmethod
    def initialize(cls):
        numericFn = om.MFnNumericAttribute()
        genericFn = om.MFnGenericAttribute()
        matrixFn = om.MFnMatrixAttribute()
        rampFn = om.MRampAttribute()
        enumFn = om.MFnEnumAttribute()

        cls.maxDistance = numericFn.create("maximumDistance", "maxDist",
                                           om.MFnNumericData.kFloat, 1.0)
        numericFn.setKeyable(True)
        numericFn.setMin(0.0)
        numericFn.setMax(50.0)

        cls.aProjectOnNormal = numericFn.create("projectOnNormal",
                                                "projectOnNormal",
                                                om.MFnNumericData.kFloat, 0.0)
        numericFn.setKeyable(True)
        numericFn.setMin(0.0)
        numericFn.setMax(1.0)

        cls.aWarnings = numericFn.create("suspendWarnings", "suspendWarnings",
                                         om.MFnNumericData.kBoolean, 0)
        numericFn.setChannelBox(True)

        cls.inputShape = genericFn.create("inputShape", "inputShape")
        genericFn.setReadable(False)
        genericFn.addDataAccept(om.MFnNurbsCurveData.kNurbsCurve)
        genericFn.addDataAccept(om.MFnNurbsCurveData.kNurbsSurface)

        cls.aInputMatrix = matrixFn.create("inputMatrix", "inputMatrix")
        matrixFn.setReadable(False)

        cls.aMaxDistanceUV = rampFn.createCurveRamp("maxDistanceUv",
                                                    "maxDistanceUv")
        cls.aFalloff = rampFn.createCurveRamp("falloff", "falloff")

        cls.aNormalDirectionLimit = enumFn.create("normalDirectionLimit",
                                                  "normalDirectionLimit", 0)
        enumFn.setKeyable(True)
        enumFn.addField("off", 0)
        enumFn.addField("Only positive", 1)
        enumFn.addField("Only negative", 2)

        cls.addAttribute(cls.maxDistance)
        cls.addAttribute(cls.inputShape)
        cls.addAttribute(cls.aInputMatrix)
        cls.addAttribute(cls.aMaxDistanceUV)
        cls.addAttribute(cls.aFalloff)
        cls.addAttribute(cls.aProjectOnNormal)
        cls.addAttribute(cls.aWarnings)
        cls.addAttribute(cls.aNormalDirectionLimit)

        outputGeom = ommpx.cvar.MPxGeometryFilter_outputGeom
        cls.attributeAffects(cls.maxDistance, outputGeom)
        cls.attributeAffects(cls.inputShape, outputGeom)
        cls.attributeAffects(cls.aInputMatrix, outputGeom)
        cls.attributeAffects(cls.aMaxDistanceUV, outputGeom)
        cls.attributeAffects(cls.aFalloff, outputGeom)
        cls.attributeAffects(cls.aProjectOnNormal, outputGeom)
        cls.attributeAffects(cls.aNormalDirectionLimit, outputGeom)
Ejemplo n.º 57
0
        def process_keyframe_animation_btn(*args):  # 377
            reinit_vars()
            #
            with Undo():
                for selected in cm.ls(sl=1):
                    if check_model(selected):
                        self.static_base_meshes.append(selected)

                # >>>> added by Hiura
                bCanceled = False
                if len(self.static_base_meshes) > 0:
                    for one_mesh in self.static_base_meshes:
                        time = 0

                        tmp_node = cm.snapshot(one_mesh,
                                               st=time,
                                               et=time,
                                               ch=0)
                        tmp_snap = cm.listRelatives(tmp_node, c=1)[0]
                        tmp_snap = cm.parent(tmp_snap, w=1)

                        cm.polySoftEdge(tmp_snap, a=180, ch=0)
                        cm.polyTriangulate(tmp_snap, ch=0)
                        org_num = get_vert_count(one_mesh)
                        new_num = get_vert_count(tmp_snap)
                        if org_num != new_num:
                            buf = 'Warning! Vertex Number Change.\n  original=' + str(
                                org_num
                            ) + ' new=' + str(
                                new_num
                            ) + '\n\nMaybe not working properly.\nContinue?'
                            ret = cm.confirmDialog(title='Confirm',
                                                   message=buf,
                                                   button=['Yes', 'No'],
                                                   defaultButton='Yes',
                                                   cancelButton='No',
                                                   dismissString='No')
                            if ret != 'Yes':
                                bCanceled = True
                        cm.delete(tmp_snap)
                        cm.delete(tmp_node)
                # <<<< added by Hiura

                if not bCanceled:
                    if len(self.static_base_meshes) > 0:
                        # >>>> added by Hiura
                        gMainProgressBar = mel.eval('$tmp = $gMainProgressBar')
                        cm.progressBar(gMainProgressBar,
                                       edit=True,
                                       beginProgress=True,
                                       isInterruptable=False,
                                       status='"VAT Converting ...',
                                       minValue=0,
                                       maxValue=100)
                        # <<<< added by Hiura

                        make_merge_snapshots(self.static_base_meshes)
                        cm.progressBar(gMainProgressBar, edit=True,
                                       step=5)  # added by Hiura
                        # smooth_copy(self.morph_array[0][0], gMainProgressBar, 15)
                        smooth_copy(self.morph_array[0], gMainProgressBar,
                                    15)  # modified by Hiura
                        pack_vert_uvs(self.original_mesh, gMainProgressBar, 30)
                        populate_morph_arrays(gMainProgressBar, 50)
                        remove_meshes()

                        cm.progressBar(gMainProgressBar,
                                       edit=True,
                                       endProgress=True)  # added by Hiura

                        render_out_textures()
                        #..
                    else:
                        cm.warning("No applicable meshes selected")
Ejemplo n.º 58
0
    def fbxImport(self):

        try:
            #Maya 2015 has one click dependency on FBX. super annoying
            cmds.loadPlugin("OneClick.mll")
        except:
            pass

        #get the file path from the UI
        filePath = self.fbxFilePath.text()

        if not os.path.exists(filePath):
            cmds.warning("No such file exists")
            return

        #stripping namespace
        if self.stripNamespace.isChecked():
            #open maya standalone
            mayaPath = None
            for path in sys.path:
                if path.find("bin") != -1:
                    if path.find("bin" + os.sep) == -1:
                        mayaPath = utils.returnFriendlyPath(
                            os.path.join(path, "mayapy.exe"))

            #error checking
            if mayaPath == None:
                try:
                    msg = interfaceUtils.DialogMessage(
                        "Error", "Unable to locate mayapy.exe", [], 0)
                    msg.show()
                except:
                    cmds.warning("Unable to locate mayapy.exe.")
                return

            scriptPath = utils.returnNicePath(
                self.scriptPath, "System/ART_StripFbxNamespace.py")

            #run a subprocess, opening mayapy/mayastandlone, running our stripNameSpace script
            maya = subprocess.Popen(mayaPath + ' ' + scriptPath + ' ' +
                                    filePath,
                                    stdout=subprocess.PIPE,
                                    stderr=subprocess.PIPE)
            out = maya.stdout.read()
            err = maya.stderr.read()

            print out

        #get the current character
        character = self.fbxCharacterCombo.currentText()

        #duplicate the character's root
        if cmds.objExists("root"):
            cmds.warning(
                "There is already a skeleton in the scene with the name \"root\". Aborting"
            )
            return

        newSkeleton = cmds.duplicate(character + ":root")
        cmds.select(newSkeleton)
        cmds.delete(constraints=True)

        #go through each module in list, find import method, and setup constraints accordingly
        moduleItems = []
        for i in range(self.fbxModuleList.count()):
            item = self.fbxModuleList.item(i)
            itemWidget = self.fbxModuleList.itemWidget(item)
            itemModule = itemWidget.property("module")

            children = itemWidget.children()
            for child in children:
                if type(child) == QtWidgets.QComboBox:
                    importMethod = child.currentText()
                    moduleItems.append([itemModule, importMethod])

        controls = []
        postModules = []

        #setup the constraints
        for each in moduleItems:
            #get inst
            modType = cmds.getAttr(each[0] + ".moduleType")
            modName = cmds.getAttr(each[0] + ".moduleName")
            mod = __import__("RigModules." + modType, {}, {}, [modType])
            reload(mod)

            #list of modules that have post bake operations needed
            specialModules = ["ART_Leg_Standard"]

            #get the class name from that module file (returns Modules.ART_Root.ART_Root for example)
            moduleClass = getattr(mod, mod.className)

            #find the instance of that module
            moduleInst = moduleClass(self, modName)

            #set namespace for instance
            moduleInst.namespace = character + ":"

            #run the module's pre import function
            moduleInst.importFBX_pre(each[1], character)

            if modType in specialModules:
                postModules.append([each[1], character, moduleInst])

            returnControls = moduleInst.importFBX(each[1], character)
            if returnControls != None:
                controls.extend(returnControls)

        #ensure that the scene is in 30fps
        cmds.currentUnit(time='ntsc')
        cmds.playbackOptions(min=0,
                             max=100,
                             animationStartTime=0,
                             animationEndTime=100)
        cmds.currentTime(0)

        #import the FBX file
        string = "FBXImportMode -v \"exmerge\";"
        string += "FBXImport -file \"" + filePath + "\""
        string += "FBXImportFillTimeline -v true"
        mel.eval(string)

        #ensure we're on the base layer
        animLayers = cmds.ls(type="animLayer")
        if animLayers != []:
            for layer in animLayers:
                cmds.animLayer(layer, edit=True, selected=False)
            cmds.animLayer("BaseAnimation",
                           edit=True,
                           selected=True,
                           preferred=True)

        #snap timeline to length of imported animation
        cmds.select("root", hi=True)
        firstFrame = cmds.findKeyframe(cmds.ls(sl=True), which='first')
        lastFrame = cmds.findKeyframe(cmds.ls(sl=True), which='last')
        if lastFrame == firstFrame:
            lastFrame = lastFrame + 1

        cmds.playbackOptions(min=firstFrame,
                             max=lastFrame,
                             animationStartTime=firstFrame,
                             animationEndTime=lastFrame)

        #BAKE!
        cmds.select(controls)
        cmds.bakeResults(simulation=True, t=(firstFrame, lastFrame))

        #Post Modules: Modules that have post-bake operations needing to be done
        for each in postModules:
            method = each[0]
            character = each[1]
            inst = each[2]

            inst.importFBX_post(method, character)

        #Clean up (delete duplicate skeleton)
        cmds.delete("root")

        #Look at frame offset, and offset animation based on that
        frameOffset = self.frameOffsetField.value()

        cmds.select(controls)
        cmds.keyframe(timeChange=frameOffset, r=True)

        firstFrame = cmds.findKeyframe(which='first')
        lastFrame = cmds.findKeyframe(which='last')
        cmds.playbackOptions(min=firstFrame,
                             max=lastFrame,
                             animationStartTime=firstFrame,
                             animationEndTime=lastFrame)
Ejemplo n.º 59
0
def get(obj=None,
        pivot='rp',
        space='ws',
        targets=None,
        mode='xform',
        asEuclid=False):
    """
    General call for querying position data in maya.
    Note -- pivot and space are ingored in boundingBox mode which returns the center pivot in worldSpace
    
    :parameters:
        obj(str): Object to check
            Transform, components supported
        pivot(str): Which pivot to use. (rotate,scale,boundingBox)
            rotatePivot
            scalePivot
            boundingBox -- Returns the calculated center pivot position based on bounding box
        space(str): World,Object,Local
        mode(str):
            xform -- Utilizes tranditional checking with xForm or pointPosition for components
        asEuclid(bool) - whether to return as Vector or not
    :returns
        success(bool)
    """
    try:
        _str_func = 'get_pos'
        _obj = VALID.mNodeString(obj)
        _pivot = VALID.kw_fromDict(pivot,
                                   SHARED._d_pivotArgs,
                                   noneValid=False,
                                   calledFrom=_str_func)
        _targets = VALID.stringListArg(targets,
                                       noneValid=True,
                                       calledFrom=_str_func)
        _space = VALID.kw_fromDict(space,
                                   SHARED._d_spaceArgs,
                                   noneValid=False,
                                   calledFrom=_str_func)
        _mode = VALID.kw_fromDict(mode,
                                  _d_pos_modes,
                                  noneValid=False,
                                  calledFrom=_str_func)
        _res = False

        if _pivot == 'boundingBox':
            log.debug("|{0}|...boundingBox pivot...".format(_str_func))
            _res = get_bb_center(_obj)
            if MATH.is_vector_equivalent(
                    _res, [0, 0, 0]) and not mc.listRelatives(_obj, s=True):
                _pivot = 'rp'
                log.warning(
                    "|{0}|...boundingBox pivot is zero, using rp....".format(
                        _str_func))

        if '[' in _obj:
            log.debug("|{0}| >> component mode...".format(_str_func))
            if ":" in _obj.split('[')[-1]:
                raise ValueError, "|{0}| >>Please specify one obj. Component list found: {1}".format(
                    _str_func, _obj)
            #_cType = VALID.get_mayaType(_obj)
            _l_comp = VALID.get_component(_obj)
            _root = _l_comp[1]
            _cType = _l_comp[3]
            if not VALID.is_shape(_root):
                _shapes = mc.listRelatives(_root, s=True, fullPath=True) or []
                if len(_shapes) > 1:
                    log.warning(
                        "|{0}| >>More than one shape found. To be more accurate, specify: {1} | shapes: {2}"
                        .format(_str_func, _obj, _shapes))
                _root = _shapes[0]

            _OBJ = '.'.join([_root, _l_comp[0]])

            log.debug(
                "|{0}| >> obj: {1}({6}) | type: {2} | pivot: {3} | space: {4} | mode: {5}"
                .format(_str_func, _OBJ, _cType, _pivot, _space, _mode, _obj))

            kws_pp = {'world': False, 'local': False}
            if _space == 'world': kws_pp['world'] = True
            else: kws_pp['local'] = True

            if _cType == 'polyVertex':
                _res = mc.pointPosition(_OBJ, **kws_pp)
            elif _cType == 'polyEdge':
                mc.select(cl=True)
                mc.select(_OBJ)
                mel.eval("PolySelectConvert 3")
                edgeVerts = mc.ls(sl=True, fl=True)
                posList = []
                for vert in edgeVerts:
                    posList.append(mc.pointPosition(vert, **kws_pp))
                _res = MATH.get_average_pos(posList)
            elif _cType == 'polyFace':
                mc.select(cl=True)
                mc.select(_OBJ)
                mel.eval("PolySelectConvert 3")
                edgeVerts = mc.ls(sl=True, fl=True)
                posList = []
                for vert in edgeVerts:
                    posList.append(mc.pointPosition(vert, **kws_pp))
                _res = MATH.get_average_pos(posList)
            elif _cType in [
                    'surfaceCV', 'curveCV', 'editPoint', 'surfacePoint',
                    'curvePoint'
            ]:
                _res = mc.pointPosition(_OBJ, **kws_pp)
                #_res =  mc.pointPosition(_OBJ)
            else:
                raise RuntimeError, "|{0}| >> Shouldn't have gotten here. Need another check for component type. '{1}'".format(
                    _str_func, _cType)

        else:
            log.debug(
                "|{0}| >> obj: {1} | pivot: {2} | space: {3} | mode: {4} | asEuclid: {5}"
                .format(_str_func, _obj, _pivot, _space, _mode, asEuclid))
            if _space == 'local' or _pivot == 'local':
                _res = ATTR.get(_obj, 'translate')
            #elif _pivot == 'local':
            #if _space == 'world':
            #    _res = mc.xform(_obj, q=True, rp = True, ws=True )
            #else:
            #    _res = ATTR.get(_obj,'translate')
            else:
                kws = {
                    'q': True,
                    'rp': False,
                    'sp': False,
                    'os': False,
                    'ws': False
                }
                if _pivot == 'rp': kws['rp'] = True
                else: kws['sp'] = True

                if _space == 'object': kws['os'] = True
                else: kws['ws'] = True

                log.debug("|{0}| >> xform kws: {1}".format(_str_func, kws))

                _res = mc.xform(_obj, **kws)

        if _res is not None:
            if asEuclid:
                log.debug("|{0}| >> asEuclid...".format(_str_func))
                return EUCLID.Vector3(_res[0], _res[1], _res[2])
            return _res
        raise RuntimeError, "|{0}| >> Shouldn't have gotten here: obj: {1}".format(
            _str_func, _obj)
    except Exception, err:
        cgmGen.cgmExceptCB(Exception, err)
Ejemplo n.º 60
0
 def exportFBX(self, export_FBX):
     SetFbxParameter()
     mel.eval('FBXExport -f "' + export_FBX + '" -s')