Пример #1
0
    def __init__(self):
        # use current modifiers to determine popup menu modifiers
        isShiftPressed, isCtrlPressed, isAltPressed = utils.getModifiers()
        self.popupKeyKwargs = {
            'mm': True,
            'aob': True,
            'parent': 'viewPanes',
            'sh': isShiftPressed,
            'ctl': isCtrlPressed,
            'alt': isAltPressed,
        }
        # variable to keep track of if this menu ever showed
        self.wasInvoked = False
        # the panel that the popup menu will be attached to
        self.panel = pm.getPanel(up=True)
        # the panel type, can be used when building to determine the menu's contents
        self.panelType = pm.getPanel(typeOf=self.panel)
        LOG.debug("Panel: " + self.panel + ", Panel Type: " + self.panelType)

        # the unique id for this popup menu, must be overridden in subclasses
        self.popupMenuId = None
        # the mouse button that triggers this popup menu, 1=lmb, 2=mmb, 3=rmb
        self.mouseButton = 1
        # when True, build menu items each time the menu is displayed
        self.buildItemsOnShow = False
Пример #2
0
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)
Пример #3
0
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()))
Пример #4
0
 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))
Пример #5
0
def getCurrentCamera():
    """Returns the current cammera with focus"""
    panelUnderPointer = pymel.getPanel( underPointer=True )
    camera = None
    if panelUnderPointer:
        if 'modelPanel' in panelUnderPointer:
            currentPanel = pymel.getPanel(withFocus=True)
            currentPanel = currentPanel.split('|')[-1]
            camera = pymel.modelPanel(currentPanel, query=True, camera=True)

            return pymel.ls(camera)[0]

    return pymel.ls('persp')[0]
Пример #6
0
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]
Пример #7
0
 def create_menu(self):
     '''
     Create's the base menu associated to the current model panel(which should always be the active viewport)
     '''
     model_panel_list = pm.getPanel(type='modelPanel')
     visible_panel_list = pm.getPanel(vis=True)
     self.model_panel = [
         x for x in model_panel_list if x in visible_panel_list
     ][0]
     self.menu = pm.popupMenu(p=self.model_panel,
                              button=1,
                              alt=True,
                              ctl=True,
                              mm=True,
                              pmc=self.build_menu)
Пример #8
0
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='')
Пример #9
0
    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
Пример #10
0
    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)
Пример #11
0
def get_nodes():
    # Get name of Node Editor Panels,
    ne = pm.getPanel(scriptType='nodeEditorPanel')

    # Get List of Nodes in the main Node Editor Panel.
    nodeList = pm.nodeEditor('{}NodeEditorEd'.format(ne[0]),
                             q=True,
                             getNodeList=True)

    # For each node in Nodes, get connections and include only connections to and from nodes in the node list.
    connections = list()
    for node in nodeList:
        connections.append([
            attr for attr in pm.listConnections(
                node, d=False, s=True, c=True, p=True)
            if attr.nodeName() in nodeList
        ])

    for node in nodeList:
        # List of tuple pairs of attributes connected
        connections = pm.listConnections(node, d=False, s=True, c=True, p=True)
        for pair in connections:
            nodes = []

    return connections
Пример #12
0
    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')
Пример #13
0
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)
Пример #14
0
def getCurrentPannel():
    try:
        panel = pymel.getPanel(underPointer=True)
        panel = panel.split('|')[-1]
        return panel

    except:
        ka_python.printError()
        print '## Failed to find current panel, make sure you have a view port with focus'
Пример #15
0
def switch2BaseMap():
    """
    切换 Base Map
    """
    for texWinName in pm.getPanel(sty='polyTexturePlacementPanel'):
        for i, _map in enumerate(
                pm.textureWindow(texWinName, q=1, textureNames=1)):
            if 'BaseMap' in _map:
                pm.textureWindow(texWinName, e=1, textureNumber=i)
