コード例 #1
0
    def inner(*args, **kwargs):
        # store current huds' names, position and visibility
        old_huds = cmds.headsUpDisplay(listHeadsUpDisplays=True) or []
        old_huds_visibility = [hud_visibility(hud) for hud in old_huds]
        sections = {i: {} for i in range(10)}
        for hud in old_huds:
            section, block = get_hud_position(hud)
            sections[section][block] = hud

        # hide all huds
        for hud in old_huds:
            cmds.headsUpDisplay(hud, e=True, visible=False)

        try:
            return func(*args, **kwargs)
        except:
            raise
        finally:
            # delete new huds
            new_huds = cmds.headsUpDisplay(listHeadsUpDisplays=True) or []
            for hud in new_huds:
                if hud not in old_huds:
                    cmds.headsUpDisplay(hud, remove=True)

            # restore huds' visibility
            for hud, visibility in zip(old_huds, old_huds_visibility):
                cmds.headsUpDisplay(hud, e=True, visible=visibility)

            # restore huds' positions
            for section, blocks in sections.items():
                for block, hud in sorted(blocks.items()):
                    cmds.headsUpDisplay(hud, e=True,
                                        section=section, block=block)
コード例 #2
0
def destroyHeadsUpDisplay():
    """Removes the HUD object of the plug-in from Maya HUD."""

    doesHUDExist = cmds.headsUpDisplay(headsUpDisplay['Name'], exists=True)
    
    if doesHUDExist:
        cmds.headsUpDisplay(headsUpDisplay['Name'], rem=True)
コード例 #3
0
 def _remove(self):
     '''remove HUD info
     '''
     huds = cmds.headsUpDisplay(lh = True)
     if huds:
         for item in huds:
             cmds.headsUpDisplay(item, rem = True)
コード例 #4
0
def guardaImagen(nombreDePose=""):
    global nombreDePoseGlobal
    nombreDePoseGlobal = nombreDePose
    mc.evalDeferred('resolucion=150')
    nombrePanel = cmds.modelPanel(tearOff=True)
    nombreEditor = mc.modelPanel(nombrePanel, q=1, modelEditor=1)
    mc.modelEditor(
        nombreEditor,
        e=1,
        activeOnly=0,
        displayAppearance="smoothShaded",
        polymeshes=1,
        wos=0,
        nurbsSurfaces=1,
        planes=1,
        lights=0,
        cameras=0,
        controlVertices=0,
        grid=0,
        hulls=0,
        joints=0,
        ikHandles=0,
        nurbsCurves=0,
        deformers=0,
        dynamics=1,
        fluids=0,
        hairSystems=0,
        follicles=0,
        nCloths=1,
        nParticles=1,
        nRigids=1,
        dynamicConstraints=0,
        locators=0,
        manipulators=0,
        dimensions=0,
        handles=0,
        pivots=1,
        textures=0,
        strokes=0,
        pluginShapes=1,
        queryPluginObjects=1,
    )

    mc.modelEditor(nombreEditor,
                   e=1,
                   activeView=1,
                   p='lay_1',
                   activeOnly=0,
                   displayAppearance="smoothShaded",
                   polymeshes=1,
                   wos=0)
    mc.headsUpDisplay(layoutVisibility=False)
    mc.evalDeferred('view=apiUI.M3dView.active3dView()')
    mc.evalDeferred('imagen=api.MImage()')
    mc.evalDeferred('view.readColorBuffer (imagen,True)')
    mc.evalDeferred('imagen.resize (resolucion,resolucion,1)')
    mc.evalDeferred(
        'imagen.writeToFile("M:/PH_SCRIPTS/ICONS/POSES/"+nombreDePoseGlobal+".png","png")'
    )
    mc.headsUpDisplay(layoutVisibility=1)
コード例 #5
0
 def _show(self):
     self._displayMode("playblast")
     # self._resize_font()
     displayLayout = self._set_show_info(*self._DefaultList)
     self.valuecolor = 16
     self.labelcolor = 14
     for display in displayLayout.keys():
         dis = displayLayout[display]
         if not dis["c"]:
             cmds.headsUpDisplay(display, s = dis["s"], b = dis["b"], ba = dis["ba"],p = dis["p"],
                                     lfs = dis["lfs"], dfs = dis["dfs"], blockSize = dis["bs"], 
                                     atr = dis["atr"],da = dis["da"],lw = dis["lw"],l = dis["l"])
         else:
             cmds.headsUpDisplay(display, s = dis["s"], b = dis["b"], ba = dis["ba"],p = dis["p"],
                                     lfs = dis["lfs"], dfs = dis["dfs"], blockSize = dis["bs"], 
                                     c = dis["c"], atr = dis["atr"],da = dis["da"],lw = dis["lw"],l = dis["l"])
     _mask_json = get_maya_shotmask()
     if _mask_json:
         result = shotmask.create_mask()
         if result:
             _mask = shotmask.get_mask()
             with open(_mask_json, 'r') as info:
                 dataInfo = json.load(info)
                 if dataInfo:
                     for _key, _value in dataInfo.items():
                         cmds.setAttr("{}.{}".format(_mask, _key), _value)
コード例 #6
0
    def showHUD(self, vis):
        """ Hide or show all HUD elements at once.
		"""
        hudLs = mc.headsUpDisplay(listHeadsUpDisplays=True)

        for hud in hudLs:
            mc.headsUpDisplay(hud, edit=True, vis=vis)
コード例 #7
0
    def restoreHUD(self, hudDic):
        """ Restore the HUD from the state stored in the dictionary.
		"""
        hudLs = mc.headsUpDisplay(listHeadsUpDisplays=True)

        for hud, vis in hudDic.iteritems():
            mc.headsUpDisplay(hud, edit=True, vis=vis)
コード例 #8
0
ファイル: main.py プロジェクト: EuniceChen1/MayaTools
 def closeEvent(self,event):
     for (hud,visi) in self.oriHud:
         cmds.headsUpDisplay(hud,e=1,vis=visi)
     for hud in cmds.headsUpDisplay(lh=1) :
         if "pbMask" in hud:
             cmds.headsUpDisplay(hud,e=1,rem=1)
     super(pipeWindow, self).closeEvent(event)
コード例 #9
0
ファイル: tak_lib.py プロジェクト: sgodanas/scripts
def showHUD(widgetName, title, sectionNum=2, blockNum=0):
    '''
	This function find available block and display hud.
	'''

    allHuds = cmds.headsUpDisplay(listHeadsUpDisplays=True)

    hudsInSection = []
    for hud in allHuds:
        if cmds.headsUpDisplay(hud, q=True, s=True) == sectionNum:
            hudsInSection.append(hud)

    if hudsInSection:
        invalidBlocks = []
        for hud in hudsInSection:
            invalidBlock = cmds.headsUpDisplay(hud, q=True, b=True)
            invalidBlocks.append(invalidBlock)

        blockNum = max(invalidBlocks) + 1

    cmds.headsUpDisplay(widgetName,
                        s=sectionNum,
                        b=blockNum,
                        blockSize='medium',
                        label=title,
                        labelFontSize='large')
コード例 #10
0
ファイル: HeadsUpDisplay.py プロジェクト: jonntd/mira
 def show(self, *args):
     if not self.__camera:
         self.__camera = mc.lookThru(q=1)
     # ----clear old huds---- #
     self.clear()
     # ----look through current camera ----#
     mc.lookThru(self.__camera)
     # ----set hud color ---- #
     mc.displayColor("headsUpDisplayLabels",
                     self.__hud_color["label_color"])
     mc.displayColor("headsUpDisplayValues",
                     self.__hud_color["value_color"])
     # ----create huds---- #
     for hud in self.__huds:
         label = self.__hud_dict[hud]["label"]
         section = self.__hud_dict[hud]["section"]
         block = mc.headsUpDisplay(nextFreeBlock=section)
         labelWidth = self.__hud_dict[hud]["labelWidth"]
         # event = self.__hud_dict[hud]["event"]
         labelFontSize = self.__hud_dict[hud]["labelFontSize"]
         dataFontSize = self.__hud_dict[hud]["dataFontSize"]
         blockSize = self.__hud_dict[hud]["blockSize"]
         command = self.__hud_dict[hud]["command"].format(
             camera=self.__camera)
         mc.headsUpDisplay(hud,
                           label=label,
                           section=section,
                           block=block,
                           labelWidth=labelWidth,
                           labelFontSize=labelFontSize,
                           dataFontSize=dataFontSize,
                           blockSize=blockSize,
                           attachToRefresh=True,
                           command=command)
コード例 #11
0
def install_hud():
    """Install clash short hud."""
    uninstall_hud()
    for _name, _pos, _cmd, _kwargs in _get_hud_data():
        cmds.headsUpDisplay(removePosition=_pos)
        cmds.headsUpDisplay(
            _name, section=_pos[0], block=_pos[1], blockSize='large',
            labelFontSize='large', command=_cmd, **_kwargs)
コード例 #12
0
ファイル: CustomViewer.py プロジェクト: yazici/damgteam
 def shotHUD(self, *args):
     shot = cmds.intFieldGrp(self.shotNumber, query=True, value1=True)
     seq = cmds.intFieldGrp(self.seqNumber, query=True, value1=True)
     blk = 0
     seCT = 1
     self.shotStage()
     cmds.headsUpDisplay('HUDShotNumber', section=seCT, block=blk, blockSize='medium',
                         label='Scene %s - Shot %s' % (str(seq), str(shot)), command=self.shotNumber)
コード例 #13
0
ファイル: MMtoKey.py プロジェクト: liudger/May9
 def changePreset(self, preset):
     self.activePreset = preset
     self._current_node_preset = self.DATA_PRESET[preset]
     if cmds.headsUpDisplay('MMtoKeyHUD', ex=True):
         cmds.headsUpDisplay('MMtoKeyHUD', remove=True)
     if self.pref_hud:
         cmds.headsUpDisplay('MMtoKeyHUD', s=self.pref_hud_x, b=self.pref_hud_y, l='MMtoKey preset', ba='center',
                             lfs='large', dfs='large', c=self._activePreset, ev='NewSceneOpened')
コード例 #14
0
def restoreHUDAttributes(showSettings, hudSettings):
    cameraShape = mc.listRelatives(CAM.getCurrentCamera(), shapes=True)[0]
    panelName = CAM.getCurrentPanel()
    huds = mc.headsUpDisplay(lh=True)

    #restore HUD values
    for i, hud in enumerate(huds):
        mc.headsUpDisplay(hud, edit=True, vis=hudSettings[hud])

    #restore viewport settings
    mc.modelEditor(panelName,
                   edit=True,
                   nc=showSettings['nc'],
                   ns=showSettings['ns'],
                   pm=showSettings['pm'],
                   sds=showSettings['sds'],
                   pl=showSettings['pl'],
                   lt=showSettings['lt'],
                   ca=showSettings['ca'],
                   cv=showSettings['cv'],
                   gr=showSettings['gr'],
                   hu=showSettings['hu'],
                   j=showSettings['j'],
                   ikh=showSettings['ikh'],
                   df=showSettings['df'],
                   dy=showSettings['dy'],
                   fl=showSettings['fl'],
                   hs=showSettings['hs'],
                   fo=showSettings['fo'],
                   ncl=showSettings['ncl'],
                   nr=showSettings['nr'],
                   dc=showSettings['dc'],
                   lc=showSettings['lc'],
                   manipulators=showSettings['manipulators'],
                   dim=showSettings['dim'],
                   ha=showSettings['ha'],
                   pv=showSettings['pv'],
                   tx=showSettings['tx'],
                   strokes=showSettings['strokes'])
    #alo = showSettings['alo']

    #restore camera gates
    mc.setAttr("{0}.displayFilmGate".format(cameraShape),
               showSettings['displayFilmGate'])
    mc.setAttr("{0}.displayResolution".format(cameraShape),
               showSettings['displayResolution'])
    mc.setAttr("{0}.displayFieldChart".format(cameraShape),
               showSettings['displayFieldChart'])
    mc.setAttr("{0}.displaySafeAction".format(cameraShape),
               showSettings['displaySafeAction'])
    mc.setAttr("{0}.displaySafeTitle".format(cameraShape),
               showSettings['displaySafeTitle'])
    mc.setAttr("{0}.displayFilmPivot".format(cameraShape),
               showSettings['displayFilmPivot'])
    mc.setAttr("{0}.displayFilmOrigin".format(cameraShape),
               showSettings['displayFilmOrigin'])
    mc.setAttr("{0}.overscan".format(cameraShape), 1.3)
コード例 #15
0
    def hideBurnin(self):
        """ Remove the custom HUD elements.
		"""
        hudLs = mc.headsUpDisplay(listHeadsUpDisplays=True)

        for hud in hudLs:
            if hud.startswith('custom_hud'):
                if mc.headsUpDisplay(hud, exists=True):
                    mc.headsUpDisplay(hud, remove=True)
コード例 #16
0
def kill_message():
    """
    Kills the Heads Up Display message created by the build_grid command if it
        still exists.  Function serves as a backup if it isn't deleted by
        another command.

    """
    if cmds.headsUpDisplay('HUD_grid_message', exists=True):
        cmds.headsUpDisplay('HUD_grid_message', remove=True)
コード例 #17
0
    def cancelSculpt(cls, *args):
        cmds.headsUpDisplay('sclptHUD', remove=True)
        cmds.delete(cls.sculptGeo)
        cmds.delete(cls.invGeo)
        cls.shpVisOnOff(cls.cacheGeo, 'off')

        # Button enable control
        cmds.button(UI.widgets['sculptBtn'], e=True, enable=True)
        cmds.button(UI.widgets['cancelBtn'], e=True, enable=False)
        cmds.button(UI.widgets['createBtn'], e=True, enable=False)
コード例 #18
0
    def storeHUD(self):
        """ Store the current state of the HUD in a dictionary.
		"""
        hudLs = mc.headsUpDisplay(listHeadsUpDisplays=True)

        hudDic = {}
        for hud in hudLs:
            hudDic[hud] = mc.headsUpDisplay(hud, query=True, vis=True)

        return hudDic
コード例 #19
0
def tglTwoSidedLit(*args):
    hudWdgName = 'twoSidedHud'

    curPanel = cmds.paneLayout('viewPanes', q = True, pane1= True)
    if cmds.modelEditor(curPanel, q = True, twoSidedLighting = True):
        cmds.modelEditor(curPanel, e = True, twoSidedLighting = False)
        cmds.headsUpDisplay(hudWdgName, remove = True)
    else:
        cmds.modelEditor(curPanel, e = True, twoSidedLighting = True)
        tak_lib.showHUD(hudWdgName, title = 'Two Sided Lighting On')
コード例 #20
0
ファイル: view_utils.py プロジェクト: lefan2016/maya_utils
def saveHUDVisibleStatus():
    """
    """
    head_obj_list = cmds.headsUpDisplay(listHeadsUpDisplays=True)
    hud_status_dict = {}
    for head_obj in head_obj_list:
        status = cmds.headsUpDisplay(head_obj, visible=True, query=True)
        hud_status_dict[head_obj] = status

    return hud_status_dict
コード例 #21
0
ファイル: Red9_Tools.py プロジェクト: miketon/SymLink
def monitorAttrs():
    cmds.headsUpDisplay(
                        section = 0,
                        block=8,
                        blockSize="small",
                        label ="Blends:",
                        labelFontSize ="large",
                        dataFontSize="large",
                        command ="BlendCounter ",
                        atr= ("HUDBlendCounter"))
コード例 #22
0
ファイル: Engine.py プロジェクト: kissinger31/May9
 def setPreset(self, preset):
     """change current preset. do not call marking menu"""
     self._preset_changed = True     # do not call no-click command this release
     self._last_preset = self.cluster["preset"][preset]
     if cmds.headsUpDisplay('MMtoKeyHUD', ex=True):
         cmds.headsUpDisplay('MMtoKeyHUD', remove=True)
     Menu.show(self._last_preset["menu_type"], self._last_preset["menu"], self.preferences, b=Menu.LMB,
               pmc=self._postMenu, **self._preset_modifiers)
     if self.preferences["preset_hud"]:
         cmds.headsUpDisplay('MMtoKeyHUD', s=self.preferences["preset_hud_s"], b=self.preferences["preset_hud_b"],
                             label='MMtoKey preset', ba='center', lfs='large', dfs='large', c=lambda: preset,
                             ev='NewSceneOpened')
コード例 #23
0
ファイル: artistplayblast.py プロジェクト: prsfx/cgitools
    def __projectNameToggle(self, *args):
        projectName = self.fileNameInput_lndt.text()

        if self.fileNameEnable_pbttn.isChecked() == True:
            cmds.headsUpDisplay("ProjectName",
                                section=8,
                                block=0,
                                blockSize="small",
                                label="Project:         " + projectName,
                                labelFontSize="small")
        else:
            cmds.headsUpDisplay("ProjectName", rem=True)
コード例 #24
0
ファイル: artistplayblast.py プロジェクト: prsfx/cgitools
    def __artistNameToggle(self, *args):
        artistName = self.artistName_lndt.text()

        if self.artistNameEnable_pbttn.isChecked() == True:
            cmds.headsUpDisplay("ArtistName",
                                section=6,
                                block=0,
                                blockSize="small",
                                label="Artist:         " + artistName,
                                labelFontSize="small")
        else:
            cmds.headsUpDisplay("ArtistName", rem=True)
コード例 #25
0
    def enterRigEditMode(self, *args):
        self.versionComboBox.setEnabled(False)
        newRig = args[0]
        global g_rigEditModeFileName
        global xmlPath
        global rootNode
        projectDir = cmds.workspace(q=True, rd=True)
        #remove the HUD item at (2,0) if one is present
        cmds.headsUpDisplay(rp=(2, 2))
        #add our HUD item for the rig edit mode
        cmds.headsUpDisplay("",
                            s=2,
                            b=2,
                            ba="center",
                            lfs="large",
                            dw=50,
                            l="Rig Edit Mode")

        tempDir = mel.eval("getenv TEMP;")
        #get the path to the XML file and save it for later use
        if newRig is False:
            current = self.rigList.currentItem()
            rootNode = "MRN_" + current.text()
            xmlPath = cmds.getAttr(str(rootNode + ".xmlPath"))
            #write over temporary rig file
            shutil.copy(xmlPath, tempDir + "/rigTemp.xml")
            xmlPath = tempDir + "/rigTemp.xml"
        else:
            rootNode = ""
            xmlPath = ""

        #save the scene to a file, and load a new, empty scene

        g_rigEditModeFileName = cmds.file(q=True, sceneName=True)
        if g_rigEditModeFileName == "":
            cmds.file(rn=tempDir + "\\rigModeTemp.ma")
        cmds.file(f=True, save=True, type="mayaAscii")
        cmds.file(f=True, new=True)

        #load the rig file into the current scene
        if newRig is False:
            commandString = "loadRig -p \"" + xmlPath + "\";"
            rigName = mel.eval(commandString)

        self.refreshListWidget()
        self.addRigBtn.setEnabled(False)
        self.updateAllBtn.setEnabled(False)
        self.enterRigEditBtn.setEnabled(False)
        self.rigList.setEnabled(False)
        self.createRigBtn.setEnabled(False)
        self.openNodeBtn.setEnabled(True)
        self.exitRigEditBtn.setEnabled(True)
コード例 #26
0
 def displayDescription(self):
     '''
     这个函数实现headsUpDisplay命令的多行显示
     '''
     textList = self.description.split('\n')
     for i in range(len(textList)):
         line = len(textList) - i
         text = textList[i]
         try:
             cmds.headsUpDisplay('MLHUD_Description_ID%s'%i,r=True)
         except:
             pass
         cmds.headsUpDisplay('MLHUD_Description_ID%s'%i,s=5,b=line,ba = "left",lfs='large',dfs='large',blockSize='small',label=text,c=lambda:'',attachToRefresh=True)
コード例 #27
0
def finish_matching():
    global hud_but
    global matching_obj
    cmds.select(cl=True)
    cmds.select(matching_obj, r=True)
    #print hud_but
    #キャンセルボタン削除
    if maya_ver != 2017:
        cmds.headsUpDisplay(removeID=int(hud_but))

    QApplication.restoreOverrideCursor()
    cmds.undoInfo(closeChunk=True)
    cmds.headsUpDisplay(removeID=int(hud_but))
コード例 #28
0
ファイル: key_util_lib.py プロジェクト: boochos/work
 def displayAnimatedDisHud(self, hudName):
     self.hud = hudName
     section = 4
     cmds.headsUpDisplay(hudName, rem=True)
     cmds.headsUpDisplay(
         hudName,
         section=section,
         block=cmds.headsUpDisplay(nfb=section),
         attachToRefresh=True,
         blockSize='medium',
         label=hudName,
         labelFontSize='small',
         command=self.disAnimate
     )
コード例 #29
0
def snapshot(outputPath, width=400, height=None, hud=False, grid=False):
    if height is None:
        height = width

    outputExt = os.path.splitext(outputPath)[1].lower().lstrip('.')

    formatNum = KNOWN_FORMATS.get(outputExt)
    if formatNum is None:
        raise ValueError(
            "input image had unrecognized extension: {}".format(outputExt))

    # if given relative path, make it relative to current dir (the test
    # temp base), rather than the workspace dir
    outputPath = os.path.abspath(outputPath)

    # save the old output image format
    oldFormat = cmds.getAttr("defaultRenderGlobals.imageFormat")
    # save the hud setting
    oldHud = cmds.headsUpDisplay(q=1, layoutVisibility=1)
    # save the grid setting
    oldGrid = cmds.grid(q=1, toggle=1)
    # save the old view transform
    oldViewTransform = cmds.colorManagementPrefs(q=1, viewTransformName=1)

    # do these in a separate try/finally from color management, because
    # color management seems a bit more finicky
    cmds.setAttr("defaultRenderGlobals.imageFormat", 32)
    cmds.headsUpDisplay(layoutVisibility=hud)
    cmds.grid(toggle=grid)
    try:
        # Doing this would be more direct:
        #   cmds.colorManagementPrefs(e=1, outputTarget="playblast",
        #                             outputTransformName="Raw")
        # ... but it causes maya-2018.3 to crash. It seems to be fixed in 2019.0.
        cmds.colorManagementPrefs(e=1, viewTransformName="Raw")
        try:
            cmds.playblast(cf=outputPath,
                           viewer=False,
                           format="image",
                           frame=cmds.currentTime(q=1),
                           offScreen=1,
                           widthHeight=(width, height),
                           percent=100)
        finally:
            cmds.colorManagementPrefs(e=1, viewTransformName=oldViewTransform)
    finally:
        cmds.setAttr("defaultRenderGlobals.imageFormat", oldFormat)
        cmds.headsUpDisplay(layoutVisibility=oldHud)
        cmds.grid(toggle=oldGrid)
コード例 #30
0
 def enterRigEditMode(self,*args):
     self.versionComboBox.setEnabled(False)
     newRig = args[0]
     global g_rigEditModeFileName
     global xmlPath
     global rootNode
     projectDir = cmds.workspace(q=True,rd=True)
     #remove the HUD item at (2,0) if one is present
     cmds.headsUpDisplay(rp=(2,2))
     #add our HUD item for the rig edit mode
     cmds.headsUpDisplay("",s=2,b=2,ba="center",lfs="large",dw=50,l="Rig Edit Mode")
     
     tempDir = mel.eval("getenv TEMP;")
     #get the path to the XML file and save it for later use
     if newRig is False:
         current = self.rigList.currentItem()
         rootNode = "MRN_"+current.text()
         xmlPath = cmds.getAttr(str(rootNode+".xmlPath"))
         #write over temporary rig file
         shutil.copy(xmlPath, tempDir+"/rigTemp.xml")
         xmlPath = tempDir+"/rigTemp.xml"
     else:
         rootNode = ""
         xmlPath = ""
         
     
     #save the scene to a file, and load a new, empty scene
     
     
     g_rigEditModeFileName = cmds.file(q=True,sceneName=True)
     if g_rigEditModeFileName == "":
         cmds.file(rn=tempDir+"\\rigModeTemp.ma")
     cmds.file(f=True,save=True,type="mayaAscii")
     cmds.file(f=True,new=True)
     
     #load the rig file into the current scene
     if newRig is False:
         commandString = "loadRig -p \""+xmlPath+"\";"
         rigName = mel.eval(commandString)
     
     
     self.refreshListWidget()
     self.addRigBtn.setEnabled(False)
     self.updateAllBtn.setEnabled(False)
     self.enterRigEditBtn.setEnabled(False)
     self.rigList.setEnabled(False)
     self.createRigBtn.setEnabled(False)
     self.openNodeBtn.setEnabled(True)
     self.exitRigEditBtn.setEnabled(True)
コード例 #31
0
def setHeadsUpDisplay(currentUnits):
    """Displays current units on Maya HUD."""

    headsUpDisplay['linearUnits'] = currentUnits
    
    destroyHeadsUpDisplay()  # Check and destroy if a HUD object exists    
    cmds.headsUpDisplay(headsUpDisplay['Name'],
                        section=headsUpDisplay['section'],
                        block=headsUpDisplay['block'],
                        blockSize=headsUpDisplay['blockSize'],
                        label=headsUpDisplay['label'],
                        labelFontSize=headsUpDisplay['labelFontSize'],
                        command=prepareLabelText, # Every command needs
                                                  # a trigger flag (tr. flag)
                        event='SelectionChanged') # <- The (random) tr. flag
コード例 #32
0
def hideHUDAttributes():
    cameraShape = mc.listRelatives(CAM.getCurrentCamera(), shapes=True)[0]
    panelName = CAM.getCurrentPanel()
    huds = mc.headsUpDisplay(lh=True)

    #turn off the camera gates
    mc.setAttr("{0}.displayFilmGate".format(cameraShape), 0)
    mc.setAttr("{0}.displayResolution".format(cameraShape), 0)
    mc.setAttr("{0}.displayFieldChart".format(cameraShape), 0)
    mc.setAttr("{0}.displaySafeAction".format(cameraShape), 0)
    mc.setAttr("{0}.displaySafeTitle".format(cameraShape), 0)
    mc.setAttr("{0}.displayFilmPivot".format(cameraShape), 0)
    mc.setAttr("{0}.displayFilmOrigin".format(cameraShape), 0)

    #turn off everything but surfaces in the viewport
    mc.modelEditor(panelName,
                   edit=True,
                   nc=0,
                   ns=1,
                   pm=1,
                   sds=1,
                   pl=0,
                   lt=0,
                   ca=0,
                   cv=0,
                   gr=0,
                   hu=0,
                   j=0,
                   ikh=0,
                   df=0,
                   dy=0,
                   fl=0,
                   hs=0,
                   fo=0,
                   ncl=0,
                   nr=0,
                   dc=0,
                   lc=0,
                   manipulators=0,
                   dim=0,
                   ha=0,
                   pv=0,
                   tx=0,
                   strokes=0)

    for hud in huds:
        mc.headsUpDisplay(hud, edit=True, vis=False)
コード例 #33
0
    def sculptMode(cls, *args):
        # Get corrective name
        cls.correctiveTrgName = cmds.textField(
            UI.widgets['correctiveTrgNameTxtFld'], q=True, text=True)

        # Check if already exists same corrective name
        if cmds.objExists(cls.correctiveTrgName):
            cmds.confirmDialog(
                title='Warning',
                message="'%s' is already exists.\nTry another corrective name."
                % (cls.correctiveTrgName),
                button='OK')
            cmds.textField(UI.widgets['correctiveTrgNameTxtFld'],
                           e=True,
                           text='')
            return

        # If cache geometry has no blend shape node add one
        if cls.bsNodeName == 'None':
            cls.addBsNode()

        # Duplicate cache geometry twice
        cls.sculptGeo = cmds.duplicate(cls.cacheGeo,
                                       n=cls.correctiveTrgName)[0]
        cls.invGeo = cmds.duplicate(cls.cacheGeo,
                                    n=cls.correctiveTrgName + '_inv')[0]

        # Delete intermediate shape
        for geo in [cls.sculptGeo, cls.invGeo]:
            shapList = cmds.ls(geo, dag=True, s=True)
            for shap in shapList:
                if cmds.getAttr('%s.intermediateObject' % (shap)):
                    cmds.delete(shap)

        # Display HUD
        if cmds.headsUpDisplay('sclptHUD', exists=True):
            cmds.headsUpDisplay('sclptHUD', remove=True)
        tak_lib.showHUD('sclptHUD', 'Sculpt Mode')

        # Button enable control
        cmds.button(UI.widgets['sculptBtn'], e=True, enable=False)
        cmds.button(UI.widgets['cancelBtn'], e=True, enable=True)
        cmds.button(UI.widgets['createBtn'], e=True, enable=True)

        # Hide cache geometry and invGeo
        cls.shpVisOnOff(cls.cacheGeo, 'off')
        cls.shpVisOnOff(cls.invGeo, 'off')
コード例 #34
0
 def initHUD(self, *args):
     if self.cam == None:
         mc.error( 'Please select the camera!' )
     else:
         mc.setAttr( '%s.displayResolution'%self.shp, 1 )
         mc.setAttr( '%s.displayGateMaskOpacity'%self.shp, 1 )
         mc.setAttr( '%s.displayGateMaskColor'%self.shp, 0,0,0, type='double3' )
         mc.setAttr( '%s.displaySafeAction'%self.shp, 1 )
         allHUD = mc.headsUpDisplay(lh = True)
         [mc.headsUpDisplay(item,e = True, vis = False) for item in allHUD]
         self.createHUD('摄像机', 1)
         self.createHUD('分辨率', 2)
         self.createHUD('时间', 3)
         self.createHUD('当前帧/总帧数', 6)
         self.createHUD('用户名', 7)
         self.createHUD('焦距', 8)
         print 'It works!'
コード例 #35
0
 def CleanUp(self):
     print "UI cleaning up"
     #Check to see if the window exists if it does delete it
     if cmds.dockControl(UIClass.MainDock, exists = True):
         try:
             cmds.deleteUI(UIClass.MainDock)
         except:
             print "Could not delete Main Dock"
     elif cmds.window(UIClass.MainWindow, exists = True):
         try:
             cmds.deleteUI(UIClass.MainWindow)
         except:
             print "Could not delete Main Window"
     
     if cmds.headsUpDisplay('SnapButton', exists = True):
         cmds.headsUpDisplay('SnapButton', rem = True)
     print "UI clean up complete"
コード例 #36
0
def cSpeedHud(state, *args):
    if state == 1:
        # for i in range(0, 10, 1):
        # 	for k in range(0, 20, 1):
        # 		cmds.headsUpDisplay(rp=(i, k))

        cSpeedHud(0)

        block = 0

        if cmds.objExists('speed_lc_grp'):
            lcs = cmds.listRelatives('speed_lc_grp', c=1)
            section = cHUDGetPostion()

            for lc in lcs:
                cmds.headsUpDisplay('headsUp' + str(lc),
                                    c=partial(cReadHudContent, 1, lc),
                                    s=section[0],
                                    b=section[1] + block,
                                    bs='small',
                                    dw=250,
                                    dfs='large',
                                    lfs='large',
                                    l=lc,
                                    event='timeChanged')
                if not cmds.objExists('exUpdate' + str(lc)):
                    exString = cExStringHudUpdate(lc)
                    cmds.expression(n='exUpdate' + lc,
                                    s=exString,
                                    o="",
                                    ae=1,
                                    uc='all')

                block += 1

    if state == 0:
        if cmds.objExists('speed_lc_grp'):
            lcs = cmds.listRelatives('speed_lc_grp', c=1)

            for lc in lcs:
                if cmds.headsUpDisplay('headsUp' + lc, ex=1):
                    cmds.headsUpDisplay('headsUp' + lc, rem=1)
                if cmds.objExists('exUpdate' + str(lc)):
                    cmds.delete('exUpdate' + lc)
コード例 #37
0
    def done(self, *args):
        # remove heads up display
        cmds.headsUpDisplay('editSkinGeoModeDisplay', remove=True)

        # delete history
        cmds.select(self.skinGeo, r=True)
        tak_cleanUpModel.delHis()
        tak_cleanUpModel.delInterMediObj()

        # transfer skin weights from temporary geometry to the original geometry
        cmds.select('tempGeo', r=True)
        cmds.select(self.skinGeo, add=True)
        tak_misc.TransSkinWeights()
        '''# copy original shader
		cmds.select('tempGeo', r = True)
		cmds.select(self.skinGeo, add = True)
		tak_misc.copyMat()'''

        # delete temporary geometry
        cmds.delete('tempGeo')
コード例 #38
0
 def exitRigEditMode(self):
     global g_rigEditModeFileName
     globals.noUpdate = True
     cmds.headsUpDisplay(rp=(2,2))
     
     tempDir = mel.eval("getenv TEMP;")
     if g_rigEditModeFileName == "":
         cmds.file(tempDir+"\\rigModeTemp.ma",f=True,open=True)
     else:
         cmds.file(g_rigEditModeFileName,f=True,open=True)
     
     self.refreshListWidget()
     self.addRigBtn.setEnabled(True)
     self.updateAllBtn.setEnabled(True)
     self.rigList.setEnabled(True)
     self.createRigBtn.setEnabled(True)
     self.openNodeBtn.setEnabled(False)
     self.exitRigEditBtn.setEnabled(False)
     self.versionComboBox.setEnabled(True)
     if "Latest" in str(self.versionComboBox.currentText()):
         self.forceRigUpdate()
コード例 #39
0
 def addHUD(self):
     self.removeHUD()
     cmds.displayColor('headsUpDisplayLabels', 18, dormant=True)
     cmds.headsUpDisplay('leftTopHUD', section=0, block=1, blockSize='medium', dataFontSize='large',
                    command=self.getShotInfo, atr=True)
     cmds.headsUpDisplay('rightTopHUD', section=4, block=1, blockSize='medium', dataFontSize='large',
                    command=self.getDate, atr=True)
     cmds.headsUpDisplay('rightBottomHUD', section=9, block=1, blockSize='medium', dataFontSize='large',
                    command=self.getFrame, atr=True)
コード例 #40
0
 def CreateArchive(*args):
     cmds.confirmDialog(m = "This action will create a copy of the scene in the temp dir")
         
     ExportTypes = cmds.textScrollList("ExportTextScrollList", query = True, si = True)
     
     for Type in ExportTypes:
         if Type == "ma" or Type == "mb":
             #Save the file copy in the new path
             if Type == "ma":
                 cmds.file( save = True, type='mayaAscii' )
             else:
                 cmds.file( save = True, type='mayaBinary' )
             
             cmds.editRenderLayerGlobals( currentRenderLayer = "defaultRenderLayer")
             
             ShadersFile.ShaderClass.DeleteWireframeShader()
             ShadersFile.ShaderClass.DeleteUVMat()
             if not cmds.objExists("ShadowPlane"):
                 ShadersFile.ShaderClass.DeleteVrayShadowMat()
                 ShadersFile.ShaderClass.DeleteMRShadowMat()
                 
             ModelName = cmds.getAttr("CMSettings.ModelName")
             
             ProjectPath = cmds.getAttr("CMSettings.ProjectPath")
             
             try:cmds.delete("CMSettings")
             except:pass
             
             if cmds.objExists("RWSPlane"):
                 cmds.delete("RWSPlane")
             if cmds.objExists("RWSTexture"):
                 cmds.delete("RWSTexture")
             if cmds.objExists("RWSTexturePlacer"):
                 cmds.delete("RWSTexturePlacer")
             if cmds.objExists("RWSShader"):
                 cmds.delete("RWSShader")
             if cmds.objExists("RWSShaderSG"):
                 cmds.delete("RWSShaderSG")
             
             try:cmds.delete("CMBackground")
             except:pass
             
             SceneParts = ["ShadowPlane", "CMLightRig", "UserLights", "CMBackground"]
             for i in SceneParts:
                 if (not cmds.checkBox( i + "CheckBox", query = True, value = True)) and cmds.objExists(i):
                     if i == "ShadowPlane": 
                         ShadersFile.ShaderClass.DeleteVrayShadowMat()
                         ShadersFile.ShaderClass.DeleteMRShadowMat()
                     if i == "CMLightRig":
                         try: cmds.delete("EnvironmentGamma")
                         except:pass
                     try:cmds.delete(i)
                     except:pass
                 
             #Delete all animations
             try:cmds.cutKey(ModelName)
             except:pass
             
             for mesh in cmds.listRelatives(ModelName, children = True):
                 try:cmds.setAttr(mesh + "Smooth.divisions", 0)
                 except:pass
                 try:cmds.delete(mesh + "Smooth")
                 except:pass
         
             
             #Move the persp to the signatures place
             for i in range(0,len(SnapShotFile.SnapShotClass.SnapShots)):
                 if cmds.getAttr(SnapShotFile.SnapShotClass.SnapShots[i].Camera+'.CMSignature') == True:
                         SnapShotFile.SnapShotClass.SnapShots[i].CopyCameraInfo()
             
             cmds.editRenderLayerGlobals( currentRenderLayer = "defaultRenderLayer")
             
             try:cmds.delete("Signature")
             except:pass
             
             try:cmds.delete("SQRSignature")
             except:pass
             
             try:cmds.delete("ContextSig")
             except:pass
             
             try:cmds.delete("Product")
             except:pass
             
             for i in TurntableFile.TurntableClass.Turntables:
                 try:cmds.delete(i.RenderLayer)
                 except:pass
             
             try:cmds.delete("Wireframe")
             except:pass
             
             try:cmds.delete("Subdivision_0")
             except:pass
             
             try:cmds.delete("Subdivision_1")
             except:pass
             
             try:cmds.delete("UVs")
             except:pass
             
             mel.eval("BakeAllNonDefHistory;")
             #cmds.delete(all = True, constructionHistory = True)
             
             #Delete all cameras
             for i in SnapShotFile.SnapShotClass.SnapShots:
                 cmds.camera(i.Camera, edit = True, startupCamera = False)
             
             for i in TurntableFile.TurntableClass.Turntables:
                     cmds.camera(i.Camera, edit = True, startupCamera = False)
             
             CameraList = SnapShotFile.SnapShotClass.SnapShots
             for i in CameraList:
                 if cmds.getAttr(i.Camera + ".CMSignature"):
                     cmds.setAttr(i.Camera + ".backgroundColor", 0.968627, 0.968627, 0.968627, type = "double3")
                     cmds.rename(i.Camera, ModelName + "Camera")
                     try:cmds.delete(i.Camera + "_ImagePlane")
                     except:pass
                 else:
                     cmds.delete(i.Camera)
             
             CameraList = TurntableFile.TurntableClass.Turntables
             for i in TurntableFile.TurntableClass.Turntables:
                 cmds.delete(i.Camera)
             
             try:cmds.delete("CMForegroundPlane")
             except:pass
             try:cmds.delete("CMBackgroundPlane")
             except:pass
                 
             cmds.select(all = True)
             cmds.editDisplayLayerMembers(ModelName + "_layer", cmds.ls(selection = True), noRecurse = True  )
             cmds.displaySmoothness(divisionsU = 1,divisionsV = 1, pointsWire = 8, pointsShaded = 2, polygonObject = 2)
             for mesh in cmds.ls(sl = True):
                     try: 
                         cmds.setAttr(mesh + ".renderSmoothLevel", 1)
                     except:
                         pass
             
             #Save the file
             if Type == "ma":
                 cmds.file( rename = ProjectPath + "/temp/" + "/CM_" + ModelName + ".ma" )
                 cmds.file( save = True, type='mayaAscii' )
             else:
                 cmds.file( rename = ProjectPath + "/temp/" + "/CM_" + ModelName + ".mb" )
                 cmds.file( save = True, type='mayaBinary' )
             
             #Create the zip file
             if Type == "ma":
                 zipf = zipfile.ZipFile(ProjectPath + "/" + ModelName + '_ma.zip', 'w')
             else:
                 zipf = zipfile.ZipFile(ProjectPath + "/" + ModelName + '_mb.zip', 'w')
                 
             
             #write to the zip file
             if Type == "ma":
                 zipf.write(ProjectPath + "/temp/" + "CM_" + ModelName + ".ma", os.path.basename(ProjectPath + "/temp/" + "CM_" + ModelName + ".ma"))                
             else:
                 zipf.write(ProjectPath + "/temp/" + "CM_" + ModelName + ".mb", os.path.basename(ProjectPath + "/temp/" + "CM_" + ModelName + ".mb"))                
             
                 
             
             ##### Get textures ####
             def GetTextures():
                 Textures = []
                 
                 for i in cmds.ls(textures = True):
                     try:
                         Textures.append(cmds.getAttr(i + ".fileTextureName"))
                     except:
                         pass
                 #Remove duplicates    
                 return list(set(Textures))
             
             for i in GetTextures():
                 try:
                     zipf.write(i, os.path.basename(i))
                 except:
                     print "Could not write file ", i , " to zip"
             zipf.close()
             
         else:            
             #Create the export file
             try:
                 fileName = cmds.file(ProjectPath+ "/Temp/" + "CM_" + ModelName, exportAll = True, type = Type )
             except:
                 print "Failed to export scene in format :" , Type
                 continue
             
             #Create the zip file
             zipf = zipfile.ZipFile(ProjectPath + "/" + ModelName + '_' + Type +'.zip', 'w')
             
             #Iges format returns a wrong path fix it 
             if not os.path.exists(fileName):
                 Name, fileExtension = os.path.splitext(fileName)
                 if fileExtension == ".iges":
                     fileName = Name + ".igs"
             
             #Write the file into the zip
             try:
                 zipf.write(fileName, os.path.basename(fileName))
             except:
                 print "Could not write the format:", Type, " to zip file"
             
             #Write the textures in the zip
             for i in GetTextures():
                 try:
                     zipf.write(i, os.path.basename(i))
                 except:
                     pass
             zipf.close()
     
     cmds.displaySmoothness(divisionsU = 0,divisionsV = 0, pointsWire = 4, pointsShaded = 1, polygonObject = 1)
     
     #Save the file
     fileName = cmds.file(l = True, q = True)
     fileName = fileName[0]
     Extension = os.path.splitext(fileName)[1]
     if Extension == '.ma':            
         cmds.file( save = True, type='mayaAscii' )
     elif Extension == '.mb':
         cmds.file( save = True, type='mayaBinary' )
     elif Extension == "":
         cmds.file( save = True, type='mayaAscii' )
     
     cmds.confirmDialog(m = "The orginal file has been saved in the project folder")
     
     #Check to see if the window exists if it does delete it
     if cmds.dockControl("CMMainDock", exists = True):
         try:
             cmds.deleteUI("CMMainDock")
         except:
             print "Could not delete Main Dock"
     elif cmds.window("CMMainWindow", exists = True):
         try:
             cmds.deleteUI("CMMainWindow")
         except:
             print "Could not delete Main Window"
     
     if cmds.headsUpDisplay('SnapButton', exists = True):
         cmds.headsUpDisplay('SnapButton', rem = True)
     
     cmds.select(cmds.listRelatives(cmds.ls(cameras = True, lights = True),parent = True))
     try:
         cmds.select("UserLights", add = True)
     except:
         pass
     try:
         cmds.select("CMLightRig", add = True)
     except:
         pass
     try:
         cmds.editDisplayLayerMembers( 'CM_Lights_and_Cameras', cmds.ls(selection = True) )
     except:
         pass
コード例 #41
0
ファイル: viewport.py プロジェクト: ewerybody/melDrop
def showTriangleHudOnly(state=1):
	print( "HUDPolyCountTriangles exists: " + str(mc.headsUpDisplay( "HUDPolyCountTriangles", ex=1 )) )
	mc.evalDeferred( 'import maya.cmds as mc; mc.headsUpDisplay( "HUDPolyCountTriangles", edit=1, vis=1 )' )
