def makeMIProxy(objs, outdir): mayafilename = os.path.basename(mc.file(q=1,sn=1)).split('.')[0] proxyObjs = list() for obj in objs: # make some names safe_long_name = obj.replace('|','_') miname = mayafilename+'-'+safe_long_name outnamepath = outdir[0]+'/'+miname+'.mi' # export the geo to mi with no shaders select(obj) mc.Mayatomr( binary=1, miStream=1, exportFilter=721600, active=1, fragmentExport=1, fis=1, fragmentChildDag=1, assembly=1, asn=miname, exportPathNames='n', file=outnamepath) # create a proxy cube and hook it up to the .mi proxyCube = polyCube(name=miname+'_makeMIProxy') proxyCube[0].getShapes()[0].setAttr('miProxyFile',outnamepath,type='string') select(proxyCube[0].getShapes()[0]) maya.app.mentalray.renderProxyUtils.resizeToBoundingBox(mc.ls(sl=1)[0]) proxyCube[0].getShapes()[0].setAttr('miUpdateProxyBoundingBoxMode',1) # force bounding box display of proxy even in shaded mode proxyCube[0].getShapes()[0].setAttr('overrideEnabled',1) proxyCube[0].getShapes()[0].setAttr('overrideLevelOfDetail',1) # get shader on original object and assign to proxy - this is money move select(obj) hyperShade(shaderNetworksSelectMaterialNodes=1) mat = ls(sl=1) select(proxyCube[0].getShapes()[0],add=1) hyperShade(assign=mat[0]) # parent the proxy parallel to the the original geo select(obj) prt = pickWalk(d='up') select(proxyCube[0]) select(prt,add=1) parent() # store the created proxy cubes proxyObjs.append(proxyCube[0]) # finish up by organizing things # select(proxyObjs) # group(name='miproxy') select(objs)
def ao_render(c): # load the respective plugins ao.setup_ao("polySurface1") # render from command line cmds.Mayatomr(render=True, logFile=True, layer='ao', xResolution=RENDER_WIDTH, yResolution=RENDER_HEIGHT, camera=c[0])
def reRender(*args): if currentRender == 'arnold': cmds.arnoldRender(cam=camera1) elif currentRender == 'vray': vrendCommand = 'vrend -camera %s' % (camera0) mel.eval(vrendCommand) elif currentRender == 'mentalRay': cmds.Mayatomr(pv=True, cam=camera0) else: cmds.warning( 'Render engine not supported. Rendering using Maya Software renderer.' ) cmds.render(camera1)
def render(rl, width, height, *args): """ renders the scene with the given attributes keyword args: width -- width of render image in pixels height -- height of render image in pixels *args -- additional args """ dar = width / float(height) cmds.setAttr('defaultResolution.deviceAspectRatio', dar) mel.eval('RenderViewWindow') cmds.Mayatomr(preview=True, layer=rl, xResolution=width, yResolution=height, camera='perspShape') editor = 'renderView' cmds.renderWindowEditor(editor, e=True, si=True)
def doFileAnalysis(infile,*args): print '\ninfile: %s' % (infile) print 'project: %s' % (cmds.workspace(q=1,fn=1)) cmds.file(infile,o=1,f=1) # first: if this is not a mayaBinary file, save it as one. scenePath = infile if os.path.splitext(infile)[-1] != '.mb': # remove all unknown nodes and save as MB unk = cmds.ls(type='unknown') if unk: for i in unk: try: cmds.lockNode(i,lock=0) cmds.delete(i) except: pass scenePath = os.path.splitext(infile)[0]+'.mb' cmds.file(rename=scenePath) cmds.file(s=1,f=1,type='mayaBinary') meshes = [] surfaces = [] meshes = cmds.ls(type='mesh',l=1) surfaces = cmds.ls(type='nurbsSurface',l=1) # create temp camera cam = cmds.camera() cmds.setAttr(cam[0]+'.rx',-35) cmds.setAttr(cam[0]+'.ry',45) meshXforms = [] if meshes: for mesh in meshes: xf = cmds.listRelatives(mesh,p=1,f=1)[0] meshXforms.append(xf) if surfaces: for surface in surfaces: xf = cmds.listRelatives(surface,p=1,f=1)[0] meshXforms.append(xf) meshXforms = [f for f in meshXforms if cmds.getAttr(f+'.visibility') == 1] if not meshXforms: # nothing here, throw an error cmds.quit(ec=86,f=1) cmds.select(meshXforms) # set active resolution before fitting. cmds.setAttr('defaultResolution.aspectLock',0) cmds.setAttr('defaultResolution.width',720) cmds.setAttr('defaultResolution.height',405) cmds.setAttr('defaultResolution.pixelAspect',1) cmds.setAttr('defaultResolution.deviceAspectRatio',1.778) cmds.viewFit(cam[1],f=0.9) cmds.viewClipPlane(cam[1],acp=1) cmds.select(cl=1) allCams = cmds.ls(type='camera') for c in allCams: cmds.setAttr(c+'.renderable',0) cmds.setAttr(cam[1]+'.renderable',1) engine = cmds.sets(renderable=1,noSurfaceShader=1,em=1) mat = cmds.shadingNode('surfaceShader',asShader=1) cmds.connectAttr(mat+'.outColor',engine+'.surfaceShader') aotex = cmds.shadingNode('mib_amb_occlusion',asTexture=1) cmds.connectAttr(aotex+'.outValue',mat+'.outColor') cmds.setAttr(aotex+'.samples',32) # create a new temporary render layer and add all objects rlayer = cmds.createRenderLayer(n='tempLayer',g=1,mc=1) # assign AO shader to all meshes and surfaces if meshes: cmds.sets(meshes,e=1,fe=engine) if surfaces: cmds.sets(surfaces,e=1,fe=engine) # get all existing file textures and add the paths to a list textures = [] fileNodes = cmds.ls(type='file') for node in fileNodes: tex = cmds.getAttr(node+'.fileTextureName') textures.append(tex.strip().replace('\n','')) # set mental ray as the current renderer and set up output settings cmds.setAttr('defaultRenderGlobals.currentRenderer','mentalRay',type='string') # to prevent overwriting other images with the same name, use the unix timestamp as the image name. rand_imageFilePrefix = str(int(time.time())) mel.eval('miCreateDefaultNodes();') cmds.setAttr('defaultRenderGlobals.imageFormat',8) cmds.setAttr('defaultRenderGlobals.outFormatControl',0) cmds.setAttr('defaultRenderGlobals.useFrameExt',0) cmds.setAttr('defaultRenderGlobals.animation',0) cmds.setAttr('defaultRenderGlobals.useMayaFileName',1) cmds.setAttr('defaultRenderGlobals.imageFilePrefix',rand_imageFilePrefix,type='string') mel.eval('miCreateDefaultNodes();') cmds.setAttr('miDefaultOptions.rayTracing',1) cmds.setAttr('miDefaultOptions.maxSamples',2) cmds.setAttr('miDefaultOptions.minSamples',0) cmds.setAttr('miDefaultOptions.maxReflectionRays',1) cmds.setAttr('miDefaultOptions.finalGather',0) cmds.setAttr('miDefaultOptions.filter',2) # get output filename tempProject = cmds.workspace(q=1,fn=1) outFile = os.path.join(tempProject,'images',rlayer,rand_imageFilePrefix+'.jpg') # disable all render layers except rlayer layers = cmds.ls(type='renderLayer') for layer in layers: cmds.setAttr(layer+'.renderable',0) cmds.setAttr(rlayer+'.renderable',1) ren = cmds.Mayatomr(r=1,camera=cam[1],x=720,y=405,l=rlayer,rv=5) st = 'screenshot written to %s' % (outFile) print(st) return infile,outFile,textures,scenePath,ren
def iprRender(*args): if currentRender == 'arnold': if cmds.arnoldIpr(q=1, mode='start'): cmds.arnoldIpr(mode='stop') else: cmds.arnoldIpr(cam=camera1, mode='start') cmds.arnoldIpr(mode='refresh') elif currentRender == 'vray': statusRT = mel.eval('vrayIsRunningIpr();') if statusRT == 0: if cmds.camera(camera1, q=1, o=1): cmds.warning('ortographic views not supported by vrayRT') else: preScale = cmds.getAttr(camera0 + '.preScale') preScale = float(1) / float(preScale) ftrh = cmds.getAttr(camera0 + '.filmTranslateH') ftrv = cmds.getAttr(camera0 + '.filmTranslateV') unitfIxed = 0.709 cmds.setAttr(camera0 + '.cameraScale', preScale) cmds.setAttr(camera0 + ".horizontalFilmOffset", ftrh * unitfIxed) cmds.setAttr(camera0 + ".verticalFilmOffset", ftrv * unitfIxed) mel.eval("vrend -ipr true -cam " + camera0 + ";") else: mel.eval("vrend -ipr false;") elif currentRender == 'mentalRay': if cmds.Mayatomr(q=1, imr=True): cmds.Mayatomr(imr=False) cmds.setAttr(camera0 + ".shakeEnabled", 0) for x in jobList[:]: cmds.scriptJob(kill=x, force=True) jobList.remove(x) else: if cmds.camera(camera1, q=1, o=1): jobIprMr = cmds.scriptJob( attributeChange=['Viewport_Render.translate', forceIpr]) jobIprMr2 = cmds.scriptJob(attributeChange=[ 'Viewport_Render.orthographicWidth', forceIpr ]) jobList.append(jobIprMr) jobList.append(jobIprMr2) else: jobIprMr = cmds.scriptJob( attributeChange=['Viewport_Render.translate', forceIpr]) jobList.append(jobIprMr) cmds.Mayatomr(imr=True, cam=camera0) else: cmds.warning( 'Render engine not supported. Rendering using Maya Software renderer.' ) cmds.render(camera1)
def getRegion(rrStart_x, rrStart_y, rrLast_x, rrLast_y): values = [rrStart_x, rrStart_y, rrLast_x, rrLast_y] camOverscan = cmds.camera(camera0, q=1, ovr=1) if LockedAttr() == 'locked': cmds.warning('Unlock you camera\'s main attributtes') return False if cmds.window("vpRenderWindow", exists=1) == False: getRvStatus() getPaneLayoutStatus() if values[3] < 0: values[3] = 0 if values[2] > formX: values[2] = formX if values[2] - values[0] < 20 or values[1] - values[3] < 20: cmds.warning('Region is too small') else: leftW = marLeft + values[0] topW = marTop + (formY - values[1]) resoX = values[2] - values[0] resoY = values[1] - values[3] main(values) if "Viewport_RenderShape" not in cmds.ls(ca=1): setToolBegin() else: cmds.setAttr('defaultResolution.width', resoX) cmds.setAttr('defaultResolution.height', resoY) aspRatio = float(cmds.getAttr('defaultResolution.width')) / float( cmds.getAttr('defaultResolution.height')) cmds.setAttr('defaultResolution.deviceAspectRatio', aspRatio) ScaleToCrop = float(formX) / resoX ScaleToCrop2 = float(formY) / resoY cmds.setAttr(camera0 + '.preScale', float(ScaleToCrop) / camOverscan) if 'OverScanExpression' not in cmds.ls(et='expression'): cmds.expression(name='OverScanExpression', s=camera0 + '.overscan = Viewport_RenderShape.overscan', o=camera0, ae=1) # Pixel Offset pixoffX = (float(formX) / 2) - (values[0] + float(resoX) / 2) pixoffY = (float(formY) / 2) - (formY - values[1]) - (float(resoY) / 2) # Film Translate FxOff = float(pixoffX) / (formX / 2) FxOff = FxOff * ScaleToCrop if FxOff > 0: FxOff = FxOff * -1 else: FxOff = -FxOff cmds.setAttr(camera0 + '.filmTranslateH', FxOff) unitY = float(formY) / 2 * float(formX) / formY FyOff = float(pixoffY) / unitY FyOff = FyOff * ScaleToCrop cmds.setAttr(camera0 + '.filmTranslateV', FyOff) cmds.setAttr('defaultResolution.width', resoX) cmds.setAttr('defaultResolution.height', resoY) aspRatio = float(cmds.getAttr('defaultResolution.width')) / float( cmds.getAttr('defaultResolution.height')) cmds.setAttr('defaultResolution.deviceAspectRatio', aspRatio) cmds.layout('scrollBarForm', e=1, vis=0) cmds.renderWindowEditor(renderViews, e=True, snp=(currentPanel, resoX, resoY)) cmds.renderWindowEditor(renderViews, e=True, rs=True, cap=0, pca=0) cmds.renderWindowEditor(renderViews, e=1, cl=(resoX, resoY, 0, 0, 0)) if currentRender == 'arnold': cmds.arnoldRender(cam=camera1) elif currentRender == 'vray': if cmds.getAttr("vraySettings.vfbOn") == 1: cmds.setAttr("vraySettings.vfbOn", 0) cmds.setAttr('vraySettings.width', resoX) cmds.setAttr('vraySettings.height', resoY) mel.eval('vraySetPixelDeviceAspect();') vrendCommand = 'vrend -camera %s' % (camera0) mel.eval(vrendCommand) elif currentRender == 'mentalRay': cmds.Mayatomr(pv=True, cam=camera0) else: cmds.warning( 'Render engine not supported. Rendering using Maya Software renderer.' ) cmds.render(camera1, x=resoX, y=resoY) reRenderVals.append(resoX) reRenderVals.append(resoY)
def render(startFrame = None,endFrame = None,frameStep = 1, render_dir = None, renderLayer = None,camera = None, renderer = 'sw',**kwargs): # 解析输入参数 startFrame = startFrame if startFrame not in ['None'] else None endFrame = endFrame if endFrame not in ['None'] else None render_dir = render_dir if render_dir not in ['None'] else None renderLayer = renderLayer if renderLayer not in ['None'] else None camera = camera if camera not in ['None'] else None renderer = renderer if renderer not in ['None'] else None # 渲染相关设置 scenepath = os.path.abspath(kwargs['scene_path']) print("\nSTEP 0 获取场景路径: {}\n".format(scenepath)) workspace = cmds.workspace(q=True,fullName = True) # /maya/projects/default print("\nSTEP 1 获取工作空间: {}\n".format(workspace)) if not render_dir: render_dir = '/'.join([workspace,'images']) print("\nSTEP 2.1 设置渲染图片路径: {}\n".format(render_dir)) if not os.path.isdir(render_dir): try: os.makedirs(render_dir) print("\nSTEP 2.2 新建图片路径: {}\n".format(render_dir)) except: raise Exception('can not make Folder named: %s ' % render_dir) open_scene(scenepath) refs = list_referenced_files() print("\nSTEP 4 场景相关文件: {} \n".format(refs)) # 设置起始和结束帧 if not startFrame: startFrame = int(cmds.currentTime(query = True)) if (not endFrame) or (endFrame < startFrame): endFrame = startFrame # startFrame,endFrame = playback_selection_range() print("\nSTEP 5 起始帧: {} 结束帧: {}\n".format(startFrame,endFrame)) # 设置渲染层, 不同的渲染器对渲染层有不同的配置参数 if not renderLayer: renderLayer = cmds.editRenderLayerGlobals(q = True,currentRenderLayer = True) print("\nSTEP 6.1 未指定渲染层,获取当前渲染层: {}\n".format(renderLayer)) elif renderLayer not in cmds.ls(type = 'renderLayer'): renderLayer = cmds.editRenderLayerGlobals(q = True,currentRenderLayer = True) print('\nSTEP 6.2 指定的渲染层不在当前maya环境上, 使用默认的渲染层: %s\n' %(renderLayer)) else: if cmds.editRenderLayerGlobals(q = True,currentRenderLayer = True) != renderLayer: cmds.editRenderLayerGlobals(currentRenderLayer = renderLayer) print('\nSTEP 6.3 指定的渲染层在当前maya环境上,但不是当前默认渲染层,设置为默认渲染层: %s\n' %(renderLayer)) # 设置摄像机 render_cam = 'persp' change_render_cam(render_cam) print("\nSTEP 7 设置默认摄像机: {}\n".format(render_cam)) # get camera 获取摄像机 if not camera: _cameras = [i for i in cmds.listCameras(p = True) if cmds.getAttr('%s.renderable' % i)] if _cameras: camera = _cameras[0] else: camera = 'persp' print("\nSTEP 8 当前使用的摄像机: {}\n".format(camera)) #打印当前渲染器设置 # render_glob = "defaultRenderGlobals" # list_Attr = cmds.listAttr(render_glob, r=True, s=True) # print("\n") # for attr in list_Attr: # get_attr_name = "%s.%s"%(render_glob, attr) # print("STEP 9 默认Render的全局配置信息: {} = {}".format(get_attr_name, cmds.getAttr(get_attr_name))) # print("\n") # load renderer 加载渲染器 currenders = cmds.renderer(q=True, namesOfAvailableRenderers=True) print('\nSTEP 9 当前可用的渲染器有: {} \n'.format(currenders)) print("\nSTEP 10 当前插件路径: {} \n".format(os.environ['MAYA_PLUG_IN_PATH'])) cmds.loadPlugin( allPlugins=True ) if renderer: if renderer: if renderer != cmds.getAttr('defaultRenderGlobals.currentRenderer'): renderer_dict = {'vray':'vrayformaya', 'arnold':'mtoa', 'mentalRay':'Mayatomr'} for key in renderer_dict.keys(): if renderer == key: if not cmds.pluginInfo(renderer_dict[key], q=True, l=True): try: cmds.loadPlugin(renderer_dict[key]) break except: raise Exception('can not load vray renderer') try: cmds.setAttr('defaultRenderGlobals.currentRenderer',renderer,type = 'string') except: raise Exception('error: set currentRenderer %s fail' % renderer) else: renderer = cmds.getAttr('defaultRenderGlobals.currentRenderer') print('\nSTEP 12 指定的渲染器位当前默认渲染器: %s\n' %(renderer)) w, h = scene_resolution() print('\nSTEP 13 当前图片分辨率:X={} Y={} .\n'.format(w,h)) # 设置图像输出格式 cmds.getAttr('defaultRenderGlobals.imageFormat',asString = True) _format = getFormatType("PNG") print('\nSTEP 14 设置输出图像的格式: %s\n' %(_format)) print('# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #') print('STEP 15 开始执行渲染任务...\n') cd = int(endFrame) + 1 for i in range(int(startFrame), int(cd)): cmds.currentTime(i, u = True) if renderer == 'sw': cmds.render() elif renderer == 'mr': out = cmds.Mayatomr(preview = True, camera = camera) print("cmds.Mayatomr:",out) else: pass if renderer == 'vray': cmds.setAttr ('defaultRenderGlobals.animation', 1 ) cmds.setAttr ('defaultRenderGlobals.startFrame', startFrame ) cmds.setAttr ('defaultRenderGlobals.endFrame', endFrame ) print(cmds.setAttr ('vraySettings.animBatchOnly', 0)) out = pm.vrend(preview = True,camera = camera) print("pm.vrend:",out) elif renderer == 'arnold': for i in range(startFrame,endFrame+1,1): cmds.currentTime(i) out = cmds.arnoldRender(seq=str(i),camera = camera ) print("cmds.arnoldRender:",out) print('# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #')