Example #1
0
def buildMA(destDir, sourcePath, newShot):

    import pipelineTools

    newFile = os.path.join(destDir, newShot)

    if os.path.isfile(newFile):
        #raise  StandardError('this file already exists')
        startStop = raw_input('\n' + newFile +
                              '\n\nAlready exists. Overwrite? (y/n):')
        if startStop == 'n':
            print 'canceled file creation'
        elif startStop == 'y':
            pass
        else:
            print 'try again. Enter only \"y\" or \"n\"'
            return
    else:
        print '\n*Creating \n    ', newFile

    mc.file(rename=newFile)
    mc.file(type='mayaAscii')

    pipelineTools.importRef(sourcePath)

    lightingBasics(essid)
    mc.file(save=True, force=True, type='mayaAscii')
    print '\nSaved', newFile
    mc.quit()
Example #2
0
def tryRender(**kwargs):

    # 在mayapy解释器中初始化渲染环境
    print("Initialize MAYA Render Env ...")
    # Start Maya in batch mode
    try:
        maya.standalone.initialize('Python')
    except:
        print "standalone already running"
    print("Initialize OK.")

    # 执行渲染
    render(**kwargs)

    # 退出渲染环境
    cmds.quit(force=True, exitCode=0, abort=True)

    print("\n\n\nStart Uninitialize version = {}".format(
        float(cmds.about(v=True))))
    # Starting Maya 2016, we have to call uninitialize to properly shutdown
    if float(cmds.about(v=True)) >= 2016.0:
        maya.standalone.uninitialize()
        print("Uninitialize OK.\n\n\n")

    print("渲染结束.")
Example #3
0
def shutdown():
    print("*" * 80)
    print("shutting down")
    print("*" * 80)
    cmds.quit(force=True)
    server_instance.shutdown()
    raise sys.exit(0)
Example #4
0
def runTests(globals_dict, stream=sys.__stderr__, verbosity=1):
    '''
    Run the unittests within the given namespace

    Intended usage:
        import fixturesUtils
        if __name__ == '__main__':
            fixturesUtils.runTests(globals())
    '''
    import maya.cmds as cmds
    suite = loadTestsFromDict(globals_dict)
    runner = unittest.TextTestRunner(stream=stream, verbosity=verbosity)
    results = runner.run(suite)
    if results.wasSuccessful():
        exitCode = 0
    else:
        exitCode = 1

    # cmds.quit will not flush the streams - make sure we do so!
    # ...flush all of the standard ones just to be sure, as well as the stream
    # given (which probably means it will be flushed twice, but that's fine)
    sys.stdout.flush()
    sys.stderr.flush()
    sys.__stdout__.flush()
    sys.__stderr__.flush()
    stream.flush()

    # maya running interactively will absorb much of the output. comment out the
    # following to prevent maya from exiting and open the script editor to look
    # at failures.
    cmds.quit(abort=True, exitCode=exitCode)
Example #5
0
 def write_dict_info(self):
     print "write_dict_info is start "
     for i in self.analyze_list:
         if i == ' ':
             self.analyze_list.remove(' ')
     info_file_path = os.path.dirname(self["cg_info_file"])
     if not os.path.exists(info_file_path):
         os.makedirs(info_file_path)
     with open(self["cg_info_file"], "w") as f:
         for key in self.analyze_list:
             if self.has_key(key):
                 str_w = '%s::%s' % (key, self[key])
                 f.write(str_w)
                 f.write('\n')
                 f.flush()
             else:
                 continue
         f.write('Texture&Cache:')
         f.write('\n')
         f.flush()
         # for i in self['texture&cache']:
         # f.write(i)
         # f.write('\n')
         # f.flush()
         # f.flush()
         print "write cg_info_file"
         cmds.quit(force=True)
     cmds.quit(force=True)
def main():
    print("Render simple object for build render cache.")

    try:
        if not cmds.pluginInfo("RadeonProRender", q=True, loaded=True):
            print("Plugin not loaded, try to load...")
            cmds.loadPlugin("RadeonProRender")
    except Exception as err:
        print("Error during plugin load. {}".format(str(err)))
        cmds.quit(abort=True)

    print("Plugin has been loaded")

    try:
        print("Render sphere with RPR...")

        cmds.sphere(radius=4)

        cmds.setAttr("defaultRenderGlobals.currentRenderer",
                     "FireRender",
                     type="string")
        cmds.setAttr("RadeonProRenderGlobals.completionCriteriaSeconds", 1)
        cmds.setAttr("RadeonProRenderGlobals.completionCriteriaIterations", 1)
        cmds.fireRender(waitForItTwo=True)
        mel.eval("renderIntoNewWindow render")
        print("Render has been finished")
    except Exception as err:
        print("Error during rendering. {}".format(str(err)))
        cmds.quit(abort=True)
    finally:
        print("Quit")
        cmds.evalDeferred("cmds.quit(abort=True)")
Example #7
0
 def shutdown():
     print  "*" * 80
     print "shutting down"
     print "*" * 80
     cmds.quit(force=True)
     server_instance.shutdown()
     raise sys.exit(0)
def main():
    read_write_arg = sys.argv[1]
    filepath = sys.argv[2]

    write = False
    if read_write_arg == "write":
        write = True

    if write:
        # read the input OTIO off stdin
        input_otio = otio.adapters.read_from_string(
            sys.stdin.read(),
            'otio_json'
        )
        build_sequence(input_otio, clean=True)
        cmds.file(rename=filepath)
        cmds.file(save=True, type="mayaAscii")
    else:
        cmds.file(filepath, o=True)
        sys.stdout.write(
            "\nOTIO_JSON_BEGIN\n" +
            otio.adapters.write_to_string(
                read_sequence(),
                "otio_json"
            ) +
            "\nOTIO_JSON_END\n"
        )

    cmds.quit(force=True)