コード例 #42
0
ファイル: core.py プロジェクト: kuzubov/maya_python_scripts
    def setHUD(self):
        self.delHUD()

        cmds.headsUpDisplay(
            "HUDObjectSceneName",
            section=0,
            block=0,
            blockSize="large",
            label="Scene:  " + self.fileName,
            dfs="large",
            labelFontSize="large",
        )
        cmds.headsUpDisplay(
            "HUDUserName",
            section=2,
            block=0,
            blockSize="large",
            label="User Name:  " + self.userName,
            dfs="large",
            labelFontSize="large",
        )
        cmds.headsUpDisplay(
            "HUDDate",
            section=4,
            block=0,
            blockSize="large",
            label="Date:  " + self.curTime,
            dfs="large",
            labelFontSize="large",
        )
        cmds.headsUpDisplay(
            "HUDFPS",
            section=5,
            block=0,
            blockSize="large",
            label="FPS:  " + str(self.curFPS),
            dfs="large",
            labelFontSize="large",
        )
        cmds.headsUpDisplay(
            "HUDDuration",
            section=7,
            block=0,
            blockSize="large",
            label="Duration:  " + str(self.duration),
            dfs="large",
            labelFontSize="large",
        )
        cmds.headsUpDisplay(
            "HUDCurentFrame",
            section=9,
            block=0,
            blockSize="large",
            label="Current Frame: ",
            dfs="large",
            labelFontSize="large",
            command=lambda: cmds.currentTime(query=True),
            atr=True,
        )
コード例 #43
0
    def setHUD(self):
        self.delHUD()

        cmds.headsUpDisplay( 'HUDObjectSceneName', section=0, block=0, blockSize='large', label='Scene:  ' + self.fileName,         dfs='large', labelFontSize='large')
        cmds.headsUpDisplay( 'HUDUserName',        section=2, block=0, blockSize='large', label='User Name:  ' + self.userName,     dfs='large', labelFontSize='large')
        cmds.headsUpDisplay( 'HUDDate',            section=4, block=0, blockSize='large', label='Date:  ' + self.curTime,           dfs='large', labelFontSize='large')
        cmds.headsUpDisplay( 'HUDFPS',             section=5, block=0, blockSize='large', label='FPS:  ' + str(self.curFPS),        dfs='large', labelFontSize='large')
        cmds.headsUpDisplay( 'HUDDuration',        section=7, block=0, blockSize='large', label='Duration:  ' + str(self.duration), dfs='large', labelFontSize='large')
        cmds.headsUpDisplay( 'HUDCurentFrame',     section=9, block=0, blockSize='large', label='Current Frame: ', dfs='large', labelFontSize='large', command = lambda: cmds.currentTime(query=True), atr=True)
コード例 #44
0
def snapshots(*args, **kwargs):
    """ in GUI mode, renders snapshots of the model views
    returns reportsDir
    render_snapshots() -> string
    """
    t0 = float(time.time())
    try:
        verbose = kwargs["verbose"]
    except KeyError:
        verbose = False
        if cmds.optionVar(exists="checkmateVerbosity"):
            verbose = cmds.optionVar(query="checkmateVerbosity")
    else:
        pass

    # check that we;re running in GUI mode
    if cmds.about(batch=True):
        print "You can't create a render view in batch mode"
        return 1
    # turn off the heads-up diplay
    cmds.headsUpDisplay(layoutVisibility=False)

    # clear selection
    cmds.select(clear=True)

    _userWorkspaceDir = cmds.internalVar(userWorkspaceDir=True)
    scene = cmds.file(query=True, sn=True, shn=True) or "unknown.mb"
    (root, ext) = os.path.splitext(scene)
    fullscenepath = cmds.file(query=True, sn=True, shn=False) or "unknown.mb"
    fullscenedirname = os.path.dirname(fullscenepath)
    if fullscenedirname == "":
        fullscenedirname = os.path.join(_userWorkspaceDir, "reports")

    reportname = "".join([root, ext.replace(".", "_")])
    img_dir = os.path.join(fullscenedirname, reportname)

    # before we render, save render globals presets
    cmds.nodePreset(save=("defaultRenderQuality", "ttRestorePreviousDefaultRenderViewPreset"))
    cmds.nodePreset(save=("defaultRenderGlobals", "ttRestorePreviousDefaultRenderViewPreset"))
    cmds.nodePreset(save=("defaultResolution", "ttRestorePreviousDefaultRenderViewPreset"))

    # override the user settings
    cmds.setAttr("defaultRenderGlobals.imageFormat", 32)
    ext = ".png"
    # set resolution ot 320x240
    cmds.setAttr("defaultResolution.width", 320)
    cmds.setAttr("defaultResolution.height", 240)
    cmds.setAttr("defaultResolution.deviceAspectRatio", (float(320) / float(240)))

    # set file format to png
    cmds.setAttr("defaultRenderGlobals.imageFormat", 32)
    ext = ".png"

    # bring up the render view
    if not cmds.window("renderViewWindow", exists=True):
        cmds.RenderViewWindow()

    # cameras to render
    cameras = ["top", "front", "side", "persp"]

    for camera in cameras:
        mel.eval("".join(["renderWindowRenderCamera snapshot renderView ", camera]))
        image = "".join([camera, ext])
        # we can get the path from the report class instance
        imagepath = os.path.join(img_dir, image)
        if verbose:
            print "imagepath : %s " % imagepath
        # delete the images before saving
        cmds.sysFile(imagepath, delete=True)
        cmds.renderWindowEditor("renderView", edit=True, writeImage=imagepath)

    # restore the node presets
    # globalsNodes = cmds.renderer( 'mayaSoftware', query=True, globalsNodes=True)
    try:
        cmds.nodePreset(load=("defaultRenderQuality", "ttRestorePreviousDefaultRenderViewPreset"))
    except LockedAttrError:
        print "Cannot restore defaultRenderQuality to defaults"
    try:
        cmds.nodePreset(load=("defaultRenderGlobals", "ttRestorePreviousDefaultRenderViewPreset"))
    except LockedAttrError:
        print "Cannot restore defaultRenderGlobals to defaults"
    try:
        cmds.nodePreset(load=("defaultResolution", "ttRestorePreviousDefaultRenderViewPreset"))
    except LockedAttrError:
        print "Cannot restore defaultRenderGlobals to defaults"
    # turn the heads-up diplay back on
    cmds.headsUpDisplay(layoutVisibility=True)

    print "%-24s : %.6f seconds" % ("render.snapshots()", (float(time.time()) - t0))
    return img_dir
コード例 #45
0
ファイル: JR_hk_map.py プロジェクト: jricker/JR_Maya
	def setCategory(self, category):
		Cache.currentCategory = category # set hotkey category to selected
		self.categoryHotkeys() # intializes the nameCommands
		cmds.headsUpDisplay('categoryHUD', edit=True, c = self.displayCategory ) # update HUD with hotkey category
		#
		if category == 'modeling':
			mel.eval('setPolyCountVisibility 1')
		else:
			mel.eval('setPolyCountVisibility 0')
		#
		# GLOBAL HOTKEYS
		# `
		cmds.hotkey( k='`', name= 'tilde' ) # tilde
		cmds.hotkey( k='`', alt=True, name= 'alt_tilde' ) # Alt + tilde
		cmds.hotkey( k='`', ctl=True, name= 'ctrl_tilde' ) # Ctrl +  tilde
		# 1
		cmds.hotkey( k='1', name= 'one' ) # one
		cmds.hotkey( k='1', alt=True, name= 'alt_one' ) # Alt + one
		cmds.hotkey( k='!', name= 'shift_one' ) # Shift + one
		# 2
		cmds.hotkey( k='2', name= 'two' ) # two
		cmds.hotkey( k='2', alt=True, name= 'alt_two' ) # Alt + two
		###
		## CHANGE THIS IF WE'RE USING A US KEYBOARD - FOR UK ONLY RIGHT NOW!!!
		###
		cmds.hotkey( k='"', name= 'shift_two' ) # Shift + two = UK KEYBOARD
		cmds.hotkey( k=u'@', name= 'shift_two' ) # Shift + two = US KEYBOARD
		# 3
		cmds.hotkey( k='3', name= 'three' ) # three
		cmds.hotkey( k='3', alt=True, name= 'alt_three' ) # Alt + three
		cmds.hotkey( k=u'£', name= 'shift_three' ) # Shift + three = UK KEYBOARD
		cmds.hotkey( k=u'#', name= 'shift_three' ) # Shift + three = US KEYBOARD
		# 4
		cmds.hotkey( k='4', alt=True, name= 'alt_four' ) # Alt + four
		# 5
		cmds.hotkey( k='5', alt=True, name= 'alt_five' ) # Alt + five
		# Q
		cmds.hotkey( k='q', name= 'q', releaseName = 'q_release' ) # q
		cmds.hotkey( k='q', alt=True, name= 'alt_q') # Alt + q
		# W
		cmds.hotkey( k='w', name= 'w', releaseName = 'w_release' ) # w
		# E
		cmds.hotkey( k='e', name= 'e', releaseName = 'e_release' ) # e
		cmds.hotkey( k='e', ctl=True, name = 'ctrl_e' ) # Ctrl + e
		# R
		cmds.hotkey( k='r', name= 'r', releaseName = 'r_release' ) # r
		cmds.hotkey( k='R', name= 'R' ) # R
		cmds.hotkey( k='r', ctl=True, name = 'ctrl_r' ) # Ctrl + r
		cmds.hotkey( k='r', alt=True, name = 'alt_r' ) # Alt + r
		# H
		cmds.hotkey( k='h', name= 'h' ) # h
		# L
		cmds.hotkey( k='l', ctl=True, name = 'ctrl_l' ) # Ctrl + l
		# P
		cmds.hotkey( k='p', alt=True, name = 'alt_p', releaseName = 'alt_p_release' ) # Alt + p
		cmds.hotkey( k='p', ctl=True, name = 'ctrl_p' ) # Ctrl + p
		# F
		cmds.hotkey( k='F', name= 'F' ) # F
		# B
		cmds.hotkey( k='b', alt=True, name= 'alt_b' ) # ctrl + b
		# M
		cmds.hotkey( k='m', name = 'm' ) # m
		cmds.hotkey( k='M', name = 'M' ) # M
		cmds.hotkey( k='m', ctl=True, name = 'ctrl_m' ) # Ctrl + m
		cmds.hotkey( k='M', ctl=True, name = 'ctrl_M' ) # Ctrl + M	
		# D
		cmds.hotkey( k='d', name= 'd' ) # d
		cmds.hotkey( k='d', alt=True, name= 'alt_d' ) # Alt + d
		# I
		cmds.hotkey( k='i', name= 'i' ) # i
		cmds.hotkey( k='i', alt=True, name= 'alt_i' ) # Alt + i
		cmds.hotkey( k='i', ctl=True, name= 'ctrl_i' ) # Ctrl + i
		# O
		cmds.hotkey( k='o', name= 'o' ) # o
		# G
		cmds.hotkey( k='g', alt=True, name= 'alt_g') # alt + g
		# C
		cmds.hotkey( k='c', name= 'c', releaseName = 'c_release') # c
		cmds.hotkey( k='c', alt=True, name= 'alt_c') # alt + c
		cmds.hotkey( k='C', alt=True, name= 'alt_shift_c') # alt + shift + c
		# V
		cmds.hotkey( k='v', name= 'v', releaseName = 'v_release') # v
		# CATEGORY HOTKEYS
		# X
		cmds.hotkey( k='x', name= 'x', releaseName = 'x_release') # x
		cmds.hotkey( k='x', alt=True, name= category + '_alt_x' ) # Alt + x
		# C
		cmds.hotkey( k='C', name= category + '_C', releaseName = 'C_release' ) # Shift + c
		# E
		cmds.hotkey( k='e', alt=True, name= category + '_alt_e' ) # Alt + e
		# S
		cmds.hotkey( k='S', name= 'S' ) # S
		cmds.hotkey( k='s', alt=True, name= 'alt_s' ) # Alt + s
		cmds.hotkey( k='S', alt=True, name= 'alt_S' ) # Alt + shift + s
		cmds.hotkey( k='S', ctl=True, name= 'ctrl_S' ) # Ctrl + Shift + s
コード例 #46
0
ファイル: core.py プロジェクト: kuzubov/maya_python_scripts
 def delHUD(self):
     for i in range(10):
         cmds.headsUpDisplay(rp=[i, 0])
コード例 #47
0
ファイル: JR_hud_class.py プロジェクト: jricker/JR_Maya
	def updateToolHUD(self):
		cmds.headsUpDisplay( 'toolHUD', edit = True, c = self.setToolHUD )
コード例 #48
0
ファイル: view.py プロジェクト: ewerybody/melDrop
def createSelCountHUD():
    if mc.headsUpDisplay('HUDSelCount', ex=1):
        mc.headsUpDisplay('HUDSelCount', e=1, remove=1)
    mc.headsUpDisplay('HUDSelCount', section=0, block=8, label='Sel:', dataFontSize='large',command=HUDSelCountUpdate, event='SelectionChanged')