Пример #16
0
def getObjectUnderCursor():
    """Return a list of Maya objects under mouse pointer."""
    pos = QtGui.QCursor.pos()
    widg = QtWidgets.QApplication.widgetAt(pos)
    x, y = widg.mapFromGlobal(pos).toTuple()
    panel = pmc.getPanel(underPointer=True)
    try:
        return pmc.hitTest(panel, x, y)
    except RuntimeError:
        return []
Пример #17
0
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
Пример #18
0
def lockCam():
    view = pm.PyNode(pm.modelPanel(pm.getPanel(wf=True), q=True, cam=True))
    cam = pm.ls(view)[0]
    
    if (cam.tx.get(l=1) == 1):
            cam.translate.set(l = 0)
            cam.rotate.set(l = 0) 
    else:
            cam.translate.set(l = 1)
            cam.rotate.set(l = 1) 
Пример #19
0
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)
Пример #20
0
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)
Пример #21
0
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'
Пример #22
0
def addImgBookMark():
    global bmCam
    bmCam = pm.modelPanel(pm.getPanel(wf=True),q=True,cam=True)
    #remove current bookmark
    cmvList = pm.ls(type='cameraView')
    if len(cmvList)!=0:
        for cmv in cmvList:
            if cmv == 'imageView_bookmark':
                pm.cameraView(cmv,c=bmCam,e=True,rb=True)
                pm.delete(cmv)
    #add bookmark
    addBM = pm.cameraView(c=bmCam,ab=True,n='imageView_bookmark')
Пример #23
0
def gui():
    '''
    Triggers the interface for zoomerate.
    '''
    
    # Warning this is causeing issues with 2012
    panel = pm.getPanel(wf=True)
    try:
        whichCam = pm.modelPanel(panel, q=1, camera=True)
    except RuntimeError:
        whichCam = pm.modelPanel('modelPanel4', q=1, camera=True)
        print 'Using: %s' % whichCam
        
    whichCamShape = pm.ls(whichCam, dag=True, shapes=True, ap=True)
    
    # Figure out what cameras to use when building the menu
    cameras = pm.ls(ca=True)
    diffCams = []
    diffCams.extend(whichCamShape)
    diffCams.extend(cameras)
    print diffCams, len(diffCams)
    
    win_name = 'zoomer_win2'
    if pm.window(win_name, ex=True):
        pm.deleteUI(win_name)
        
    win = pm.window(win_name, s=0, ip=True, iconName='zoomer', w=400, h=180,
                    t='Camera zoomeratro v1.0')
    main = pm.columnLayout()
    pm.frameLayout(borderVisible=True, labelVisible=True, labelAlign='cener', label='Zoom Options', marginWidth=5, marginHeight=5)
    pm.columnLayout()
    global which_cam_menu
    which_cam_menu = pm.optionMenuGrp(label='Camera to Zoom', cc=connect)
    pm.menuItem(label=whichCamShape[0])
    for i in xrange(len(diffCams)-1):
        pm.menuItem(label=cameras[i])
    
    horizontal_attr = '%s.horizontalFilmOffset' % whichCamShape[0]
    vertical_attr = '%s.verticalFilmOffset' % whichCamShape[0]
    overscan_attr = '%s.overscan' % whichCamShape[0]
    
    global horizontal_slider, vertical_slider, overscan_slider
    horizontal_slider = pm.floatSliderGrp(field=True, label='Horizontal', min=-3, max=3, pre=3, step=0.001)
    vertical_slider = pm.floatSliderGrp(field=True, label='Vertical', min=-3, max=3, pre=3, step=0.001)
    overscan_slider = pm.floatSliderGrp(field=True, label='Overscan', min=-3, max=3, pre=3, step=0.001)
    
    pm.connectControl(horizontal_slider, horizontal_attr)
    pm.connectControl(vertical_slider, vertical_attr)
    pm.connectControl(overscan_slider, overscan_slider)
    
    pm.button(label='Reset', c=reset)
    win.show()