Example #9
0
def main(argv):
    parser = argparse.ArgumentParser(description='Get partnames for group.')
    parser.add_argument('-group', help='Group Name', required=True)
    parser.add_argument('-file', help='File Name', required=True)

    # initialize maya
    maya.standalone.initialize('Python')
    args = parser.parse_args()

    group = args.group
    filename = args.file

    cmds.file(filename, o=True, f=True)
    parts = cmds.listRelatives(group, ad=True, type='mesh')
    finalParts = []

    # Ignore any intermediate objects
    for part in parts:
        if not cmds.getAttr(part + '.intermediateObject'):
            finalParts.append(part)

    logging.info("GEO_PARTS: " + ','.join(finalParts))

    cmds.quit()
    os._exit(0)
Example #10
0
def main(argv):
    parser = argparse.ArgumentParser(description='Get partnames for group.')
    parser.add_argument('-group', help='Group Name', required=True)
    parser.add_argument('-file', help='File Name', required=True)

    # initialize maya
    maya.standalone.initialize('Python')
    args = parser.parse_args()

    group = args.group
    filename = args.file

    cmds.file(filename, o=True, f=True)
    parts = cmds.listRelatives(group, ad=True, type='mesh')
    finalParts = []

    # Ignore any intermediate objects
    for part in parts:
        if not cmds.getAttr(part+'.intermediateObject'):
            finalParts.append(part)

    logging.info("GEO_PARTS: " + ','.join(finalParts))

    cmds.quit()
    os._exit(0)
Example #11
0
 def wedgeSetup(self, mayaFile, cacheDir, containerName, wedgeName, wedgeNode, wedgeAttr):        
     wedgePath = "bla"
     try:
         attr = float(wedgeAttr)
     except ValueError:
         print(sys.exc_info())
         sys.exit("Cant convert {0} into a float number".format(wedgeAttr))
     try:
         # Initialize a new instance of maya
         maya.standalone.initialize()
         # Open up the source maya scene file
         #self.loadMaya()
         #cmds.file(mayaFile, open=True)
         print("maya init")
     except: 
         print(sys.exc_info())
         sys.exit("Something went wrong while trying to open the maya scene file: {0}. Check the path and try again".format(mayaFile))
     
     """
     # Select node for wedge and change attrs
     try: 
         print(wedgeNode)
         print(attr)
         cmds.setAttr(wedgeNode, attr)
     except:
         print(sys.exc_info())
         sys.exit("Couldn't set the wedge attributes {0} on this node: {1}".format(attr, wedgeNode))
     # Set containerNode to write cache
     try:
         # Wrties cache on /tmp folder
         # cmds.setAttr(containerName+'.cachingControl', 0)
         # Writes cache on cache folder
         cmds.setAttr(containerName + '.enableDiskCache', 1)
         cmds.setAttr(containerName + '.cachingControl', 2)
         # This will break window version --> adding /
         cmds.setAttr(containerName + '.cacheDir', cacheDir + '/', type="string")
         cmds.setAttr(containerName + '.cacheName', wedgeName, type="string")
     except: 
         print(sys.exc_info())        
         sys.exit("Couldn't set the Bifrost container: {0} to write status".format(containerName))
     # Rename the scene file and saves it
     try:
         # Setup new file name
         wedgePath = os.path.join(cacheDir, wedgeName + '.mb')
         print(wedgePath)
         # save new maya scene file
         cmds.file(rename=wedgePath)
         cmds.file(save=True, force=True, defaultExtensions=False, type='mayaBinary')
     except:
         print(sys.exc_info())
         sys.exit("Can't save to the following location: {0}. Please check and try agian".format(wedgePath))
     """
     # QUIT MAYA
     cmds.quit(force=True)
     print("Success")
     
     return wedgePath
Example #12
0
def initialize_maya():
    """ Initialize Maya before calling the test """

    # uses pymel which will correctly initialize maya startup
    import pymel.core as pm  # @UnusedImport

    yield

    # quits Maya
    cmds.quit(force=True)
Example #13
0
def main(argv):
    parser = argparse.ArgumentParser(
        description='Builds a lighting scene file.')
    parser.add_argument('-taskid', help='Ftrack Task ID', required=True)
    parser.add_argument('-taskDir', help='Task Directory', required=True)

    # initialize maya
    maya.standalone.initialize('Python')
    cmds.loadPlugin('AbcImport')

    args = parser.parse_args()
    taskid = args.taskid
    taskDir = args.taskDir

    task = ftrack.Task(taskid)
    shot = task.getParent()
    shotCam = getRenderCam(shot)
    envFile, envVersion = getEnvPublishFile(shot)
    animMeta, animVersion = getCharPublishFile(shot)

    metadata = task.getMeta()
    # Get the char bake version
    charVersion = getCharBakeVersion(envVersion, animVersion, metadata)
    # Bake out the char file from latest animation publish
    charFile = buildCharFile(taskDir, animMeta, charVersion)

    filename = '%s_v01.mb' % shot.getName()
    filepath = os.path.join(taskDir, filename)

    if os.path.exists(filepath):
        version = getLatestVersion(taskDir)
        oldFile = '%s_v%02d.mb' % (shot.getName(), version)
        newFile = '%s_v%02d.mb' % (shot.getName(), version + 1)
        oldFilePath = os.path.join(taskDir, oldFile)
        newFilePath = os.path.join(taskDir, newFile)
        shutil.copyfile(oldFilePath, newFilePath)
        metadata['filename'] = newFilePath
        cmds.file(newFilePath, open=True)
    else:
        cmds.file(new=True)
        cmds.file(rename=filepath)
        metadata['filename'] = filepath

    # build the scene
    buildScene(shotCam, envFile, charFile)

    cmds.quit()
    # Set metadata
    metadata['charFile'] = charFile
    metadata['char_version'] = 'v%02d' % charVersion
    metadata['anim_version'] = animVersion
    metadata['env_version'] = envVersion
    task.setMeta(metadata)

    os._exit(0)