コード例 #49
0
ファイル: utils.py プロジェクト: Bumpybox/Tapp
def PlayblastScene(filePath, camera, width=640, height=360,
              exportType='movie', HUD=None):
    ''' Exports playblast to filePath

        filePath=path to file with no extension
                    eg. c:/temp

        camera=camera to generate playblast from

        type=['movie','still','sequence']
            movie = exports video
            still = exports image from middle of timeline
            sequence = exports image sequence

        HUD is a list of dictionaries following this format.

        usage:
        HUD=[]
        time=time.time()
        timestamp=str(datetime.datetime.fromtimestamp(time).strftime('%d-%m-%Y %H:%M:%S'))
        HUD.append({'label':timestamp,
                    'block':0,
                    'section':1})
        HUD.append({'label':'Bait Studio',
                    'block':0,
                    'section':2})
        username = str(getpass.getuser())
        HUD.append({'label':username,
                    'block':0,
                    'section':3})
        filePath='c:/temp.ext'
        HUD.append({'label':filePath,
                    'block':1,
                    'section':7})

        __exportPlayblast__('c:/temp', 'shotCam', HUD=HUD,exportType='still')
    '''

    result = cmds.objExists(camera)

    if result:

        #string $visPanels[] = `getPanel -vis`; < for fail safe of active panel
        panel = "modelPanel4"
        prevcam = cmds.modelEditor(panel, q=True, camera=True)

        mel.eval("lookThroughModelPanel " + camera + " " + panel)

        #getting current settings
        currentTime = cmds.currentTime(q=True)
        displayFilmGate = cmds.camera(camera, q=True, displayFilmGate=True)
        displayResolution = cmds.camera(camera, q=True, displayResolution=True)
        overscan = cmds.camera(camera, q=True, overscan=True)
        grid = cmds.modelEditor(panel, q=True, grid=True)
        displayAppearance = cmds.modelEditor(panel, q=True,
                                             displayAppearance=True)
        nurbsCurves = cmds.modelEditor(panel, q=True, nurbsCurves=True)

        #prepping for playblast
        cmds.camera(camera, edit=True, displayFilmGate=False,
                    displayResolution=False, overscan=1)
        cmds.modelEditor(panel, e=True, grid=False,
                         displayAppearance='smoothShaded',
                         nurbsCurves=False)

        #query and hide previous huds
        prevHUD = {}
        for headsup in cmds.headsUpDisplay(listHeadsUpDisplays=True):

            vis = cmds.headsUpDisplay(headsup, q=True, vis=True)
            prevHUD[headsup] = vis

            cmds.headsUpDisplay(headsup, e=True, vis=False)

        #creating custom huds
        customHUD = []
        if HUD != None:
            itr = 1
            for headsup in HUD:

                cmd = 'cmds.headsUpDisplay(\'temp' + str(itr) + '\''
                for key in headsup:
                    if type(headsup[key]) == str:
                        cmd += ',' + key + '=\'' + str(headsup[key]) + '\''
                    else:
                        cmd += ',' + key + '=' + str(headsup[key])

                cmd += ')'
                eval(cmd)

                customHUD.append('temp' + str(itr))

                itr += 1

        #playblasting
        if exportType == 'movie':

            result = cmds.playblast(f=filePath, format='qt',
                                    forceOverwrite=True, offScreen=True,
                                    percent=100, compression='H.264',
                                    quality=100, width=width,
                                    height=height, viewer=False)
        elif exportType == 'still':

            startTime = cmds.playbackOptions(q=True, minTime=True)
            endTime = cmds.playbackOptions(q=True, maxTime=True)

            midTime = ((endTime - startTime) / 2) + startTime

            result = cmds.playblast(f=filePath, format='iff',
                                    forceOverwrite=True, offScreen=True,
                                    percent=100, compression='png',
                                    quality=100, startTime=midTime,
                                    endTime=midTime, width=width,
                                    height=height, viewer=False,
                                    showOrnaments=True)

            path = result.split('.')[0]
            ext = result.split('.')[-1]

            oldfile = filePath + '.' + str(int(midTime)).zfill(4) + '.' + ext
            newfile = path + '.' + ext

            move(oldfile, newfile)

            result = newfile
        elif exportType == 'sequence':

            startTime = cmds.playbackOptions(q=True, minTime=True)
            endTime = cmds.playbackOptions(q=True, maxTime=True)

            result = cmds.playblast(f=filePath, format='iff',
                                    forceOverwrite=True, offScreen=True,
                                    percent=100, compression='png',
                                    quality=100, startTime=startTime,
                                    endTime=endTime, width=width,
                                    height=height, viewer=False,
                                    showOrnaments=True)

        #revert to settings
        cmds.currentTime(currentTime)
        cmds.camera(camera, edit=True, displayFilmGate=displayFilmGate,
                    displayResolution=displayResolution,
                    overscan=overscan)
        cmds.modelEditor(panel, e=True, grid=grid,
                         displayAppearance=displayAppearance,
                         nurbsCurves=nurbsCurves)

        for headsup in prevHUD:

            cmds.headsUpDisplay(headsup, e=True, vis=prevHUD[headsup])

        for headsup in customHUD:

            cmds.headsUpDisplay(headsup, remove=True)

        mel.eval("lookThroughModelPanel " + prevcam + " " + panel)

        return result
    else:
        cmds.warning('Requested camera cant be found!')

        return None
