def toggleXRay(): """Toggle x-ray view""" newState = not pm.modelEditor( 'modelPanel4', query=True, xray=True ) for i in range( 1, 5 ): pm.modelEditor( 'modelPanel%s' % i, edit=True, xray=newState )
def addItems(self, parent): column = 0 self.renderLayers = self.getRenderLayers() # Get render layers self.renderLayerDict = {} # Dictionary to store layer name and the assosiated AOVS for layer in self.renderLayers: if str(layer.name()) not in self.renderLayerDict: self.renderLayerDict[str(layer.name())] = [] # Add elements to Dictionary as Key with empty list as value # vrayRenderElements = pm.listConnections(layer, s=1, type='VRayRenderElement') # Find all the AOVS connected to each render layers and Append to the Dictionary self.renderLayerDict[Key] = Value vrayRenderElements = pm.ls(type='VRayRenderElement') for element in vrayRenderElements: if element.name() not in self.renderLayerDict[str(layer.name())]: self.renderLayerDict[str(layer.name())].append(str(element.name())) # vrayRenderElementSets = pm.listConnections(layer, s=1, type='VRayRenderElementSet') vrayRenderElementSets = pm.ls(type='VRayRenderElementSet') for set in vrayRenderElementSets: if set.name() not in self.renderLayerDict[str(layer.name())]: self.renderLayerDict[str(layer.name())].append(str(set.name())) panels = pm.getPanel( type='modelPanel' ) # Get all the Model panels and Set show to None for panel in panels: if '|' in panel: panel = panel.split('|')[-1] pm.modelEditor(panel, e=1, allObjects=0) for key, values in self.renderLayerDict.iteritems(): # Update tree widget with top parent node as render layer name and childs as Aovs pm.editRenderLayerGlobals(currentRenderLayer=key) # select current render layer and find the Aovs state (Enabled or Disabled) layer_item = self.addParent(parent, column, key, 'data Layers') for value in sorted(values): self.addChild(layer_item, column, value, 'data Aovs')
def toggleWireframeOnShaded(): """Toggle Wireframe On Shaded view""" newState = not pm.modelEditor( 'modelPanel4', query=True, wireframeOnShaded=True ) for i in range( 1, 5 ): pm.modelEditor( 'modelPanel%s' % i, edit=True, wireframeOnShaded=newState )
def playblast(self): """ Run the playblast of the image. Will only work if the layer has been pushed. """ # Set up the camera pm.modelEditor(self.playblast_panel, edit=True, camera=self.camera, displayAppearance='flatShaded') pm.playblast(**self.playblast_args)
def _createNode(self): try: cam = pm.ls(sl=True, type="camera")[0] except: raise AttributeError("Please select a camera shape!") node = pm.nodetypes.ImagePlane() # adapted from cameraImagePlaneUpdate.mel node.message.connect(cam.imagePlane, nextAvailable=True) cam.horizontalFilmAperture.connect(node.sizeX) cam.verticalFilmAperture.connect(node.sizeY) cam.orthographicWidth.connect(node.width) cam.orthographicWidth.connect(node.height) node.attr("center").set(cam.getWorldCenterOfInterest()) for item in pm.listRelatives(cam, parent=True): pm.showHidden(item, below=True) for modelPanel in pm.getPanel(type="modelPanel"): modelCamera = pm.modelPanel(modelPanel, query=True) if modelCamera != "": for shape in pm.listRelatives(modelCamera, shapes=True): if shape == cam: editor = pm.modelPanel(modelPanel, query=True, modelEditor=True) pm.modelEditor(editor, edit=True, updateColorMode=True) break return node
def toggle_nurbs_curves(): """Toggle nurbs curves on/off""" active_view = pm.getPanel(withFocus=True) if pm.modelEditor(active_view, q=True, nurbsCurves=True): pm.modelEditor(active_view, edit=True, nurbsCurves=False) else: pm.modelEditor(active_view, edit=True, nurbsCurves=True)
def getSelectedCamera(self): sel = pm.ls(sl=1) # NOTE 当前的 modelEditor cur_mp = None for mp in pm.getPanel(type="modelPanel"): if pm.modelEditor(mp, q=1, av=1): cur_mp = mp break # NOTE 获取摄像机节点 pm.pickWalk(d="down") cam_list = pm.ls(sl=1, ca=1) # NOTE 获取选择的摄像机 没有 则获取当前视窗的摄像机 cam = cam_list[0].getParent() if cam_list else pm.modelEditor( cur_mp, q=1, cam=1) for i in range(self.Cam_Combo.count()): text = self.Cam_Combo.itemText(i) if text == str(cam): self.Cam_Combo.setCurrentIndex(i) break pm.select(sel)
def saveName(*pArgs): #save the vertex positions currentSelection = getVertexPositions() storedList = open( 'EqualRealityData\SavedVertexPositions%s.txt' % (globalGender[0]), 'a') storedList.write('\r\n\r\n') for item in currentSelection: storedList.write('%s|' % (item)) storedList.close() #save the name myText = cmds.textField("Name_Textfield", query=True, text=True) myNames = open('EqualRealityData\EyeShapes%s.txt' % (globalGender[0]), 'a') myNames.write('\r\n%s' % (myText)) myNames.close() shaderSwitch('Flat') myWindow = pm.window('Icon Render') form = pm.formLayout() editor = pm.modelEditor() column = pm.columnLayout('true') pm.formLayout(form, edit=True, attachForm=[(column, 'top', 0), (column, 'left', 0), (editor, 'top', 0), (editor, 'bottom', 0), (editor, 'right', 0)], attachNone=[(column, 'bottom'), (column, 'right')], attachControl=(editor, 'left', 0, column)) myCam = 'IconRendererShape' pm.modelEditor(editor, activeView=True, camera=myCam, displayTextures=True, edit=True, displayAppearance='smoothShaded') pm.showWindow(myWindow) pm.select('Body_%s' % (globalGender[0])) pm.playblast(completeFilename="%s_%s.iff" % (myText, globalGender[0]), viewer=False, showOrnaments=False, frame=[1], percent=100, format="image", width=84, height=84) shaderSwitch('Normal') pm.deleteUI(myWindow) cmds.deleteUI('popupID') globalEyeKey = [] rolloutParameters(names=['modellingToolkit', 'EyeShapes'], edit=True) createUI('Poly Morph')
def toggle_joints_x_ray(): focused_panel = pm.getPanel(withFocus=True) if "modelPanel" in focused_panel: set_value = not pm.modelEditor(focused_panel, q=True, jointXray=True) pm.modelEditor(focused_panel, e=True, jointXray=set_value) if set_value: pm.modelEditor(focused_panel, e=True, joints=set_value)
def update_model_editors(cls, *args, **kwargs): ''' ''' model_panel_list = pm.lsUI(editors=True) for model_panel in model_panel_list: if 'modelPanel' in model_panel: try: pm.modelEditor(model_panel, edit=True, **kwargs) except: Utility.lc_print_exception()
def toggle_viewport_nurbs_curves(): panel = pm.getPanel(withFocus=True) if panel is not None: panelType = pm.getPanel(typeOf=panel) # panel is model panel if panelType == "modelPanel" and panel: nc = not pm.modelEditor(panel, q=True, nc=True) pm.modelEditor(panel, e=True, nurbsCurves=nc)
def getCamPos(self): # NOTE 获取当前摄像机 cur_mp = None for mp in pm.getPanel(type="modelPanel"): if pm.modelEditor(mp, q=1, av=1): cur_mp = mp break cam = pm.modelEditor(cur_mp, q=1, cam=1) cam_pos = dt.Vector(pm.xform(cam, q=1, ws=1, t=1)) return cam_pos
def cleanPlayblastWindow(ui, renderers): print 'Remove playblasting windows and restore settings...' # display stereo layers if any try: scf.showLayer2() except: print traceback.format_exc() # recover transparent sorting try: pm.modelEditor(ui['editor'], e=True, sortTransparent=True) except: print traceback.format_exc() # delete hud expression if pm.objExists('stereoUpdateHUD'): pm.delete('stereoUpdateHUD') # delete custom hud, restore previous hud try: if pm.headsUpDisplay(ui['hud_stereo'], query=True, ex=True): pm.headsUpDisplay(ui['hud_stereo'], rem=True) for huds in ui['huds_current']: if pm.headsUpDisplay(huds, query=True, ex=True): pm.headsUpDisplay(huds, edit=True, vis=True) except: print traceback.format_exc() # delete safe area try: safeareaShapes = pm.ls(type='spReticleLoc') for safe in safeareaShapes: try: pm.delete(safe.getParent()) except: pass except: print traceback.format_exc() # restore background color if ui['bgColor']: makeBluescreen( ui['bgColor'], renderers ) # delete preview window try: pm.deleteUI(ui['window'].name(), window=True) except: print traceback.format_exc() try: pm.lookThru('persp') except: print traceback.format_exc()
def toggle_nurbs_in_viewport(): """ Toggles the visibility of NURBS Curves/Surfaces in the viewport """ focused_panel = pm.getPanel(withFocus=True) if "modelPanel" in focused_panel: current_state = pm.modelEditor(focused_panel, q=True, nurbsCurves=True) pm.modelEditor(focused_panel, e=True, nurbsCurves=not current_state) pm.modelEditor(focused_panel, e=True, nurbsSurfaces=not current_state)
def toggle_poly_meshes(cls): """toggles mesh selection in the current panel """ panel_in_focus = pm.getPanel(wf=True) panel_type = pm.getPanel(typeOf=panel_in_focus) if panel_type == "modelPanel": poly_vis_state = pm.modelEditor(panel_in_focus, q=True, polymeshes=True) pm.modelEditor(panel_in_focus, e=True, polymeshes=(not poly_vis_state))
def loadRender(): """ Sets the viewport's render engine to DirectX11 and the tone map to use Stingray """ pm.mel.eval('setRenderingEngineInModelPanel "{}";'.format( pcfg.maya_default_rendering_api)) tone_maps = pm.colorManagementPrefs(q=True, vts=True) if pcfg.maya_default_tone_map not in tone_maps: return pm.colorManagementPrefs(e=True, vtn=pcfg.maya_default_tone_map) pm.modelEditor('modelPanel4', e=True, vtn=pcfg.maya_default_tone_map)
def main(): # NOTE 获取当前视窗的 modelEditor 开启 locator 显示 for mp in pm.getPanel(type="modelPanel"): if pm.modelEditor(mp, q=1, av=1): pm.modelEditor(mp, e=1, locators=1) break loc_list, warning_list = generateAnimPivotLocator() pm.select(loc_list) if warning_list: warn_str = "\n".join(warning_list) pm.confirmDialog(title=u'警告', message=u'以下控制器创建失败:\n\n%s' % warn_str)
def getActivePanel(self): cur_mp = None for mp in pm.getPanel(type="modelPanel"): if pm.modelEditor(mp, q=1, av=1): cur_mp = mp break return cur_mp
def set_wireframe_mode(mode): """ Select a viewport wireframe mode: "none": no wireframes "selected": wireframes on selected objects "all": wireframes on all objects """ assert mode in ('none', 'selected', 'all'), mode if mode == 'none': pm.displayPref(wireframeOnShadedActive='none') else: pm.displayPref(wireframeOnShadedActive='full') for model_panel in pm.getPanel(type='modelPanel'): enabled = mode == 'all' pm.modelEditor(model_panel, e=True, wireframeOnShaded=enabled)
def duplicateTearPanel(self): # Make playblast model panel with an apropriade size #tearCopy = pc.windows.control(pc.windows.getPanel(withFocus=True), q=True, parent=True) #fullPathName=True) tearCopy = pc.windows.getPanel(withFocus=True) if tearCopy not in pc.windows.getPanel(type="modelPanel"): # Print worning and stop procedure show_error_dialog("Select (focus on) a panel that you want to make playblast from.") return() pbmodpanel = pc.windows.modelPanel(l='axplayBlastModelPanel1', tearOffCopy=tearCopy.split("|")[-1]) # Scale panel to fit size pc.windows.control(pbmodpanel, e=True, w=self.resx()+100) pc.windows.control(pbmodpanel, e=True, h=self.resy()+100) # Deselect on option if self.isChecked(self.selectionBox): store_shots = pc.ls(sl=True, type='shot') pc.general.select(deselect=True) pc.general.select(store_shots, add=True) # Create raw folder if not there if not os.path.exists(self.tempfldr): os.mkdir(self.tempfldr) # Set HQ Rendering on the panel (Andy's request) if self.hqrendering: pc.modelEditor( pbmodpanel.split("|")[-1], edit=True, rnm="hwRender_OpenGL_Renderer" ) # NOTE If framecount gets requestes on HUD # if not pc.mel.eval('''optionVar -q frameRateVisibility'''): # pc.runtime.ToggleFrameRate() # if not pc.mel.eval('''optionVar -q cameraNamesVisibility'''): # pc.runtime.ToggleCameraNames() hudobj = 'HUDObjectPosition', if not pc.headsUpDisplay(hudobj, q=True, ex=True): pc.headsUpDisplay( hudobj, section=1, block=0, blockSize='medium', label='v%03d'%self.checkForNextVersions(), labelFontSize='small', ) else: pc.headsUpDisplay( hudobj, e=True, label='v%03d'%self.checkForNextVersions(), ) return([pbmodpanel, tearCopy])
def create_window(self): """Create a custom window with related modelEditor, as well as running the pre- and post-window methods. Returns: bool: Success of the window, modelEditor, and pre- and post- window methods. """ w_success = False # call various pre-window methods cam_check = self.set_camera() if cam_check: self.set_imageplanes_colorspace() self.set_vp2_globals() try: # create window (clean up first) self.destroy_window() window = pm.window(PLAYBLAST_WINDOW, titleBar=True, iconify=True, leftEdge=100, topEdge=100, width=DEFAULT_WIDTH, height=DEFAULT_HEIGHT, sizeable=False) # create window model editor layout = pm.formLayout() editor = pm.modelEditor(**MODEL_EDITOR_PARAMS) pm.setFocus(editor) pm.formLayout(layout, edit=True, attachForm=((editor, "left", 0), (editor, "top", 0), (editor, "right", 0), (editor, "bottom", 0))) # show window pm.setFocus(editor) pm.showWindow(window) pm.refresh() # call various post-window methods self.generate_all_uv_tile_previews() # success! w_success = True except Exception as e: m = '>> Failed to create playblast window > {}'.format(str(e)) self.logger.info(m) return w_success
def createWindow(): """ try to get data from shotgun project fields need to get context's project context's shotgun instance """ app = self.parent project = app.context.project sg = app.context.tank.shotgun # set filters and search fields for entity type "Project" filters=[["id", "is", project['id']],] fields=["sg_width", "sg_height"] result=sg.find_one("Project", filters, fields) # with result, set parameters accordingly or use default otherwise if result: videoWidth = result.get("sg_width", DEFAULT_WIDTH) videoHeight = result.get("sg_height", DEFAULT_HEIGHT) # Find first camera matching pattern and set as active camera # if not use default current active camera camera_name_pattern = app.get_setting( "camera_name_pattern", "persp" ) cameraList = [c.name() for c in pm.ls(type="camera", r=True) if re.search( camera_name_pattern, c.name() )] if not "cam" in MODEL_EDITOR_PARAMS.keys() and cameraList: MODEL_EDITOR_PARAMS["cam"] = cameraList[0] # Give Viewport 2.0 renderer only for Maya 2015++ # mayaVersionString = cmds.about(version=True) # mayaVersion = int(mayaVersionString[:4]) if len(mayaVersionString) >= 4 else 0 # if mayaVersion >= 2015: # params[ "rendererName" ] = "vp2Renderer" # Create window if pm.windowPref( PLAYBLAST_WINDOW, exists=True ): pm.windowPref( PLAYBLAST_WINDOW, remove=True ) window = pm.window( PLAYBLAST_WINDOW, titleBar=True, iconify=True, leftEdge = 100, topEdge = 100, width = videoWidth, height = videoHeight, sizeable = False) # Create editor area layout = pm.formLayout() editor = pm.modelEditor( **MODEL_EDITOR_PARAMS ) pm.setFocus( editor ) pm.formLayout( layout, edit=True, attachForm = ( ( editor, "left", 0 ), ( editor, "top", 0 ), ( editor, "right", 0 ), ( editor, "bottom", 0 ) ) ) # Show window pm.setFocus( editor ) pm.showWindow( window ) pm.refresh() try: yield True except: traceback.print_exc() finally: pm.deleteUI(window)
def toggleViewport2Point0(flag): '''Activates the Viewport 2.0 if flag is set to True''' panl = 'modelPanel4' for pan in pc.getPanel(allPanels=True): if pan.name().startswith('modelPanel'): if pc.modelEditor(pan, q=True, av=True): panl = pan.name() if flag: pc.mel.setRendererInModelPanel("ogsRenderer", panl) else: pc.mel.setRendererInModelPanel("base_OpenGL_Renderer", panl)
def hide_show_joints(cls): """ Hides and shows joints. """ # clear selection cmds.select(cl=True) # query for joints active_view = pm.getPanel(withFocus=True) try: joints = pm.modelEditor(active_view, q=True, joints=True) except RuntimeError: cmds.warning("Please make sure you're in an active view port.") return # set display mode if joints: pm.modelEditor(active_view, e=True, joints=False) else: pm.modelEditor(active_view, e=True, joints=True)
def getEditor(): """ The modelEditor is the node in maya that contains all the information about a modelPanel. A panel is an object in maya that acts as the root of a ui element. The model editor for instance holds information about what cameras have been added to a panel. """ if pm.modelEditor("mypanel", exists=True): print("the panel exists...deleting and creating a new one") pm.deleteUI("mypanel") cam = pm.ls(selection=True)[0] #SETTING CAMERA VIEWPORT SETTINGS pm.camera(cam, edit=True, displayResolution=False, displayFilmGate=False) window = pm.window(width=1280, height=720, backgroundColor=(1.0, 0.0, 0.0)) lay = pm.paneLayout() pan = pm.modelPanel() pm.modelEditor("mypanel", camera=cam, activeView=True, displayAppearance="smoothShaded") pm.showWindow(window, window=True)
def get_wireframe_mode(): if pm.displayPref(q=True, wireframeOnShadedActive=True) == 'none': return 'none' # Look at an arbitrary viewport for the wireframeOnShaded viewport mode. model_panels = pm.getPanel(type='modelPanel') if not model_panels: return 'none' if pm.modelEditor(model_panels[0], q=True, wireframeOnShaded=True): return 'all' else: return 'selected'
def toggle_orthographic_camera(): # get camera name panel = pm.getPanel(withFocus=True) if panel is not None: panelType = pm.getPanel(typeOf=panel) # modelPanel is camera if panelType == "modelPanel" and panel: cam = pm.modelEditor(panel, q=True, camera=True) cam_shape = cam.getShape() cam_shape.attr('orthographic').set(not (cam_shape.attr('orthographic').get()))
def bdSetCameraVP2(cam): pm.createReference("P:/smurfs/working_project/cameras/worldcup_cam.ma",ns='cam') pm.mel.eval('setNamedPanelLayout \"Single Perspective View\"'); perspModel = "".join(pm.getPanel(withLabel = 'Persp View')) pm.setFocus(perspModel) perspView = pm.getPanel(wf=1) pm.lookThru(perspView,cam) #pm.modelPanel (perspView, query=1,label=1) pm.modelEditor(perspView,e=1,alo=0) pm.modelEditor(perspView,e=1,polymeshes=1,imagePlane=1,grid=0) pm.modelEditor(perspView,e=1,displayAppearance='smoothShaded',displayTextures=1,wireframeOnShaded=0) consolidate = pm.mel.eval('checkMemoryForConsolidatedWorld()') if consolidate: pm.modelEditor(perspView,e=1,rnm="vp2Renderer",rom='')
def importCallback(*Args): loadPopup = pm.confirmDialog(title='Import', message='Choose Gender: ', button=['Female', 'Male', 'Cancel'], dismissString='Cancel') global globalGender localGender = '' if loadPopup == 'Cancel': return else: cmds.NewScene() globalNameKey[:] = [] globalVertexKey[:] = [] if loadPopup == 'Female': pm.mel.FBXImport(f="assets\EqualReality\NudeFemale.fbx") localGender = 'Female' pm.move('persp', [0, 156, 89]) if loadPopup == 'Male': pm.mel.FBXImport(f="assets\EqualReality\NudeMale.fbx") localGender = 'Male' pm.move('persp', [0, 169, 89]) pm.rotate('persp', [-8, 0, 0]) myScene = ['Eyes', 'Eyelashes', 'Body_%s' % (localGender)] pm.createDisplayLayer(name='Game_Model', number=1) for item in myScene: pm.editDisplayLayerMembers('Game_Model', item) #pm.hide('mixamorig:Hips') pm.hide('Eyes') global OnStart OnStart = 1 pm.modelEditor('modelPanel4', edit=True, displayTextures=True) rolloutParameters(names=[None], edit=True) createUI('Poly Morph')
def pop(self): """ Pop the render layer to remove display in the scene. """ # Set back tot he old render layer pm.editRenderLayerGlobals(currentRenderLayer=self.old_render_layer) editor = pm.modelEditor(self.playblast_panel, edit=True, displayTextures=True) # Reset the background colors pm.displayRGBColor("background", *self.old_bkg_color) pm.displayRGBColor("backgroundTop", *self.old_bkg_top_color) pm.displayRGBColor("backgroundBottom", *self.old_bkg_bottom_color) # Change the attributes on the meshes for obj in self.meshes_with_color: obj.setAttr('displayColors', 1) self.handle_gpu_mesh(1) self.pop_namespace_materials()
def setTimeline(): #get current camera activeView = pm.playblast(activeEditor=1) activeCamera = pm.modelEditor(activeView, q=1, camera=1).name() camNameParts = activeCamera.split("_") startTime = int(camNameParts[-2]) endTime = int(camNameParts[-1]) pm.playbackOptions( animationEndTime=endTime, animationStartTime=startTime, maxTime=endTime, minTime=startTime )
def push(self): """ Push the render layer to display in the scene. """ self.old_render_layer = pm.editRenderLayerGlobals(query=True, currentRenderLayer=True) editor = pm.modelEditor(self.playblast_panel, edit=True, displayTextures=False, displayAppearance='smoothShaded') # pm.modelEditor(editor, edit=True, displayTextures=False) pm.editRenderLayerGlobals(currentRenderLayer=self.layer.name()) # pm.modelEditor('modelPanel4', query=True, displayTextures=False) # Change the background color pm.displayRGBColor("background", 0, 0, 0) pm.displayRGBColor("backgroundTop", 0, 0, 0) pm.displayRGBColor("backgroundBottom", 0, 0, 0) self.get_meshes_with_color() for obj in self.meshes_with_color: obj.setAttr('displayColors', 0) self.handle_gpu_mesh(0) self.push_namespace_materials()
def setupModelEditor(self, me): """ Setup the view style of the model editor, sometimes the model editor cant be found for some reason so we just have to accept it if we cant adjust it. """ if me is None: return me = pm.ui.ModelEditor(me.split('|')[-1]) try: pm.modelEditor(me, e=True, da='smoothShaded', dtx=True, allObjects=False, sel=False) pm.modelEditor(me, e=True, manipulators=False, grid=False, hud=False) pm.modelEditor(me, e=True, polymeshes=True, subdivSurfaces=True, nurbsSurfaces=True) except: pass
def bdSetCamera(self, referenceCam): pm.mel.eval( 'setNamedPanelLayout "Single Perspective View"; updateToolbox();') sceneReferences = pm.getReferences() print sceneReferences camera = '' for item in sceneReferences: if sceneReferences[item].isLoaded(): if referenceCam.lower() in sceneReferences[item].path.lower(): print 'cam loaded already' camera = pm.ls(item + ':*', type='camera')[0] break print referenceCam stageCam = pm.ls(referenceCam + '*', type='camera')[0] print stageCam if stageCam: camera = stageCam if camera == '': if os.path.isfile(referenceCam): pm.createReference(referenceCam, namespace="CAM") camera = pm.ls('CAM:*', type='camera')[0] else: print 'No cam file, creating a default one' cameraList = pm.camera(n='playblastCam') camera = cameraList[1] cameraList[0].setTranslation([0, 10, 60]) ''' perspModel = "".join(pm.getPanel(withLabel = 'Persp View')) if perspModel == '': perspModel = "".join(pm.getPanel(withLabel = 'Side View')) print camera, perspModel pm.setFocus(perspModel) ''' perspView = pm.getPanel(wf=1) pm.modelEditor(perspView, e=1, alo=0, activeView=True) pm.modelEditor(perspView, e=1, polymeshes=1, wos=0, grid=0) pm.modelEditor(perspView, e=1, displayAppearance='smoothShaded', displayTextures=1) try: pm.lookThru(perspView, camera) except: print 'Failed to look through playblast camera'
def bdSetCamera(camera,referenceCam): if referenceCam: pm.createReference(referenceCam,namespace="CAM") camera = pm.ls('CAM:*',type='camera')[0] perspModel = "".join(pm.getPanel(withLabel = 'Persp View')) pm.setFocus(perspModel) perspView = pm.getPanel(wf=1) pm.lookThru(perspView,camera) #pm.modelPanel (perspView, query=1,label=1) pm.modelEditor(perspView,e=1,alo=0) pm.modelEditor(perspView,e=1,polymeshes=1,grid=0) pm.modelEditor(perspView,e=1,displayAppearance='smoothShaded',displayTextures=1) perspCam = pm.ls('persp',type='transform')[0]
def push(self): """ Push the render layer to display in the scene. """ self.old_render_layer = pm.editRenderLayerGlobals( query=True, currentRenderLayer=True) editor = pm.modelEditor(self.playblast_panel, edit=True, displayTextures=False, displayAppearance='smoothShaded') # pm.modelEditor(editor, edit=True, displayTextures=False) pm.editRenderLayerGlobals(currentRenderLayer=self.layer.name()) # pm.modelEditor('modelPanel4', query=True, displayTextures=False) # Change the background color pm.displayRGBColor("background", 0, 0, 0) pm.displayRGBColor("backgroundTop", 0, 0, 0) pm.displayRGBColor("backgroundBottom", 0, 0, 0) self.get_meshes_with_color() for obj in self.meshes_with_color: obj.setAttr('displayColors', 0) self.handle_gpu_mesh(0) self.push_namespace_materials()
def toggleLighting(): """Toggle between vertex colors and scene lighting""" currentPanel = pm.getPanel( withFocus=True ) if pm.getPanel( typeOf=currentPanel ) == 'modelPanel': displayLights = pm.modelEditor( currentPanel, query=True, displayLights=True ) if displayLights != 'all': pm.polyOptions( cs=0 ) pm.modelEditor( currentPanel, edit=True, displayLights='all' ) msg = 'ON (scene lights)' else: pm.polyOptions( cs=1, cm='ambientDiffuse' ) pm.modelEditor( currentPanel, edit=True, displayLights='default' ) pm.modelEditor( currentPanel, edit=True, displayLights='none' ) msg = 'OFF (vertex colors)' return 'Lighting: %s' % msg
def bdSetCamera(self,referenceCam): pm.mel.eval('setNamedPanelLayout "Single Perspective View"; updateToolbox();') sceneReferences = pm.getReferences() print sceneReferences camera = '' for item in sceneReferences : if sceneReferences[item].isLoaded(): if referenceCam.lower() in sceneReferences[item].path.lower(): print 'cam loaded already' camera = pm.ls(item + ':*',type='camera')[0] break print referenceCam stageCam = pm.ls(referenceCam + '*',type='camera')[0] print stageCam if stageCam: camera = stageCam if camera == '': if os.path.isfile(referenceCam): pm.createReference(referenceCam,namespace="CAM") camera = pm.ls('CAM:*',type='camera')[0] else: print 'No cam file, creating a default one' cameraList = pm.camera(n='playblastCam') camera = cameraList[1] cameraList[0].setTranslation([0,10,60]) ''' perspModel = "".join(pm.getPanel(withLabel = 'Persp View')) if perspModel == '': perspModel = "".join(pm.getPanel(withLabel = 'Side View')) print camera, perspModel pm.setFocus(perspModel) ''' perspView = pm.getPanel(wf=1) pm.modelEditor(perspView,e=1,alo=0,activeView = True) pm.modelEditor(perspView,e=1,polymeshes=1,wos=0,grid=0) pm.modelEditor(perspView,e=1,displayAppearance='smoothShaded',displayTextures=1) try: pm.lookThru(perspView,camera) except: print 'Failed to look through playblast camera'
def makeCamWidget(parent, namespace): refNode = namespace[0:-1]+"RN" try: derWin = pmc.window() derForm = pmc.columnLayout() # if NOT referenced, there is no refNode # if namespace == ":": refList = pmc.ls(geometry=True) else: refList = pmc.referenceQuery(refNode, nodes=True) pmc.select(refList) derME = pmc.modelEditor(camera=namespace+guiCam, hud=False, viewSelected=True, addSelected=True) pmc.select(clear=True) ptr = mui.MQtUtil.findControl(derME) self.camBG = shiboken2.wrapInstance(long(ptr), QtWidgets.QWidget) self.camBG.setParent(parent) #self.camBG.setEnabled(False) pmc.deleteUI(derWin) except: pmc.warning("Could not connect to camera {0}.".format(namespace+guiCam))
def get_active_camera(): """ Return the active camera. Thanks to Nohra Seif for the snippet! """ # seems that $gMainPane contain the name of the main window pane layout holding the panels. main_pane = mel.eval('string $test = $gMainPane;') if main_pane != "": # get the layout's immediate children main_pane_ctrls = pymel.paneLayout(main_pane, q=True, childArray=True) for i in range(len(main_pane_ctrls)): # panel containing the specified control panel_name = pymel.getPanel(containing=main_pane_ctrls[i]) if "" != panel_name: # Return the type of the specified panel. if ("modelPanel" == pymel.getPanel(typeOf=panel_name)): # Return whether the control can actually be seen by the user, isObscured for invisible if not (pymel.control(main_pane_ctrls[i], q=True, isObscured=True)): model_editor = pymel.modelPanel(panel_name, q=True, modelEditor=True) if model_editor: # If this view is already active, let's continue to use it. if pymel.modelEditor(model_editor, q=True, activeView=True): # get the camera in the current modelPanel return pymel.PyNode(pymel.modelPanel(model_editor, q=True, camera=True))
def DisplayGeomesh(): activeView = pm.getPanel(wf=True) ##Disable Item if pm.modelEditor(activeView, query=True, polymeshes=True) == 1: pm.modelEditor(activeView, edit=True, polymeshes=False) pm.warning("HideGeometry") pm.inViewMessage(amg='<hl>Hide_Geometry</hl>.', pos='midCenter', fade=True) else: ##Enable Item if pm.modelEditor(activeView, query=True, polymeshes=True) == 0: pm.modelEditor(activeView, edit=True, polymeshes=True) pm.warning("ShowGeometry") pm.inViewMessage(amg='<hl>Show_Geometry</hl>.', pos='midCenter', fade=True)
def poseScreenShot(self, name, directory=dirFiles): path = os.path.join(directory, '%s.png' % name) pm.modelEditor("modelPanel4", edit=True, allObjects=False) pm.modelEditor("modelPanel4", edit=True, polymeshes=True) pm.setAttr('defaultRenderGlobals.imageFormat', 32) pm.playblast(completeFilename=path, forceOverwrite=True, format='image', width=500, height=400, showOrnaments=False, startTime=1, endTime=1, viewer=False) pm.modelEditor("modelPanel4", edit=True, allObjects=True) return path
def setDisplay(self, enabled, keys): kwargs = {} for k in keys: kwargs[k] = enabled pm.modelEditor(self.panel, e=True, **kwargs)
def main(): prefRun() renderWidth = pm.getAttr("defaultResolution.width") renderHeight = pm.getAttr("defaultResolution.height") current_selection = pm.selected() currentState = toggleSpeakers(1) #toggle display color pm.displayRGBColor("background", 0.0, 0.0, 0.0) #get current camera activeView = pm.playblast(activeEditor=1) activeCamera = pm.modelEditor(activeView, q=1, camera=1).name() camNameParts = activeCamera.split("_") pbVersion ="" for camNamePart in camNameParts: if camNamePart[0] == "v": pbVersion = camNamePart startTime = int(camNameParts[-2]) endTime = int(camNameParts[-1]) setTimeline() pm.select(cl=1) pathWithVersion = "X:/Projects/GREY11_ANM71_Rewe_Starzone/GR11A71_Shots/GR11A71_Animatic/Animatic_Maya/data/%s/" % pbVersion playblastPath = pathWithVersion+activeCamera #make playblast pm.playblast( filename = playblastPath, format = "movie", width = renderWidth, height = renderHeight, percent = 100, compression = "none", quality = 100, forceOverwrite = 1, offScreen = 1, framePadding = 4, startTime = startTime, endTime = endTime, showOrnaments=0 ) pm.displayRGBColor("background", 0.632, 0.632, 0.632) pm.select(current_selection, r=1) toggleSpeakers(currentState)
def generate_ass(self): """generates the ASS representation of the current scene For Model Tasks the ASS is generated over the LookDev Task because it is not possible to assign a material to an object inside an ASS file. """ # before doing anything, check if this is a look dev task # and export the objects from the referenced files with their current # shadings, then replace all of the references to ASS repr and than # add Stand-in nodes and parent them under the referenced models # load necessary plugins pm.loadPlugin('mtoa') # disable "show plugin shapes" active_panel = auxiliary.Playblaster.get_active_panel() show_plugin_shapes = pm.modelEditor(active_panel, q=1, pluginShapes=1) pm.modelEditor(active_panel, e=1, pluginShapes=False) # validate the version first self.version = self._validate_version(self.version) self.open_version(self.version) task = self.version.task # export_command = 'arnoldExportAss -f "%(path)s" -s -mask 24 ' \ # '-lightLinks 0 -compressed -boundingBox ' \ # '-shadowLinks 0 -cam perspShape;' export_command = 'arnoldExportAss -f "%(path)s" -s -mask 60' \ '-lightLinks 1 -compressed -boundingBox ' \ '-shadowLinks 1 -cam perspShape;' # calculate output path output_path = \ os.path.join(self.version.absolute_path, 'Outputs/ass/')\ .replace('\\', '/') # check if all references have an ASS repr first refs_with_no_ass_repr = [] for ref in pm.listReferences(): if ref.version and not ref.has_repr('ASS'): refs_with_no_ass_repr.append(ref) if len(refs_with_no_ass_repr): raise RuntimeError( 'Please generate the ASS Representation of the references ' 'first!!!\n%s' % '\n'.join(map(lambda x: str(x.path), refs_with_no_ass_repr)) ) if self.is_look_dev_task(task): # in look dev files, we export the ASS files directly from the Base # version and parent the resulting Stand-In node to the parent of # the child node # load only Model references for ref in pm.listReferences(): v = ref.version load_ref = False if v: ref_task = v.task if self.is_model_task(ref_task): load_ref = True if load_ref: ref.load() ref.importContents() # Make all texture paths relative # replace all "$REPO#" from all texture paths first # # This is needed to properly render textures with any OS types_and_attrs = { 'aiImage': 'filename', 'file': 'fileTextureName', 'imagePlane': 'imageName' } for node_type in types_and_attrs.keys(): attr_name = types_and_attrs[node_type] for node in pm.ls(type=node_type): orig_path = node.getAttr(attr_name).replace("\\", "/") path = re.sub( r'(\$REPO[0-9/]+)', '', orig_path ) tx_path = self.make_tx(path) inputs = node.attr(attr_name).inputs(p=1) if len(inputs): # set the input attribute for input_node_attr in inputs: input_node_attr.set(tx_path) else: node.setAttr(attr_name, tx_path) # randomize all render node names # This is needed to prevent clashing of materials in a bigger scene for node in pm.ls(type=RENDER_RELATED_NODE_TYPES): if node.referenceFile() is None and \ node.name() not in READ_ONLY_NODE_NAMES: node.rename('%s_%s' % (node.name(), uuid.uuid4().hex)) nodes_to_ass_files = {} # export all root ass files as they are for root_node in auxiliary.get_root_nodes(): for child_node in root_node.getChildren(): # check if it is a transform node if not isinstance(child_node, pm.nt.Transform): continue if not auxiliary.has_shape(child_node): continue # randomize child node name # TODO: This is not working as intended, node names are like |NS:node1|NS:node2 # resulting a child_node_name as "node2" child_node_name = child_node\ .fullPath()\ .replace('|', '_')\ .split(':')[-1] child_node_full_path = child_node.fullPath() pm.select(child_node) child_node.rename('%s_%s' % (child_node.name(), uuid.uuid4().hex)) output_filename =\ '%s_%s.ass' % ( self.version.nice_name, child_node_name ) output_full_path = \ os.path.join(output_path, output_filename) # run the mel command pm.mel.eval( export_command % { 'path': output_full_path.replace('\\', '/') } ) nodes_to_ass_files[child_node_full_path] = \ '%s.gz' % output_full_path # print('%s -> %s' % ( # child_node_full_path, # output_full_path) # ) # reload the scene pm.newFile(force=True) self.open_version(self.version) # convert all references to ASS # we are doing it a little bit early here, but we need to for ref in pm.listReferences(): ref.to_repr('ASS') all_stand_ins = pm.ls(type='aiStandIn') for ass_node in all_stand_ins: ass_tra = ass_node.getParent() full_path = ass_tra.fullPath() if full_path in nodes_to_ass_files: ass_file_path = \ Repository.to_os_independent_path( nodes_to_ass_files[full_path] ) ass_node.setAttr('dso', ass_file_path) elif self.is_vegetation_task(task): # in vegetation files, we export the ASS files directly from the # Base version, also we use the geometry under "pfxPolygons" # and parent the resulting Stand-In nodes to the # pfxPolygons # load all references for ref in pm.listReferences(): ref.load() # Make all texture paths relative # replace all "$REPO#" from all texture paths first # # This is needed to properly render textures with any OS types_and_attrs = { 'aiImage': 'filename', 'file': 'fileTextureName', 'imagePlane': 'imageName' } for node_type in types_and_attrs.keys(): attr_name = types_and_attrs[node_type] for node in pm.ls(type=node_type): orig_path = node.getAttr(attr_name).replace("\\", "/") path = re.sub( r'(\$REPO[0-9/]+)', '', orig_path ) tx_path = self.make_tx(path) inputs = node.attr(attr_name).inputs(p=1) if len(inputs): # set the input attribute for input_node_attr in inputs: input_node_attr.set(tx_path) else: node.setAttr(attr_name, tx_path) # randomize all render node names # This is needed to prevent clashing of materials in a bigger scene for node in pm.ls(type=RENDER_RELATED_NODE_TYPES): if node.referenceFile() is None and \ node.name() not in READ_ONLY_NODE_NAMES: node.rename('%s_%s' % (node.name(), uuid.uuid4().hex)) # find the _pfxPolygons node pfx_polygons_node = pm.PyNode('kks___vegetation_pfxPolygons') for node in pfx_polygons_node.getChildren(): for child_node in node.getChildren(): #print('processing %s' % child_node.name()) child_node_name = child_node.name().split('___')[-1] pm.select(child_node) output_filename =\ '%s_%s.ass' % ( self.version.nice_name, child_node_name.replace(':', '_').replace('|', '_') ) output_full_path = \ os.path.join(output_path, output_filename) # run the mel command pm.mel.eval( export_command % { 'path': output_full_path.replace('\\', '/') } ) # generate an aiStandIn node and set the path ass_node = auxiliary.create_arnold_stand_in( path='%s.gz' % output_full_path ) ass_tra = ass_node.getParent() # parent the ass node under the current node # under pfx_polygons_node pm.parent(ass_tra, node) # set pivots rp = pm.xform(child_node, q=1, ws=1, rp=1) sp = pm.xform(child_node, q=1, ws=1, sp=1) # rpt = child_node.getRotatePivotTranslation() pm.xform(ass_node, ws=1, rp=rp) pm.xform(ass_node, ws=1, sp=sp) # ass_node.setRotatePivotTranslation(rpt) # delete the child_node pm.delete(child_node) # give it the same name with the original ass_tra.rename('%s' % child_node_name) # clean up other nodes pm.delete('kks___vegetation_pfxStrokes') pm.delete('kks___vegetation_paintableGeos') elif self.is_model_task(task): # convert all children of the root node # to an empty aiStandIn node # and save it as it is root_nodes = self.get_local_root_nodes() for root_node in root_nodes: for child_node in root_node.getChildren(): child_node_name = child_node.name() rp = pm.xform(child_node, q=1, ws=1, rp=1) sp = pm.xform(child_node, q=1, ws=1, sp=1) pm.delete(child_node) ass_node = auxiliary.create_arnold_stand_in(path='') ass_tra = ass_node.getParent() pm.parent(ass_tra, root_node) ass_tra.rename(child_node_name) # set pivots pm.xform(ass_tra, ws=1, rp=rp) pm.xform(ass_tra, ws=1, sp=sp) # because there will be possible material assignments # in look dev disable overrideShaders ass_node.setAttr('overrideShaders', False) # we definitely do not use light linking in our studio, # which seems to create more problems then it solves. ass_node.setAttr('overrideLightLinking', False) # convert all references to ASS for ref in pm.listReferences(): ref.to_repr('ASS') ref.load() # fix an arnold bug for node_name in ['initialShadingGroup', 'initialParticleSE']: node = pm.PyNode(node_name) node.setAttr("ai_surface_shader", (0, 0, 0), type="float3") node.setAttr("ai_volume_shader", (0, 0, 0), type="float3") # if this is an Exterior/Interior -> Layout -> Hires task flatten it is_exterior_or_interior_task = self.is_exterior_or_interior_task(task) if is_exterior_or_interior_task: # and import all of the references all_refs = pm.listReferences() while len(all_refs) != 0: for ref in all_refs: if not ref.isLoaded(): ref.load() ref.importContents() all_refs = pm.listReferences() # assign lambert1 to all GPU nodes pm.sets('initialShadingGroup', e=1, fe=auxiliary.get_root_nodes()) # now remove them from the group pm.sets('initialShadingGroup', e=1, rm=pm.ls()) # and to make sure that no override is enabled [node.setAttr('overrideLightLinking', False) for node in pm.ls(type='aiStandIn')] # clean up self.clean_up() # check if all aiStandIn nodes are included in # ArnoldStandInDefaultLightSet set try: arnold_stand_in_default_light_set = \ pm.PyNode('ArnoldStandInDefaultLightSet') except pm.MayaNodeError: # just create it arnold_stand_in_default_light_set = \ pm.createNode( 'objectSet', name='ArnoldStandInDefaultLightSet' ) pm.select(None) pm.sets( arnold_stand_in_default_light_set, fe=pm.ls(type='aiStandIn') ) # save the scene as {{original_take}}___ASS # use maya take_name = '%s%s%s' % ( self.base_take_name, Representation.repr_separator, 'ASS' ) v = self.get_latest_repr_version(take_name) self.maya_env.save_as(v) # export the root nodes under the same file if is_exterior_or_interior_task: pm.select(auxiliary.get_root_nodes()) pm.exportSelected( v.absolute_full_path, type='mayaAscii', force=True ) # new scene pm.newFile(force=True) # reset show plugin shapes option active_panel = auxiliary.Playblaster.get_active_panel() pm.modelEditor(active_panel, e=1, pluginShapes=show_plugin_shapes)
def viewportCapture(cls, camera_node, model_panel, path=None, toSquare=False, height=600, width=960, file_format='jpg'): from tempfile import NamedTemporaryFile file_path = NamedTemporaryFile(suffix=".%s" % file_format, delete=False) pmc.setFocus(model_panel) pmc.modelPanel( model_panel, edit=True, camera=camera_node ) pmc.modelEditor( model_panel, edit=True, allObjects=False, polymeshes=True, wireframeOnShaded=False, displayAppearance='smoothShaded' ) pmc.camera( camera_node, edit=True, displayFilmGate=False, displayResolution=False, overscan=1 ) # Capture image pmc.playblast( frame=pmc.currentTime(query=True), format="image", completeFilename=file_path.name, compression=file_format, percent=100, quality=100, viewer=False, height=height, width=width, offScreen=True, showOrnaments=False ) # Store img var and delete file q_image = QtGui.QImage(file_path.name) image_width = q_image.size().width() image_height = q_image.size().height() file_path.close() os.unlink(file_path.name) # Crop image if toSquare is True: rect = cls.get_containedSquare(image_width, image_height) else: rect = QtCore.QRect(0, 0, image_width, image_height) cropped = q_image.copy(rect) # Save image File if path is not None: cropped.save(fullPath, file_format, quality) return cropped, path, rect