def setUpClass(cls): standalone.initialize('usd') # Stage with simple (non-nested) instancing. mayaFile = os.path.abspath('InstancedShading.ma') cmds.file(mayaFile, open=True, force=True) usdFilePath = os.path.abspath('InstancedShading.usda') cmds.loadPlugin('pxrUsd') cmds.usdExport(mergeTransformAndShape=True, file=usdFilePath, shadingMode='displayColor', exportInstances=True, materialsScopeName='Materials', exportCollectionBasedBindings=True, exportMaterialCollections=True, materialCollectionsPath="/World") cls._simpleStage = Usd.Stage.Open(usdFilePath) # Stage with nested instancing. mayaFile = os.path.abspath('NestedInstancedShading.ma') cmds.file(mayaFile, open=True, force=True) usdFilePath = os.path.abspath('NestedInstancedShading.usda') cmds.loadPlugin('pxrUsd') cmds.usdExport(mergeTransformAndShape=True, file=usdFilePath, shadingMode='displayColor', exportInstances=True, materialsScopeName='Materials', exportCollectionBasedBindings=True, exportMaterialCollections=True, materialCollectionsPath="/World") cls._nestedStage = Usd.Stage.Open(usdFilePath)
def create(self,targetList,influenceList,defaultWeightVal=1.0,maxDist=0.0,name='surfaceSkin1'): """ Create surfaceSkin deformer for the given target list or selection @param targetList: list of shapes to bind using surfaceSkin @type targetList: list @param influenceList: list of influences to affect surfaceSkin @type influenceList: list @param defaultWeightVal: Default influence weight value assigned to components @type defaultWeightVal: float @param maxDist: Maximum distance to search for components to affect, from the influence surface @type maxDist: float @param name: Name for new surfaceSkin node @type name str """ # Load plugin if not mc.pluginInfo('isoMuscle',l=1,q=1): try: mc.loadPlugin('isoMuscle') except: raise MissingPluginError('Unable to load surfaceSkin (isoMuscle) plugin!!') # Create Deformer surfaceSkin = mc.deformer(targetList,type='surfaceSkin',n=name)[0] # Add influences self.addInfluence(influenceList,surfaceSkin,defaultWeightVal,maxDist,calculatePrebind=False) # Ensure surfaceSkin::paintWeight and surfaceSkin::weights are paintable attrs self.makePaintable() # Return result return surfaceSkin
def setupScene(): ''' Setup some scene attributes we want to be common to all Spinifex car scenes TODO: make width over height as float ''' # Check if we haven't done this before if cmds.objExists('vraySettings.setupSceneHasBeenRun'): # Check that everything is setup correctly before continuing. dialogMessage = 'setupScene has already been run. Do you wish to continue? Some of your render settings will be reset.' result = cmds.confirmDialog( title='spckSetupScene', message=dialogMessage, button=['YES','NO'], defaultButton='NO', cancelButton='NO', dismissString='NO' ) if result == 'NO' : print("Aborted. We\'ve done this before...\n") return else: # Check that everything is setup correctly before continuing. dialogMessage = 'Have you set up your workspace.mel?' result = cmds.confirmDialog( title='spckSetupScene', message=dialogMessage, button=['YES','NO'], defaultButton='YES', cancelButton='NO', dismissString='NO' ) if result == 'NO' : print('Go setup your workspace and run again.\n') return # Units for working in metric and 30fps cmds.currentUnit (linear='cm') cmds.currentUnit (angle='deg') cmds.currentUnit (time='ntsc') # Load VRAY if not active cmds.loadPlugin ('vrayformaya', quiet=True) cmds.pluginInfo ('vrayformaya', edit=True, autoload=True) cmds.setAttr ('defaultRenderGlobals.ren', 'vray', type='string') cmds.evalDeferred ( 'createBaseRenderSettings()' , lowestPriority=True ) print('Success.\n')
def loadPlugins(): pluginList = ['redshift4maya.mll', 'Mayatomr.mll'] for plugin in pluginList: if cmds.pluginInfo( plugin, q=1, l=1 ): continue try:cmds.loadPlugin( plugin ) except:pass
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 )
def loadPlugin(): """ load softSelectionQuery plugin """ mayaVers = int(mayaVersion()) os = cmds.about(os=1) if os == 'win64': pluginName = 'softSelectionQuery_%s-x64.mll' % mayaVers elif os == 'mac': pluginName = 'softSelectionQuery_%s.bundle' % mayaVers elif os == 'linux64': pluginName = 'softSelectionQuery_%s.so' % mayaVers else: cmds.error('Soft Cluster EX is available for 64bit version of Autodesk Maya 2011 ' 'or above under Windows 64bit, Mac OS X and Linux 64bit!') if not cmds.pluginInfo(pluginName, q=True, l=True ): cmds.loadPlugin(pluginName) version = cmds.pluginInfo(pluginName, q=1, v=1) log.info('Plug-in: %s v%s loaded success!' % (pluginName, version)) else: version = cmds.pluginInfo(pluginName, q=1, v=1) log.info('Plug-in: %s v%s has been loaded!' % (pluginName, version))
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)
def testExportWithKindFlag(self): """ Tests exporting a Maya file with no USD_kind custom attributes and using the usdExport -kind flag. """ cmds.file(os.path.abspath('KindTest.ma'), open=True, force=True) cmds.loadPlugin('pxrUsd') usdFilePath = os.path.abspath('KindTest.usda') # Check the error mark; this ensures that we actually got a Tf error # (that was eventually converted into a Maya error, which Maya raises # in Python as a RuntimeError). mark = Tf.Error.Mark() mark.SetMark() with self.assertRaises(RuntimeError): cmds.usdExport(mergeTransformAndShape=True, file=usdFilePath, kind='assembly') errors = mark.GetErrors() self.assertEqual(len(errors), 1) self.assertIn( "</KindTest> has kind 'assembly', which is derived from 'assembly'", str(errors[0])) cmds.usdExport(mergeTransformAndShape=True, file=usdFilePath, kind='fakeKind') stage = Usd.Stage.Open(usdFilePath) self.assertTrue(stage) rootPrim = stage.GetPrimAtPath('/KindTest') self.assertTrue(Kind.Registry().IsA(Usd.ModelAPI(rootPrim).GetKind(), 'fakeKind'))
def testExportWithKindAttrAndKindFlag(self): """ Tests exporting a Maya file with both USD_kind custom attributes and using the usdExport -kind flag; there should be an error if the USD_kind is not derived from the kind specified in the -kind flag. """ cmds.file(os.path.abspath('KindTestUsdKindAttr.ma'), open=True, force=True) cmds.loadPlugin('pxrUsd') usdFilePath = os.path.abspath('KindTestUsdKindAttr.usda') with self.assertRaises(RuntimeError): cmds.usdExport(mergeTransformAndShape=True, file=usdFilePath, kind='assembly') cmds.usdExport(mergeTransformAndShape=True, file=usdFilePath, kind='model') stage = Usd.Stage.Open(usdFilePath) self.assertTrue(stage) rootPrim = stage.GetPrimAtPath('/KindTest') self.assertTrue(Kind.Registry().IsA(Usd.ModelAPI(rootPrim).GetKind(), 'component')) rootPrim2 = stage.GetPrimAtPath('/KindTest2') self.assertTrue(Kind.Registry().IsA(Usd.ModelAPI(rootPrim2).GetKind(), 'assembly'))
def create_pointer(m): if (BAXER_POINTER == True): # import Baxter Pointer model and use it try: cmds.loadPlugin("objExport") except: pass name = os.path.dirname(os.path.realpath(__file__)) + "/models/baxter_gripper.obj" mel.eval('file -import -type "OBJ" -ignoreVersion -ra true -mergeNamespacesOnClash false -rpr "gripper" -options "mo=1" -pr "%s";' \ % name) try: mel.eval('rename "gripper_Mesh" "pointer' + str(m) + '";') except: pass else: # Create a pointer mesh that represents the robot claw cmds.polyCone(name="pointer" + str(m), sx=3, r=0.5, h=2) cmds.select("pointer" + str(m)) cmds.rotate("180deg", 0, 0, r=True) cmds.move(0, -1, 0, "pointer" + str(m) + ".scalePivot", "pointer" + str(m) + ".rotatePivot") cmds.move(0, 1, 0, absolute=True) cmds.makeIdentity(apply=True, t=1, r=1, s=1) bbx = cmds.xform("table", q=True, bb=True, ws=True) cur_size = abs(bbx[3] - bbx[0]) cmds.scale(cur_size/TABLE_SIZE, cur_size/TABLE_SIZE, cur_size/TABLE_SIZE, "pointer" + str(m), centerPivot = True) mel.eval('select -r pointer' + str(m) + '; sets -e -forceElement pointer_matSG;') mel.eval("makeCollideNCloth")
def testExportWithAssemblyAndMesh(self): """ Tests exporting a Maya file with a root prim containing an assembly and a mesh. """ cmds.file(os.path.abspath('KindTestAssemblyAndMesh.ma'), open=True, force=True) cmds.loadPlugin('pxrUsd') # Should fail due to the mesh. usdFilePath = os.path.abspath('KindTestAssemblyAndMesh.usda') with self.assertRaises(RuntimeError): cmds.usdExport(mergeTransformAndShape=True, file=usdFilePath, kind='assembly') # Should be 'component' because of the mesh usdFilePath = os.path.abspath('KindTestAssemblyAndMesh.usda') cmds.usdExport(mergeTransformAndShape=True, file=usdFilePath) stage = Usd.Stage.Open(usdFilePath) self.assertTrue(stage) rootPrim = stage.GetPrimAtPath('/KindTest') self.assertTrue(Kind.Registry().IsA(Usd.ModelAPI(rootPrim).GetKind(), 'component'))
def loadPlugin(): ''' Load edgFlowMirror plugin. ''' if not mc.pluginInfo('edgeFlowMirror',q=True,l=True): mc.loadPlugin('edgeFlowMirror') return 1
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()
def importDisplaceInscene(self): cmds.loadPlugin('abcMayaShader.mll', qt=1) shader = self.cache.assignations.getDisplace(self.getPath(), self.interface.getLayer()) if shader: abcShader = cmds.shadingNode('abcMayaShader', asShader=True, n="%s" % shader["shader"].replace("SG", "")) cmds.setAttr(abcShader +".shader", self.cache.getAbcShader(), type="string") cmds.setAttr(abcShader +".shaderFrom", shader["shader"], type="string")
def setUpClass(cls): standalone.initialize('usd') cmds.loadPlugin('pxrUsd') usdFile = os.path.abspath('UsdImportColorSetsTest.usda') cmds.usdImport(file=usdFile, shadingMode='none', excludePrimvar='ExcludeMe')
def setUpClass(cls): standalone.initialize('usd') cmds.file(os.path.abspath('UsdExportPrefTest.ma'), open=True, force=True) cmds.loadPlugin('pxrUsd', quiet=True)
def cameraFrustum_build(cam_shape): #make sure a camera is loaded if cam_shape==0: cmds.error('no camera loaded...select a camera and load') else: #create frustum only if one doesnt already exist selCamXform = cmds.listRelatives(cam_shape[0], p=1) prefix = 'frust_' frustumGrpName = prefix + 'camera_frustum_all_grp' if cmds.objExists(frustumGrpName)==0: #create main grp frustumMainGrp = cmds.group(em=1, n=frustumGrpName); cmds.setAttr(frustumGrpName + '.tx', lock=1, keyable=0, channelBox=0) cmds.setAttr(frustumGrpName + '.ty', lock=1, keyable=0, channelBox=0) cmds.setAttr(frustumGrpName + '.tz', lock=1, keyable=0, channelBox=0) cmds.setAttr(frustumGrpName + '.rx', lock=1, keyable=0, channelBox=0) cmds.setAttr(frustumGrpName + '.ry', lock=1, keyable=0, channelBox=0) cmds.setAttr(frustumGrpName + '.rz', lock=1, keyable=0, channelBox=0) cmds.setAttr(frustumGrpName + '.sx', lock=1, keyable=0, channelBox=0) cmds.setAttr(frustumGrpName + '.sy', lock=1, keyable=0, channelBox=0) cmds.setAttr(frustumGrpName + '.sz', lock=1, keyable=0, channelBox=0) cmds.setAttr(frustumGrpName + '.v', lock=1, keyable=0, channelBox=0) #create frustum geo frustumGeo = cmds.polyCube(w=2, h=2, d=2, n=prefix + 'camera_frustum_geo') cmds.delete(frustumGeo[0], constructionHistory=True) cmds.parent(frustumGeo[0], frustumMainGrp) #load plugin "nearestPointOnMesh.mll" if needed and connect plugin = cmds.pluginInfo('nearestPointOnMesh.mll', q=1, l=1) if plugin==0: cmds.loadPlugin('nearestPointOnMesh.mll') nearNodeName = prefix + 'npomNode' npomNode = cmds.createNode('nearestPointOnMesh', n=nearNodeName) cmds.connectAttr(frustumGeo[0] + '.worldMesh', npomNode + '.inMesh') #create clusters cmds.select(frustumGeo[0] + '.vtx[4:7]', r=1) nearCluster = cmds.cluster(n=prefix + 'camera_nearFrustum_cluster') cmds.select(frustumGeo[0] + '.vtx[0:3]', r=1) farCluster = cmds.cluster(n=prefix + 'camera_farFrustum_cluster') #create near/far/camera locs cameraLoc = cmds.spaceLocator(p=(0, 0, 0), n=prefix + 'camera_loc') cmds.parent(cameraLoc[0], frustumMainGrp) nearLoc = cmds.spaceLocator(p=(0, 0, 0), n=prefix + 'camera_nearFrustum_loc') cmds.move(0, 0, -1) farLoc = cmds.spaceLocator(p=(0, 0, 0), n=prefix + 'camera_farFrustum_loc') cmds.move(0, 0, 1) #parent clusters under loc -- parent locs under camera loc cmds.parent(nearCluster[1], nearLoc[0]) cmds.parent(farCluster[1], farLoc[0]) cmds.parent(nearLoc[0], cameraLoc[0]) cmds.parent(farLoc[0], cameraLoc[0]) #constrain camera loc to camera cmds.parentConstraint(selCamXform, cameraLoc, weight=1) return frustumGeo[0]
def __init__(self): # set up necessary plug-ins if not cmds.pluginInfo('nearestPointOnMesh', query=True, loaded=True): try: cmds.loadPlugin('nearestPointOnMesh') except NameError: pass
def snapObjectsOnSupport(objects, support): """ Snaps objects on support. :param objects: Objects to snap. :type objects: list :param value: Support. :type value: str """ if cmds.pluginInfo("nearestPointOnMesh", q=True, loaded=False): cmds.loadPlugin("nearestPointOnMesh") nearestPointOnMesh = cmds.createNode("nearestPointOnMesh") supportShape = getShapes(support)[0] cmds.connectAttr(supportShape + ".outMesh", nearestPointOnMesh + ".inMesh", f=True) allAxis = ("X", "Y", "Z") for object in objects: position = cmds.xform(object, q=True, rp=True, ws=True, a=True) for i, axis in enumerate(allAxis): cmds.setAttr(nearestPointOnMesh + ".inPosition" + axis, position[i]) cmds.select(object) cmds.move(cmds.getAttr(nearestPointOnMesh + ".positionX"), cmds.getAttr(nearestPointOnMesh + ".positionY"), cmds.getAttr(nearestPointOnMesh + ".positionZ"), rpr=True) cmds.delete(nearestPointOnMesh)
def __init__(self): 'The instructor' # check for os if os.name == "posix": ext="so" else: ext="mll" # load the plug-in mc.loadPlugin( 'objExport.%s' % ext )
def loadPlugins(): cmds.loadPlugin( 'finShelf.py' ) mel.eval( 'if(!`pluginInfo -query -l -n Mayatomr`) loadPlugin "Mayatomr";') mel.eval( 'if(!`pluginInfo -query -l -n OpenEXRLoader`) loadPlugin "OpenEXRLoader";') mel.eval( 'if(!`pluginInfo -query -l -n stereoCamera`) loadPlugin "stereoCamera";') mel.eval( 'if(!`pluginInfo -query -l -n objExport`) loadPlugin "objExport";') mel.eval( 'if(!`pluginInfo -query -l -n fbxmaya`) loadPlugin "fbxmaya";') # external plugins try: if pm.versions.current() in ( 201402, 2014 ): mel.eval( 'if(!`pluginInfo -query -l -n "MASH-2014"`) loadPlugin "MASH-2014";') mel.eval('if (`shelfLayout -exists MASH `) deleteUI MASH;') mel.eval('loadNewShelf "shelf_MASH.mel"') cmds.loadPlugin( 'SOuP.bundle') mel.eval('if(!`pluginInfo -query -l -n "SOuP"`) loadPlugin "SOuP";') mel.eval('if (`shelfLayout -exists soup `) deleteUI soup;') mel.eval('loadNewShelf "shelf_soup.mel"') except: print "Check external plugin paths" # set the optionVar that enables hidden mentalray shaders pm.optionVar['MIP_SHD_EXPOSE'] = 1 pm.runtime.SavePreferences() cmds.setAttr('defaultRenderGlobals.ren', 'mentalRay', type='string' )
def setUpClass(cls): standalone.initialize('usd') cmds.loadPlugin('pxrUsd') if not UsdMaya.WriteUtil.WriteUVAsFloat2(): cmds.file(os.path.abspath('UsdExportUVSetsTest.ma'), open=True, force=True) else: cmds.file(os.path.abspath('UsdExportUVSetsTest_Float.ma'), open=True, force=True) # Make some live edits to the box with weird UVs for the # testExportUvVersusUvIndexFromIterator test. cmds.select("box.map[0:299]", r=True) cmds.polyEditUV(u=1.0, v=1.0) usdFilePath = os.path.abspath('UsdExportUVSetsTest.usda') cmds.usdExport(mergeTransformAndShape=True, file=usdFilePath, shadingMode='none', exportColorSets=False, exportDisplayColor=False, exportUVs=True) cls._stage = Usd.Stage.Open(usdFilePath)
def load_plugins_deferred(): #plugin_list plugin_list = ['vrayformaya.mll', 'rrSubmit_Maya_8.5+.py', 'helga_asset_metadata.py', 'helga_shots_metadata.py', 'AnimSchoolPicker.mll', 'LBrush'] #iterate plugin_list and load for plugin_name in plugin_list: try: if not(cmds.pluginInfo(plugin_name , query = True, loaded = True)): try: cmds.loadPlugin(plugin_name) #Print to console instead of script editor sys.__stdout__.write('->Successfully loaded ' +plugin_name +' deferred\n') except: sys.__stdout__.write('->Error loading ' +plugin_name +' deferred\n') else: sys.__stdout__.write('->Skipped loading ' +plugin_name +' deferred. Plugin was already loaded\n') except: sys.__stdout__.write('->Error loading ' +plugin_name +' deferred\n') #Dividerline sys.__stdout__.write(DIVIDERLINE)
def main(argv = None): print "Initializing..." # Load Plugin cmds.loadPlugin("AbcImport.mll") # Get current dir basedir = os.getcwd() os.chdir(basedir) # Create new file cmds.file(basedir + "/" + "null.mb", o=True, force=True) # Create empty scenes createNewScenes() # Load Alembics in every scene for file in os.listdir("."): if file.endswith(".mb") and file != "null.mb": print "Opening " + file cmds.file(basedir+'/'+file, o=True, force=True) importAbcInFolder() cmds.file(save=True) quit()
def cmdFunction(*args): for pluginName in plugin_names: cmds.loadPlugin(pluginName) if ui_mel is not None: mel.eval(ui_mel) if ui_python is not None: ui_python()
def initializePlugin(obj): plugin = OpenMayaMPx.MFnPlugin(obj) try: plugin.registerNode( ms_environment_nodeTypeName, ms_environment_nodeTypeId, ms_environment_nodeCreator, ms_environment_nodeInitializer, OpenMayaMPx.MPxNode.kLocatorNode, ) except: sys.stderr.write("Failed to register node: %s" % ms_environment_nodeTypeName) try: plugin.registerNode( ms_renderSettings_nodeTypeName, ms_renderSettings_nodeTypeId, ms_renderSettings_nodeCreator, ms_renderSettings_nodeInitializer, ) except: sys.stderr.write("Failed to register node: %s\n" % ms_renderSettings_nodeTypeName) # load objExport plugin if its not loaded yet try: if not cmds.pluginInfo("objExport", query=True, loaded=True): cmds.loadPlugin("objExport") except: print "objExport plugin could not be loaded, cannot load mayaseed" ms_menu.createMenu() ms_menu.buildMenu()
def reloadAndReopen( self, *args ): codePath = cmds.textField( self.fld_codePath, q=1, tx=1 ) plugPath = cmds.textField( self.fld_plugPath, q=1, tx=1 ) srcName = cmds.textField( self.fld_srcName, q=1, tx=1 ) dstName = cmds.textField( self.fld_dstName, q=1, tx=1 ) srcPath = ( codePath + '/' + srcName ).replace( '\\', '/' ) dstPath = ( plugPath + '/' + dstName ).replace( '\\', '/' ) currentSceneName = cmds.file( q=1, sceneName=1 ) cmds.file( new=1, f=1 ) cmds.unloadPlugin( dstName ) shutil.copy2( srcPath, dstPath ) print "Copy From : ", srcPath print "Past To : ", dstPath if not currentSceneName: currentSceneName = tempPluginTestPath try:cmds.file( currentSceneName, f=1, options="v=0;", o=1 ) except:cmds.file( rename = currentSceneName ) cmds.loadPlugin( dstName ) self.textFieldSaveCommand()
def _gather_exported_alembic_info_(): cmds.loadPlugin("AbcImport.mll", quiet=True) template_obj, fields, tk = _get_shotgun_fields_from_file_name_() if not pm.objExists("animatedAlembicGroup"): pm.createNode("transform", name="animatedAlembicGroup") temp, fields, tk = _get_shotgun_fields_from_file_name_() masterAlembicTemplate = tk.templates["master_alembic_cache"] alembicFolder = libFile.get_parent_folder(masterAlembicTemplate.apply_fields(fields)) # Get all the abc files exported_alemblic_info = {} if libFile.exists(alembicFolder): for alembicFile in libFile.listfiles(alembicFolder, "abc"): alembicFilePath = libFile.join(alembicFolder, alembicFile) # Edited by Chet # Project Kitten Witch 25 May 2016 # ======================================================== # Old code that was causing the list of alembics to build # niceName = alembicFile.split(".")[0].split("_")[] niceName = alembicFile.split(".")[0] niceName = niceName.split("_") niceName = " ".join(niceName[1:]) exported_alemblic_info[niceName] = alembicFilePath return exported_alemblic_info
def exportObjects(self): for object in self.objects: cmds.select(object, r= True) if self.exportType == 1: fileType = 'Fbx' cmds.loadPlugin('fbxmaya', qt= True) melCmd.eval('FBXExportShowUI -v false;') else: fileType = 'OBJexport' cmds.loadPlugin('objExport', qt= True) if bool(self.exportGeometrySequence) == bool(True): startF = self.startFrame endF = self.endFrame else: startF = endF = cmds.currentTime( query=True ) nameExtension = '' exportName = object.replace(':', '_') for timevalue in range(startF, (endF+1), 1): if bool(self.exportGeometrySequence) == bool(True): nameExtension = '.%04d' % timevalue cmds.currentTime(timevalue) if self.exportType == 1: melCmd.eval('FBXExport -f "' + self.exportPath + exportName + nameExtension + '.fbx" -s') else: cmds.file(self.exportPath+exportName+nameExtension, op='', typ=fileType, pr=True, es=True ) print 'Exported: ' + object;
def reload(source,destination): ''' reloads plugin: * close file * unload plugin * copy new compiled version * load plugin * load file ''' currFile = cmds.file( sceneName=True,q=True) # close file for a while if currFile: cmds.file( f=True, new=True ) try: cmds.unloadPlugin(os.path.basename(destination),force=True) print ("plugin unloaded: %s" % destination) shutil.copy(source,destination) print ("plugin copied: %s" % source) cmds.loadPlugin(destination) print "plugin loaded: "+destination finally: if currFile: cmds.file(currFile, open=True)
def loadObjPlugin(): if not cmds.pluginInfo('objExport', q=1, loaded=True ): cmds.loadPlugin('objExport')
def gtu_load_plugins(plugin_list): ''' Attempts to load provided plug-ins, then gives the user feedback about their current state. (Feedback through inView messages and stdout.write messages) Parameters: plugin_list (list): A list of strings containing the name of the plug-ings yo uwant to load ''' already_loaded = [] not_installed = [] now_loaded = [] # Load Plug-in for plugin in plugin_list: if not cmds.pluginInfo(plugin, q=True, loaded=True): try: cmds.loadPlugin(plugin) if cmds.pluginInfo(plugin, q=True, loaded=True): now_loaded.append(plugin) except: not_installed.append(plugin) else: already_loaded.append(plugin) # Give Feedback if len(not_installed) > 0: message_feedback = '' for str in not_installed: message_feedback += str + ', ' is_plural = 'plug-ins don\'t' if len(not_installed) == 1: is_plural = 'plug-in doesn\'t' message = '<span style=\"color:#FF0000;text-decoration:underline;\">' + message_feedback[: -2] + '</span> ' + is_plural + ' seem to be installed.' cmds.inViewMessage(amg=message, pos='botLeft', fade=True, alpha=.9) sys.stdout.write(message_feedback[:-2] + ' ' + is_plural + ' seem to be installed.') if len(now_loaded) > 0: message_feedback = '' for str in now_loaded: message_feedback += str + ', ' is_plural = 'plug-ins are' if len(now_loaded) == 1: is_plural = 'plug-in is' message = '<span style=\"color:#FF0000;text-decoration:underline;\">' + message_feedback[: -2] + '</span> ' + is_plural + ' now loaded.' cmds.inViewMessage(amg=message, pos='botLeft', fade=True, alpha=.9) sys.stdout.write(message_feedback[:-2] + ' ' + is_plural + ' now loaded.') if len(already_loaded) > 0: message_feedback = '' for str in already_loaded: message_feedback += str + ', ' is_plural = 'plug-ins are' if len(already_loaded) == 1: is_plural = 'plug-in is' message = '<span style=\"color:#FF0000;\">' + message_feedback[: -2] + '</span> ' + is_plural + ' already loaded.' cmds.inViewMessage(amg=message, pos='botLeft', fade=True, alpha=.9) sys.stdout.write(message_feedback[:-2] + ' ' + is_plural + ' already loaded.')
def on_action_create(self, *args): sName = self.ui.edtNewName.toPlainText() # loading Maya matrix node if not (cmds.pluginInfo("decomposeMatrix", query=True, loaded=True)): try: # Maya 2012 cmds.loadPlugin("decomposeMatrix.mll") except: try: # Maya 2013 or earlier cmds.loadPlugin("matrixNodes.mll") except: print self.langDic[ self.langName]['e002_decomposeMatrixNotFound'] aSel = pymel.selected() if (len(aSel) == 2): #Create the container of the system data pData = PoseReaderData() with pymel.UndoChunk(): #Get Needed matrix information pData.nParent = aSel[1] pData.nChild = aSel[0] m4ParentMat = pData.nParent.getMatrix(worldSpace=True) m4ChildMat = pData.nChild.getMatrix(worldSpace=True) #Create the two node needed to extract the rotation pData.nPGrp = pymel.createNode("transform", name=sName + "_PoseReader_Parent_Grp", p=pData.nParent) pData.nPGrp.setMatrix(m4ChildMat, worldSpace=True) pData.nParentLoc = self.createLoc( sName + "_AngExtract_ParentLoc", pData.nPGrp) pData.nCGrp = pymel.createNode("transform", name=sName + "_PoseReader_Child_Grp", p=pData.nChild) pData.nCGrp.setMatrix(m4ChildMat, worldSpace=True) pData.nChildLoc = self.createLoc( sName + "_AngExtract_ChildLoc", pData.nCGrp) #Add usefull attributes for the tool pData.nChildLoc.setDynamicAttr("posereaderdata", True) pData.nChildLoc.addAttr("angleMaxValue", min=-360.0, max=360.0) pData.nChildLoc.setAttr("angleMaxValue", 180, edit=True, keyable=False, lock=False) pData.nChildLoc.addAttr("axis", at="enum", enumName="X:Y:Z") pData.nChildLoc.setAttr("axis", 1, edit=True, keyable=False, lock=False) #Setup the rotation extaction pData.nMultM = pymel.createNode("multMatrix", name=sName + "_ExtactAngle_MM") pymel.connectAttr(pData.nParentLoc.worldMatrix[0], pData.nMultM.matrixIn[0]) pymel.connectAttr(pData.nChildLoc.worldInverseMatrix[0], pData.nMultM.matrixIn[1]) pData.nDecM = pymel.createNode("decomposeMatrix", name=sName + "_ExtractAngle_DM") pymel.connectAttr(pData.nMultM.matrixSum, pData.nDecM.inputMatrix) #Setup the rotation affection pData.nMD = pymel.createNode("multiplyDivide", name=sName + "_NormValue_MD") pData.nMD.operation.set(2) pymel.connectAttr(pData.nDecM.outputRotateY, pData.nMD.input1X) pymel.connectAttr(pData.nChildLoc.angleMaxValue, pData.nMD.input2X) pData.nCD = pymel.createNode("condition", name=sName + "_SmallerThanOne_CD") pymel.connectAttr(pData.nMD.outputX, pData.nCD.firstTerm) pymel.connectAttr(pData.nMD.outputX, pData.nCD.colorIfTrueR) pData.nCD.secondTerm.set(1) pData.nCD.operation.set(5) #Less or equal pData.nCDNoNeg = pymel.createNode("condition", name=sName + "_OverZero_CD") pymel.connectAttr(pData.nCD.outColorR, pData.nCDNoNeg.firstTerm) pymel.connectAttr(pData.nCD.outColorR, pData.nCDNoNeg.colorIfTrueR) pData.nCDNoNeg.secondTerm.set(0) pData.nCDNoNeg.colorIfFalseR.set(0) pData.nCDNoNeg.operation.set(3) #Greater or Equal #Node for manual activation connection pData.nMDActive = pymel.createNode("multiplyDivide", name=sName + "_Active_MD") pymel.connectAttr(pData.nCDNoNeg.outColorR, pData.nMDActive.input1X) #for o in pData.__dict__: #print o libSerialization.export_network(pData) self.addItem(pData) else: pymel.confirmDialog( title='Selection Problem', message='You need to have exactly two nodes selected')
def loadPlugin(self): if cmds.pluginInfo('nearestPointOnMesh.mll', q=True, l=True) == False: cmds.loadPlugin('nearestPointOnMesh.mll')
#loadPlugin arnold for maya import maya.cmds as mc if not mc.pluginInfo('mtoa', q=1, loaded=1): mc.loadPlugin('mtoa') mc.setAttr('defaultRenderGlobals.currentRenderer', 'arnold', type='string')
import maya.cmds as mc, maya.OpenMaya as om import ADCtrl as ct, ADUtils as au import re from string import digits reload(ct) reload(au) # load Plug-ins matrixNode = mc.pluginInfo('matrixNodes.mll', query=True, loaded=True) quatNode = mc.pluginInfo('quatNodes.mll', query=True, loaded=True) if not matrixNode: mc.loadPlugin('matrixNodes.mll') if not quatNode: mc.loadPlugin('quatNodes.mll') class Build: def __init__(self, crv, eyeballJnt, worldUpObject, scale, sideLFT, sideRGT, side, offsetEyelidPos, directionLip01, directionLip02, ctrlColor, controllerLidDown): self.pos = mc.xform(eyeballJnt, q=1, ws=1, t=1)[0] # self.prefixNameCrv = au.prefixName(crv) self.vtxCrv = mc.ls('%s.cv[0:*]' % crv, fl=True) self.createJointLid(crv=crv, worldUpObject=worldUpObject,
def rigcleantool(arg): if cmds.pluginInfo("Fur",q=1,loaded=1,name=1)==0: cmds.loadPlugin("Fur") if cmds.pluginInfo("Mayatomr",q=1,loaded=1,name=1)==0: cmds.loadPlugin("Mayatomr") if cmds.pluginInfo("mtoa",q=1,loaded=1,name=1)==0: cmds.loadPlugin("mtoa") delsel =[] aiAov = cmds.ls(type="aiAOV") aiAovnum=[] for a in range(len(aiAov)): aovadj = cmds.listConnections(aiAov[a]+".message",s=0,type="aiOptions") if aovadj ==None: delsel.append(aiAov[a]) camv = cmds.ls(type="cameraView") for c in range(len(camv)): delsel.append(camv[c]) jointlayer = cmds.ls(type="displayLayer") jointlayernum = [] for j in range(len(jointlayer)): adj = cmds.listConnections( jointlayer[j], d=True) if adj ==None: delsel.append(jointlayer[j]) mrOptions = cmds.ls(type="mentalrayOptions") for m in range(len(mrOptions)): delsel.append(mrOptions[m]) swfursel =cmds.ls(type="FurGlobals") for s in range(len(swfursel)): delsel.append(swfursel[s]) animcurve = cmds.ls(type="animCurveUL") delancv = [] for a in range(len(animcurve)): unitconup = cmds.listConnections(animcurve[a],s=0) unitcondn = cmds.listConnections(animcurve[a],d=0) if unitconup==None and unitcondn==None: delancv.append(animcurve[a]) delsel.append(animcurve[a]) hpginfo = cmds.ls(type="hyperGraphInfo") delhpginfo = [] for h in range(len(hpginfo)): if hpginfo[h]!="hyperGraphInfo": delhpginfo.append(hpginfo[h]) delsel.append(hpginfo[h]) hpview = cmds.ls(type="hyperView") delhpview = [] for p in range(len(hpview)): delsel.append(hpview[p]) delhpview.append(hpview[p]) hplayout = cmds.ls(type="hyperLayout") delhplayout = [] for h in range(len(hplayout)): delhplayout.append(hplayout[h]) delsel.append(hplayout[h]) groupid = cmds.ls(type="groupId") delgroupid = [] for i in range(len(groupid)): unitcon = cmds.listConnections(groupid[i],s=0) if unitcon==None: delgroupid.append(groupid[i]) delsel.append(groupid[i]) unit = cmds.ls(type="unitConversion") delunit = [] for i in range(len(unit)): unitcon = cmds.listConnections(unit[i],s=0) if unitcon==None: delunit.append(unit[i]) delsel.append(unit[i]) for d in range(len(delsel)): cmds.delete(delsel[d]) print ".............\n", print "已删除"+str(len(delunit))+"个无用的unitConversion节点,"+str(len(delancv))+"个无用的animCurveUL节点,"+str(len(delhpginfo))+"个无用的hyperGraphInfo节点,"+str(len(delhpview))+"个无用的hyperView节点,"+str(len(delhplayout))+"个无用的hyperLayout节点,"+str(len(delgroupid))+"个无用的groupId节点,"+str(len(camv))+"个无用的cameraView节点,"+str(len(jointlayernum))+"个无用的displayLayer节点,"+str(len(mrOptions))+"个无用的mentalrayOptions节点,"+str(len(aiAovnum))+"个无用的aiAov节点,"+str(len(swfursel))+"个无用的FurGlobals节点!!",
def sk_sceneCameraBK(self ,shotInfos = [],shotType = sk_infoConfig.sk_infoConfig().checkShotType() , stereoCam = 0,stereoMode = 1,step = 1,bkCam = '' ): if not shotInfos: shotInfo = sk_infoConfig.sk_infoConfig().checkShotInfo() else: shotInfo = shotInfos camBase = '' camFind = 1 if bkCam: camBase = bkCam else: if shotType == 2: camBase = 'cam_' + str(shotInfo[1]) + '_' + str(shotInfo[2]) if shotType == 3: camBase = 'cam_' + str(shotInfo[1]) + '_' + str(shotInfo[2]) + '_' + str(shotInfo[3]) if '.' in camBase: camBase = camBase.split('.')[0] if stereoMode: camBase += '_stCam' # 判断cam在不在 if not camBase: camFind = 0 if not mc.ls(camBase): camFind = 0 else: if len(mc.ls(camBase)) != 1: camFind = 0 if not camFind: #errorInfo = (u'==========No Correct Cam[%s],or More Than One Cam[%s],please Fix the Camera Name=========='%(camBase,camBase)) errorInfo = (u'==========未找到正版cam[%s],或cam名字不合法==========\n'%camBase) print errorInfo sk_infoConfig.sk_infoConfig().checkErrorWindows(errorInfo) sk_infoConfig.errorCode = errorInfo mc.error(errorInfo) # 准备工作 # 时间轴信息 io = (mc.playbackOptions(q=1, minTime=1)-10, mc.playbackOptions(q=1, maxTime=1)+10) # 一次BK开始 locTemp = mc.spaceLocator() cons = mc.parentConstraint(camBase , locTemp , maintainOffset = 0) # 一次烘焙 mc.bakeResults(locTemp, t = io, simulation = 0, sampleBy=step, disableImplicitControl=1, preserveOutsideKeys=1, sparseAnimCurveBake=1, removeBakedAttributeFromLayer=0, bakeOnOverrideLayer=0, controlPoints=0, shape=1) mc.delete(cons) # 复制出信息 camNeed = (camBase.split('|')[-1] + '_baked') checkCam = mc.ls(camNeed,l=1) if checkCam: mc.delete(checkCam) if stereoMode: pluginName = 'stereoCamera' if not mc.pluginInfo(pluginName,q= 1,loaded = 1): mc.loadPlugin(pluginName) from maya.app.stereo import stereoCameraRig camNew = stereoCameraRig.createStereoCameraRig(rigName='StereoCamera') camNew = mc.rename(camNew[0],camNeed) shapesOld = mc.listRelatives(camBase,s=1,f=1) shapesNew = mc.listRelatives(camNew,s=1,f=1) for i in range(len(shapesOld)): # 连接 self.sk_bakeStereoCameraConnect(shapesOld[i],shapesNew[i]) else: camNew = mc.duplicate(camBase,returnRootsOnly = 1,inputConnections = 1) camNew = mc.rename(camNew[0],camNeed.split('|')[-1]) # cam mode不需要sx,sy,sz和v noNeedList = ['.sx','.sy','.sz','.v'] for checkAttr in noNeedList: camAttr = camNew + checkAttr cons = mc.listConnections(camAttr,s=1,d=0,plugs=1) mc.setAttr(camAttr,l=0) if cons: mc.disconnectAttr(cons[0],camAttr) lockState = mc.getAttr(camAttr,l=1) if lockState: tempAttr = mc.connectionInfo(camAttr,gla=1) if tempAttr: mc.setAttr(tempAttr,l=0) mc.setAttr(camAttr,1) # 清理目标camera物体 chilrdNodes = mc.listRelatives(camNew,ad = 1,f=1) for checkNode in chilrdNodes: if not mc.ls(checkNode): continue checkType = mc.nodeType(checkNode) if checkType in ['camera','stereoRigFrustum','stereoRigCamera']: continue deleteState = 1 if checkType in ['transform']: child = mc.listRelatives(checkNode,s=1,f=1) if not child: deleteState = 0 else: for checkChild in child: checkType = mc.nodeType(checkChild) if checkType in ['camera','stereoRigFrustum','stereoRigCamera']: deleteState = 0 if deleteState: mc.delete(checkNode) # 解锁 from idmt.maya.commonCore.core_mayaCommon import sk_sceneTools reload(sk_sceneTools) sk_sceneTools.sk_sceneTools().checkLockObjs([camNeed],0,1) # 祛除translate和rotate的约束 if shotInfo[0] !='nj': camNewFull = mc.ls(camNew,l=1)[0] if len(camNewFull.split('|')) != 2: mc.parent(camNew,world = 1) for attr in ['.tx','.ty','.tz','.rx','.ry','.rz']: mc.setAttr((camNew + attr), lock = False) consAttr = mc.listConnections((camNew + attr),s=1,d=0,plugs=1) if not consAttr: continue mc.disconnectAttr(consAttr[0],(camNew + attr)) # 二次BK开始 cons = mc.parentConstraint(locTemp , camNew , maintainOffset = 0) # 二次烘焙 mc.bakeResults(camNew, t=io, simulation = 0, sampleBy=step, disableImplicitControl = 1 , preserveOutsideKeys = 1 , sparseAnimCurveBake = 1 , removeBakedAttributeFromLayer = 0 , bakeOnOverrideLayer = 0 , controlPoints = 0 , shape = 1 ) if stereoMode: camShape = mc.listRelatives(camNew,s = 1,ni=1)[0] childGrps = mc.listRelatives(camNew,c=1,type = 'transform') leftGrp = '' rightGrp = '' for checkGrp in childGrps: if 'Left' in checkGrp: leftGrp = checkGrp if 'Right' in checkGrp: rightGrp = checkGrp # 重新处理立体连接 leftGrpAttr = '%s|%s.tx'%(camNew,leftGrp) tempAttr = mc.connectionInfo(leftGrpAttr,gla=1) if tempAttr: mc.setAttr(tempAttr,l=0) cons = mc.listConnections(leftGrpAttr,s=1,d=0,plugs=1) if shotInfo[0] in ['do6'] and cons: mel.eval('source "channelBoxCommand.mel"') mel.eval('CBunlockAttr %s'%leftGrpAttr) if cons: mc.disconnectAttr(cons[0],leftGrpAttr) mc.expression(s = '%s=-0.5*%s.interaxialSeparation'%(leftGrpAttr,camShape),o = leftGrp ) rightGrpAttr = '%s|%s.tx'%(camNew,rightGrp) tempAttr = mc.connectionInfo(rightGrpAttr,gla=1) if tempAttr: mc.setAttr(tempAttr,l=0) cons = mc.listConnections(rightGrpAttr,s=1,d=0,plugs=1) if shotInfo[0] =='do6' and cons: mel.eval('source "channelBoxCommand.mel"') mel.eval('CBunlockAttr %s' %rightGrpAttr) if cons: mc.disconnectAttr(cons[0],rightGrpAttr) mc.expression(s = '%s=0.5*%s.interaxialSeparation'%(rightGrpAttr,camShape),o = rightGrp ) # pairx rigShape = mc.listRelatives(camNew,s=1,type = 'stereoRigCamera')[0] rigFrustum = mc.listRelatives(camNew,s=1,type = 'stereoRigFrustum')[0] print '------------tMode' print camShape print rigShape mc.connectAttr('%s.zeroParallax'%camShape,'%s.zeroParallax'%camNew,f=1) mc.connectAttr('%s.zeroParallax'%camShape,'%s.zeroParallax'%rigFrustum,f=1) # center attrs = ['.filmOffsetLeftCam','.filmOffsetRightCam','.interaxialSeparation','.stereo','.toeInAdjust'] centerPre = camNeed centerShape = centerPre + 'CenterCamShape' centerGrp = centerPre for attr in attrs: mc.setAttr((centerGrp + attr),l = 0) mc.connectAttr((centerShape + attr),(centerGrp + attr) ,f = 1) cons = mc.listConnections(camNew,s = 1 ,type = 'constraint') if cons: cons = list(set(cons)) mc.delete(cons) # 清理shape的某些信息 camNewShape = mc.listRelatives(camNew,s=1,type = 'camera',f=1) shapeCons = mc.listConnections(camNewShape,s=1,d=0,c=1,plugs=1) if shapeCons: consNum = len(shapeCons) for num in range(consNum/2): consAttr = shapeCons[num*2+1] if '>' in consAttr: consAttr = consAttr.split('>')[-1] consNode = consAttr.split('.')[0] # 判断 nodeType = mc.nodeType(consNode) if 'animCurve' in nodeType: continue checkAttr = shapeCons[num*2+1] if (not mc.referenceQuery(checkAttr.split('.')[0],inr = 1)) and mc.getAttr(checkAttr,l=1): mc.setAttr(checkAttr,l=0) checkAttr = shapeCons[num*2] if (not mc.referenceQuery(checkAttr.split('.')[0],inr = 1)) and mc.getAttr(checkAttr,l=1): mc.setAttr(checkAttr,l=0) # 断开 mc.disconnectAttr(shapeCons[num*2+1],shapeCons[num*2]) # 善后,清理 mc.delete(locTemp) # 属性 baseShape = mc.listRelatives(camBase,s=1,f=1)[0] newShape = mc.listRelatives(camNew,s=1,type = 'camera',f=1)[0] fixAttrList = ['.horizontalFilmAperture','.verticalFilmAperture','.filmFit'] for attr in fixAttrList: newAttr = newShape + attr if not mc.ls(newAttr): continue oldAttr = baseShape + attr mc.setAttr(newAttr,l=0) mc.setAttr(newAttr,mc.getAttr(oldAttr)) # 处理scale,属性打1 for attr in ['.sx','.sy','.sz']: cons = mc.listConnections((camNew + attr),s=1,d=0,plugs=1) if cons: mc.disconnectAttr(cons[0],(camNew + attr)) mc.setAttr((camNew + attr),l=0) mc.setAttr((camNew + attr),1) # 恢复立体连接 # 锁、出组 fixCamList = [] if stereoMode: camShapes = mc.listRelatives(camNew,ad=1,type='camera',f=1) fixCamList = mc.listRelatives(camShapes,p=1,type='transform',f=1) sk_sceneTools.sk_sceneTools().checkLockObjs(fixCamList,1,1) for checkCam in fixCamList: attrs = mc.listAttr(checkCam,k=1) if not attrs: continue for attr in attrs: mc.setAttr((checkCam + '.' +attr),l = 1)
def load_plugin(): if not mc.pluginInfo('normalCopy', q=1, l=1): mc.loadPlugin('normalCopy.mll')
def setUpClass(cls): standalone.initialize('usd') cmds.loadPlugin('pxrUsd', quiet=True)
import maya.standalone as ms import maya.cmds as mc import functions as f ms.initialize("Python") mc.loadPlugin("Mayatomr") # Load all plugins you might need mc.loadPlugin("RadeonProRender") if __name__ == "__main__": parser = f.createParser() ns = parser.parse_args(f.sys.argv[1:]) print(ns) f.createObjects(ns.objecttype, ns.objectcount, ns.materialcount) f.createLights(ns.lighttype, ns.lightcount) if(ns.isibl): f.createIBL() f.changeMaxSamples(ns.maxsamples) f.changeThreshold(ns.threshold) f.createMetadata(ns) f.makeImage() f.setCamera(ns.objectcount) #>mayapy D:\Workspace\test_scpirts\test.py -ot Cube -oc 3 -lt Physical -mc 2 -lc 4 -ibl true -ms 400 -th 0.001 #>render -r FireRender -rd C:\Users\Denispoper\Desktop\testResults -of jpeg -im testResultImage -x 1000 -y 1000 C:\Users\Denispoper\Desktop\mayaimages\test.mb
''' Script Batch Processes Maya Preview Images . requires C:\Program Files\Autodesk\Maya2014\bin\mayapy.exe as python executable ''' import maya.standalone maya.standalone.initialize("Python") import maya.cmds as cmds cmds.loadPlugin("Mayatomr") import os import getpass import sys import subprocess import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from email.mime.image import MIMEImage class MayaScene(): def find(self): # Find Path with open('Path.txt', 'rb') as myfile: print(myfile) self.assetspath = myfile.read().rstrip() myfile.close
import maya.cmds as cmds from pipeline.engines import engine import sys cmds.loadPlugin('AbcExport.mll') cmds.file(sys.argv[3], o=True) print("SYSTEME ARG!!!!!!!!!!!!!!!!!!!!!!!!!!! : " + str(sys.argv)) #cmds.file(r"D:\projets\artfx\TD4\py_dcc\scene_Test.mb", o=True ) selected_namespace = "namespace" # Get all the object from the scene with the input namespace namespace = "{}:*".format(selected_namespace) nodes = cmds.ls(namespace, type='transform') command_list = [] for node in nodes: print node command_list.append( "-frameRange 1 25 -uvWrite -dataFormat ogawa -root {} -file D:/projets/artfx/TD4/py_dcc/alambic_exporter/esportABC/{}.abc" .format(node, node.replace(':', '_'))) cmds.AbcExport(j=command_list, verbose=True)
# @date 2013/5/13 # for debug #import debugmaya #debugmaya.startDebug() # Import Maya Modules import maya.cmds as cmds import pymel.core as pm #deformerTypes = ["probeDeformer","probeDeformerARAP","probeDeformerPy","probeLocator"] deformerTypes = ["probeDeformer", "probeDeformerARAP", "probeLocator"] for type in deformerTypes: try: cmds.loadPlugin(type) except: print("Plugin %s already loaded" % (type)) ## prepare interface class UI_ProbeDeformer: uiID = "ProbeDeformer" title = "ProbeDeformerPlugin" deformers = [] probes = {} ## Constructor def __init__(self): if pm.window(self.uiID, exists=True): pm.deleteUI(self.uiID)
def main(): if not mel.eval('exists "u3dUnfold"'): cmds.loadPlugin('Unfold3D') selFaces = cmds.ls(sl=1) selFaces = cmds.ls(selFaces,fl=1) selObj = selFaces[0].split('.')[0] faceUnwarp(selFaces) selUVs = cmds.polyListComponentConversion(selFaces,ff=1,tuv=1) faceDic = getDic(selFaces) vtxid_uvid = faceDic[0] vtxid_edgeid = faceDic[1] edgeid_vtxid = faceDic[2] vtxid_faceid = faceDic[3] faceid_numTriangles = faceDic[4] edgeid_length = faceDic[5] triangles = 0 for faceid in faceid_numTriangles: if faceid_numTriangles[faceid] == 1: triangles += 1 startVtxid = -1 for vtxid in vtxid_faceid: if len(vtxid_faceid[vtxid]) == 1 and faceid_numTriangles[vtxid_faceid[vtxid][0]] == 1: startVtxid = vtxid if startVtxid == -1: for vtxid in vtxid_faceid: if len(vtxid_faceid[vtxid]) == 1: startVtxid = vtxid vtxCount = len(vtxid_uvid) vtxLine0 = [] vtxLine1 = [] if triangles == 2 or triangles == 1: maxCount = vtxCount/2 nextEdge0 = vtxid_edgeid[startVtxid][0] nextEdge1 = vtxid_edgeid[startVtxid][1] currentVtx0 = startVtxid currentVtx1 = startVtxid tempCount = 0 while tempCount < maxCount: tempCount += 1 nextVtxes = edgeid_vtxid[nextEdge0] for i in nextVtxes: if i != currentVtx0: currentVtx0 = i break vtxLine0.append(currentVtx0) nextEdges = vtxid_edgeid[currentVtx0] for i in nextEdges: if i != nextEdge0: nextEdge0 = i break tempCount = 0 while tempCount < maxCount: tempCount += 1 nextVtxes = edgeid_vtxid[nextEdge1] for i in nextVtxes: if i != currentVtx1: currentVtx1 = i break vtxLine1.append(currentVtx1) nextEdges = vtxid_edgeid[currentVtx1] for i in nextEdges: if i != nextEdge1: nextEdge1 = i break vtxLineIntersect = list(set(vtxLine0).intersection(set(vtxLine1))) vtxLine0String = [] for i in vtxLine0: if not i in vtxLineIntersect: uvid = vtxid_uvid[i] vtxLine0String.append( selObj + '.map[' + str(uvid) + ']') vtxLine1String = [] for i in vtxLine1: if not i in vtxLineIntersect: uvid = vtxid_uvid[i] vtxLine1String.append( selObj + '.map[' + str(uvid) + ']') cmds.select(selFaces,r=1) uvbb = cmds.polyEvaluate(selUVs,bc2=1) if (uvbb[0][1]-uvbb[0][0]) > (uvbb[1][1]-uvbb[1][0]) : cmds.polyEditUV(rot=1,angle=90) uvbb0 = cmds.polyEvaluate(vtxLine0String,bc2=1) uvbb1 = cmds.polyEvaluate(vtxLine1String,bc2=1) if uvbb0[0][0]<uvbb1[0][0]: cmds.polyEditUV(vtxLine0String, u=-1,r=0) cmds.polyEditUV(vtxLine1String, u=-0.9,r=0) else: cmds.polyEditUV(vtxLine0String, u=-0.9,r=0) cmds.polyEditUV(vtxLine1String, u=-1,r=0) cmds.select(selUVs,r=1) cmds.select(vtxLine0String,d=1) cmds.select(vtxLine1String,d=1) cmds.unfold(i=5000,ss=0.001,gb=0,gmb=0.5,pub=0,ps=0,oa=0,us=0) cmds.unfold(selUVs,i=5000,ss=0,gb=0,gmb=0,pub=0,ps=0,oa=1,us=0) else: maxCount = vtxCount/2 nextEdge0 = vtxid_edgeid[startVtxid][0] nextEdge1 = vtxid_edgeid[startVtxid][1] currentVtx0 = startVtxid currentVtx1 = startVtxid tempCount = 0 while tempCount < maxCount: tempCount += 1 nextVtxes = edgeid_vtxid[nextEdge0] for i in nextVtxes: if i != currentVtx0: currentVtx0 = i break vtxLine0.append(currentVtx0) nextEdges = vtxid_edgeid[currentVtx0] for i in nextEdges: if i != nextEdge0: nextEdge0 = i break tempCount = 0 while tempCount < maxCount: tempCount += 1 nextVtxes = edgeid_vtxid[nextEdge1] for i in nextVtxes: if i != currentVtx1: currentVtx1 = i break vtxLine1.append(currentVtx1) nextEdges = vtxid_edgeid[currentVtx1] for i in nextEdges: if i != nextEdge1: nextEdge1 = i break vtxLineIntersect = list(set(vtxLine0).intersection(set(vtxLine1))) vtxLine0String = [] for i in vtxLine0: if not i in vtxLineIntersect: uvid = vtxid_uvid[i] vtxLine0String.append( selObj + '.map[' + str(uvid) + ']') vtxLine1String = [] for i in vtxLine1: if not i in vtxLineIntersect: uvid = vtxid_uvid[i] vtxLine1String.append( selObj + '.map[' + str(uvid) + ']') uvbb = cmds.polyEvaluate(selUVs,bc2=1) cmds.select(selFaces,r=1) if (uvbb[0][1]-uvbb[0][0]) > (uvbb[1][1]-uvbb[1][0]) : cmds.polyEditUV(rot=1,angle=90) cmds.unfold(selUVs,i=5000,ss=0,gb=0,gmb=0,pub=0,ps=0,oa=1,us=0) uvbb = cmds.polyEvaluate(selUVs,bc2=1) scale = 1/(uvbb[1][1]-uvbb[1][0]) moveV = 0.5-(uvbb[1][1]+uvbb[1][0])/2 cmds.polyEditUV(selUVs,v=moveV) cmds.polyEditUV(selUVs,s=1,su=scale,sv=scale,pu=-1,pv=0.5) length_vtxes = cmds.polyListComponentConversion(vtxLine0String,fuv=1,tv=1) length_edges = cmds.polyListComponentConversion(length_vtxes,fv=1,te=1,internal=1) cmds.select(vtxLine0String,r=1) edgeuvbb = cmds.polyEvaluate(vtxLine0String,bc2=1) uvheight = edgeuvbb[1][1] - edgeuvbb[1][0] edgesLength = 0 length_edges = cmds.ls(length_edges,fl=1) for edgeid in length_edges: edgesLength += edgeid_length[int(edgeid.split('[')[1][:-1])] densityScale = edgesLength/uvheight cmds.polyEditUV(selUVs,s=1,su=densityScale,sv=densityScale,pu=-1,pv=0.5) cmds.select(selUVs,r=1)
def main(): cmds.loadPlugin("AbcExport.mll") # get the top one objs = pm.ls(sl=True) if not objs: return pm.inViewMessage(smg="select object first", pos="midCenterTop", bkc=0x00FF1010, fade=True) pm.select(clear=True) for obj in objs: parent_node = pm.listRelatives(obj, children=True, fullPath=True, allParents=True) if parent_node: final = get_top(obj)[0] else: final = obj # judge the selection is ref or not ref_jud = pm.referenceQuery("%s" % final, isNodeReferenced=True) if ref_jud: file_path = pm.referenceQuery("%s" % final, filename=True) print file_path name_space = pm.referenceQuery("%s" % final, namespace=True) print name_space pm.mel.eval('file -importReference "%s"' % file_path) # remove the namespace pm.mel.eval('namespace -mv "%s" ":" -force' % name_space) # trying to get the shape group(filter of the curve and rig) pm.select(final, add=True) #deal with the samename node after import the reference readonly obj_list = cmds.ls(sl=True, long=True, dag=True) obj_list.sort(key=len, reverse=True) renamedict = {} namelist = [] for obj in obj_list: obj_name = obj.split("|")[-1] print obj_name if not namelist.count(obj_name): namelist.append(obj_name) renamedict[obj_name] = [obj] else: renamedict[obj_name].append(obj) for name in namelist: paths = renamedict[name] paths.sort(key=len, reverse=True) if len(paths) == 1: continue print name, paths index = 1 for path in paths: new_name = "%s_%s" % (name, index) index += 1 cmds.rename(path, new_name) # pm.select(clear=True) # pm.select(final, add=True) objs = pm.ls(sl=True, long=True) geo_list = [] for obj in objs: print obj geo = None children = pm.listRelatives(obj, children=True, fullPath=True) for child in children: print pm.objectType(child) if "geo" in child.name() or "Geo" in child.name(): geo = child geo_list.append(geo) break else: geo = None if not geo: if len(children) == 1 and pm.objectType(children) == "mesh": geo = obj geo_list.append(geo) continue else: for child in children: if get_next(child): geo = child geo_list.append(geo) pm.select(clear=True) pm.select(geo_list, add=True) print(666666666666666666666666666666666666666666666666666) # use the current filepath as the clue to query the destination current_path = pm.mel.eval("file -q -sn") filename = os.path.basename(current_path) abc_name = os.path.splitext(filename)[0] + ".abc" rp_code = os.path.dirname(current_path).split("/")[-1] dirname = os.path.join( os.path.dirname(current_path)[:-len(rp_code)], "abc") abc_name = os.path.normpath(os.path.join(dirname, abc_name)) sel_frameRange = str(pm.playbackOptions(q=True, minTime=True) - 10) + " " + str( pm.playbackOptions(q=True, maxTime=True) + 10) root_geo = "" for obj in geo_list: root_geo += "-root %s " % obj print root_geo pm.AbcExport( j="-frameRange {frameRange} -uvWrite -worldSpace -writeVisibility -dataFormat hdf {file} -file {path}" .format(frameRange=sel_frameRange, file=root_geo, path=abc_name))
def export_interior_mappings(fbx_source_folder="C:\\Users\\their\\Documents\\AndreJukebox_Irene\\fbx_refs", json_out_dir="C:\\Users\\their\\dev\\andre_jukebox\\scripts\\maya_jukebox\\mtoa_convert"): maya. standalone.initialize() cmds.loadPlugin("fbxmaya") cmds.loadPlugin("mtoa") interior_mapping = {} unmapped_shaders = {} fbx_paths = [] for root, dirnames, filenames in os.walk(fbx_source_folder): for filename in fnmatch.filter(filenames, "*.fbx"): fbx_paths.append(os.path.join(root, filename)) for fbx_path in fbx_paths: print(fbx_path) building = os.path.splitext(os.path.basename(fbx_path))[0] cmds.file(new=True, force=True) cmds.file(fbx_path, o=True, ignoreVersion=True) for interior_name_pattern in (constants.INTERIOR, constants.EXPOSITION): for transform in cmds.ls(interior_name_pattern, transforms=True): interior_name_key = interior_name_pattern shader_engine = cmds.listConnections(cmds.listHistory(transform), type = 'shadingEngine') shaders = cmds.ls(cmds.listConnections(shader_engine), materials=True, type="phong") if shaders: shader = shaders[0] if interior_name_pattern == constants.INTERIOR: transform_id = transform.lower() if "hop_" in transform: # "*hop_interior_*" only has one shader interior_name_key = constants.SHOP_INTERIOR transform = ("_").join(transform.split("_")[0:-1]) version = 1 elif not shader.startswith(("am215", "AM215")): if unmapped_shaders.has_key(building): unmapped_shaders[building].update({transform: shader}) else: unmapped_shaders[building] = {transform: shader} continue else: transform = ("_").join(transform.split("_")[0:-1]) version_tail = re.split("_V", shader, flags=re.IGNORECASE)[-1] version = int(version_tail.split("_")[0]) elif interior_name_pattern == constants.EXPOSITION: if not shader.startswith(("am215", "AM215")): if unmapped_shaders.has_key(building): unmapped_shaders[building].update({transform: shader}) else: unmapped_shaders[building] = {transform: shader} continue transform_id = cmds.polyEvaluate(transform, v=True) # vertex count file_node = cmds.listConnections("{}".format(shader), type="file") if not file_node: continue file_map = cmds.getAttr("{}.fileTextureName".format(file_node[0])) version = int(os.path.splitext(file_map)[0].split("_V")[-1]) if interior_mapping.has_key(building) and transform_id not in interior_mapping[building].keys(): interior_mapping[building].update({transform_id: constants.interior_mapping[interior_name_key].format(version)}) elif not interior_mapping.has_key(building): interior_mapping[building] = {transform_id: constants.interior_mapping[interior_name_key].format(version)} outfile = os.path.join(json_out_dir, "interior_mappings.json") with open(outfile, "w") as outfile: json.dump(interior_mapping, outfile) unmapped_outfile = os.path.join(json_out_dir, "unmapped_shaders.json") with open(unmapped_outfile, "w") as unmapped_outfile: json.dump(unmapped_shaders, unmapped_outfile) print("_---------_") print(interior_mapping) maya.standalone.uninitialize()
hr.hairSystemAutomator( 'cejas' ) import hair.hair as hr import general.mayaNode.mayaNode as mn import maya.cmds as mc reload( hr ) sel = mn.ls( sl = True )[0] mc.select( sel.children ) asd = hr.hairSystemAutomator( sysName = sel.name.replace( '_lock_grp', '' ), scalp = 'CabezaBase_hrs' ) """ full_path = os.path.realpath(__file__) mc.loadPlugin(os.path.dirname(full_path) + '/curvesFromMesh.mll') def hairSystemAutomator(sysName='', scalp=None): """creates a hair system based on selected lock meshes, if you specify a scalp it will use that to place follicles""" hair_polygons = mn.ls(sl=1) all_grp = mn.Node(mc.group(n=sysName + '_hair_grp', em=True)) hairSystem = mn.createNode('hairSystem') hairSystemPar = hairSystem.parent hairSystemPar.name = sysName + '_hairSystem' hairSystem = hairSystemPar.shape hairSystemPar.parent = all_grp pfxHair = mn.createNode('pfxHair') pfxHairPar = pfxHair.parent pfxHairPar.name = sysName + '_pfxHair'
mc.error("****CLEAN FOR RECOMPILING NODE*****") print('BUILD TEST __________________________ PREPARE SCENE') mc.file(pathBuildTest, i=True) curve = 'curve' curveShape = mc.listRelatives(curve, c=True, s=True)[0] upCurve = 'upCurve' upCurveShape = mc.listRelatives(upCurve, c=True, s=True)[0] curveBase = 'curveBase' curveBaseShape = mc.listRelatives(curveBase, c=True, s=True)[0] upCurveBase = 'upCurveBase' upCurveBaseShape = mc.listRelatives(upCurveBase, c=True, s=True)[0] print('BUILD TEST __________________________ LOAD NODE') mc.loadPlugin(pathNode) print('BUILD TEST __________________________ CREATE NODE') newNode = mc.createNode(nodeType) print('BUILD TEST __________________________ CONNECT IN') mc.connectAttr(curveShape + '.worldSpace[0]', newNode + '.curve') mc.connectAttr(upCurveShape + '.worldSpace[0]', newNode + '.upCurve') mc.connectAttr(curveBaseShape + '.worldSpace[0]', newNode + '.curveBase') mc.connectAttr(upCurveBaseShape + '.worldSpace[0]', newNode + '.upCurveBase') mc.connectAttr('locator1.worldMatrix[0]', newNode + '.matrices[0]') mc.connectAttr('locator1.param', newNode + '.matricesParams[0]') mc.connectAttr('locator2.worldMatrix[0]', newNode + '.matrices[1]') mc.connectAttr('locator2.param', newNode + '.matricesParams[1]')
def setUpClass(cls): cmds.loadPlugin('mayaUsdPlugin')
def setUpClass(cls): mc.file(f=True, new=True) mc.loadPlugin('AL_USDMayaPlugin')
Usage: mayapy RunTests.py AbcExport AbcImport AbcStitcher [tests.py] Where: AbcExport is the location of the AbcExport Maya plugin to load. AbcImport is the location of the AbcImport Maya plugin to load. AbcStitcher is the location of the AbcStitcher command to use. If no specific python tests are specified, all python files named *_test.py in the same directory as this file are used. """ if len(sys.argv) < 4: raise RuntimeError(usage) MayaCmds.loadPlugin(sys.argv[1]) print 'LOADED', sys.argv[1] MayaCmds.loadPlugin(sys.argv[2]) print 'LOADED', sys.argv[2] if not os.path.exists(sys.argv[3]): raise RuntimeError(sys.argv[3] + ' does not exist') else: os.environ['AbcStitcher'] = sys.argv[3] suite = unittest.TestSuite() main_dir = os.path.dirname(os.path.abspath(__file__)) os.chdir(main_dir) MelEval('chdir "%s"' % main_dir)
import os import subprocess import sys import tempfile # Initialize import maya.standalone try: maya.standalone.initialize(name='python') except RuntimeError: pass import maya.cmds as cmds cmds.loadPlugin("fbxmaya") import maya.cmds as mc def convert_skeleton(): group_name = mc.group(empty=True, name="PrimitiveSkeleton") parents = [ j for j in mc.ls(type='joint') if not mc.listRelatives(j, p=True, type='joint') ] for joint in parents: convert_joint(joint, group_name)
def copyReqFileToFolder(self): plugFileName = 'Kang_SimpExpNode' # 修改這個 #判斷版本,一律假設64bit mversion = str( maya.mel.eval( "float $mayaVersion = `getApplicationVersionAsFloat` ;")) strMversion = mversion.split('.')[0] #丟到有帶版本號的 script folder usd = cmds.internalVar(usd=True) usrFold = usd[:-8] custPlugFold = usrFold + "plug-ins/" cpyDestFolder = custPlugFold plgFod = self.thisScrptPth + '/MXSController/mll/maya' + strMversion + '/' plgDllFile = plgFod + plugFileName + '.mll' cpyDestDllFile = cpyDestFolder + plugFileName + '.mll' # 有可能會有版本衝突,先刪除 try: os.remove(cpyDestDllFile) except: pass opRes = None if (os.path.isfile(cpyDestDllFile)): try: opRes = open(cpyDestDllFile, 'r') except: pass if (not opRes): #檔存在的話就不用co了 try: res = os.makedirs(cpyDestFolder) #強制建Folder except: pass #Copy 所需的pyd files #import shutil shutil.copy2(plgDllFile, cpyDestDllFile) else: opRes.close() #臨時加入當前 plugin Folder sysplugFldPth = maya.mel.eval("$sr = `getenv MAYA_PLUG_IN_PATH`;") if (not (cpyDestFolder in sysplugFldPth)): maya.mel.eval("$str = `putenv MAYA_PLUG_IN_PATH \"" + cpyDestFolder + "\"`;") #load try: cmds.unloadPlugin(plugFileName) except: pass if not cmds.pluginInfo((plugFileName + ".mll"), q=True, loaded=True): cmds.loadPlugin(plugFileName) #set autoloaded cmds.pluginInfo((plugFileName + ".mll"), e=True, autoload=True) #找尋maya.env檔,寫入 usd = cmds.internalVar(usd=True) usrFold = usd[:-8] mayaEnvFilePath = usrFold + "Maya.env" if os.path.isfile(mayaEnvFilePath): # read all f = open(mayaEnvFilePath, 'r') allLines = [] newAllLines = [] line = f.readline() line = line.replace("\r", "") line = line.replace("\n", "") if (len(line)): allLines.append(line) while (line != ''): line = f.readline() if (len(line)): line = line.replace("\r", "") line = line.replace("\n", "") allLines.append(line) f.close() if (len(allLines)): for li in allLines: #li=allLines[0] if ("MAYA_PLUG_IN_PATH" in li): lnChk = li.replace(" ", "") lnChk = li.replace("=", "") ssrt = lnChk.split('MAYA_PLUG_IN_PATH')[1] ssrt = ssrt.replace(" ", "") if (not len(ssrt)): li += cpyDestFolder elif (not cpyDestFolder in li): li += ';' + cpyDestFolder li += "\r\n" newAllLines.append(li) else: newAllLines.append("MAYA_PLUG_IN_PATH = " + cpyDestFolder) #write all f = open(mayaEnvFilePath, 'w') f.writelines(newAllLines) f.close() else: #創一個新的 f = open(mayaEnvFilePath, 'w+') f.write("MAYA_PLUG_IN_PATH=" + cpyDestFolder) f.close()
def setUpClass(cls): standalone.initialize('usd') cmds.loadPlugin('pxrUsd') cls.usdFile = os.path.abspath('CubeWithVariantsModel.usda') cls.primPath = '/CubeWithVariantsModel'
def extract_anim(self): cmds.loadPlugin("animImportExport", quiet=True) package_path = self.create_package() entry_file = self.file_name("anim") entry_path = os.path.join(package_path, entry_file) sele_file = self.file_name("mel") sele_path = os.path.join(package_path, sele_file) # Save animated nodes with order with capsule.maintained_selection(): cmds.select(self.data["outAnim"], replace=True) with contextlib.nested( capsule.namespaced(self.data["animatedNamespace"], new=False), capsule.relative_namespaced() ): # Save with basename with open(sele_path, "w") as fp: fp.write("select -r\n" + "\n".join(cmds.ls(sl=True)) + ";") context_data = self.context.data start = context_data.get("startFrame") end = context_data.get("endFrame") with contextlib.nested( capsule.no_refresh(), capsule.maintained_selection(), capsule.undo_chunk(), ): lib.bake(self.data["outAnim"], frame_range=(start, end), shape=False) cmds.select(self.data["outAnim"], replace=True, noExpand=True) cmds.file(entry_path, force=True, typ="animExport", exportSelectedAnim=True, options=("options=keys;" "hierarchy=none;" "precision=17;" "intValue=17;" "nodeNames=1;" "verboseUnits=0;" "whichRange=1;" "helpPictures=0;" "useChannelBox=0;" "controlPoints=1;" "shapes=1;" "copyKeyCmd=" "-animation objects " "-option keys " "-hierarchy none " "-controlPoints 1 " "-shape 1") ) self.add_data({"entryFileName": entry_file, "animatedAssetId": self.data["animatedAssetId"]})
# Variables # test_out = sys.argv[1] rendercam = sys.argv[1] template = sys.argv[2] anim_file = sys.argv[3] render_file = sys.argv[4] min_time = sys.argv[5] max_time = sys.argv[6] # List the plugins that are currently loaded plugins = cmds.pluginInfo(query=True, listPlugins=True) # Load Redshift if "redshift4maya" in plugins: print "Redshift is already loaded." else: cmds.loadPlugin('redshift4maya') print "Redshift is now loaded." # full path to your Maya file to OPEN maya_file_to_open = r"P:/sequence_rnd_02/sequences/001/clayblast/Rendering/work/maya/clayblast_Rendering_Template_v001.ma" # full path to your Maya file to IMPORT maya_file_to_import = r"P:/sequence_rnd_02/sequences/001/clayblast/Lay/work/maya/clayblast_Lay_v001.ma" render_file = r"C:/mayapyTest/" + test_out + ".ma" # Have a namespace if you want (recommended) namespace = "anim" cmds.file(maya_file_to_open, o=True) # Import the file. the variable "nodes" will hold the names of all nodes imported, just in case.
def load_fbx(version_string): cmds.loadPlugin(PLUGIN, quiet=True), plugin_is_loaded = cmds.pluginInfo(PLUGIN, q=True, v=True) == version_string assert plugin_is_loaded
def exportNodesToVrayScene(nodeList,fpn,range=None): ''' THE BIG CHEESE this is th main method here's the inputs nodeList list of nodes you would like to export fpn the name of your output file example c:\temp\objects.vrscene range optional tuple with the first and last frame if you need to export of a time range the default of none sets it to export only the current frame ''' if not len(nodeList): print 'ERROR: select some nodes homie' return False #this snippet is used to set the visiblity of objects back to on in the vrscene... code = str(''' from vray.utils import * nodes=findByType("Node") for i in nodes:i.set("visible", 1) ''') #make sure we set vray as the active render... plugins = {'vrayformaya.mll':False, 'xgenVRay.py':False} #if vray is not the current render then lets try to make it so... if mel.eval('currentRenderer()') != 'vray': #check if vray dlls are loaded and if they are not load them for p in plugins: if cmds.pluginInfo(p,q=True,l=True): plugins[p] = True continue val = cmds.loadPlugin( p,quiet=True) if not val:continue plugins[p] = True #if we fail to at least load vrayformaya.mll let's quit out :( if not plugins['vrayformaya.mll']: print 'method exportNodesToVrayScene could not load vray, sorry booboo' return False #now that vray is loaded let's set it as the current renderer cmds.setAttr('defaultRenderGlobals.currentRenderer', 'vray', type='string' ) #now that vray has been set let's add a vray settings node if it doesn't exist if not cmds.objExists('vraySettings'):mel.eval('vrayCreateVRaySettingsNode()') #capture settings attrs = ['vraySettings.globopt_geom_doHidden', 'vraySettings.postTranslatePython', 'vraySettings.vrscene_render_on', 'vraySettings.vrscene_on', 'vraySettings.vrscene_filename', 'vraySettings.animType', 'defaultRenderGlobals.startFrame', 'defaultRenderGlobals.endFrame', 'defaultRenderGlobals.byFrameStep'] backUp = attrListToDic(attrs) #let's now apply all our export settings cmds.setAttr('vraySettings.globopt_geom_doHidden',2) cmds.setAttr('vraySettings.postTranslatePython',code,type='string') cmds.setAttr("vraySettings.vrscene_render_on",False) cmds.setAttr("vraySettings.vrscene_on", True) cmds.setAttr('vraySettings.vrscene_filename',fpn,type='string') cmds.setAttr("vraySettings.animType",0) #if a range is provided (tuple first and last frame) if range: cmds.setAttr('vraySettings.animType',1) cmds.setAttr('defaultRenderGlobals.startFrame',range[0]) cmds.setAttr('defaultRenderGlobals.endFrame',range[1]) cmds.setAttr('defaultRenderGlobals.byFrameStep',1.0) #export if os.path.isfile(fpn):os.remove(fpn) ndLString = ' '.join(nodeList) print '--->NodeString=',ndLString cmds.vrend(bat=True,exportSpecific=ndLString) #restore settings setAttrsFromDic(backUp) #check to see that our file was written out if not os.path.isfile(fpn): print 'looks like the export failed output path could not be verified' return False return True
def shotSplitter_process(*args): start_time = time.time() #get info textFile = cmds.textField("shotSplitterTextFile", q=True, text=True) audioFile = cmds.textField("shotSplitterAudioFile", q=True, text=True) #fbxFile = cmds.textField("shotSplitterFBXFile", q = True, text = True) output = cmds.textField("shotSplitterOutput", q=True, text=True) mel.eval('trace "Getting Data from text file..." ;') #get shot data from the text file shotInfo = shotSplitter_getShotData(textFile) #import in the audio file #if audioFile != "": #mel.eval('trace "Importing audio..." ;') #cmds.file(audioFile, i = True, type = "audio") ##offset audio 300 frames #firstShot = shotInfo[0] #offsetValue = firstShot[1] #audioFileName = audioFile.rpartition("/")[2].partition(".")[0] #cmds.setAttr(audioFileName + ".offset", offsetValue) #import in the fbx file and set it up #mel.eval('trace "Setting up matinee FBX file..." ;') cmds.unloadPlugin("fbxmaya.mll") cmds.loadPlugin("fbxmaya.mll") shotSplitter_setupFBXFile() #snap the characters to their spots and orient everything correctly #mel.eval('trace "Snapping Characters..." ;') #shotSplitter_setupCharacters() #save out individual shot files mel.eval('trace "Saving out master file..." ;') masterFile = shotSplitter_SaveMaster() i = 0 sceneFrameEnd = shotSplitter_findSceneFrameRange() for shot in shotInfo: shotNum = shot[0] mel.eval('trace "Creating shot %s" ;' % str(shotNum)) shotFrameStart = shot[1] try: shotFrameEnd = shotInfo[i + 1][1] except IndexError: print "Last shot. Using Scene Frame Range" shotFrameEnd = sceneFrameEnd shotCamera = shot[2] shotName = shot[3] #set frame range, set camera, save out shot cmds.playbackOptions(min=shotFrameStart, max=shotFrameEnd, ast=shotFrameStart, aet=shotFrameEnd) if cmds.objExists(shotCamera): cameraName = cmds.listRelatives(shotCamera, children=True)[0] #debug print print(cameraName) #if shake is in the name #select the non shake camera if 'Shake' in cameraName: print('changing name') cameraName = cameraName.partition('_Shake')[0] #debug print print('changing the camera name to ' + cameraName) newCamName = cmds.rename(cameraName, "SHOT_CAM") #lock the camera cmds.setAttr(newCamName + ".tx", lock=True) cmds.setAttr(newCamName + ".ty", lock=True) cmds.setAttr(newCamName + ".tz", lock=True) cmds.setAttr(newCamName + ".rx", lock=True) cmds.setAttr(newCamName + ".ry", lock=True) cmds.setAttr(newCamName + ".rz", lock=True) cmds.setAttr(newCamName + ".sx", lock=True) cmds.setAttr(newCamName + ".sy", lock=True) cmds.setAttr(newCamName + ".sz", lock=True) #This will get replaced when the new text file info is in f = open(textFile, "r") lines = f.readlines() f.close() #find the cine name cineFullName = lines[1] cineName = cineFullName.partition(": ")[2] cineName = cineName.rstrip("\r\n") #chop off excess keys cmds.select(all=True) try: cmds.cutKey(option="keys", time=(0, shotFrameStart - 30)) cmds.cutKey(option="keys", time=(shotFrameEnd + 30, 120000)) except: pass #save out the shot if shotName.find("<Unknown>") == -1: newFileName = (output + "/" + cineName + "_" + shotName + ".mb") cmds.file(rename=newFileName) shotFile = cmds.file(save=True, type='mayaBinary', force=True) #rename the shot cam back if cmds.objExists(shotCamera): cmds.rename(newCamName, cameraName) #iterate i i = i + 1 #open up the master file cmds.file(masterFile, open=True, force=True, prompt=False) elapsed_time = time.time() - start_time timeInMins = str((elapsed_time / 60))[0:4] minutes = str(timeInMins).partition(".")[0] seconds = str(timeInMins).rpartition(".")[2] seconds = ("." + seconds) seconds = float(seconds) * 60 seconds = str(seconds)[0:2] finalTime = "Total Time: " + minutes + " minutes and " + seconds + " seconds" result = cmds.confirmDialog( title="Shot Splits Complete", message="Yay! Your shots have been generated! Total time: " + minutes + " minutes and " + seconds + " seconds", button=["Close"], cancelButton="Close", dismissString="Close")