Пример #24
0
    def getViewport(self):
        '''
        Function to get the current maya viewport.
        Return: viewport modelPanel
        
        '''

        # get the current viewport
        pan = pm.getPanel(withFocus=True)
        if not re.search('modelPanel', pan):
            pan = 'modelPanel4'

        return pm.windows.modelPanel(pan, query=True, camera=True)
Пример #25
0
    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'
Пример #26
0
def IsolateSelected(state=True, showSelected=False):

    if state:  # turn ON isolation
        if not showSelected:  # hide everything ( useful during point cache )
            pm.select(clear=True)

        allModelPanels = pm.getPanel(type='modelPanel')

        for onePanel in allModelPanels:

            if pm.isolateSelect(onePanel, q=True, state=True):
                pm.isolateSelect(onePanel, loadSelected=True)
                #pm.isolateSelect( onePanel, update=True )
                mel.eval('doReload %s;' % onePanel)
            else:
                pm.isolateSelect(onePanel, state=True)
                #pm.isolateSelect( onePanel, update=True )
                mel.eval('doReload %s;' % onePanel)

    else:  # turn OFF isolation
        allModelPanels = pm.getPanel(type='modelPanel')
        for onePanel in allModelPanels:
            pm.isolateSelect(onePanel, state=False)
Пример #27
0
def IsolateSelected( state=True, showSelected=False ):

	if state: # turn ON isolation
		if not showSelected: # hide everything ( useful during point cache )
			pm.select( clear=True )
			
		allModelPanels = pm.getPanel( type='modelPanel' )

		for onePanel in allModelPanels:
				
			if pm.isolateSelect( onePanel, q=True, state=True ):
				pm.isolateSelect( onePanel, loadSelected=True )
				#pm.isolateSelect( onePanel, update=True )
				mel.eval( 'doReload %s;'%onePanel )
			else:
				pm.isolateSelect( onePanel, state=True )
				#pm.isolateSelect( onePanel, update=True )
				mel.eval( 'doReload %s;'%onePanel )
	
	else: # turn OFF isolation
		allModelPanels = pm.getPanel( type='modelPanel' )
		for onePanel in allModelPanels:
			pm.isolateSelect( onePanel, state=False )
Пример #28
0
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))
Пример #29
0
	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'
Пример #30
0
    def __init__(self):
        title = 'pbUV'
        ver = '1.00'

        if pm.window('pbUV', exists=True):
            pm.deleteUI('pbUV')

        window = pm.window('pbUV', s=True, title='{0} | {1}'.format(title, ver))

        try:
            pane = pm.paneLayout('textureEditorPanel', paneSize=[1, 1, 1], cn='vertical2', swp=1)
        except:
            pane = pm.paneLayout('textureEditorPanel', paneSize=[1, 1, 1], cn='vertical2')

        uvtextureviews = pm.getPanel(scriptType='polyTexturePlacementPanel')
        if len(uvtextureviews):
            pm.scriptedPanel(uvtextureviews[0], e=True, unParent=True)

        with pm.columnLayout(p=pane):
            TransformUI()
            opts = GlobalOptions()
            SetEditorUI()
            DensityUI(opts)
            SnapshotUI(opts)

        pm.scriptedPanel(uvtextureviews[0], e=True, parent=pane)

        # Replace Default UV Editor Toolbar
        flowlayout = pm.melGlobals['gUVTexEditToolBar']
        framelayout = pm.flowLayout(flowlayout, q=True, p=True)
        framelayout = pm.uitypes.FrameLayout(framelayout)
        pm.deleteUI(flowlayout)

        flowlayout = pm.flowLayout(p=framelayout)
        Tools01UI(flowlayout)
        CutSewUI(flowlayout)
        UnfoldUI(flowlayout)
        AlignUI(flowlayout)
        PushUI(flowlayout)
        SnapUI(flowlayout)
        LayoutUI(flowlayout)
        IsolateUI(flowlayout, uvtextureviews[0])
        Opts01UI(flowlayout, uvtextureviews[0])
        Opts02UI(flowlayout, uvtextureviews[0])
        Opts03UI(flowlayout, uvtextureviews[0])
        ManipUI(flowlayout)

        window.show()