def main(argv):
    parser = argparse.ArgumentParser(description='Builds a lighting scene file.')
    parser.add_argument('-taskid', help='Ftrack Task ID', required=True)
    parser.add_argument('-taskDir', help='Task Directory', required=True)

    # initialize maya
    maya.standalone.initialize('Python')
    cmds.loadPlugin('AbcImport')

    args = parser.parse_args()
    taskid = args.taskid
    taskDir = args.taskDir

    task = ftrack.Task(taskid)
    shot = task.getParent()
    shotCam = getRenderCam(shot)
    envFile, envVersion = getEnvPublishFile(shot)
    animMeta, animVersion = getCharPublishFile(shot)

    metadata = task.getMeta()
    # Get the char bake version
    charVersion = getCharBakeVersion(envVersion, animVersion, metadata)
    # Bake out the char file from latest animation publish
    charFile = buildCharFile(taskDir, animMeta, charVersion)

    filename = '%s_v01.mb' % shot.getName()
    filepath = os.path.join(taskDir, filename)

    if os.path.exists(filepath):
        version = getLatestVersion(taskDir)
        oldFile = '%s_v%02d.mb' % (shot.getName(), version)
        newFile = '%s_v%02d.mb' % (shot.getName(), version+1)
        oldFilePath = os.path.join(taskDir, oldFile)
        newFilePath = os.path.join(taskDir, newFile)
        shutil.copyfile(oldFilePath, newFilePath)
        metadata['filename'] = newFilePath
        cmds.file(newFilePath, open=True)
    else:
        cmds.file(new=True)
        cmds.file(rename=filepath)
        metadata['filename'] = filepath

    # build the scene
    buildScene(shotCam, envFile, charFile)

    cmds.quit()
    # Set metadata
    metadata['charFile'] = charFile
    metadata['char_version'] = 'v%02d' % charVersion
    metadata['anim_version'] = animVersion
    metadata['env_version'] = envVersion
    task.setMeta(metadata)

    os._exit(0)
Example #15
0
def openMayaFile():
    maya.standalone.initialize(name='python')
    cmds.file(new=True, f=True, prompt=True)

    import importlib
    importlib.import_module('sys')
    print sys.argv[0]
    cmds.polyCube(n=nodeStr)
    print(cmds.ls())

    cmds.quit()
Example #16
0
def finish():
    """Finish the installation by cleaning up and displaying a
    confirmation window to restart Maya.
    """
    disableButtons()

    result = cmds.confirmDialog(
        title="Installation successful",
        message="You need to restart Maya for changes to take affect.",
        button=("Close", "Quit Maya"))
    if result == "Quit Maya":
        cmds.quit(force=True)
Example #17
0
def restartMaya(brute=True):
    '''force restart maya (use restartDialog)'''
    if not brute:
        mayaPyDir = os.path.join(os.path.dirname(sys.executable), "mayapy")
        if cmds.about(nt=True, q=True):
            mayaPyDir += ".exe"
        scriptDir = os.path.join(os.path.dirname(os.path.realpath(__file__)),
                                 "coopRestart.py")
        print scriptDir
        subprocess.Popen([mayaPyDir, scriptDir])
        cmds.quit(force=True)
    else:
        os.execl(sys.executable, sys.executable, *sys.argv)
Example #18
0
def fix_rig():
    import maya.cmds as mc
    # open file
    ext = os.path.splitext(options.file)[1]
    base_name = os.path.basename(options.file).split(".")[0]
    new_base_name = "%sbak%s" % (base_name, ext)
    new_os_name = os.path.abspath(
        os.path.join(os.path.dirname(options.file), new_base_name))
    if os.path.isfile(new_os_name):
        os.remove(new_os_name)
    mc.file(options.file, open=1, pmt=1)
    # bake file
    try:
        os.rename(options.file, new_os_name)
    except Exception as e:
        print "[AAS] error: %s" % (str(e))
    # fix rig
    try:
        mc.setAttr("R_Elbow_FK_Ctrl.rx", lock=1, keyable=0, channelBox=0)
    except:
        try:
            mc.setAttr("R_ElbowFK_Ctrl.rx", lock=1, keyable=0, channelBox=0)
        except Exception as e:
            print "[AAS] error: %s" % str(e)

    try:
        mc.setAttr("L_Elbow_FK_Ctrl.rx", lock=1, keyable=0, channelBox=0)
    except:
        try:
            mc.setAttr("L_ElbowFK_Ctrl.rx", lock=1, keyable=0, channelBox=0)
        except Exception as e:
            print "[AAS] error: %s" % str(e)

    try:
        mc.setAttr("R_Elbow_FK_Ctrl.rz", lock=1, keyable=0, channelBox=0)
    except:
        try:
            mc.setAttr("R_ElbowFK_Ctrl.rz", lock=1, keyable=0, channelBox=0)
        except Exception as e:
            print "[AAS] error: %s" % str(e)

    try:
        mc.setAttr("L_Elbow_FK_Ctrl.rz", lock=1, keyable=0, channelBox=0)
    except:
        try:
            mc.setAttr("L_Elbow_FKCtrl.rz", lock=1, keyable=0, channelBox=0)
        except Exception as e:
            print "[AAS] error: %s" % str(e)
    # save file
    mc.file(save=1)
    mc.quit(f=1)
