예제 #1
0
파일: parsers.py 프로젝트: tbarbieri/pymel
def mayaDocsLocation(version=None):
    docLocation = None
    if (version == None or version == versions.installName() ) and mayaIsRunning():
        # Return the doc location for the running version of maya
        from maya.cmds import showHelp
        docLocation = showHelp("", q=True, docs=True)

        # Older implementations had no trailing slash, but the result returned by
        # showHelp has a trailing slash... so eliminate any trailing slashes for
        # consistency
        while docLocation != "" and os.path.basename(docLocation) == "":
            docLocation = os.path.dirname(docLocation)

    # Want the docs for a different version, or maya isn't initialized yet
    if not docLocation or not os.path.isdir(docLocation):
        docLocation = getMayaLocation(version) # use original version
        if docLocation is None and version is not None:
            docLocation = getMayaLocation(None)
            _logger.warning("Could not find an installed Maya for exact version %s, using first installed Maya location found in %s" % (version, docLocation) )

        if version:
            short_version = versions.parseVersionStr(version, extension=False)
        else:
            short_version = versions.shortName()
        if platform.system() == 'Darwin':
            docLocation = os.path.dirname(os.path.dirname(docLocation))

        docLocation = os.path.join(docLocation , 'docs/Maya%s/en_US' % short_version)

    return os.path.realpath(docLocation)
예제 #2
0
def mayaDocsLocation(version=None):
    docLocation = os.environ.get('MAYA_DOC_DIR')

    if (not docLocation and (version is None or version == versions.installName() )
            and mayaIsRunning()):
        # Return the doc location for the running version of maya
        from maya.cmds import showHelp
        docLocation = showHelp("", q=True, docs=True)

        # Older implementations had no trailing slash, but the result returned by
        # showHelp has a trailing slash... so eliminate any trailing slashes for
        # consistency
        while docLocation != "" and os.path.basename(docLocation) == "":
            docLocation = os.path.dirname(docLocation)

    # Want the docs for a different version, or maya isn't initialized yet
    if not docLocation or not os.path.isdir(docLocation):
        docBaseDir = os.environ.get('MAYA_DOC_BASE_DIR')
        if not docBaseDir:
            docBaseDir = getMayaLocation(version) # use original version
            if docBaseDir is None and version is not None:
                docBaseDir = getMayaLocation(None)
                _logger.warning("Could not find an installed Maya for exact version %s, using first installed Maya location found in %s" % (version, docBaseDir) )

            if platform.system() == 'Darwin':
                docBaseDir = os.path.dirname(os.path.dirname(docBaseDir))
            docBaseDir = os.path.join(docBaseDir, 'docs')

        if version:
            short_version = versions.parseVersionStr(version, extension=False)
        else:
            short_version = versions.shortName()
        docLocation = os.path.join(docBaseDir , 'Maya%s' % short_version, 'en_US')

    return os.path.realpath(docLocation)
    def createUi(self):
        # TODO:: Create a simple dialog
        # Top layout
        fileNameLabel = QtGui.QLabel("Asset File:")
        self.assetFileNameLineEdit = QtGui.QLineEdit()
        self.assetFileNameLineEdit.setText(pymutils.getMayaLocation() + \
                                           "\\Python\\Lib\site-packages\\MayaHairAttribAsset\\testAsset.json")
        self.seletCacheFileBtn = QtGui.QPushButton("...")

        topLayout = QtGui.QHBoxLayout()
        topLayout.addWidget(fileNameLabel)
        topLayout.addWidget(self.assetFileNameLineEdit)
        topLayout.addWidget(self.seletCacheFileBtn)

        # cached attrib list
        self.assetAttribsListView = QtGui.QListView()
        self.assetAttribsListModel = QtGui.QStringListModel()

        # operation buttons
        self.applyAttribBtn = QtGui.QPushButton("Apply")
        self.addAttribToLibBtn = QtGui.QPushButton("Add2Asset")
        self.refreshListBtn = QtGui.QPushButton("Refresh")
        buttonsLayout = QtGui.QVBoxLayout()
        buttonsLayout.addWidget(self.applyAttribBtn)
        buttonsLayout.addWidget(self.addAttribToLibBtn)
        buttonsLayout.addWidget(self.refreshListBtn)

        # hair nodes list
        self.hairNodesListView = QtGui.QListView()
        self.hairNodesListModel = QtGui.QStringListModel()

        # bottom layout
        bottomLayout = QtGui.QHBoxLayout()
        bottomLayout.addWidget(self.assetAttribsListView)
        bottomLayout.addLayout(buttonsLayout)
        bottomLayout.addWidget(self.hairNodesListView)

        # main layout, vertical
        mainLayout = QtGui.QVBoxLayout()
        mainLayout.addLayout(topLayout)
        mainLayout.addLayout(bottomLayout)

        self.setLayout(mainLayout)
        self.setWindowTitle("Hair Attrib Asset")

        # setup connections
        self.seletCacheFileBtn.clicked.connect(self.specifyAssetFile)

        self.applyAttribBtn.clicked.connect(self.applyAssetAttribs)
        self.addAttribToLibBtn.clicked.connect(self.addAttribsToAssetLib)
        self.refreshListBtn.clicked.connect(self.refreshList)
        pass