def main():
    global panel_hyperShd
    
    #// collect hyperShade Window
    win_hyperShd = [ win for win in pm.lsUI( type='window' ) if win.find('hyperShade') != -1 ]
    
    #// test if hyershade is open
    if len(win_hyperShd) == 0:
        pm.runtime.HypershadeWindow()
    
    panel_hyperShd = pm.getPanel( scriptType='hyperShadePanel' )[0]
    print panel_hyperShd
    
    #// add button in hyperShade 
    pm.setParent( panel_hyperShd + '|mainForm|hyperShadeToolbarForm' )
    if( not(pm.button( 'grab', exists=True )) ):
         pm.button('grab', bgc=[0.5,0.5,0], c=pm.Callback( addMaterialinGraph ),  width=50 )
Пример #32
0
    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)
Пример #33
0
    def restorePanes(self, panel, tearoff):
        # Delete TearOff panel
        if pc.windows.window(panel.split('|')[-1]+'Window', q=True, exists=True):
            pc.windows.deleteUI(panel.split('|')[-1]+'Window', window=True)
        # Update maya UI panels to avoid crashing
        # NOTE may not be necessary at all pc.mel.eval('switchPanes single 0')
        # Restore visible elements
        if self.isChecked(self.smarthud):
            self.toggleVisiblePanelElements(tearoff.split("|")[-1])
        # Convert to output
        curr_frm = pc.animation.currentTime(q=True)
        max_plbopt = self.timerange_max()

        # Set focus to other panel (avoid crashing if called agani straight
        # after)
        for i in pc.getPanel(all=True):
            if i != panel:
                pc.setFocus()
                break
        hudobj = 'HUDObjectPosition', 
        pc.headsUpDisplay(hudobj, rem=True)
Пример #34
0
def createImgPln():
    global imgOp
    global imgDep
    global curCam
    global ImgPln
    global fileNm
    global pLoc

    #comfirmDialog for checking if ImgPln in the scene
    allTransNd = pm.ls(type='transform',fl=True)
    isImgPln = []
    for trans in allTransNd:
        if trans == 'ImagePlane_Parent_Loc':
            isImgPln.append(trans)
    if len(isImgPln) >= 1:
        cfmAnswer = pm.confirmDialog( title='Confirm', message='Delete Image Plane?', button=['Yes','No'], defaultButton='Yes', cancelButton='No', dismissString='No' )
        if cfmAnswer == 'Yes':
            cleanupImgPln()
            createImgPln()
    elif len(isImgPln) == 0:
        #image plane opacty and offset from camera
        imgOp = 1
        imgDep = 10
        #get current camera
        curCam = pm.modelPanel(pm.getPanel(wf=True),q=True,cam=True)
        #select image and creat imagePlane and setup
        fileNm = pm.fileDialog2(ds=0,fm=1,cap='open',okc='Select Image')
        ImgPln = pm.imagePlane(fn=fileNm[0],lookThrough=curCam,maintainRatio=1)
        pm.setAttr(ImgPln[1]+'.displayOnlyIfCurrent',True)
        pm.setAttr(ImgPln[0]+'.translateZ',-pm.getAttr(curCam+'.translateZ')/3+-imgDep)
        pm.setAttr(ImgPln[1]+'.alphaGain',imgOp)
        pm.setAttr(ImgPln[1]+'.textureFilter',1)
        
        #aligh to the camera
        #create locator to be the parent and then create parent constraint
        pLoc = pm.spaceLocator(name='ImagePlane_Parent_Loc')
        pm.parent(ImgPln[0],pLoc)
        LocCons = pm.parentConstraint(curCam,pLoc)
        pm.setAttr(pLoc+'Shape.template',1)
        pm.setAttr(LocCons+'.template',1)