Example #19
0
def external_Ops_ReplaceString(filepath):
    timeVar = str(time.localtime().tm_year) + '_' + str(
        time.localtime().tm_mon) + '_' + str(time.localtime().tm_mday)
    newpath = os.path.dirname(filepath) + '/history'
    if os.path.exists(newpath) is False:
        os.mkdir(newpath)
    filename = os.path.basename(filepath)
    shutil.copy(filepath, newpath + '/' + filename + '_' + timeVar)
    #os.rename(newpath+'/'+filename,newpath+'/'+filename+'_'+timeVar)

    try:
        maya.standalone.initialize('python')
    except:
        print 'Cannot initialize the python standalone'
        return

    import pymel.core
    import maya.cmds as cmds

    print 1
    libPath = '//S3/软件库/P_插件目录/YunMan_Toolsets/Common/Python'.decode('utf-8')
    arnoldPath = 'C:/solidangle/mtoadeploy/2016/scripts'
    print 2
    if sys.path.count(libPath) == 0:
        sys.path.append(libPath)
    if sys.path.count(arnoldPath) == 0:
        sys.path.append(arnoldPath)
    print 3
    try:
        cmds.file(filepath, open=True, prompt=True, f=True)
        print 4
    except:
        print 'Cannot Open the file: ' + filepath
        #maya.standalone.uninitialize()
        return

    if cmds.pluginInfo('AbcExport', q=True, loaded=True) is False:
        cmds.loadPlugin('AbcExport')
    if cmds.pluginInfo('mtoa', q=True, loaded=True) is False:
        cmds.loadPlugin('mtoa')

    try:
        replaceString()
    except:
        pass

    #maya.standalone.uninitialize()
    cmds.file(s=True)
    cmds.quit()
Example #20
0
def main():

    mel.eval("setProject(\"{res_path}\")")
    tests = {tests}
    for each in tests:
        prerender(each, 300)
    cmds.evalDeferred(cmds.quit(abort=True))
Example #21
0
def restartMaya(brute=True):
    """
    Restarts maya (CAUTION)
    Args:
        brute (bool): True if the Maya process should stop, False if Maya should be exited normally
    """
    if not brute:
        mayaPyDir = os.path.join(os.path.dirname(sys.executable), "mayapy")
        if cmds.about(nt=True, q=True):
            mayaPyDir += ".exe"
        scriptDir = os.path.join(os.path.dirname(os.path.realpath(__file__)), "coopRestart.py")
        print(scriptDir)
        subprocess.Popen([mayaPyDir, scriptDir])
        cmds.quit(force=True)
    else:
        os.execl(sys.executable, sys.executable, *sys.argv)
def myExit():
    base = studioBase.StudioSQL()

    if cmds.file(q=True, mf=True):
        saved = confirmSave()
        if saved:
            base.setAction('exit')
            mouseTimer.stopMouseTimer()
            cmds.quit(force=True)
    
    else:
        base.setAction('exit')
        mouseTimer.stopMouseTimer()
        cmds.quit(force=True)

    return True
Example #23
0
def external_Ops_exportABC(filepath):

    try:
        maya.standalone.initialize('python')
    except:
        print 'Cannot initialize the python standalone'
        return

    import pymel.core
    import maya.cmds as cmds

    print 1
    libPath = '//S3/软件库/P_插件目录/YunMan_Toolsets/Common/Python'.decode('utf-8')
    arnoldPath = 'C:/solidangle/mtoadeploy/2016/scripts'
    print 2
    if sys.path.count(libPath) == 0:
        sys.path.append(libPath)
    if sys.path.count(arnoldPath) == 0:
        sys.path.append(arnoldPath)
    print 3
    try:
        cmds.file(filepath, open=True, f=True)
        print 4
    except:
        print 'Cannot Open the file: ' + filepath
        #maya.standalone.uninitialize()
        return

    if cmds.pluginInfo('AbcExport', q=True, loaded=True) is False:
        cmds.loadPlugin('AbcExport')
    if cmds.pluginInfo('mtoa', q=True, loaded=True) is False:
        cmds.loadPlugin('mtoa')

    try:
        setRenderableCameras()
        exportCamera()
    except:
        pass
    try:
        exportAbcCmd()
    except:
        pass

    #maya.standalone.uninitialize()
    cmds.quit()
Example #24
0
def prerender(scene, rpr_iter):

    scene_name = cmds.file(q=True, sn=True, shn=True)
    print("Processing: " + scene_name + "\n")
    if scene_name != scene:
        try:
            cmds.file(scene,
                      f=True,
                      options="v=0;",
                      ignoreVersion=True,
                      o=True)
        except:
            print("Failed to open scene")
            cmds.evalDeferred(cmds.quit(abort=True))

    if not cmds.pluginInfo("redshift4maya", q=True, loaded=True):
        cmds.loadPlugin("redshift4maya")

    if not cmds.pluginInfo("RadeonProRender", q=True, loaded=True):
        cmds.loadPlugin("RadeonProRender")

    convertRS2RPR.auto_launch()

    print "Conversion finished.\n"

    cmds.setAttr("defaultRenderGlobals.currentRenderer",
                 "FireRender",
                 type="string")
    cmds.setAttr("defaultRenderGlobals.imageFormat", 8)
    cmds.setAttr("RadeonProRenderGlobals.completionCriteriaIterations",
                 rpr_iter)

    render_time = rpr_render(scene)

    print "Render finished. Render time: {{}}\n".format(render_time)

    filePath = "{work_dir}" + "/" + scene + "_RPR.json"
    report = {{}}
    report['render_device'] = cmds.optionVar(q="RPR_DevicesName")[0]
    report['tool'] = "Maya " + cmds.about(version=True)
    report['date_time'] = datetime.datetime.now().strftime("%m/%d/%Y %H:%M:%S")
    report['render_version'] = mel.eval("getRPRPluginVersion()")
    report['core_version'] = mel.eval("getRprCoreVersion()")
    report['file_name'] = "converted_" + scene + ".jpg"
    report['render_color_path'] = "Color/converted_" + scene + ".jpg"
    report['baseline_color_path'] = "Color/" + scene + ".jpg"
    report['scene_name'] = scene
    report['render_time'] = render_time
    report['test_case'] = scene
    report['difference_color'] = -0
    report['test_status'] = "passed"
    report['difference_time'] = -0
    report['difference_time_or'] = -0

    with open(filePath, 'w') as file:
        json.dump([report], file, indent=4)