コード例 #50
0
	def execute(self, tasks, work_template, comment, thumbnail_path, sg_task, primary_task, primary_publish_path, progress_cb, **kwargs):
		"""
		Main hook entry point
		:param tasks:				   List of secondary tasks to be published.  Each task is a 
										dictionary containing the following keys:
										{
											item:   Dictionary
													This is the item returned by the scan hook 
													{   
														name:		   String
														description:	String
														type:		   String
														other_params:   Dictionary
													}
												   
											output: Dictionary
													This is the output as defined in the configuration - the 
													primary output will always be named 'primary' 
													{
														name:			 String
														publish_template: template
														tank_type:		String
													}
										}
						
		:param work_template:		   template
										This is the template defined in the config that
										represents the current work file
			   
		:param comment:				 String
										The comment provided for the publish
						
		:param thumbnail:			   Path string
										The default thumbnail provided for the publish
						
		:param sg_task:				 Dictionary (shotgun entity description)
										The shotgun task to use for the publish	
						
		:param primary_publish_path:	Path string
										This is the path of the primary published file as returned
										by the primary publish hook
						
		:param progress_cb:			 Function
										A progress callback to log progress during pre-publish.  Call:
										
											progress_cb(percentage, msg)
											 
										to report progress to the UI
						
		:param primary_task:			The primary task that was published by the primary publish hook.  Passed
										in here for reference.  This is a dictionary in the same format as the
										secondary tasks above.
		
		:returns:					   A list of any tasks that had problems that need to be reported 
										in the UI.  Each item in the list should be a dictionary containing 
										the following keys:
										{
											task:   Dictionary
													This is the task that was passed into the hook and
													should not be modified
													{
														item:...
														output:...
													}
													
											errors: List
													A list of error messages (strings) to report	
										}
		"""
		def FindFirstImageOfSequence(FolderPath):
			ImgsList=[]
			for file in (os.listdir(FolderPath)):
				SeqImgName = str.split(str(file),".")[1]
				ImgsList.append(SeqImgName)
			First_elmnt=ImgsList[0]
			return First_elmnt
			
		def FindFirstImageOfSequence(FolderPath):
			ImgsList=[]
			for file in (os.listdir(FolderPath)):
				if file.endswith(".png"):
					SeqImgName = str.split(str(file),".")[1]
					ImgsList.append(int(SeqImgName))
				First_elmnt=ImgsList[0]
			return First_elmnt

		def FindLastImageOfSequence(FolderPath):
			ImgsList=[]
			for file in (os.listdir(FolderPath)):
				if file.endswith(".png"):
					SeqImgName = str.split(str(file),".")[1]
					ImgsList.append(int(SeqImgName))
				Last_elmnt=ImgsList[-1]
			return Last_elmnt
			
		def FindLengthOfSequence(FolderPath):
			ImgsList=[]
			for file in (os.listdir(FolderPath)):
				if file.endswith(".png"):
					SeqImgName = str.split(str(file),".")[1]
					ImgsList.append(int(SeqImgName))
				Length_seq=len(ImgsList)
			return Length_seq
			
		def MakeListOfSequence(FolderPath):
			ImgsList=[]
			for file in (os.listdir(FolderPath)):
				if file.endswith(".png"):
					SeqImgName = str.split(str(file),".")[1]
					ImgsList.append(int(SeqImgName))
			return ImgsList

		def FindMissingFramesFromSequence(SequenceSet,inputStart,inputEnd):
			# my_list= list(range( int(FindFirstImageOfSequence(os.path.dirname(RenderPath)))	, int(FindLastImageOfSequence(os.path.dirname(RenderPath)))	 ))
			my_list= list(range( inputStart, inputEnd))
			MissingFrames =  set(my_list)-set(SequenceSet)
			return sorted(MissingFrames)
			
		def combineMediaFiles(fileList,output,concatTxt=None, ffmpeg_path = "ffmpeg"):
			rootPath = str.split(str(fileList[0]),"/q")[0]
			mediaType = str.rsplit(str(fileList[0]),".",1)[1]
			mediaFilePresent = False
			mediaListFile = rootPath+'/tmp_'+mediaType+'List.txt'
			if concatTxt != None:
				mediaListFile = concatTxt
			with open(mediaListFile, 'w') as mediaTxtFile:
				for mediaFile in fileList:
					if os.path.exists(mediaFile):
						mediaFilePresent = True
						#print mediaFile
						shotPath = str.split(str(mediaFile),"/")[-1]
						if 'Sequences' in mediaFile:
							shotPath = str.split(str(mediaFile),"Sequences")[1][1:]
						if concatTxt != None:
							shotPath = str.split(str(mediaFile),os.path.dirname(concatTxt))[1][1:]
						mediaTxtFile.write("file '" +shotPath+"'")
						mediaTxtFile.write('\r\n')
					else:
						print("AUDIO FILE NOT FOUND :  " + str(mediaFile))
						# results.append({"task":"audio stuff", "errors":("AUDIO FILE NOT FOUND :  " + str(mediaFile))})
			if mediaFilePresent:
				# command = os.path.normpath(ffmpeg_path + ' -f concat -i '+mediaListFile+' -c copy '+output + " -y")
				# command = os.path.normpath(ffmpeg_path + ' -f concat -r 24 -i '+mediaListFile+' -vcodec mjpeg -r 24 -qscale 1 -pix_fmt yuvj420p -acodec pcm_s16le -ar 48000 -ac 2 '+output + " -y")
				command = os.path.normpath(ffmpeg_path + ' -f concat -r 24 -i '+mediaListFile+' -vcodec mjpeg -r 24 -qscale 1 -pix_fmt yuvj420p '+output + " -y")
				command = str.replace(str(command), "\\" , "/")
				#print command
				value = subprocess.call(command, creationflags=CREATE_NO_WINDOW, shell=False)
				return output
			else:
				return None
		
		def findLastVersion(FolderPath,returnFile=False,returnFilePath=False):
			if os.path.exists(FolderPath):
				fileList=os.listdir(FolderPath)
			else:
				return 0
			if fileList != []:
				fileList.sort()
				lastVersion = fileList[-1]
				version = int(re.findall('\d+', lastVersion)[-1])
				if returnFilePath:
					return FolderPath+"/"+lastVersion
				if returnFile:
					return lastVersion
				return version
				#return str(FolderPath+"/"+lastVersion)
			else:
				return 0
		
		def orderMovs(movList,orderList):
			tmp = ""

		def setAudioToCorrectPath():
			scenePath = cmds.file(q=True,sceneName=True)
			scene_template = tk.template_from_path(scenePath)
			flds = scene_template.get_fields(scenePath)
			audio_template = tk.templates["shot_published_audio"]

			tank = sgtk.tank_from_entity('Project', 66)

			allShots = cmds.ls(type="shot")
			allAudio = cmds.ls(type="audio")
			reportList = []
			returnList = []
			for seqShot in allShots:
				audio = cmds.shot(seqShot,q=True,audio=True)
				audioFile = cmds.getAttr(audio+".filename")# "W:/RTS/1_PREPROD/13_ANIMATIC/q340/splitshots/wav new 01/q340_s260_snd_v001.wav";
				#print audioFile
				flds['Shot'] = flds['Sequence']+"_"+seqShot
				audioOutputFile = audio_template.apply_fields(flds)
				#audioOutputPath = str.replace(str(audioOutputPath),"\\","/")
				#print audioFile
				audioFile = str.replace(str(audioFile),"Z:/Richard The Stork","W:/RTS")
				audioOutputPath = str.rsplit(str(audioOutputFile),"\\",1)[0]
				print audioOutputPath
				if os.path.exists(audioOutputPath):
					audioOutputFile = findLastVersion(audioOutputPath,True,True)
					if audioOutputFile != 0:
						newAudio = str.rsplit(audioOutputFile,"/",1)[-1]
						newAudio = str.split(newAudio,".")[0]
						print newAudio
						cmds.delete(audio)
						ref = cmds.file( audioOutputFile, r=True, type="audio",mergeNamespacesOnClash=False, namespace="audio")
						#
						offset = cmds.getAttr(seqShot+".sequenceStartFrame")
						cmds.setAttr(newAudio+".offset", offset)
						cmds.connectAttr(newAudio+".message", seqShot+".audio")
						
						shotEnd =  cmds.getAttr(seqShot +".sequenceEndFrame")
						audioEnd = cmds.getAttr(newAudio+".endFrame")
						if audioEnd < shotEnd:
							reportList += [newAudio + "  is shorter than shot !!!"]
						if audioEnd > shotEnd:
							reportList += [newAudio + "  was longer than shot. now cut to match!!!"]
							cmds.setAttr(newAudio+".endFrame",shotEnd+1)

						returnList += [newAudio]
				else:
					print "skipped ", audio
			for report in reportList:
				print report
			return returnList
		
		def getStereoCams(sht):
			leftCam = ""
			rightCam = ""
			prevCamShape = cmds.shot(sht,q=True,cc=True)
			prevCam = cmds.listRelatives(prevCamShape,p=True)
			prevCamParent = cmds.listRelatives(prevCam,p=True)
			for obj in cmds.listRelatives(prevCamParent):
				if cmds.objectType(obj) == 'stereoRigTransform':
					leftCam = str(cmds.listConnections(obj+".leftCam",source=True)[0])
					rightCam = str(cmds.listConnections(obj+".rightCam",source=True)[0])
			return[leftCam,rightCam]

		wtd_fw = self.load_framework("tk-framework-wtd_v0.x.x")
		ffmpeg = wtd_fw.import_module("pipeline.ffmpeg")
		# ffmpeg.test()
		
		def _register_publish(path, name, sg_task, publish_version, tank_type, comment, thumbnail_path, context = None):
			"""
			Helper method to register publish using the 
			specified publish info.
			"""
			ctx = self.parent.tank.context_from_path(str(path))
			# construct args:
			args = {"tk": self.parent.tank,"sg_status_list": "cmpt","context": context,"comment": comment,"path": path,"name": name,"version_number": publish_version,"thumbnail_path": thumbnail_path,"sg_task": sg_task,"published_file_type":tank_type,"user": ctx.user,"created_by": ctx.user}
			print "-------------------"
			for a in args:
				print a , args[a]
			# print args
			# register publish;
			sg_data = tank.util.register_publish(**args)
			print 'Register in shotgun done!'
			
			return sg_data


		def orderShots(shotDictList):
			valueOrderList = []
			valueOrderListSecondary = []
			listIndex = 0
			for sht in shotDictList:
				orderNr = str("00000"+str(sht['sg_cut_order']))[-4:]
				addValue = str(listIndex)
				if sht['sg_status_list'] == 'omt':
					addValue = 'omt'
				if sht['parent_shots'] == []:
					valueOrderList += [orderNr+">>"+addValue]
				else:
					valueOrderListSecondary += [orderNr+">>"+addValue]
				listIndex += 1
			valueOrderList = sorted(valueOrderList)+sorted(valueOrderListSecondary)
			orderedList = []
			for sht in valueOrderList:
				addValue = str.split(sht,'>>')[1]
				if addValue != "omt":
					orderedList+=[shotDictList[int(addValue)]]
			return orderedList

		def checkSoundCut():
			allShots = cmds.ls(type="shot")
			allAudio = cmds.ls(type="audio")
			sequenceList = []
			for seqShot in allShots:
				#print "---", seqShot
				shotStart =  int(cmds.getAttr(seqShot +".sequenceStartFrame"))
				shotEnd  =   int(cmds.getAttr(seqShot +".sequenceEndFrame"))
				#print shotStart
				#print shotEnd
				sequenceList.append({"shot": seqShot})
				audioList = []
				audioIn = []
				audioOut = []
				for aud in allAudio:
					
					add = False
					aIn = 0
					aOut= 0
					audioStart   =  int(cmds.getAttr(aud+".offset" ))
					audioEnd = int(cmds.getAttr(aud+".endFrame"))-1
					audioOriginalDuration = int(cmds.getAttr(aud+".duration"))
					audioDuration  =  audioEnd-audioStart
					
						
					if shotStart < audioStart < shotEnd:
						add = True
						if audioEnd > shotEnd:
							aOut = shotEnd - audioStart
					if shotStart < audioEnd < shotEnd:
						add = True
						aIn = audioDuration-(audioEnd-shotStart)
					if audioStart < shotStart < audioEnd:
						add = True
						aIn = shotStart - audioStart
					if audioStart < shotEnd < audioEnd:
						add = True
						aOut = audioDuration-(audioEnd-shotEnd)+1
					
					if add:
						audioList.append([aud,aIn,aOut])

				sequenceList[-1]["audioList"] = audioList
			
			tmpFolder = "C:/temp"
			if not os.path.exists(tmpFolder):
				os.makedirs(tmpFolder)

			scenePath = cmds.file(q=True,sceneName=True)
			scene_template = tk.template_from_path(scenePath)
			audio_template = tk.templates["shot_published_audio"]
			flds = scene_template.get_fields(scenePath)
			flds['Step'] = 'snd'
			soundCheckList = ["These audio cuts dont match the camera cuts."]
			for audio in sequenceList:
				if audio['audioList'] != []:
					#print audio['shot']
					flds['Shot'] = flds['Sequence']+"_"+str(audio['shot'])
					i=0
					newAudio =[]
					soundCheckList += [""]
					soundCheckList += ["audio files overlapping shot " + audio['shot']]
					for aud in audio['audioList']:
						inSec = float(aud[1])/24
						outSec = float(aud[2])/24
						print aud[0],inSec,outSec
						# print "------>>>>>>>>>", aud
						soundCheckList += [aud[0] +"   cut in offset = "+ str(aud[1]) +"   cut out offset = "+ str(aud[2])]

			return sequenceList
		def MakeSoundCuts(ffmpegPath,Input,Output,Position,Duration ):
			time01= Position
			time02= Duration
			if os.path.isfile(Output):
				os.remove(Output)
			subprocess.call('%s -i "%s" -ss "%s" -t "%s" -acodec copy "%s"' %(ffmpegPath,Input,time01,time02,Output))
		def fixSound(sequenceList):
			tmpFolder = "C:/temp"
			if not os.path.exists(tmpFolder):
				os.makedirs(tmpFolder)
			scenePath = cmds.file(q=True,sceneName=True)
			scene_template = tk.template_from_path(scenePath)
			audio_template = tk.templates["shot_published_audio"]
			flds = scene_template.get_fields(scenePath)
			flds['Step'] = 'snd'
			for audio in sequenceList:
				if audio['audioList'] != []:
					print audio['shot']
					flds['Shot'] = flds['Sequence']+"_"+str(audio['shot'])
					i=0
					newAudio =[]
					for aud in audio['audioList']:
						inSec = float(aud[1])/24
						outSec = float(aud[2])/24
						print aud[0],inSec,outSec
						if outSec == 0.0:
							outSec = 10000
						input = cmds.getAttr(aud[0]+'.filename')
						output = tmpFolder+"/"+audio['shot']+"_part"+str(i)+str.split(str(input),"/")[-1]
						i+=1
						MakeSoundCuts(ffmpegPath,input,output,inSec,outSec)
						newAudio +=[output]
					audioOutput = audio_template.apply_fields(flds)
					
					# version UP
					latestVersion = findLastVersion(os.path.dirname(audioOutput))+1
					flds['version'] = latestVersion
					audioOutput = audio_template.apply_fields(flds)
					# combine
					mergedAudio = combineMediaFiles(newAudio,audioOutput,tmpFolder+"/tmp_wavList.txt",ffmpegPath)
					
					ver = str(findLastVersion(os.path.dirname(audioOutput),True))
					newAudioName = str.rsplit(ver,"_",1)[0]
					cmds.file( audioOutput, i=True, type="audio",mergeNamespacesOnClash=False, namespace=flds['Shot']+"_audio",resetError=True)
					crappyAudioName = str.split(ver,".")[0]
					cmds.rename(crappyAudioName,newAudioName)
					cutIn = cmds.getAttr(audio['shot']+".startFrame")
					cutOut = cmds.getAttr(audio['shot']+".endFrame")
					cutDuration = cutOut-cutIn
					cmds.setAttr(newAudioName+".offset", cutIn)
					cmds.setAttr(newAudioName+".sourceEnd",cutDuration+1)
					cmds.connectAttr(newAudioName+".message", audio['shot']+".audio",f=True)
					print "-----------------------------------------------------------------------------________________-------------------------------------------------------------------------"
					# PUBLISH
					file_template = tk.template_from_path(audioOutput)
					flds = file_template.get_fields(audioOutput)
					print audioOutput
					ctx = tk.context_from_path(audioOutput)

					print ctx

					sg_task = tk.shotgun.find("Task",[['content', 'is',"Sound"],["entity",'is',ctx.entity]], ['id'])
					try:
						sg_task = sg_task[0]
					except indexError:
						print "SKIPPED - are the folders already created on shotgun?????"
						errors.append("SKIPPED - are the folders already created on shotgun?????")
					if sg_task != []:
						_register_publish(audioOutput,newAudioName,sg_task,flds['version'],"Audio", "publish","",ctx)
					else:
						print "SKIPPED - are the folders already created on shotgun?????"
						errors.append("SKIPPED - are the folders already created on shotgun?????")
						#popup('error',"skipped creation of "+newAudioName+" - are the folders already created on shotgun??")

			for audio in sequenceList:
				if audio['audioList'] != []:
					for aud in audio['audioList']:
						if cmds.objExists(aud[0]):
							print "------------------",aud[0],"------------------------"
							cmds.delete(aud[0])


		shots = cmds.ls(type="shot")
		shotCams = []
		unUsedCams = []

		sides=["L","R"]

		pbShots = []
		CutInList = []
		parentShotList = []
		
		# these booleans can be used for 
		noOverscan = False
		resetCutIn = False

		# template stuff...
		# tk = tank.tank_from_path("W:/RTS/Tank/config")
		tk = self.parent.tank
		scenePath = cmds.file(q=True,sceneName=True)
		scene_template = tk.template_from_path(scenePath)
		flds = scene_template.get_fields(scenePath)
		flds['width'] = 1724
		flds['height'] = 936
		pb_template = tk.templates["maya_seq_playblast_publish"]
		pb_template_current = tk.templates["maya_seq_playblast_current"]
		pbArea_template = tk.templates["maya_seq_playblast_publish_area"]
		audio_template = tk.templates["shot_published_audio"]
		mov_template = tk.templates["maya_seq_playblast_publish_currentshots_mov"]
		concatMovTxt = tk.templates["maya_seq_playblast_publish_concatlist"]
		pbMov = tk.templates["maya_seq_playblast_publish_mov"]
		pbMp4 = tk.templates["maya_seq_playblast_review_mp4"]

		# get extra shot info through shotgun
		fields = ['id']
		sequence_id = self.parent.shotgun.find('Sequence',[['code', 'is',flds['Sequence'] ]], fields)[0]['id']
		fields = ['id', 'code', 'sg_asset_type','sg_cut_order','sg_cut_in','sg_cut_out','sg_cut_duration','sg_status_list','parent_shots']
		filters = [['sg_sequence', 'is', {'type':'Sequence','id':sequence_id}]]
		assets= self.parent.shotgun.find("Shot",filters,fields)
		results = []
		errors = []
		ffmpegPath = '"'+os.environ.get('FFMPEG_PATH')
		if "ffmpeg.exe" not in ffmpegPath:
			ffmpegPath += "\\ffmpeg.exe"
		ffmpegPath += '"'
		soundFixList = checkSoundCut()
		print soundFixList
		fixSound(soundFixList)

		for task in tasks:
			item = task["item"]
			output = task["output"]
			errors = []
			
			#get shots from scan scene
			if item["type"] == "shot":
				shotTask = [item["name"]][0]
				pbShots += [shotTask]
			# get corresponding cut values from shotgun
				for sht in assets:
					shot_from_shotgun = str.split(sht['code'],"_")[1]
					if shot_from_shotgun == shotTask:
						CutInList += [sht['sg_cut_in']]
						parentShotList += [sht['parent_shots']]
			
			# set extra settings
			if item["type"] == "setting":
				if item["name"]=="overscan":
					noOverscan = True
				if item["name"]=="set Cut in":
					resetCutIn = True

			# if there is anything to report then add to result
			if len(errors) > 0:
				# add result:
				results.append({"task":task, "errors":errors})

		# temporarily hide cams and curves
		modPan = cmds.getPanel(type="modelPanel")
		for pan in modPan:
			cmds.modelEditor( pan,e=True, alo= False, polymeshes =True )
			cmds.modelEditor( pan,e=True,displayAppearance="smoothShaded")
			cmds.modelEditor( pan,e=True,displayTextures=True)
			allobjs = cmds.ls(type= "transform")
			boundingboxObjsList = []


			for i in allobjs:
				if cmds.getAttr(i+".overrideEnabled"):
					if cmds.getAttr(i+".overrideLevelOfDetail") == 1:
						boundingboxObjsList.append(i)
						cmds.setAttr(i+".overrideLevelOfDetail",0)
						
		currentselection= cmds.ls(sl=True)
		cmds.select(cl=True)
		
		cmds.headsUpDisplay(lv=False)

		CamsList = cmds.listCameras()
		for Cam in CamsList:
			cmds.camera(Cam, e=True, dr=True, dgm=True,ovr=1.3)
		

		#Get USER
		USER = sgtk.util.get_current_user(tk)
		if USER == None:
			USER = {'email': '*****@*****.**',
			 'id': 63,
			 'image': 'https://sg-media-usor-01.s3.amazonaws.com/7df0575d53fc3b61c36343837da18effb72bb6ff/86f714413d0a2c68382b706e8e45991d41a0ffed/thumb_t.jpg?AWSAccessKeyId=AKIAIFHY52V77FIVWKLQ&Expires=1415784134&Signature=%2Ff4qeNQMq4oHscIKePb1IrtRPZQ%3D',
			 'login': '******',
			 'name': 'WTD RND',
			 'type': 'HumanUser'}


		# audio stuff
		'''
		stepVersion = flds['version']
		step = flds['Step']
		audioList = []
		for sht in shots:
			#print sht
			flds['Shot'] = (flds['Sequence']+"_"+sht)
			flds['version'] = findLastVersion(os.path.dirname(audio_template.apply_fields(flds)))
			flds['Step'] = 'snd'
			print flds['version']
			if flds['version'] > 0:
				audioList += [str.replace(str(audio_template.apply_fields(flds)),"\\","/")]
		flds['Shot'] = flds['Sequence']
		flds['version'] = stepVersion #set version back
		flds['Step'] = step
		
		audioOutput = pbArea_template.apply_fields(flds)+"/"+flds['Sequence']+"_"+flds['Step']+".wav"
		if audioList != []:
			combinedAudio = combineMediaFiles(audioList,audioOutput, ffmpeg_path = ffmpegPath)
		print ("combined audio at  " + audioOutput)
		'''


		# replacedAudio = setAudioToCorrectPath()
		# for aud in replacedAudio:
		# 	results.append({"task":{'item': aud , 'output': 'replaced' }})

		Test = True;
		#Test = False;
		if Test:
			j = 0
			RenderPath = ""
			for pbShot in pbShots:
				CutIn = CutInList[j]
				if parentShotList[j] != []:
					parentShot = str.split(parentShotList[j][0]['name'],"_")[-1]
				j += 1
				
				sequenceName = flds ['Sequence']
				shotName = pbShot
				
				# ... correct this in the templates?
				flds['Shot'] = flds['Sequence']+"_"+pbShot

				

				#get camera name from sequence shot 
				shotCam = cmds.shot(pbShot, q=True, currentCamera=True)

				# overscanValue = cmds.getAttr(shotCam+".overscan")
				cmds.setAttr(shotCam+".overscan", 1.3)
				if noOverscan:
					cmds.setAttr(shotCam+".overscan", 1)


				shotCams = [shotCam]
				previewCam = shotCam
				if flds['Step'] == 's3d':
					shotCams = getStereoCams(pbShot)
				s = 0
				for shotCam in shotCams:
					side = sides[s]
					s += 1
					if flds['Step'] == 's3d':
						flds['eye'] = side

					cmds.shot(pbShot, e=True, currentCamera=shotCam)
					focal = cmds.getAttr(shotCam+'.focalLength')
					# make outputPaths from templates
					RenderPath = pb_template.apply_fields(flds)
					pbPath = str.split(str(RenderPath),".")[0]
					renderPathCurrent = pb_template_current.apply_fields(flds)
					pbPathCurrent = str.split(str(renderPathCurrent),".")[0]
					if not os.path.exists(os.path.dirname(pbPathCurrent)):
						os.makedirs(os.path.dirname(pbPathCurrent))
					pbPathCurrentMov = mov_template.apply_fields(flds)
					if not os.path.exists(os.path.dirname(pbPathCurrentMov)):
						os.makedirs(os.path.dirname(pbPathCurrentMov))

					# report progress:
					progress_cb(0, "Publishing", task)

					shotStart = cmds.shot(pbShot,q=True,sequenceStartTime=True)
					shotEnd = cmds.shot(pbShot,q=True,sequenceEndTime=True)
					progress_cb(25, "Making playblast %s" %pbShot)
					cmds.playblast(indexFromZero=False,filename=(pbPath),fmt="iff",compression="png",wh=(flds['width'], flds['height']),startTime=shotStart,endTime=shotEnd,sequenceTime=1,forceOverwrite=True, clearCache=1,showOrnaments=1,percent=100,offScreen=True,viewer=False,useTraxSounds=True)
					progress_cb(50, "Placing Slates %s" %pbShot)
					
					Film = "Richard the Stork"
					#GET CURRENT DATE
					today = datetime.date.today()
					todaystr = today.isoformat()
					
					"""
						Adding Slates to playblast files
					"""
					for i in range(int(shotStart),int(shotEnd)+1):
						FirstPartName = RenderPath.split( '%04d' )[0]
						EndPartName = '%04d' % i + RenderPath.split( '%04d' )[-1]
						ImageFullName = FirstPartName + EndPartName
						pbFileCurrent = pbPathCurrent+"."+EndPartName
						print 'fld ===>',flds
						print 'USER===>',USER
						ffmpeg.ffmpegMakingSlates(inputFilePath= ImageFullName, outputFilePath= ImageFullName, topleft = flds ['Sequence']+"_"+flds['Step']+"_v"+str('%03d' % (flds['version'])), topmiddle = Film, topright = str(int(CutIn))+"-"+str('%04d' %(i-int(shotStart)+CutIn))+"-"+str('%04d' %(int(shotEnd)-int(shotStart)+CutIn))+"  "+str('%04d' %(i-int(shotStart)+1))+"-"+str('%04d' %(int(shotEnd)-int(shotStart)+1)), bottomleft = shotName+" - focal_Length "+ str(focal), bottommiddle = USER['name'], bottomright = todaystr , ffmpegPath =ffmpegPath, font = "C:/Windows/Fonts/arial.ttf"  )
						print("COPYING PNG "+ImageFullName+"  TO  "+pbFileCurrent+"  FOR SHOT  " + shotName)
						shutil.copy2(ImageFullName, pbFileCurrent)
					
					shotAudio = audio_template.apply_fields(flds)
					shotAudio = findLastVersion(os.path.dirname(shotAudio),True,True)
					if shotAudio == 0:
						print " NO PUBLISHED AUDIO FOUND"
						for aud in [parentShot,pbShot]:
							try:
								audio = cmds.shot(pbShot,q=True,audio=True)
								shotAudio = '"'+cmds.getAttr(audio+".filename")+'"'
								shotAudio = str.replace(str(shotAudio),"Z:/Richard The Stork/",'W:/RTS/')
								print "used audio from maya :  ", shotAudio
							except:
								shotAudio = ''
					print ffmpeg.ffmpegMakingMovie(inputFilePath=renderPathCurrent, outputFilePath=pbPathCurrentMov, audioPath=shotAudio, start_frame=int(shotStart),end_frame=int(shotEnd), framerate=24 , encodeOptions='libx264',ffmpegPath=ffmpegPath)
				# end_frame=shotEnd
				cmds.shot(pbShot, e=True, currentCamera=previewCam)
			
			if currentselection != []:
				cmds.select(currentselection)
			
			if flds['Step'] == 'lay':
				sides = ['']
			for side in sides:
				if flds['Step'] == 's3d':
					flds['eye'] = side
					
				
				RenderPath = pb_template.apply_fields(flds)

				for i in boundingboxObjsList:
					cmds.setAttr(i+".overrideEnabled",True)
					cmds.setAttr(i+".overrideLevelOfDetail",1)
				sequenceTest= MakeListOfSequence(os.path.dirname(RenderPath))
				FistImg= int(FindFirstImageOfSequence(os.path.dirname(RenderPath))) 
				LastImg= int(FindLastImageOfSequence(os.path.dirname(RenderPath)))

				FramesMissingList= FindMissingFramesFromSequence( sequenceTest ,FistImg ,LastImg )
				
				"""
					Copy empty frames
				"""
				# blackFrame = False
				# blackFrameName = ""
				# for n in FramesMissingList:
					# if blackFrame == False:
						# blackFrameName = FirstPartName+str('%04d' % n)+".png"
						# value = subprocess.call('%s -f lavfi -i color=c=black:s="%s" -vframes 1 "%s"' %(ffmpegPath,(str(flds['width'])+"x"+ str(flds['height'])),FirstPartName+str('%04d' % n)+".png"))
						# print '%s -f lavfi -i color=c=black:s="%s" -vframes 1 "%s"' %(ffmpegPath,(str(flds['width'])+"x"+ str(flds['height'])),FirstPartName+str('%04d' % n)+".png")
						# blackFrame = True
					
					# newFrameName = FirstPartName+str('%04d' % n)+".png"
					# if blackFrameName != newFrameName:
						# shutil.copy2(blackFrameName, newFrameName)	

				FirstImageNumber= FindFirstImageOfSequence(os.path.dirname(RenderPath))
				FirstImageNumberSecond= FirstImageNumber/24

				'''
				makeSeqMov
				'''
				concatTxt = concatMovTxt.apply_fields(flds)
				pbMovPath = pbMov.apply_fields(flds)
				pbMp4Path = pbMp4.apply_fields(flds)
				pbMp4Path = str.replace(str(pbMp4Path),'\\','/')

				pbMovFile =  str.split(str(pbMovPath),os.path.dirname(pbMovPath))[1][1:]

				# movList = []
				# for mov in os.listdir(os.path.dirname(pbPathCurrentMov)):
				# 	movList += [os.path.dirname(pbPathCurrentMov)+"/"+mov]
				# print movList

				assetsOrdered = orderShots(assets)
				movList = []
				for ass in assetsOrdered:
					for mov in os.listdir(os.path.dirname(pbPathCurrentMov)):
						movName = str.split(str(mov),".")[0]
						if ass['code'] == movName:
							movList += [os.path.dirname(pbPathCurrentMov)+"/"+mov]


				makeSeqMov = True
				if makeSeqMov:
					if not os.path.exists(os.path.dirname(pbMovPath)):
						self.parent.ensure_folder_exists(os.path.dirname(pbMovPath))
						# os.makedirs(os.path.dirname(pbMovPath))
					
					if not os.path.exists(os.path.dirname(pbMp4Path)):
						print "creating", pbMp4Path
						self.parent.ensure_folder_exists(os.path.dirname(pbMp4Path))
						print "created", pbMp4Path
						# os.makedirs(os.path.dirname(pbMp4Path))
					"""
						SEQUENCE MOV and MP4 Creation
					"""
					print "Making mov and mp4: \n", pbMovPath, ' --- ', pbMp4Path
					print combineMediaFiles(movList,pbMovPath,concatTxt,ffmpegPath)
					
					amount = 0
					while not os.path.exists(pbMovPath) and amount < 10:
						time.sleep(1)
						amount += 1
						
					print ffmpeg.ffmpegMakingMovie(pbMovPath,pbMp4Path,encodeOptions="libx264",ffmpegPath=ffmpegPath)
							
						
					# ----------------------------------------------
					# UPLOAD MP4
					# ----------------------------------------------
					
					upload = True
					if upload:
						user = self.parent.context.user
						scenePath = cmds.file(q=True,sceneName=True)
						ctx = self.parent.tank.context_from_path(scenePath)
						fields = ['id']
						sg_task = self.parent.shotgun.find("Task",[['content', 'is',ctx.step['name']],["entity",'is',ctx.entity]], fields)
						
						data = {'project': {'type':'Project','id':66},
								'entity': {'type':'Sequence', 'id':int(sequence_id)},
								'code': flds ['Sequence']+"_"+flds['Step']+"_v"+str('%03d' % (flds['version'])),
								'sg_path_to_frames':os.path.dirname(RenderPath),
								'sg_path_to_movie':pbMovPath,
								'user': user,
								'created_by': user,
								'updated_by': user,
								'sg_task': sg_task[0]
								}

						if not os.path.exists(os.path.dirname(pbMp4Path)):
							os.makedirs(os.path.dirname(pbMp4Path))
						
						result = tk.shotgun.create('Version', data)
						print "---> UPLOADING ",pbMp4Path
						executed = tk.shotgun.upload("Version",result['id'],pbMp4Path,'sg_uploaded_movie')
						print executed
				
					# PUBLISH
					if sg_task != []:
						version = findLastVersion(os.path.dirname(pbMovPath))
						#sg_task = sg_task[0]
						print sg_task
						_register_publish(pbMovPath,pbMovFile,sg_task,version,"Movie", "published playblast mov","",ctx)
						print "PUBLISHED"
					else:
						print "SKIPPED PUBLISH"
				
					
				# print "TODO : make mov of whole sequence with audio"
		return results