Пример #35
0
def saveAllRenderViewImages( saveTo=None, ext='PNG' ):
    '''
    렌더뷰에 임시저장된 이미지들을 따로 몽땅 저장

    saveAllRenderViewImages( 'D:/Users/Desktop/hello', ext='png')
    saveAllRenderViewImages( 'D:/Users/Desktop/hello.png' )
    '''
    # 렌더뷰 컨트롤 찾기
    renderViewPanels = pm.getPanel( scriptType='renderWindowPanel' )
    if not renderViewPanels:
        pm.error( u"Render View window를 열어주세요." )

    renderViewPanel = renderViewPanels[0]
    renderViewForm = pm.renderWindowEditor( renderViewPanel, q=True, parent=True )
    if not renderViewForm:
        pm.error( u"Render View window를 열어주세요." )

    scrollBarName = '|'.join( renderViewForm.split('|')[:-1] ) + '|scrollBarForm|scrollBar'

    # 어디다 저장할지?
    dirname = None
    basename = None
    padding = 4
    if not saveTo:
        ws      = pm.workspace( q=True, fullName=True )
        images  = pm.workspace( 'images', q=True, fileRuleEntry=True)
        dirname = ws + '/' + images
        basenameEx = '/renderViewCapture'
    else:
        # path = r'Z:\2013_MapleStory2\3D_project\Share\scenes\GameData\Alon.mb'
        dirname    = os.path.dirname( saveTo )
        basename   = os.path.basename( saveTo )
        basenameEx = None
        if '.' in basename:
            basenameEx = '.'.join( basename.split('.')[:-1] )
            ext        = basename.split('.')[-1]
        else:
            basenameEx = basename

        if not os.path.isdir( dirname ):
            pm.error( u'그런 이름의 디렉토리는 없네용' )

    # numPadding
    padding    = basenameEx.count('#')
    basenameEx = basenameEx.replace('#','')
    paddingStr = '%d'
    if padding > 1:
        paddingStr = '%0' + str(padding) +'d'        

    saveTo = dirname + '/' + basenameEx + paddingStr +'.'+ ext.lower()
    #print 'name : "%s"' % saveTo

    # 지금 보고있는 렌더뷰 이미지가 어디 있는지 찾아야해용.
    # 그래서 하나하나 뒤로 돌려봅네당..
    currentIndex = pm.intScrollBar( scrollBarName, q=True, value=True )

    # now step through all the saved images in the render view window, saving each one out
    #int $maxImageIndex = `intScrollBar -query -maxValue $scrollBarName`;
    maxImageIndex = pm.renderWindowEditor( 'renderView', q=True, nbImages=True )    
    imagesWritten = 0
    number = 0 # 파일명이 겹치지 않도록 하는 변수
    for i in range( maxImageIndex+1 ):
        if not maxImageIndex == 0:
            # 한장의 이미지만 있고, 스크롤바가 안생긴 상태가 아니면...
            pm.intScrollBar( scrollBarName, e=True, value=i-1 )

        # 저장될 파일명
        number += 1
        fileName = saveTo % number
        
        # 같은 파일명의 이름이 있으면 뒤에 번호를 더 붙임
        while os.path.exists(fileName):
            #print '"%s" is Exists' % fileName
            number += 1
            fileName = saveTo % number
        
        # 저장
        pm.mel.renderWindowScrollDisplayImage( 'renderView' )
        pm.mel.renderWindowSaveImageCallback( 'renderView', fileName, ext.upper() )
        
        # 내용 출력
        print '# save To : %s' % fileName.replace('/','\\')
        
        # 저장된 이미지 개수 증가
        imagesWritten += 1
    
    # reset the current render view back to what it was before stepping through them
    pm.intScrollBar( scrollBarName, e=True, value=currentIndex )
    pm.mel.renderWindowScrollDisplayImage( 'renderView' )

    if imagesWritten == 0:
        print u"# Error saving: render view 에 이미지가 없습니다.\n"
    else:
        print u"# Save complete: %d장의 render view 이미지가 저장 되었습네다.\n"%imagesWritten