Example #25
0
def startup(*args):
    #validate startup.xml
    if os.path.isfile('startup.xml') == False:
        #startup not found
        repVar=cmds.confirmDialog(icn='critical',t='error',message='There is no startup.xml found!',\
                           button=['Start Default','Close'])
        if repVar == 'Close': cmds.quit(f=True)
    else:
        #call layoutdialog
        try:
            cmds.layoutDialog(ui=uiFunction, t='ASIIST Startup')
        except:
            pass

    #start callback function
    om.MSceneMessage.addCallback(om.MSceneMessage.kBeforeSave,
                                 beforeSaveCallbackFun)
    om.MSceneMessage.addCallback(om.MSceneMessage.kAfterSave,
                                 afterSaveCallbackFun)
    return
Example #26
0
def buildCharFile(taskDir, animMeta, version):
    '''
    Build a char file containing the baked animation.
    :param taskDir: Lighting folder on disk
    :param animMeta: Animation task metadta
    :param version: Version of the baked char file
    :return: charFile: Baked char file path
    '''
    bakedDir = os.path.join(taskDir, 'baked')
    charFile = os.path.join(bakedDir, 'char.mb')
    if os.path.exists(charFile):
        os.remove(charFile)
    versionDir = os.path.join(bakedDir, 'v%02d' % version)
    if not os.path.exists(versionDir):
        os.makedirs(versionDir)
    charRefFile = os.path.join(versionDir, 'char.mb')
    if os.path.exists(charRefFile):
        os.remove(charRefFile)
    cmds.file(new=True, f=True)
    cmds.file(rename='%s' % charRefFile)

    for char in animMeta:
        if 'ref' in animMeta[char]:
            rigFile = animMeta[char]['ref']
            if 'modeling' in rigFile:
                modelRef = rigFile
            else:
                modelRef = getModelingRef(rigFile)
            if modelRef != '':
                cmds.file(modelRef, i=True, namespace='char_%s' % char)
                if 'publish' in animMeta[char] and 'mayaNode' in animMeta[char]:
                    cmds.AbcImport(animMeta[char]['publish'],
                                   connect=animMeta[char]['mayaNode'],
                                   mode='import',
                                   fitTimeRange=True)
                    print 'asset import: ' + animMeta[char]['publish']

    cmds.file(save=True, type='mayaBinary', force=True)
    cmds.quit()
    os.symlink(charRefFile, charFile)
    return charFile
Example #27
0
def exit_application(application="maya"):
    """
    This script is like close_script_job but it is much more aggressive and 
    forces the current application to shut off
    """
    if application == "maya":
        closeApp = functools.partial(cmds.quit(f=True))
        cmds.scriptJob(runOnce=True, e=['idle', closeApp])
    elif application == "nuke":
        nuke.scriptExit()
    elif application == "houdini":
        hou.exit()
Example #28
0
    def ErrorBase(self):
        self.print_trilateral(mode=1)
        print ('\n\n---------------------------------------------[ERROR BASE]start--------------------------------------------------\n\n')
        print ('\n')

        if len(self.error_list) != 0:
            if "..........Analysis  OK ,no error, analysis results have been written............" not in self.error_list:
                if len(self.error_list) != 0:
                    for i in self.error_list:
                        print ("[Analyze Error]%s" % (self.unicode_to_str(i)))
                # self.running_time("running")
                # print ('\n\n---------------------------------------------[ERROR BASE]end----------------------------------------------------\n\n')
                # self.print_trilateral(mode=2)
                cmds.quit(exitCode=555,force=True)
                # os._exit(-1)
            else:
                if len(self.reference_list) != 0:
                    # self.running_time("running")
                    # print ('\n\n---------------------------------------------[ERROR BASE]end----------------------------------------------------\n\n')
                    # self.print_trilateral(mode=2)
                    cmds.quit(exitCode=555, force=True)
                else:
                    self.print_info_err(u"..............没毛病.................")
                    # self.running_time("running")
                    # print ('\n\n---------------------------------------------[ERROR BASE]end----------------------------------------------------\n\n')
                    # self.print_trilateral(mode=2)
                    cmds.quit(exitCode=0, force=True)
        else:
            self.print_info_err(u"..............问题可能比较复杂,联系TD吧.................")
            # self.running_time("running")
            # print ('\n\n---------------------------------------------[ERROR BASE]end----------------------------------------------------\n\n')
            # self.print_trilateral(mode=2)
        print ('\n')