예제 #4
0
    def _buildApiRelationships(self) :
        """
        Used to rebuild api info from scratch.
        """
        # Put in a debug, because this can be crashy
        _logger.debug("Starting ApiCache._buildApiTypeHierarchy...")        
        
        def _MFnType(x) :
            if x == api.MFnBase :
                return self.apiEnumsToApiTypes[ 1 ]  # 'kBase'
            else :
                try :
                    return self.apiEnumsToApiTypes[ x().type() ]
                except :
                    return self.apiEnumsToApiTypes[ 0 ] # 'kInvalid'

        if not startup.mayaStartupHasRun():
            startup.mayaInit()
        import maya.cmds

        import pymel.mayautils as mayautils
        # load all maya plugins
        mayaLoc = mayautils.getMayaLocation()
        # need to set to os.path.realpath to get a 'canonical' path for string comparison...
        pluginPaths = [os.path.realpath(x) for x in os.environ['MAYA_PLUG_IN_PATH'].split(os.path.pathsep)]
        for pluginPath in [x for x in pluginPaths if x.startswith( mayaLoc ) and os.path.isdir(x) ]:
            for x in os.listdir( pluginPath ):
                if os.path.isfile( os.path.join(pluginPath,x)):
                    try:
                        maya.cmds.loadPlugin( x )
                    except RuntimeError: pass

        # all of maya OpenMaya api is now imported in module api's namespace
        mfnClasses = inspect.getmembers(api, lambda x: inspect.isclass(x) and issubclass(x, api.MFnBase))
        for name, mfnClass in mfnClasses:
            current = _MFnType(mfnClass)
            if not current:
                _logger.warning("MFnClass gave MFnType %s" % current)
            elif current == 'kInvalid':
                _logger.warning("MFnClass gave MFnType %s" % current)
            else:
                self.apiTypesToApiClasses[ current ] = mfnClass

        self._buildApiClassInfo()

        allMayaTypes = self.reservedMayaTypes.keys() + maya.cmds.ls(nodeTypes=True)
        self._buildMayaToApiInfo(allMayaTypes)
        
        _logger.debug("...finished ApiCache._buildApiTypeHierarchy")