Пример #36
0
	def BakeTransform( self, bakeOnNewLocator=True, *args ): # BakeTransform( bakeOnNewLocator=False )
		'''
		Useful for exporting translate and rotate animation to other 3D packages.	
		
		if bakeOnNewLocator in True: For every selected object, creates a locator and bakes object's animation on this locator.
		if bakeOnNewLocator in False: For every selected object, bakes their translate, rotate and scale animations in world space.
		
		'''
		objs = pm.ls( sl=True )
		
		if not objs:
			pm.warning( "ehm_tools...BakeAnimation: Select an object to bake it's transform animation." )
			return


		try: # get info from UI, if in UI mode
			selectedItem = pm.radioCollection( self.bakeModeRC, q=True, select=True )
			bakeOnNewLocatorState = pm.radioButton( selectedItem, q=True, label=True )
			
			if bakeOnNewLocatorState == 'Bake On New Locator':
				bakeOnNewLocator=True
			else:
				bakeOnNewLocator=False
		except:
			pass
		
		
		timeRange = self.getTimeRange()
	
	

		locs = []
		cons = []
		
		
					
		# for each selected object...
		for obj in objs: # bake it's animation on a new locator
			if obj.type() in [ 'transform', 'joint' ]:
				loc = pm.spaceLocator( name= '%s_SRT'%obj.name() )
				cons.append( pm.pointConstraint( obj, loc ) )
				cons.append( pm.orientConstraint( obj, loc ) )
				cons.append( pm.scaleConstraint( obj, loc ) )
				
				# hide all objects to increase speed of baking animation, 
				IsolateSelected(  state=True, showSelected=False  )
				
				locs.append( loc )				
		
			
		pm.bakeResults( locs , simulation=True, t=timeRange, disableImplicitControl=True, preserveOutsideKeys=True, removeBakedAttributeFromLayer=False, bakeOnOverrideLayer=False, controlPoints=False, shape=False )

		
		# unhide all objects
		allModelPanels = pm.getPanel( type='modelPanel' )
		for onePanel in allModelPanels:
			pm.isolateSelect( onePanel, state=False )
		
		pm.delete( cons )

		pm.select( locs )
		
		
		cons = []
		
		# for each selected object...	
		if not bakeOnNewLocator: # bake keys on selected objects themseleves not on new locators
			bakedObjects = pm.group( empty=True, name='baked_objects_grp')
			
			for i in range( len(objs) ):
				UnlockUnhideAttrs( objs = objs[i] )
				self.removeConnections( objs = objs[i] )
				pm.parent( objs[i], bakedObjects )
				
				cons.append( pm.pointConstraint( locs[i], objs[i] ) )
				cons.append( pm.orientConstraint( locs[i], objs[i] ) )
				cons.append( pm.scaleConstraint( locs[i], objs[i] ) )			
				
				# hide all objects to increase speed of baking animation, 
				IsolateSelected(  state=True, showSelected=False )
					

			pm.bakeResults( objs , simulation=True, t=timeRange, disableImplicitControl=True, preserveOutsideKeys=True, removeBakedAttributeFromLayer=False, bakeOnOverrideLayer=False, controlPoints=False, shape=False )
					
			
			# unhide all objects
			for onePanel in allModelPanels:
				pm.isolateSelect( onePanel, state=False )
		
			pm.delete( cons )
			pm.delete( locs )	
			pm.select( objs )