コード例 #51
0
ファイル: JR_attribute_class.py プロジェクト: jricker/JR_Maya
 def updateAttrHUD(self):
     cmds.headsUpDisplay("currAttrHUD", edit=True, c=self.setCurrentHUD)
     cmds.headsUpDisplay("nextAttrHUD", edit=True, c=self.setNextHUD)
     cmds.headsUpDisplay("prevAttrHUD", edit=True, c=self.setPreviousHUD)
コード例 #52
0
 def disableHUD(self, *args):
     HUDList = ['HUDObjectResolation','HUDObjectFrame','HUDObjectUserName','HUDObjectTime','HUDObjectCamera','HUDObjectFocalLength' ]
     for each in HUDList:
         mc.headsUpDisplay( each, rem=1 )
コード例 #53
0
ファイル: BlastMaster.py プロジェクト: Mauricio3000/MSH_Maya
 def removeHUDs(self,*args):
     """
     Remove BlastMaster HUDs / Restore Users'
     """
     #Delete the HUD's 
     cmds.headsUpDisplay('HUDComment',rem=True)
     cmds.headsUpDisplay('HUDFile',rem=True)
     cmds.headsUpDisplay('HUDCam',rem=True)
     cmds.headsUpDisplay('HUDDuration',rem=True)
     cmds.headsUpDisplay('HUDFrame',rem=True)
     cmds.headsUpDisplay('HUDtc',rem=True)
     cmds.headsUpDisplay('HUDName',rem=True)
     cmds.headsUpDisplay('HUDDate',rem=True)
     
     #Reset HUD to user settings
     mel.eval('setSelectDetailsVisibility(%i);'%self.userHUD['selectDetails'])       
     mel.eval('setObjectDetailsVisibility(%i);'%self.userHUD['objectDetails'])   
     mel.eval('setSubdDetailsVisibility(%i);'%self.userHUD['subdivDetails'])   
     mel.eval('setPolyCountVisibility(%i);'%self.userHUD['polyCount'])   
     mel.eval('setAnimationDetailsVisibility(%i);'%self.userHUD['animationDetails'])   
     mel.eval('setFbikDetailsVisibility(%i);'%self.userHUD['fbikDetails'])   
     mel.eval('setFrameRateVisibility(%i);'%self.userHUD['frameRate'])   
     mel.eval('setCurrentFrameVisibility(%i);'%self.userHUD['currentFrame'])   
     mel.eval('setCurrentContainerVisibility(%i);'%self.userHUD['currentContainer'])   
     mel.eval('setCameraNamesVisibility(%i);'%self.userHUD['cameraNames'])   
     mel.eval('setFocalLengthVisibility(%i);'%self.userHUD['focalLength'])   
     mel.eval('setViewAxisVisibility(%i);'%self.userHUD['viewAxis'])   
     mel.eval('setToolMessageVisibility(%i);'%self.userHUD['toolMessage'])
     
     #Delete the HUD expressions
     cmds.delete("TC_HUDRefreshExp")
     cmds.delete("Duration_HUDVisExp")
     cmds.delete("Comment_HUDVisExp")
コード例 #54
0
ファイル: pipeUtilities.py プロジェクト: sid2364/Maya_Python
def sceneCleanup(silent = True):
    mc.displayColor('headsUpDisplayLabels', 16, dormant=True)
    namespaces = mc.namespaceInfo(lon = True)
    if "Suleiman00s_pr01" in namespaces:
        mc.namespace(ren = ("Suleiman00s_pr01", "Suleiman00p_pr01"), f = True)
    mayaShot = ppc.MayaShot()
    if not mayaShot.validShot:
        msgWin("Error", "Invalid Shot or Project", silent)
        return False
    epsq = mayaShot.epSqName
    shot = mayaShot.shName
    stereoCams = []
    mc.setAttr("defaultResolution.width", mayaShot.projInfo.resWidth)
    mc.setAttr("defaultResolution.height", mayaShot.projInfo.resHeight)
    mc.setAttr("defaultResolution.deviceAspectRatio", mayaShot.projInfo.aspectRatio)
    camPattern = "(ep|sq)[0-9]{3}sh[0-9]{3}([a-b]{1})?_camCt"
    camName = "%s%s_camCt" % (epsq, shot)
    scCams = mc.ls(type = "camera")
    renCams = []
    for cam in scCams:
        camTr = mc.listRelatives(cam, p = True)
        pMatch = re.search(camPattern, camTr[0])
        if pMatch:
            renCams.append(camTr[0])
    if not renCams:
        msgWin("Error", "Couldn't find a valid camera", silent)
        return False
    if len(renCams) > 1:
        msgWin("Error", "Too many cameras in the scene.\nPlease delete unwanted cameras", silent)
        return False
    if not renCams[0] == camName:
        mc.rename(renCams[0], camName)
    if mayaShot.projInfo.stereo:
        stereoCams = mc.listRelatives(camName, c = 1, typ = 'transform')
        for stCam in stereoCams:
            nodeTyp = mc.nodeType(stCam, i = True)
            if "constraint" in nodeTyp:
                continue
            if mc.getAttr(stCam + ".tx") < 0:
                mc.rename(stCam, camName.replace("_camCt", "_camLt"))
            else:
                mc.rename(stCam, camName.replace("_camCt", "_camRt"))
        camShape = "%sCenterCamShape" % camName
    else:
        camShape = "%sShape" % camName
    camShps = mc.listRelatives(camName, c = True, s = True)
    for shp in camShps:
        sMatch = re.search(camPattern, shp)
        if sMatch:
            mc.rename(shp, shp.replace(sMatch.group(0), camName))
        else:
            print "Unable to find correct name for %s" % shp
    camParent = mc.listRelatives(camName, p = True)
    if camParent:
        camParent = camParent[0]
    if not camParent in ["CAM", "Aim_camera", "Ctl_Camera", "camera_group"]:
        if not mc.objExists("CAM"):
            mc.group(n = "CAM", em = True)
        try:
            mc.parent(camName, "CAM")
        except:
            pass
    camTopGrp = mc.listRelatives("CAM", p = True)
    if not camTopGrp == "CAMERAS":
        if not mc.objExists("CAMERAS"):
            mc.group(n = "CAMERAS", em = True)
        try:
            mc.parent("CAM", "CAMERAS")
        except:
            pass
    huds = ["HUDShotName", "HUDUserName", "HUDfocalLength", "HUDFrameNo"]
    for hud in huds:
        if mc.headsUpDisplay(hud, ex = True):
            mc.headsUpDisplay(hud, rem = True)
    focLen = mc.getAttr("%s.focalLength" % camShape)
    mc.headsUpDisplay('HUDfocalLength', s = 5, b = 1, bs = 'small', l = 'focalLength: %s' % focLen, lfs = 'large')
    mc.headsUpDisplay('HUDShotName', s = 6, b = 1, bs = 'small', l = 'shot: %s%s' % (epsq, shot), lfs = 'large')
    #username = os.environ['USERNAME']
    #mc.headsUpDisplay('HUDUserName', s = 7, b = 1, bs = 'small', l = 'user: %s' % username, lfs = 'large')
    mc.headsUpDisplay('HUDFrameNo', s = 8, b = 1, bs = 'small', l = 'frame: ', lfs = 'large', c = 'import maya.cmds as mc; mc.currentTime(q = True)', atr = True)
    scnCameras = [camName]
    if stereoCams: scnCameras.extend(mc.listRelatives(camName, c = 1, typ = 'transform'))
    for scnCam in scnCameras:
        mc.camera(scnCam, e = 1, dfg = 0, dgm = 1, dr = 1, ovr = 1.1)
        if mayaShot.projInfo.stereo and scnCam.endswith("_camCt"):
            scnCam = scnCam + "CenterCam"
        mc.setAttr('%sShape.displayGateMaskOpacity' % scnCam, l = 0)
        mc.setAttr('%sShape.displayGateMaskOpacity' % scnCam, 1)
        mc.setAttr ('%sShape.displayGateMaskColor' % scnCam, l = 0)
        mc.setAttr ('%sShape.displayGateMaskColor' % scnCam, 0, 0, 0)
    if mc.objExists('hudFix_node'):
        mc.delete('hudFix_node')
    mayaShot.moveAssetsToGrps()
    shotFrames = mayaShot.frames
    mc.playbackOptions(min=101, max=100+int(shotFrames), ast=101, aet=100+int(shotFrames))
    om.MGlobal.displayInfo("Scene cleaned up.")