예제 #5
0
def runImgcvt(
    dirName='',
    sameDirFlag='True',
    fileName='',
    startNum=1,
):

    # if dirName == '': #ディレクトリ名がない場合は実行できないようにする
    # return

    myNode = pm.selected()
    if len(myNode) == 1:  #選択したオブジェクトのアトリビュートがshapしかない場合
        imagePlaneName = myNode[0]
    else:
        imagePlaneName = myNode[0].getShape()  #選択したオブジェクトのアトリビュートが複数ある場合
    myName = pm.getAttr("%s.imageName" %
                        imagePlaneName)  #イメージデータフォルダのパス(絶対パスで取得できてるぽい)
    currentDir = os.path.dirname(myName)
    currentDirName = os.path.basename(currentDir)
    file_type = os.path.splitext(myName)[1]
    print 'myNameで何が取得できているか確認。', file_type
    mayaLocation = mutl.getMayaLocation() + '\\bin'
    print 'test', mayaLocation
    rejectPadName = re.search(r"[^.]*(?=\.)", str(os.path.basename(myName)))
    # currentImgPath = currentDir + '/' + rejectPadName.group() + '.#' + file_type
    print 'rejectPadName', os.path.basename(myName), rejectPadName.group()
    #現在使用している画像のファイルフォーマットを取得
    currentImgName = currentDir + '/' + myName

    # ユーザー入力情報
    start_num = startNum
    new_dir_name = 'tmp_Dir'
    if fileName == '':
        new_file_name = rejectPadName.group()
    else:
        new_file_name = fileName
    if not sameDirFlag:
        new_file_name = dirName
    new_dir_path = currentDir + '/' + new_dir_name
    imgFormatList = {
        'JPEG': '.jpg',
        'PNG': '.png',
        'TIFF 6.0': '.tif',
        'Targa': '.tga',
        'GIF': '.gif',
        'Abekas NTSC': '.yuv',
        'Alias': '.als',
        'Kodak Cineon': '.cin',
        'Lucas Film': '.lff',
        'Pixibox PXB': '.pxb',
        'SCN': '.scn',
        'PPM raw/ascii': '.ppm',
        'Prisms': '.pri',
        'Quantel': '.qtl',
        'SGI': '.sgi',
        'Avid® Softimage®': '.pic',
        'Vista': '.vst',
        'Wavefront RLA': '.rla'
    }

    #カレントディレクトリの下に新しいディレクトリを作って画像データをコピーする処理
    if __name__ == '__main__':
        cmtime = os.path.getmtime(currentDir)
        cTimestamp = datetime.datetime.now()
        oldDirPath = currentDir + '/' + currentDirName + '_' + cTimestamp.strftime(
            '%Y-%m%d-%H%M%S')
        print 'oldDirPath', oldDirPath
        os.mkdir(oldDirPath)
        if os.path.isdir(new_dir_path) is False:  #指定したディレクトリパスが存在しない場合
            os.mkdir(new_dir_path)  #新しくディレクトリを作成する
        arr = []
        for files in os.listdir(currentDir):
            if files.endswith(file_type):
                arr.append(files)
                # ファイルのコピーと移動
                print 'でバッグ1'
                shutil.copyfile(currentDir + '/' + files,
                                new_dir_path + '/' + files + '_tmp')
                shutil.move(currentDir + '/' + files, oldDirPath)
                print 'でバッグ2'
    # 更新日時順に画像ファイルを連番でリネームする処理
    if __name__ == '__main__':
        print 'test'
        arr = []
        child_dir = new_dir_path + '/'
        # arrに更新日時:ファイル名の連想配列を追加していく処理
        for file_name in os.listdir(new_dir_path):
            path = child_dir + file_name
            arr.append((os.path.getmtime(path), file_name))
        ind = start_num
        print arr
        #画像をソートしてファイル名に連番をつける処理
        for mtime, file_name in sorted(arr):
            new_name = new_file_name + '.' + str(ind).zfill(5) + file_type
            t = datetime.datetime.fromtimestamp(mtime)
            print 'mtimeにはパスが入っているはず', t, new_name, mtime, ind
            shutil.move(child_dir + file_name, child_dir + new_name)
            ind += 1
            print ind

    # フォーマット変換
    selectFormat = imgFormatList[imgFormat.getValue()]
    if file_type != selectFormat:
        renameList = os.listdir(new_dir_path)
        listLen = len(renameList)
        print 'フォーマット確認', selectFormat, listLen
        cmd = [
            'imgcvt', '-r',
            str(startNum) + '-' + str(listLen + startNum - 1).encode('cp932'),
            new_dir_path.encode('cp932') + '/' +
            new_file_name.encode('cp932') + '.@@@@@' +
            file_type.encode('cp932'),
            currentDir.encode('cp932') + '/' + new_file_name.encode('cp932') +
            '.@@@@@' + selectFormat.encode('cp932')
        ]
        print 'test', cmd
        returncode = subprocess.call(cmd, cwd=mayaLocation)
        shutil.rmtree(new_dir_path)
        # for removeFile in renameList:
        # if removeFile.endswith(file_type):
        # os.remove(new_dir_path + '/' + removeFile)
    else:
        for img in os.listdir(new_dir_path):
            shutil.move(os.path.join(new_dir_path, img), currentDir)
        print 'new_dir_path', new_dir_path
        shutil.rmtree(new_dir_path)
    pm.setAttr(
        "%s.imageName" % imagePlaneName, currentDir + '/' + new_file_name +
        '.' + str(start_num).zfill(5) + selectFormat)