Пример #37
0
    def one_cam_to_shots(self):
        # make sure selected object is a camera
        sel = pm.selected()
        if len(sel) != 1:
            raise RuntimeError('Select just 1 camera.')
        the_cam = sel[0]
        if the_cam.getShape().type() != 'camera':
            message = 'Select just 1 Camera.\r\n'
            pm.confirmDialog(title='Error', message=message, button='OK')
            raise RuntimeError('Select just 1 camera.')

        # unlock locked attrs
        attributes_locked = []
        for attr in pm.listAttr(the_cam, locked=1):
            attributes_locked.append(attr)
        for attr in pm.listAttr(the_cam.getShape(), locked=1):
            attributes_locked.append(attr)

        for attr in attributes_locked:
            the_cam.attr(attr).unlock()

        id = 0
        for shot in self.shots_descending:
            s_frame = shot.getStartTime()
            e_frame = shot.getEndTime()

            # duplicate, clear parents and unparent shot cam from original
            pm.currentTime(s_frame)
            id += 1
            shot_camera = pm.duplicate(the_cam, rr=1, name='camera__shotExp_%s' % str(id))
            tr_parents = shot_camera[0].listRelatives(type='transform')
            for tr in tr_parents:
                pm.delete(tr)
            pm.parent(shot_camera, w=1)

            # connect animation curves from original to duplicated shot cam
            anim_curves = []
            connections = the_cam.getShape().listConnections()
            for connection in connections:
                if 'animCurve' in str(connection.type()):
                    attribute_name = str(connection.listConnections(p=1)[0].split('.')[-1:][0])
                    new_key = pm.duplicate(connection, rr=1)
                    anim_curves.append(new_key[0])
                    pm.connectAttr('%s.output' % new_key[0], '%s.%s' % (shot_camera[0].getShape(), attribute_name))

            # parent constraint shot cam to original
            constraint = pm.parentConstraint(the_cam, shot_camera[0], mo=0, weight=1)

            # isolate none to speed things up
            panel_list = pm.getPanel(type='modelPanel')
            pm.select(None)
            for panel in panel_list:
                pm.isolateSelect(panel, state=1)

            # bake all keyable attrs between shot frame range
            pm.mel.eval('bakeResults -simulation true -t "%s:%s" -sampleBy 1 -disableImplicitControl true '
                            '-preserveOutsideKeys true -sparseAnimCurveBake false -removeBakedAttributeFromLayer false '
                            '-bakeOnOverrideLayer false -minimizeRotation true -controlPoints false -shape true %s;'
                            % (int(s_frame), int(e_frame), shot_camera[0]))

            # restore isolation
            for panel in panel_list:
                pm.isolateSelect(panel, state=0)

            # set some forced attrs
            shot_camera[0].disconnectAttr('scaleX')
            shot_camera[0].setAttr('scaleX', 1)
            shot_camera[0].disconnectAttr('scaleY')
            shot_camera[0].setAttr('scaleY', 1)
            shot_camera[0].disconnectAttr('scaleZ')
            shot_camera[0].setAttr('scaleZ', 1)
            shot_camera[0].disconnectAttr('visibility')
            shot_camera[0].setAttr('visibility', 1)
            shot_camera[0].getShape().disconnectAttr('farClipPlane')
            shot_camera[0].getShape().setAttr('farClipPlane', 10000000)

            # make all camera anim curves linear
            for curve in shot_camera[0].listAttr(k=1):
                pm.selectKey(curve, add=1, k=1)
                pm.keyTangent(itt='linear', ott='linear')
            for curve in shot_camera[0].getShape().listAttr(k=1):
                pm.selectKey(curve, add=1, k=1)
                pm.keyTangent(itt='linear', ott='linear')

            # no need for constraint node
            pm.delete(constraint)

            # lock previously unlocked attrs again
            for attr in attributes_locked:
                the_cam.attr(attr).lock()

            # set shot camera
            pm.select(cl=1)
            shot.set_camera(shot_camera[0])
Пример #38
0
 def __init__ (self, *args, **kwargs):
   """ set some initial values """
   self.uvTextureView = pm.getPanel(scriptType='polyTexturePlacementPanel') #specifies the UV Texture Editor, there is only one