def buildCharFile(taskDir, animMeta, version):
    '''
    Build a char file containing the baked animation.
    :param taskDir: Lighting folder on disk
    :param animMeta: Animation task metadta
    :param version: Version of the baked char file
    :return: charFile: Baked char file path
    '''
    bakedDir = os.path.join(taskDir, 'baked')
    charFile = os.path.join(bakedDir, 'char.mb')
    if os.path.exists(charFile):
        os.remove(charFile)
    versionDir = os.path.join(bakedDir, 'v%02d' % version)
    if not os.path.exists(versionDir):
        os.makedirs(versionDir)
    charRefFile = os.path.join(versionDir, 'char.mb')
    if os.path.exists(charRefFile):
        os.remove(charRefFile)
    cmds.file(new=True, f=True)
    cmds.file(rename='%s' % charRefFile)

    for char in animMeta:
        if 'ref' in animMeta[char]:
            rigFile = animMeta[char]['ref']
            if 'modeling' in rigFile:
                modelRef = rigFile
            else:
                modelRef = getModelingRef(rigFile)
            if modelRef != '':
                cmds.file(modelRef, i=True, namespace='char_%s' % char)
                if 'publish' in animMeta[char] and 'mayaNode' in animMeta[char]:
                    cmds.AbcImport(animMeta[char]['publish'], connect=animMeta[char]['mayaNode'],
                                   mode='import', fitTimeRange=True)
                    print 'asset import: ' + animMeta[char]['publish']

    cmds.file(save=True, type='mayaBinary', force=True)
    cmds.quit()
    os.symlink(charRefFile, charFile)
    return charFile
Example #30
0
def main():
    try:
        parser = parse_arg(sys.argv[1:])
        source = parser.source
        destination = parser.destination
    except Exception as e:
        sys.stderr.write('Make simple process was failed')
        raise
    # Open file
    mc.file(source, force=True, open=True)
    # Process
    if parser.freeze: freezeAll()
    if parser.instance: convertInstance()
    if parser.copyTexture: copyTexture()
    if parser.deleteIntermediate: deleteAllIntermediateObject()
    if parser.vertexZero: setAllVertexToZero()
    #
    mc.file(rename=destination)
    mc.file(save=True, force=True, type='mayaAscii', uiConfiguration=False)
    mc.quit(f=True)
    print '# --- successiful! --- #'
    return 0
Example #31
0
def main():
    read_write_arg = sys.argv[1]
    filepath = sys.argv[2]

    write = False
    if read_write_arg == "write":
        write = True

    if write:
        # read the input OTIO off stdin
        input_otio = otio.adapters.read_from_string(sys.stdin.read(),
                                                    'otio_json')
        build_sequence(input_otio, clean=True)
        cmds.file(rename=filepath)
        cmds.file(save=True, type="mayaAscii")
    else:
        cmds.file(filepath, o=True)
        sys.stdout.write(
            "\nOTIO_JSON_BEGIN\n" +
            otio.adapters.write_to_string(read_sequence(), "otio_json") +
            "\nOTIO_JSON_END\n")

    cmds.quit(force=True)
Example #32
0
    def simulation_sanity_checks(nodes, timelimit, stretchmax):
        """ this function is a time changed callback which kill the
        simulation in case of explosion detected """
        result = False
        if stretchmax > 0:
            for node in nodes:
                if is_output_too_streched(node, stretchmax):
                    result = True
                    message = "excessive strech detect for node: " + node
                    logging.error(message)
                    break

        timespent = get_timespent_since_last_frame_set()
        if timespent is not None:
            if 0 < timelimit < timespent.seconds:
                message = "simulation time exceeds the limit allowed: {}"
                logging.error(message.format(timespent))
                result = True

        if result is True:
            logging.error("User defined explosion limit reached.")
            cmds.quit(force=True)
            exit()
Example #33
0
	def versionUp(self, runScripts=True, deleteUi=True):
		
		if cmds.file(q=True, sn=True) == '':
			cmds.file(rename=__main__.activeFilePath)
		
		if runScripts:
			self.runPreScripts(type='pre')
		
		workDir = '%s/work/%s' %(__main__.activeBasePath, __main__.activeApplication)
		__main__.activeFilePath = self.generateLatestVersionName(workDir)[0]
		cmds.file(rename=__main__.activeFilePath)
		cmds.file(save=True, type='mayaAscii')
				
		
		__main__.activeFile = __main__.activeFilePath.split('/')[-1]
		#__main__.activeFile = cmds.file(q=True, sceneName=True, shn=True)
		
		
		if runScripts:
			self.runPreScripts(type='post')
		
		afterProcess = cmds.optionMenu('saverGeneralAfterProcess_comboBox', q=True, value=True)
		if afterProcess == 'Exit Maya':
			cmds.quit(force=True)
		elif afterProcess == 'New Task':
			browser.Browser()
		
		# fileInfo file
		
		
		comment = cmds.scrollField('saverGeneralComment_text', q=True, text=True)
		name = self.activeUser
		
		fileName = __main__.activeBasePath+"/work/maya/fileInfo.py"
		if not os.path.isfile(fileName):  
			pathFile = os.popen('attrib +h ' + fileName)
			pathFile = open(fileName, 'w') 
		else:
			pathFile = open(fileName, 'a')
		pathFile.write(__main__.activeFile+'|'+comment+'|'+name+'\n')
		pathFile.close()
		# thumbnail
		thumbnail()
		
		
		# update browserUI
		filePath = __main__.activeFilePath
		tmp = filePath.split('/')[-1]
		path = filePath.split(tmp)[0]
		
		try:
			cmds.textScrollList('file_listWidget', e=True, ra=True)
			cmds.textScrollList('file_listWidget', e=True, append='Create initial work file')
			cmds.textScrollList('file_listWidget', e=True, append='Set to active task')
			cmds.textScrollList('file_listWidget', e=True, append='Latest file')
			cmds.textScrollList('file_listWidget', e=True, append='-----')
			sortedList = sorted(os.listdir(path))
			if sortedList:
				for file in sortedList:
						if file.endswith('ma'):
							cmds.textScrollList('file_listWidget', e=True, append=file)
		except:
			pass
			
		
		if deleteUi:
			cmds.deleteUI('saver_window')