コード例 #55
0
ファイル: BlastMaster.py プロジェクト: Mauricio3000/MSH_Maya
    def createHUDs(self,*args):
        """
        Create the HUD's for playblasting
        """
        #Store user HUD settings in dictionary
        self.userHUD = {
            'selectDetails':cmds.optionVar(query='selectDetailsVisibility'),
            'objectDetails':cmds.optionVar(query='objectDetailsVisibility'),
            'polyCount':cmds.optionVar(query='polyCountVisibility'),
            'subdivDetails':cmds.optionVar(query='subdivDetailsVisibility'),
            'animationDetails':cmds.optionVar(query='animationDetailsVisibility'),
            'fbikDetails':cmds.optionVar(query='fbikDetailsVisibility'),
            'frameRate':cmds.optionVar(query='frameRateVisibility'),
            'currentFrame':cmds.optionVar(query='currentFrameVisibility'),
            'currentContainer':cmds.optionVar(query='currentContainerVisibility'),
            'cameraNames':cmds.optionVar(query='cameraNamesVisibility'),
            'focalLength':cmds.optionVar(query='focalLengthVisibility'),
            'viewAxis':cmds.optionVar(query='viewAxisVisibility'),
            'toolMessage':cmds.optionVar(query='toolMessageVisible')}

        #Set HUD for play blasting
        mel.eval('setSelectDetailsVisibility(0);')       
        mel.eval('setObjectDetailsVisibility(0);')   
        mel.eval('setSubdDetailsVisibility(0);')   
        mel.eval('setPolyCountVisibility(0);')   
        mel.eval('setAnimationDetailsVisibility(0);')   
        mel.eval('setFbikDetailsVisibility(0);')   
        mel.eval('setFrameRateVisibility(0);')   
        mel.eval('setCurrentFrameVisibility(0);')   
        mel.eval('setCurrentContainerVisibility(0);')   
        mel.eval('setCameraNamesVisibility(0);')   
        mel.eval('setFocalLengthVisibility(0);')   
        mel.eval('setViewAxisVisibility(0);')   
        mel.eval('setToolMessageVisibility(0);') 

        #Create HUDs    
        #Slate comment
        cmds.headsUpDisplay('HUDComment',rem=True)
        cmds.headsUpDisplay( 'HUDComment', 
                                label="   COMMENT: ",
                                ao=True,
                                padding=0,
                                ba='left',
                                section=6, 
                                block=4, 
                                blockSize='small',
                                dataFontSize='large',
                                c=(self.commentProc),
                                ct='playingBack' )       
            
        #File
        cmds.headsUpDisplay('HUDFile',rem=True)
        cmds.headsUpDisplay( 'HUDFile', 
                                label="   FILE: ",
                                ao=True,
                                padding=0,
                                ba='left',
                                section=5, 
                                block=2, 
                                blockSize='small',
                                dataFontSize='large',
                                c=(self.fileProc),
                                ct='playingBack' )        
        #Current Frame
        cmds.headsUpDisplay('HUDFrame',rem=True)
        cmds.headsUpDisplay( 'HUDFrame', ao=True, s=5, b=1, 
                             label=" ", blockSize="small",
                             dataFontSize='large', ba='right', dw=50, 
                             pre='currentFrame')
        
        #Duration
        cmds.headsUpDisplay('HUDDuration',rem=True)
        cmds.headsUpDisplay( 'HUDDuration', 
                                label="   DURATION: ",
                                ao=True,
                                padding=0,
                                ba='left',
                                section=6, 
                                block=6, 
                                blockSize='small',
                                dataFontSize='large',
                                c=(self.durationProc),
                                ct='playingBack' )
        
        #Camera
        cmds.headsUpDisplay('HUDCam',rem=True)
        cmds.headsUpDisplay( 'HUDCam', 
                                label="CAMERA: ",
                                ao=True,
                                padding=0,
                                ba='right',
                                section=7, 
                                block=2, 
                                blockSize='small',
                                dataFontSize='large',
                                c=(self.camProc),
                                ct='playingBack' ) 
        
        #Time code
        cmds.headsUpDisplay('HUDtc',rem=True)
        cmds.headsUpDisplay( 'HUDtc',
                                label=" ",
                                ao=True,
                                padding=0,
                                ba='right', 
                                section=7, 
                                block=1, 
                                blockSize='small',
                                dataFontSize='large',
                                c=self.tcProc,
                                ct='playingBack' )

        #Name
        cmds.headsUpDisplay('HUDName',rem=True)
        cmds.headsUpDisplay( 'HUDName',
                                label=" NAME: ",
                                ao=True,
                                padding=0,
                                ba='right', 
                                section=8, 
                                block=1, 
                                blockSize='small',
                                dataFontSize='large',
                                c=self.nameProc,
                                ct='playingBack' )
        
        #Date
        cmds.headsUpDisplay('HUDDate',rem=True)
        cmds.headsUpDisplay( 'HUDDate',
                                label=" DATE (m/d/y): ",
                                ao=True,
                                padding=0,
                                ba='right', 
                                section=8, 
                                block=0, 
                                blockSize='small',
                                dataFontSize='large',
                                c=self.dateProc,
                                ct='playingBack' )   

        #Create Timecode HUD refresh expression
        cmds.expression(n="TC_HUDRefreshExp",
                        s="headsUpDisplay -refresh HUDtc;",
                        ae=True)  
        
        #Slate HUD vis expressions 
        #Slate Length HUD vis expression string
        slateStr = 'if(`currentTime -query`== %i)\n'%(self.classScopeData['startTime']-1)
        slateStr = slateStr + '{ headsUpDisplay -edit -visible 1 HUDDuration;}\n' 
        slateStr = slateStr + 'else{ headsUpDisplay -edit -visible 0 HUDDuration;}'
        
        cmds.expression(n="Duration_HUDVisExp",
                        s=slateStr,
                        ae=True)  
        
        #Slate Comment HUD vis expression string
        commentStr = 'if(`currentTime -query`== %i)\n'%(self.classScopeData['startTime']-1)
        commentStr = commentStr + '{ headsUpDisplay -edit -visible 1 HUDComment;}\n' 
        commentStr = commentStr + 'else{ headsUpDisplay -edit -visible 0 HUDComment;}'
        
        cmds.expression(n="Comment_HUDVisExp",
                        s=commentStr,
                        ae=True) 
コード例 #56
0
ファイル: JR_playblast_tool.py プロジェクト: jricker/JR_Maya
def playblastStart(cameraList, directory, formatInfo):
	focus = cmds.getPanel( withFocus=True )
	## set attributes for Viewport 2.0
	cmds.modelEditor( focus, edit = True, cameras = False, locators = False, grid = 0, lights = 0, displayTextures =1, textureHilight = 1, shadows = 1,  rendererName = 'ogsRenderer' ) # sets viewport to Viewport 2.0
	if len(cmds.ls(lights = 1) ) == 0:
		cmds.modelEditor( focus, edit = 1, displayLights = 'default' )
	else:
		cmds.modelEditor( focus, edit = 1, displayLights = 'all' )
	# motion blur on
	cmds.setAttr ("hardwareRenderingGlobals.motionBlurEnable", 1)
	cmds.setAttr ("hardwareRenderingGlobals.motionBlurShutterOpenFraction", 0.1 )
	cmds.setAttr ("hardwareRenderingGlobals.motionBlurSampleCount", 32)
	# anti aliasing on
	cmds.setAttr ("hardwareRenderingGlobals.multiSampleEnable", 1)
	cmds.setAttr ("hardwareRenderingGlobals.multiSampleCount", 16)
	## set transparecy sorting
	cmds.setAttr ("hardwareRenderingGlobals.transparencyAlgorithm", 3)
	cmds.setAttr ("hardwareRenderingGlobals.transparencyQuality", 1)
	# screen space AO
	cmds.setAttr ("hardwareRenderingGlobals.ssaoEnable", 1)
	cmds.setAttr ("hardwareRenderingGlobals.ssaoAmount", .5)
	cmds.setAttr ("hardwareRenderingGlobals.ssaoRadius", 25)
	cmds.setAttr ("hardwareRenderingGlobals.ssaoFilterRadius", 25)
	cmds.setAttr ("hardwareRenderingGlobals.ssaoSamples", 32)
	if formatInfo[0] == 'qt':
		fileExtension = '.mov'
	elif formatInfo[0] == 'avi':
		fileExtension = '.avi'
	# setup the HUD elements to be visible
	mel.eval( "setCurrentFrameVisibility  (1) ;" )
	mel.eval( "setSceneTimecodeVisibility (1) ;" )
	mel.eval( "setFocalLengthVisibility   (1) ;" )
	cmds.headsUpDisplay( 'sceneNameHUD', edit = True, c = setSceneHUD )
	#
	for x in cameraList:
		# cache current clipping planes just in case we need them for some reason
		near = cmds.getAttr(str(x) + '.nearClipPlane')
		far = cmds.getAttr(str(x) +'.farClipPlane')
		# Set attrs to avoid clipping issues
		cmds.setAttr(str(x) + '.nearClipPlane', 0.1 )
		cmds.setAttr(str(x) + '.farClipPlane', 100000 )
		cmds.setAttr( str(x) + '.bestFitClippingPlanes', False )
		#
		cmds.select(x)
		start = cmds.findKeyframe( x, which="first" )
		end = cmds.findKeyframe( x, which="last" )
		sceneNameFull = cmds.file(query = True, shortName = True, sceneName = True)
		if '.mb' in sceneNameFull or '.ma' in sceneNameFull:
			sceneName = sceneNameFull[:-3]
		else:
			sceneName = SceneNameFull
		cmds.modelPanel ( focus, edit=True, camera = x )
		if start == end: # this means there's no keyframes
			cmds.warning ('no keyframes found on ' + str(x) + ', playblasting timeline duration' )
			cmds.playblast (format = formatInfo[0], compression = formatInfo[1], forceOverwrite = 1, showOrnaments = 1, filename = directory + sceneName + '_' + x + fileExtension , clearCache = 1 , viewer = 0, percent = 100, quality = 100, widthHeight = formatInfo[2] )
		else:
			cmds.warning('keyframes found on ' + str(x) + ', playblasting ' + str(start) + ' to ' + str(end) )
			cmds.playblast (startTime = start, endTime = end, format = formatInfo[0], compression = formatInfo[1], forceOverwrite = 1, showOrnaments = 1, filename = directory + sceneName + '_' + x + fileExtension , clearCache = 1 , viewer = 0, percent = 100, quality = 100, widthHeight = formatInfo[2] )
		# Set attrs back to normal 
		cmds.setAttr(str(x) + '.nearClipPlane', near )
		cmds.setAttr(str(x) + '.farClipPlane', far )
		cmds.setAttr( str(x) + '.bestFitClippingPlanes', True )
	####
	mel.eval( "setCurrentFrameVisibility  (0) ;" )
	mel.eval( "setSceneTimecodeVisibility (0) ;" )
	mel.eval( "setFocalLengthVisibility   (0) ;" )
	####
	cmds.headsUpDisplay( 'sceneNameHUD', edit = True, c = resetSceneHUD )
	cmds.modelEditor( focus, edit = True, cameras = True, locators = True, grid = 1, lights = 1, displayTextures=0, shadows = 0, displayLights = 'default' , rendererName = 'base_OpenGL_Renderer', camera = 'persp'  ) # sets viewport back to default
コード例 #57
0
 def __init__(self):    
     self.functions = []
     
     if cmds.headsUpDisplay('SnapButton', exists = True):
         cmds.headsUpDisplay('SnapButton', rem = True)
     cmds.hudButton('SnapButton', s=7, b=5, vis = False, l='Snap Image', bw = 120, bsh ='roundRectangle' ) 
コード例 #58
0
    def createHUD(self, labelName, section):
        # Set the arguments of the HUD
        blockIndex = mc.headsUpDisplay(nfb = section)
        blockSizeNum = 'large'
        labelFont = 'large'
        dataFont = 'large'
        if labelName == '分辨率':
            #File Name
			try:
				mc.headsUpDisplay( 'HUDObjectResolation', 
								section=section, block=blockIndex, 
								blockSize=blockSizeNum, 
								label=self.resolution(), vis = 1,
								labelFontSize=labelFont)
			except:
				pass
				#mc.headsUpDisplay('HUDObjectResolation', e = True, vis = self.state)
        elif labelName == '当前帧/总帧数':
            #Current Frame
			try:
				mc.headsUpDisplay( 'HUDObjectFrame', 
							section=section, block=blockIndex, 
							blockSize=blockSizeNum, 
							label=labelName, vis = 1,
							labelFontSize=labelFont, 
                            dataFontSize = dataFont,
							command = self.allFrame, 
							attachToRefresh = True)
			except:
				pass
				#mc.headsUpDisplay('HUDObjectFrame', e = True, vis = self.state)
        elif labelName == '用户名':
            #User Name
			try:
				mc.headsUpDisplay( 'HUDObjectUserName', 
							section=section, block=blockIndex, 
							blockSize=blockSizeNum, 
							label=self.hostName(), vis = 1,
							labelFontSize=labelFont)
			except:
				pass
				#mc.headsUpDisplay('HUDObjectUserName', e = True, vis = self.state)
        elif labelName == '时间':
            #Current Time
			try:
				mc.headsUpDisplay( 'HUDObjectTime', 
							section=section, block=blockIndex, 
							blockSize=blockSizeNum, 
							label=labelName, vis = 1,
							labelFontSize=labelFont, 
                            dataFontSize = dataFont,
							command=self.timeNow, 
							attachToRefresh = True)
			except:
			    pass
				#mc.headsUpDisplay('HUDObjectTime', e = True, vis = self.state)
        elif labelName == '摄像机':
            #Camera Name
			try:
				mc.headsUpDisplay( 'HUDObjectCamera', 
							section=section, block=blockIndex, 
							blockSize=blockSizeNum, 
							label=labelName, vis = 1,
							labelFontSize=labelFont, 
                            dataFontSize = dataFont,
							command=self.cameraHud, 
							attachToRefresh = True )
			except:
			    pass
				#mc.headsUpDisplay('HUDObjectTime', e = True, vis = self.state)
        elif labelName == '焦距':
            #FocalLength
			try:
				mc.headsUpDisplay( 'HUDObjectFocalLength', 
							section=section, block=blockIndex, 
							blockSize=blockSizeNum, 
							label=labelName, vis = 1,
							labelFontSize=labelFont, 
                            dataFontSize = dataFont,
							command=self.focalLength, 
							attachToRefresh = True )
			except:
				pass