예제 #6
0
파일: apicache.py 프로젝트: cgrebeld/pymel
    def _buildApiTypeHierarchy(self) :
        """
        Used to rebuild api info from scratch.

        Set 'apiClassInfo' to a valid apiClassInfo structure to disable rebuilding of apiClassInfo
        - this is useful for versions < 2009, as these versions cannot parse the api docs; by passing
        in an apiClassInfo, you can rebuild all other api information.  If left at the default value
        of 'None', then it will be rebuilt using the apiDocParser.
        """
        def _MFnType(x) :
            if x == api.MFnBase :
                return self.apiEnumsToApiTypes[ 1 ]  # 'kBase'
            else :
                try :
                    return self.apiEnumsToApiTypes[ x().type() ]
                except :
                    return self.apiEnumsToApiTypes[ 0 ] # 'kInvalid'

        if not startup.mayaStartupHasRun():
            startup.mayaInit()
        import maya.cmds

        import pymel.mayautils as mayautils
        # load all maya plugins
        mayaLoc = mayautils.getMayaLocation()
        # need to set to os.path.realpath to get a 'canonical' path for string comparison...
        pluginPaths = [os.path.realpath(x) for x in os.environ['MAYA_PLUG_IN_PATH'].split(os.path.pathsep)]
        for pluginPath in [x for x in pluginPaths if x.startswith( mayaLoc ) and os.path.isdir(x) ]:
            for x in os.listdir( pluginPath ):
                if os.path.isfile( os.path.join(pluginPath,x)):
                    try:
                        maya.cmds.loadPlugin( x )
                    except RuntimeError: pass

        allMayaTypes = self.reservedMayaTypes.keys() + maya.cmds.ls(nodeTypes=True)

        # all of maya OpenMaya api is now imported in module api's namespace
        MFnClasses = inspect.getmembers(api, lambda x: inspect.isclass(x) and issubclass(x, api.MFnBase))
        MFnTree = inspect.getclasstree( [x[1] for x in MFnClasses] )
        self.apiTypeHierarchy = {}

        for x in expandArgs(MFnTree, type='list') :
            MFnClass = x[0]
            current = _MFnType(MFnClass)
            if current and current != 'kInvalid' and len(x[1]) > 0:
                #Check that len(x[1]) > 0 because base python 'object' will have no parents...
                parent = _MFnType(x[1][0])
                if parent:
                    self.apiTypesToApiClasses[ current ] = MFnClass
                    self.apiTypeHierarchy[ current ] = parent

        if not self.apiClassInfo:
            self._buildApiClassInfo()

        # print self.apiTypeHierarchy.keys()
        # Fixes for types that don't have a MFn by faking a node creation and testing it
        # Make it faster by pre-creating the nodes used to test
        dagMod = api.MDagModifier()
        dgMod = api.MDGModifier()
        #nodeDict = self._createNodes(dagMod, dgMod, *self.apiTypesToApiEnums.keys())
        nodeDict, mayaDict, unableToCreate = self._createNodes( dagMod, dgMod, *allMayaTypes )
        if len(unableToCreate) > 0:
            _logger.warn("Unable to create the following nodes: %s" % ", ".join(unableToCreate))

        for mayaType, apiType in mayaDict.items() :
            self.mayaTypesToApiTypes[mayaType] = apiType
            self.addMayaType( mayaType, apiType )

        # Fix? some MFn results are not coherent with the hierarchy presented in the docs :
        self.apiTypeHierarchy.pop('kWire', None)
        self.apiTypeHierarchy.pop('kBlendShape', None)
        self.apiTypeHierarchy.pop('kFFD', None)
        for k in self.apiTypesToApiEnums.keys() :
            if k not in self.apiTypeHierarchy.keys() :
                #print "%s not in self.apiTypeHierarchy, looking for parents" % k
                #startParent = time.time()
                p = self._parentFn(k, dagMod, dgMod, **nodeDict)
                #endParent = time.time()
                if p :
                    #print "Found parent: %s in %.2f sec" % (p, endParent-startParent)
                    self.apiTypeHierarchy[k] = p
                else :
                    #print "Found none in %.2f sec" % (endParent-startParent)
                    pass