Example #34
0
def Export_Abc():
    exportCamera()
    exportAbcCmd()
    maya.standalone.uninitialize()
    cmds.quit()
    exit()
        stage.DefinePrim(newPrimPath, "xform")
        with tempfile.NamedTemporaryFile(delete=True,
                                         suffix=".ma") as _tmpMayafile:
            cmds.file(rename=_tmpMayafile.name)
            cmds.file(save=True, force=True)
            cmds.file(new=True, force=True)
            cmds.file(_tmpMayafile.name, open=True)
            self.assertTrue(
                cmds.getAttr('%s.sessionLayerName' % self._proxyName))

            ps = ProxyShape.getByName(self._proxyName)
            self.assertTrue(ps)
            stage = ps.getUsdStage()
            self.assertTrue(stage)
            self.assertTrue(stage.GetPrimAtPath(newPrimPath))
            self.assertTrue(stage.GetSessionLayer().Reload())
            self.assertFalse(stage.GetPrimAtPath(newPrimPath))


if __name__ == "__main__":

    tests = [
        unittest.TestLoader().loadTestsFromTestCase(
            TestLayerManagerSerialisation),
    ]
    results = [
        unittest.TextTestRunner(verbosity=2).run(test) for test in tests
    ]
    exitCode = int(not all([result.wasSuccessful() for result in results]))
    cmds.quit(exitCode=(exitCode))
Example #36
0
def mayaStandaloneGeoCache(exportPath, importPath, smooth, projPath, exMin, exMax, imMin, imMax, isPartial= None, assetName= None, sceneName= None):

	#charInd = 0
	#charName = ['assassin', 'BOSS', ''][charInd]

	logger.info('start')

	
	mel.eval('setProject \"' + projPath + '\"')

	#charFile = ''
	#if charName == 'assassin':
	#	charFile = charName + '_shdaing_master'
	#else:
	#	charFile = charName + '_shading_master'

	for maFile in maFileList.keys():

		if exportPath:
			cmds.file(new= 1, f= 1)
			cmds.file(exportPath, o= 1, lar= 1, f= 1)
			cmds.playbackOptions(min= 1)
			
			targetList = cmds.ls(charName + '*:geo_grp', r= 1)
			if targetList:
				cmds.select(targetList, r= 1)
				logger.info('[' + os.path.basename(exportPath) + '] Export Start.')

				moGeoCache.exportGeoCache(smooth, isPartial= None, assetName= None, sceneName= None)

			else:
				logger.info('[' + os.path.basename(exportPath) + '] Nothing to Export.')
				continue

			logger.info('[' + os.path.basename(exportPath) + '] Export Done.')
		

		if importPath:
			cmds.file(new= 1, f= 1)
			cacheName = importPath.split('/')[1].split('.')[0]
			geoCacheDir = moRules.rGeoCacheDir(charName, cacheName)
			if not cmds.file(geoCacheDir, q= 1, ex= 1):
				logger.info('[' + os.path.basename(importPath) + '] Nothing to Import.')
				continue
			refFile = 'O:/201603_SongOfKnights/Maya/assets/char/' + charFile + '.ma'
			cmds.file(refFile, r= 1, type= 'mayaAscii', iv= 1, gl= 1, lrd= 'all', shd= 'renderLayersByName', mnc= 0, ns= charFile, op= 'v=0;')
			cmds.select(cmds.ls(charName + '*:geo_grp', r= 1), r= 1)
			logger.info('[' + os.path.basename(importPath) + '] Import Start.')
			
			moGeoCache.importGeoCache(cacheName, isPartial= None, assetName= None)

			mel.eval('source cleanUpScene;')
			mel.eval('putenv "MAYA_TESTING_CLEANUP" "1";')
			mel.eval('scOpt_saveAndClearOptionVars(1);')
			mel.eval('scOpt_setOptionVars( {"unknownNodesOption"} );')
			mel.eval('cleanUpScene( 1 );')
			mel.eval('scOpt_saveAndClearOptionVars(0);')
			mel.eval('putenv "MAYA_TESTING_CLEANUP" "";')

			cmds.file(rename= importPath)
			cmds.file(s= 1, type='mayaAscii')
			logger.info('[' + os.path.basename(importPath) + '] Import Done.')


	logger.info('quit')
	cmds.quit(force= True)
 def doQuit():
     sys.stdout.flush()
     sys.__stdout__.flush()
     sys.stderr.flush()
     sys.__stderr__.flush()
     cmds.quit(abort=1, exitCode=code)
            os.remove(shelfName)
            continue
        os.rename(shelfName,deletedShelfName)

#get environment file
envFile = os.path.join(envDir, 'Maya.env')
#find template environment file
thisFile = inspect.getframeinfo(inspect.currentframe()).filename
templateDir = os.path.dirname(os.path.abspath(thisFile))
templateFile = os.path.join(templateDir, 'Maya.env')
#copy and replace file
shutil.copy(templateFile, envFile)
cmds.headsUpMessage( '    MAYA EXPLOSION IN...    ')
cmds.pause(sec=3)
cmds.headsUpMessage( '    5    ')
cmds.pause(sec=1) 
cmds.headsUpMessage( '    4    ')
cmds.pause(sec=1) 
cmds.headsUpMessage( '    3    ')
cmds.pause(sec=1) 
cmds.headsUpMessage( '    2    ')
cmds.pause(sec=1) 
cmds.headsUpMessage( '    farewell world...    ')
cmds.pause(sec=1) 
#exit maya
cmds.quit(f=True)
#restarting right away doesn't work



        # Set renderglobal imageformat
        cmds.setAttr('defaultRenderGlobals.imageFormat', IMAGE_FORMAT_DICT[format])
        logging.info('Image format: %s' % format)

        playblastArgs = {
                        'filename': fileout,
                        'startTime': start,
                        'endTime': end,
                        'format': 'image',
                        'widthHeight': [int(width), int(height)],
                        'percent': 100,
                        'viewer': False,
                        'offScreen': True,
                        'forceOverwrite': True
                        }
                        #'sequenceTime' = True
                        #'framePadding' = 4 (default)
                        #'rawFrameNumbers' = True (maybe)
        logging.info('Playblasting with arguments: %s' % playblastArgs)
        logging.debug('Playblasting with arguments: %s' % playblastArgs)
        cmds.playblast(**playblastArgs)
        logging.info('Playblast completed succesfully.')
        
    except Exception, e:
        logging.error(e)

    finally:
        # Exit
        cmds.quit(abort=True)
Example #40
0
	cmds.playbackOptions(min= 101)

	if not cmds.pluginInfo('AbcExport', q= 1, l= 1):
		cmds.loadPlugin('AbcExport')

	targetList = cmds.ls('*:geo_grp', r= 1)
	if targetList:
		cmds.select(targetList, r= 1)
		logger.info('[' + os.path.basename(maFile) + '] Export Start.')
		# export abc
		frameRange = '%d %d' % (cmds.playbackOptions(q= 1, min= 1), cmds.playbackOptions(q= 1, max= 1))
		root = cmds.ls(sl= 1, l= 1)[0]
		abcPath = 'O:/201603_SongOfKnights/Maya/cache/alembic/0614/' + maFileList[maFile]
		doExport = 1
		if cmds.file(abcPath, q= 1, ex= 1) and not override:
			doExport = 0

		if doExport:
			if not cmds.file(os.path.dirname(abcPath), q= 1, ex= 1):
				os.mkdir(os.path.dirname(abcPath))
			mel.eval('AbcExport -j "-frameRange ' + frameRange + ' -ro -stripNamespaces -uvWrite -worldSpace -writeVisibility -dataFormat hdf -root ' + root + ' -file ' + abcPath + '";')
	else:
		logger.info('[' + os.path.basename(maFile) + '] Nothing to Export.')
		continue

	logger.info('[' + os.path.basename(maFile) + '] Export Done.')


logger.info('quit')
cmds.quit(force= True)
Example #41
0
def quit_maya():
    mc.quit(f=1)
Example #42
0
import os
import maya.cmds as mc

# set render globals > common > pre render frame
# python "execfile('/path/to/this/scripts/skipExisting.py')"


#def skipExisting():
dir = "/jobs/olay_2009/moisturizer/shots/olay15_001/images/renders"
root = "xxx"
ext = "rgb"
padsize = 4
frame = mc.currentTime(q=True)
format = "%0"+str(padsize)+"d"
framepad = format % frame # pad of 4, 3 would be '%03d'
image = dir+"/"+root+"."+framepad+"."+ext
if (os.path.isfile(image)):
	print "-------------------------------------"
	print "\n\n"+image+" exists! quitting.\n\n"
	print "-------------------------------------"
	mc.quit()
else:
	print "rendering "+image

Example #43
0
    def testPerfGridOfCubeGridsModelRefsLegacyViewport(self):
        """
        Tests selection correctness and performance with a grid of proxy shape
        nodes underneath reference assemblies using the legacy viewport.

        The geometry in this scene is a grid of grids. The top-level grid is
        made up of USD reference assembly nodes. Each of those assembly nodes
        references a USD file with many references to a "CubeModel" asset USD
        file. This results in equivalent geometry but a higher prim/mesh count
        than the "CombinedMesh" test above.

        The camera in the scene is positioned in a side view.
        """
        self._testName = 'ModelRefs_LegacyViewport'
        self._RunPerfTest()


if __name__ == '__main__':
    suite = unittest.TestLoader().loadTestsFromTestCase(testProxyShapeSelectionPerformance_LegacyViewport)

    results = unittest.TextTestRunner(stream=sys.stdout).run(suite)
    if results.wasSuccessful():
        exitCode = 0
    else:
        exitCode = 1
    # maya running interactively often absorbs all the output.  comment out the
    # following to prevent maya from exiting and open the script editor to look
    # at failures.
    cmds.quit(abort=True, exitCode=exitCode)
            height=1080)

    def testDrawPxrUsdPreviewSurface(self):
        """
        Tests performing a Viewport 2.0 render of a collection of spheres
        bound to pxrUsdPreviewSurface materials. The spheres are arranged in
        rows with material assignments that ramp the attribute values through
        the typical ranges for those attributes.
        """
        self._testName = 'PxrUsdPreviewSurfaceDrawTest'

        mayaSceneFile = '%s.ma' % self._testName
        mayaSceneFullPath = os.path.abspath(mayaSceneFile)
        cmds.file(mayaSceneFullPath, open=True, force=True)

        self._WriteViewportImage(self._testName, 'value_ramps')


if __name__ == '__main__':
    suite = unittest.TestLoader().loadTestsFromTestCase(testPxrUsdPreviewSurfaceDraw)

    results = unittest.TextTestRunner(stream=sys.stdout).run(suite)
    if results.wasSuccessful():
        exitCode = 0
    else:
        exitCode = 1
    # Maya running interactively often absorbs all the output. Comment out the
    # following to prevent Naya from exiting and open the script editor to look
    # at failures.
    cmds.quit(abort=True, exitCode=exitCode)