def deletetab(*args):
    alltabs = mc.tabLayout ('tabs',q=1,st=1)
    chktabs = mc.tabLayout ('Animation',q=1,st=1)
    chktabs1= mc.tabLayout ('Poses',q=1,st=1)
    if alltabs == 'Animation':
        seltab = mc.tabLayout('Animation',q=1,st=1) 
        mc.deleteUI(seltab)
        Del_tab=savepathini+'Savepose/Animation/'+seltab
        Del1_in=Del_tab+'/'
        list_in=mc.getFileList(fld=Del1_in)
        for i in range(len(list_in)):
            mc.sysFile(Del1_in+'/'+list_in[i],delete=1)
        mc.sysFile(Del_tab,red=1)
        if chktabs=='':
            mc.confirmDialog (title='Error',message='No tabs to delete', button='OK',defaultButton='Yes')    
#        else :
#            return
    else :
        seltab = mc.tabLayout('Poses',q=1,st=1) 
        mc.deleteUI(seltab)
        Del_tab=savepathini+'Savepose/Poses/'+seltab
        Del1_in=Del_tab+'/'
        list_in=mc.getFileList(fld=Del1_in)
        for i in range(len(list_in)):
            mc.sysFile(Del1_in+'/'+list_in[i],delete=1)
        mc.sysFile(Del_tab,red=1)
        if chktabs1=='':
            mc.confirmDialog (title='Error',message='No tabs to delete', button='OK',defaultButton='Yes')    
        else :
            return          
Esempio n. 2
0
    def checkProjectAssetNames(self):
        import maya.cmds as mc
        shotInfo = self.checkShotInfo()

        projectPathBase = self.checkProjectServerPath(typeMode=1)

        prePath = projectPathBase + '\\scenes\\'

        charPath = prePath + 'characters\\'

        charAssets = mc.getFileList(folder=charPath)
        if charAssets:
            if 'bak' in charAssets:
                charAssets.remove('bak')
        else:
            charAssets = []

        propPath = prePath + 'props\\'

        propAssets = mc.getFileList(folder=propPath)
        if propAssets:
            if 'bak' in propAssets:
                propAssets.remove('bak')
        else:
            propAssets = []

        setPath = prePath + 'sets\\'

        setsAssets = mc.getFileList(folder=setPath)
        if setsAssets:
            if 'bak' in setsAssets:
                setsAssets.remove('bak')
        else:
            setsAssets = []

        miscPath = prePath + 'misc\\'

        miscAssets = mc.getFileList(folder=miscPath)
        if miscAssets:
            if 'bak' in miscAssets:
                miscAssets.remove('bak')
        else:
            miscAssets = []

        resultAsset = []
        resultAsset.append(charAssets + propAssets + setsAssets + miscAssets)
        resultAsset.append(charAssets)
        resultAsset.append(propAssets)
        resultAsset.append(setsAssets)
        resultAsset.append(miscAssets)
        return resultAsset
Esempio n. 3
0
def copyYetiCacheAndTex():
    allYetiCacheFiles = mc.ls(type='pgYetiMaya')
    if allYetiCacheFiles:
        for myYetiCacheFile in allYetiCacheFiles:
            #yeti缓存
            YetiCachePath = mc.getAttr('%s.cacheFileName' % myYetiCacheFile)
            if YetiCachePath:
                YetiCachePath = myChangeNetPath(YetiCachePath)
                YetiCachePath = os.path.normpath(YetiCachePath)

                YetiCacheBasePath = os.path.basename(YetiCachePath)

                oldPathCache = os.path.dirname(YetiCachePath)
                YetiPath = oldPathCache.split(type_file)[-1]
                YetiPath = CachePath + YetiPath
                YetiPath = YetiPath.replace("/", "\\")
                cacheFiles = mc.getFileList(fld=(oldPathCache + "\\"))
                if not os.path.isdir(YetiPath):
                    os.makedirs(YetiPath)
                print YetiPath
                for caches in cacheFiles:
                    print(oldPathCache + "\\" + caches)
                    shutil.copy((oldPathCache + "\\" + caches), YetiPath)
                    #mc.sysFile((oldPathCache+"\\"+caches),copy=YetiPath)

                mc.setAttr('%s.cacheFileName' % myYetiCacheFile,
                           (YetiPath + "\\" + YetiCacheBasePath),
                           type='string')
                os.startfile(YetiPath)
            #yeti贴图
            YetiTexPath = mc.getAttr('%s.imageSearchPath' % myYetiCacheFile)
            if YetiTexPath:
                YetiCachePath = myChangeNetPath(YetiCachePath)
                YetiTexPath = YetiTexPath.replace("/", "\\")
                YetiTexPath = os.path.normpath(YetiTexPath)
                YetiPath = YetiTexPath.split("sourceimages")[-1]
                YetiPath = sourcePath + YetiPath
                YetiPath = YetiPath.replace("/", "\\")
                YetiTexFiles = mc.getFileList(fld=(YetiTexPath + "\\"))
                print YetiTexFiles
                if not os.path.isdir(YetiPath):
                    os.makedirs(YetiPath)
                for Tex in YetiTexFiles:
                    print(YetiTexPath + "\\" + Tex)
                    shutil.copy((YetiTexPath + "\\" + Tex), YetiPath)

                mc.setAttr('%s.imageSearchPath' % myYetiCacheFile,
                           YetiPath,
                           type='string')
                os.startfile(YetiPath)
Esempio n. 4
0
 def CopyTexture(self):
     allFile=mc.ls(type="file")
     fullPath=mc.workspace(expandName="sourceimages")
     filePath=""
     fileName=""
     fileNames=""
     for files in allFile:
         buf=[]
         path=mc.getAttr("%s.fileTextureName"%files)
         if path=="":
             continue
         path = path.replace('\\','/')
         
         filePath=os.path.dirname(path)
         fileName=os.path.basename(path) 
         
         if mc.getAttr("%s.useFrameExtension"%files):
             fileNames=fileName.split(".")
             buffers=mc.getFileList(filespec=(os.path.dirname(path)+"/*"))
             for buffer in buffers:
                 NewFile = filePath+"/"+buffer
                 if os.path.isfile(NewFile):
                     buf.append(NewFile)
         # ==========2018.12.11===========add by zhangben ========== fix the file nodes use the tilling mode,the tool can't copy all maps=
         elif mc.attributeQuery('uvTilingMode', node=files, exists=True) and mc.getAttr('{}.uvTilingMode'.format(files)) == 3:
             fileNames = fileName.split(".")
             buffers = mc.getFileList(filespec=(os.path.dirname(path) + "/*"))
             for eamap in buffers:
                 map_bnm = re.sub(u'_\d+', '', fileNames[0])
                 if eamap.find(map_bnm) != -1 and eamap.split('.')[-1] == fileNames[-1]:
                     mapPath = filePath + "/" + eamap
                     buf.append(mapPath)
         # ===============================================================================================================================
         else:
             buf.append(path)  
         paths=filePath.split("/")[-1]   
         for i in buf:
             fileNames=os.path.basename(i)
             if not os.path.isdir(fullPath+"/"+paths):
                 os.makedirs(fullPath+"/"+paths)
                 mc.sysFile(i,copy=(fullPath+"/"+paths+"/"+fileNames))
             else:
                 if not os.path.exists(fullPath+"/"+paths+"/"+fileNames) or (os.path.exists(fullPath+"/"+paths+"/"+fileNames) and os.path.getsize(fullPath+"/"+paths+"/"+fileNames) != os.path.getsize(i)):
                     mc.sysFile(i,copy=(fullPath+"/"+paths+"/"+fileNames))
                     
         if os.path.isfile(fullPath+"/"+paths+"/"+fileName):
             print (fullPath+"/"+paths+"/"+fileName)
             mc.setAttr("%s.fileTextureName"%files,(fullPath+"/"+paths+"/"+fileName),type="string")
Esempio n. 5
0
    def createBlendNode(self):

        files = cmds.getFileList(folder=PATH_OF_FILES, filespec="*.{}".format(FILE_TYPE))
        
        if files:
            for x in files:
                cmds.file(PATH_OF_FILES + "/" + x, i=True, defaultNamespace=True)
        else:
            cmds.warning("No files found")

        print ("------------complete-faceShape-imports--------------")

        cmds.file(HEAD_PATH, i=True, defaultNamespace=True)
        pm.rename(NEUTRAL, "bsMan_fRig_PLY")

        fShapes = []
        for x in files:
            item = x.split(".")
            fShapes.append(item[0])

        pm.select(fShapes)
        pm.blendShape(fShapes, "bsMan_fRig_PLY", name="faceShapes_BSN")
        pm.delete(fShapes)

        print ("------------complete---blending-Of-faceShapes--------------")
        
        pm.select(clear=True)
        pm.select("bsMan_fRig_PLY")
        cmds.file(OUT_BLEND_PATH + "\\" + BSMAN_NAME, type="mayaAscii", force=True, exportSelected=True)

        print ("------------complete---exporting-Of-blendNode--------------")

        pm.delete("bsMan_fRig_PLY")
Esempio n. 6
0
def creaLayout(parentL=""):
    posesEnM = mc.getFileList(folder="x:\PH_SCRIPTS\ICONS\POSES",
                              filespec='*.png')
    posesEnM.sort()
    indice = 0
    lay0 = mc.columnLayout(cat=["both", 0],
                           adjustableColumn=1,
                           cal="center",
                           p=parentL)
    lay1 = mc.rowColumnLayout(rowSpacing=[1, 1], numberOfColumns=3, p=lay0)
    for i in range(len(posesEnM)):
        mc.iconTextButton(style='iconOnly',
                          image1='x:\PH_SCRIPTS\ICONS\POSES\\' + posesEnM[i],
                          width=100,
                          height=65,
                          c=partial(cargaPose, posesEnM[i][:-4]),
                          dcc=partial(cargaPose, posesEnM[i][:-4], 1),
                          ann=posesEnM[i][:-4].replace("_", " "))
    lay2 = mc.columnLayout(cat=["both", 0],
                           adjustableColumn=1,
                           cal="center",
                           p=lay0,
                           bgc=[0.23, 0.23, 0.23])
    mc.text(
        p=lay2,
        l="""Un click izquierdo asigna pose a mano izquierda. \nDoble click izquierdo asigna pose a mano derecha. \nDebido a que la mano derecha esta mal riggeada,\nel pulgar derecho lo van a ver raro.\n
	Si todo lo seleccionado es un 'hikFKJoint',\n carga esos huesos de la pose.\nSi lo seleccionado no es 'hikFKJoint',\n carga la pose entera."""
    )
    mc.separator(p=lay2)
Esempio n. 7
0
def import_maps(srcTextField):
    folderName = cmds.textField(srcTextField, query=True, text=True)

    if not folderName:
        cmds.error("No folder selected.")
        return


    #Create aiStandardSurface and shading group node
    baseMatName = os.path.basename(os.path.normpath(folderName))
    surfaceName = cmds.shadingNode('aiStandardSurface', name=baseMatName + '_mat', asShader=True)
    SGName = cmds.sets(name=baseMatName + '_SG', empty=True, renderable=True, noSurfaceShader=True)
    cmds.connectAttr(surfaceName + '.outColor', SGName + '.surfaceShader')


    #Find the relevant files in the folder and create the file nodes
    fileList = cmds.getFileList( folder=folderName, filespec='*.png')

    nodesCreated = 0;
    totalNodes = 0;
    for suffix in [BASE_COLOR, METALNESS, ROUGHNESS, NORMAL]:
        totalNodes = totalNodes + 1;

        for fileName in fileList:
            if(suffix in fileName):
                createTexNodeByType(folderName, fileName, surfaceName, suffix)
                nodesCreated = nodesCreated + 1;

    #Sanity check
    if nodesCreated != totalNodes:
        cmds.error("Made " + nodesCreated + " file nodes, expected " + totalNodes + ". Check file names?")

    return
Esempio n. 8
0
    def load_existing_library(self):
        # select existing lib folder. If obj's exist, skip, or if not
        # check for thumbnail image and load the obj's into new cells
        file_type = "obj"
        libfolder_le_text = self.libraryload_le.text()

        if not libfolder_le_text:
            self.show_folder_select_dialog()
        else:
            files = cmds.getFileList(folder=libfolder_le_text, filespec='*.%s' % file_type)

            if len(files) == 0:          
                cmds.warning("No Files to Import")
            else:
                for f in files:
                    obj_name = os.path.splitext(f)[0]
                    self.create_filepath(obj_name)
                    obj_exists = self.check_obj_exists(self.filename)[0]
                    if not obj_exists:
                        emptyIndex = self.find_empty_cell()
                        obj_img_name = os.path.join(self.img_path, obj_name + ".jpg")
                        obj_img_name = os.path.normpath(obj_img_name)
                        img_exists = cmds.file(obj_img_name, q=True, ex=True)
                        if img_exists:
                            cropImage = self.create_img(obj_img_name)
                            self.add_cell(emptyIndex, cropImage, True)
                        else:
                            self.add_cell(emptyIndex, None, False)
                    else:
                        print("{0} ".format(obj_name) + "already exists")
def cGetPath(action, *args):
    defaultPath = "X:/zorro_zor-5069/_library/assets/characters/chr_zorroFox/cfx_groom/"

    if action == 'default':
        cmds.textField('tfPathxGen', tx=defaultPath, e=1)
        cmds.textField('xGenVersion', tx=approvedxGen, e=1)

    if action == 'choose':
        xGenPath = cmds.fileDialog2(fm=2,
                                    ds=1,
                                    dir=defaultPath,
                                    cap='Select Directory')
        cmds.textField('tfPathxGen', tx=xGenPath[0] + '/', e=1)
        files = cmds.getFileList(filespec='*.xgen', fld=xGenPath[0])

        if files:
            if approvedxGen not in files:
                cmds.textField('xGenVersion',
                               tx='Choose a xGen Collection!',
                               e=1)

        else:
            cmds.textField('xGenVersion',
                           tx='No xGen descriptions in that Folder!',
                           e=1)
Esempio n. 10
0
def stMapPath(proj):

    #Gets the correct filename
    temp = string.split(proj, '/')
    seq = "sc" + temp[6]
    shot = "sh" + temp[7]

    pubDir = ('/mnt/projects/tt/publish/scenes/' + seq + '/' + shot +
              '/distortion/')

    distortion = []
    distortion = str(cmds.getFileList(fld=pubDir, fs='*distorted.exr'))
    distortion = distortion[3:-2]
    print "Looking for {}".format(distortion)

    dirList = str(pubDir) + str(distortion)
    fileExists = os.path.exists(dirList)

    global distortionFilename
    distortionFilename = pubDir + "tt_{}_{}_distorted.exr".format(seq, shot)

    if fileExists == True:

        mapPath = dirList
        print "File exists: {} ".format(dirList)
        return mapPath
        exists = True

    else:
        return
Esempio n. 11
0
    def getBackFile(self, dirPath, fileName):

        dirBackPath = os.path.join(dirPath, "Backups").replace("\\", "/")
        newfileName = os.path.splitext(fileName)[0]

        listDir = mc.getFileList(fld = dirBackPath, fs = "%s*"% newfileName)

        newNum = ""
        if listDir:
            num = int(sorted(listDir)[-1][-3:]) + 1
            newNum = "%03d" % num
        else:
            newNum = "001"

        bakName = "%s_c%s" % (newfileName, newNum)
        createDirName = os.path.join(dirBackPath, "%s_c%s" % (newfileName, newNum))

        createDirName = createDirName.replace("/", "\\")
        self.getCreateDir(createDirName)

        sourceFile = os.path.join(dirPath, fileName).replace("/", "\\")
        destFile = os.path.join(createDirName, fileName).replace("/", "\\")

        self.getCopyFile(sourceFile, destFile)

        self.delSourceFile(sourceFile)
        return bakName
Esempio n. 12
0
def mkSyncPresets():
	dstFile				=			mkSharePreset()
	presetfiles			=			cmds.getFileList( folder=dstFile)
	for entry in presetfiles:
		presetFullPath	=			dstFile + entry
		distutils.dir_util.copy_tree( presetFullPath, localPresetPath + entry )
	print ("files copied to " + localPresetPath)
Esempio n. 13
0
def mkSyncPresets():
    dstFile = mkSharePreset()
    presetfiles = cmds.getFileList(folder=dstFile)
    for entry in presetfiles:
        presetFullPath = dstFile + entry
        distutils.dir_util.copy_tree(presetFullPath, localPresetPath + entry)
    print("files copied to " + localPresetPath)
Esempio n. 14
0
def QSR_SearchReferencesInFolder():
    global qsr_planes

    refDir = cmds.fileDialog2(dialogStyle=1, fileMode=3)

    # I do stuff on the directory only if it's not empty
    if refDir is None:
        cmds.confirmDialog(m='Please enter a valid directory path')
        return

    directory = refDir[0]
    files = cmds.getFileList(folder=directory)

    for file in files:
        # If the path is empty I don't add the plane
        if file is None:
            continue

        if re.search(r'top', file):
            qsr_planes[QSR_PlaneType.TOP] = directory + '/' + file
        elif re.search(r'bottom', file):
            qsr_planes[QSR_PlaneType.BOTTOM] = directory + '/' + file
        elif re.search(r'left', file):
            qsr_planes[QSR_PlaneType.SIDE_L] = directory + '/' + file
        elif re.search(r'right', file):
            qsr_planes[QSR_PlaneType.SIDE_R] = directory + '/' + file
        elif re.search(r'front', file):
            qsr_planes[QSR_PlaneType.FRONT] = directory + '/' + file
        elif re.search(r'back', file):
            qsr_planes[QSR_PlaneType.BACK] = directory + '/' + file

    RefreshAllUIImgPath()
def savefolder(savepathini):
    newpath=mc.fileDialog2(ds = 1, fm = 3)
    if newpath:
        chkpath= newpath[0]+'/'
        counts=mc.getFileList (folder=chkpath)
        nc=counts.count('SavePose')
        if not nc:
            cofirm_but=mc.confirmDialog( title='Confirm', message='Do u want to create a new library in '+newpath[0]+ '   ??', button=['Yes','No'], defaultButton='Yes', cancelButton='No', dismissString='No' )
            if cofirm_but=='Yes':
                getMnuItms=mc.menu('chgFld',q=1,ia=1)
                if len(getMnuItms) >= 7:
                    mc.deleteUI(getMnuItms[3],mi=1)
                getMnuItms=mc.menu('chgFld',q=1,ia=1)    
                getItmLab=[]
                for each in getMnuItms:
                    lab=mc.menuItem(each,q=1,l=1)
                    getItmLab.append(lab)  
                if newpath:
                    if newpath[0] not in getItmLab:
                        mc.menuItem(label=newpath[0],p='chgFld',c=partial(changepath,newpath))
                savepathini=newpath[0]
            else:
                return
        else:
            savepathini=newpath[0]      
    else:
        return 
    Refresh_UI(savepathini)
    temp_path(savepathini)
Esempio n. 16
0
def get_textures_info(*args):
    global textures
    
    dir = cmds.textField('dirTextCtrl', q=True, text=True)
    files = cmds.getFileList(folder=dir, filespec='*.png')
    files.sort()
    textures = []

    items = cmds.optionMenu('textureOptionCtrl', q=True, itemListLong=True)
    if items:
        cmds.deleteUI(items)
    
    for file_name in files:
        match = re.search(r'(.+)_(BaseColor|Height|Normal|Roughness|Metalness)\.(.+)\.', file_name)
        
        if match:
            texData = match.groups()
            new_tex = TextureInfo(file_name, texData[0], texData[1], texData[2].isdigit())

            if new_tex.is_tiled:
                new_tex.set_udim(texData[2])
            else:
                new_tex.set_material_name(texData[2])

            textures.append(new_tex)
            
    for tex in {t.name for t in textures}:
        cmds.menuItem(label=tex)
    
    cmds.optionMenu(textureOptionCtrl, edit=True, enable=True, changeCommand=change_texture_map)
    change_texture_map(textures[0].name)
Esempio n. 17
0
        def __setFileTextureName():
            if userDefinedPath == '':
                projectPath = mc.workspace(o =1 ,q =1)
                targetPath = projectPath + r'/' + 'sourceimages/'

            elif userDefinedPath[:2] == r'//' or userDefinedPath[:2] == r'\\' :
                relativePath = userDefinedPath[2:]
                projectPath = mc.workspace(o =1 ,q =1)
                targetPath = projectPath + r'/' + 'sourceimages/' + relativePath + r'\\'
            else:
                targetPath = userDefinedPath + r'\\'

            allFileNames = mc.getFileList(folder = targetPath)
            haveThisTexture = False
            if allFileNames is not None:
                for fileName in allFileNames:

                    if materialName in fileName and specificAttrName in fileName:
                        haveThisTexture = True
                        self.fileTextureName = targetPath + fileName
                        break
                if not haveThisTexture:
                    mc.warning('no ' + self.specificAttrName + ' texture exist' )
            else:
                mc.error('the folder is empty')
Esempio n. 18
0
def mkCopyPresets():
    print userName
    dstFile = mkSharePreset()
    presetfiles = cmds.getFileList(folder=localPresetPath)
    for entry in presetfiles:
        presetFullPath = localPresetPath + entry
        distutils.dir_util.copy_tree(presetFullPath, dstFile + entry)
    print("files copied to " + dstFile)
Esempio n. 19
0
def mkCopyPresets():
	print userName
	dstFile				=			mkSharePreset()
	presetfiles			=			cmds.getFileList( folder=localPresetPath )
	for entry in presetfiles:
		presetFullPath	=			localPresetPath + entry
		distutils.dir_util.copy_tree( presetFullPath,dstFile + entry )
	print ("files copied to " + dstFile)
Esempio n. 20
0
def searchScripts():
    searchTxt = cmds.textField('searchField', q=True, tx=True)
    print('Searching for Scripts  ' + searchTxt)
    cmds.textScrollList('searchResultList', ra=True, e=True)
    flist = cmds.getFileList(
        folder="B:/Eternal_Code_Directory/Code_Search_Index",
        filespec=('*' + searchTxt + '*'))
    for i in flist:
        cmds.textScrollList('searchResultList', e=True, a=i)
Esempio n. 21
0
    def p(self):  
        pathA=self.pathA1[0:]
        getpath=cmds.textField('Path',q=True,tx=True)
        delto=getpath.replace('\\','/')
        path=delto+'/'    
        trvsel=cmds.treeView('ok',q=True,si=True)
        trvselP=cmds.treeView('ok',q=True,ip=trvsel[0])
        object=cmds.tabLayout('tuplistlayout',q=True,st=True)
        Path1=path+trvselP+'/'+trvsel[0]+'/'+object[0:]+'/'
        id1=cmds.getFileList(folder=Path1)
        slLc=cmds.scrollLayout(object[0:],q=True,ca=True)
        #cmds.rowColumnLayout('RowL',numberOfColumns=1,p=object[0:])
        if slLc!=None:
            for slLcobj in slLc:
                cmds.deleteUI(slLcobj,control=True)
        else:
            print '没有'
        if cmds.formLayout('RowL',ex=True):
             cmds.deleteUI('RowL')
        #cmds.rowColumnLayout('RowL',numberOfColumns=1,p=object[0:])  
        cmds.formLayout('RowL',p=object[0:]) 
        ksymbolButtonk=[] 
        ktextk=[]
        k_tW=100
        k_tH=100 
        k_tH=20     
            
        for i in range(len(id1)):
            pic=[w for w in os.listdir(Path1+id1[i]+'/') if w.endswith('.jpg')]
            pp=Path1+id1[i]+'/'
            #cmds.symbolButton(image=(Path1+id1[i]+'/'+pic[0]),ann='oo',p='RowL',w=100,h=100,c=partial(self.showFileInfo,(Path1+id1[i]+'/'))) #增加图片按钮 
            ksymbolButtonk.append(cmds.symbolButton(image=(Path1+id1[i]+'/'+pic[0]),p='RowL',w=k_tW,h=k_tH,c=partial(self.showFileInfo,(Path1+id1[i]+'/'))))#增加图片按钮                    
            cmds.popupMenu()
            cmds.menuItem(l=u'导入动画数据',c = partial(self.eidtpath,(Path1+id1[i]+'/')))
            cmds.menuItem(l=u'观看视频!',c=self.OPENVIDEO)
            cmds.menuItem(l=u'打开文件夹!',c=self.OPENFILE)
            cmds.menuItem(l=u'打开文件!',c=self.OPENMB)
            cmds.menuItem(l=u'信息查看与动画截取',c=self.editaniwin)
            #cmds.text(l=id1[i],p='RowL')
            ktextk.append(cmds.iconTextButton (style=('textOnly'),enable=0,l=id1[i],w=k_tW,h=k_tH,p='RowL'))
            self.editSBsize()
            
        for o in range(len(id1)):
            if o==0:
                cmds.formLayout('RowL',e=True,attachPosition=((ksymbolButtonk[o],'top',0,0),(ksymbolButtonk[o],'left',0,0)))
            elif o==1:
                cmds.formLayout('RowL',e=True,attachPosition=(ksymbolButtonk[o],'top',0,0),attachControl=(ksymbolButtonk[o],'left',0,ksymbolButtonk[o-1]))
            elif o%2==1:  
                cmds.formLayout('RowL',e=True,attachControl=((ksymbolButtonk[o],'top',0,ktextk[o-2]),(ksymbolButtonk[o],'left',0,ksymbolButtonk[o-1])))
            else:
                cmds.formLayout('RowL',e=True,attachControl=(ksymbolButtonk[o],'top',k_tH,ksymbolButtonk[o-2]),attachPosition=(ksymbolButtonk[o],'left',0,0))

        for u in range(len(id1)):
            if u%2==1:
                cmds.formLayout('RowL',e=True,attachControl=((ktextk[u],'top',0,ksymbolButtonk[u]),(ktextk[u],'left',0,ktextk[u-1])))
            else:
                cmds.formLayout('RowL',e=True,attachControl=(ktextk[u],'top',0,ksymbolButtonk[u]),attachPosition=(ktextk[u],'left',0,0))            
Esempio n. 22
0
def getFiles(folder, fileTypes=['obj', 'fbx']):
    files = []

    for fileType in fileTypes:
        files += (cmds.getFileList(folder=folder, filespec='*.%s' % fileType))

    for i in range(len(files)):
        files[i] = '%s\%s' % (folder, files[i])

    return files
Esempio n. 23
0
def displayRefs(refDir):
    if cmds.columnLayout("refContainer", q=True, exists=True):
        cmds.deleteUI("refContainer", layout=True)

    storage.unityRefs.clear()
    cmds.columnLayout("refContainer", p="refWraper")
    cmds.radioCollection("unityRefs")
    refFbx = cmds.getFileList(folder=refDir, filespec="*.fbx") or []
    refObj = cmds.getFileList(folder=refDir, filespec="*.obj") or []
    cmds.button('unityImportRef',
                e=True,
                enable=len(refFbx) > 0 or len(refObj))

    refStorage(refFbx)
    refStorage(refObj)

    cmds.text(l="")
    cmds.setParent('..')
    cmds.setParent('..')
Esempio n. 24
0
def projectsSearch():
    MAYA_SCRIPT_PATH = mm.eval('getenv "MAYA_SCRIPT_PATH";')
    #加载各项目到MAYA_SCRIPT_PATH里
    projRoot = r"\\octvision.com\cg\Tech\maya_sixteen\scripts\Themes"
    ret = mc.getFileList(folder=projRoot)
    for item in ret:
        subfolder = projRoot + item
        if os.path.isdir(subfolder):
            MAYA_SCRIPT_PATH += ";" + subfolder
            mm.eval('putenv "MAYA_SCRIPT_PATH" "%s";' % MAYA_SCRIPT_PATH)
Esempio n. 25
0
 def HbChangeReSets4(self, projectInfo):
     questSets = mc.optionMenu("EPNUM", q=True, v=True)
     questEP = mc.optionMenu("EP", q=True, v=True)
 
     for m in range(1000):
         mc.menuItem("TheMenuItem" + str(m), e=1, en=0, label="        ")    
     TheFileList = mc.getFileList(folder="//file-cluster/GDC/Projects/" + projectInfo + "/" + projectInfo + "_Scratch/TD/SetCam/" + questEP + "/")
 
     if TheFileList != None:
         for i in range(len(TheFileList)):
             mc.menuItem("TheMenuItem" + str(i), e=1, en=1, label=TheFileList[i])
 
     questEP = mc.optionMenu("EP", q=True, v=True)
     questSets = mc.optionMenu("EPNUM", q=True, v=True)
     for m in range(0, 100):
         mc.iconTextButton("Temp" + str(m), e=1, visible=0 , style='iconAndTextVertical', image1="sphere.xpm")
         # popupMenu("ThePopup"+str(m))
         mc.menuItem("TheObMenu" + str(m), e=1)
         mc.menuItem("Cancle" + str(m), e=1)
 
     mc.sysFile("//file-cluster/GDC/Projects/" + projectInfo + "/" + projectInfo + "_Scratch/TD/SetCam/" + questEP + "/" + questSets + "/images/", makeDir=True)
 
     try:
 
         TheUpDateSc = os.listdir("//file-cluster/GDC/Projects/" + projectInfo + "/" + projectInfo + "_Scratch/TD/SetCam/" + questEP + "/" + questSets + "/images/")
         TheBmp = []
 
         for i in range(len(TheUpDateSc)):
             if TheUpDateSc[i].split(".")[-1] == "bmp":
                 TheBmp.append(TheUpDateSc[i])    
         for j in range(len(TheBmp)):
             theCommand = 'HbImportReCam(\"' + TheBmp[j] + '\")'
             theCommand2 = 'HbImageOk(\"' + TheBmp[j] + '\")'
             theCommand3 = 'HbCancleHook(\"' + TheBmp[j] + '\")'
             mc.iconTextButton("Temp" + str(j) , e=1, visible=1, bgc=(1, 1, 1), style='iconAndTextVertical', image1=("//file-cluster/GDC/Projects/" + projectInfo + "/" + projectInfo + "_Scratch/TD/SetCam/" + questEP + "/" + questSets + "/images/" + TheBmp[j]), label=TheBmp[j].split(".")[0], c=theCommand)
             mc.menuItem("TheObMenu" + str(j), e=1, l="This Camera is ok", c=theCommand2)
             mc.menuItem("Cancle" + str(j), e=1, l="cancle the hook", c=theCommand3)
 
         mc.text("TheNumber", e=1, bgc=(1, 0.9, 0.9), label=str(len(TheBmp)), align='center')
         questTheNum = mc.intField("TheNumber", q=1, v=1)
         if float(questTheNum) != 0:
             TheStr = str(float(len(TheBmp)) / float(questTheNum) * 100) + "%"
             mc.text("part", e=1, bgc=(0, 1, 0), label=TheStr, align='center')
         if float(questTheNum) == 0:
             mc.text("part", e=1, bgc=(0, 1, 0), label="erro", align='center')
 
         try:
             TheOKDateSc = os.listdir("//file-cluster/GDC/Projects/" + projectInfo + "/" + projectInfo + "_Scratch/TD/SetCam/" + questEP + "/" + questSets + "/images/old/")
             mc.text("TheOkNumber", e=1, bgc=(1, 0.9, 0.9), label=len(TheOKDateSc), align='center')
         except:
             mc.text("TheOkNumber", e=1, bgc=(1, 0.9, 0.9), label=0, align='center')
     except:
         pass
 
     self.HbShowDateLibSc(projectInfo)
 def add_items(self):  # add all assets to table
     self.tableWidget.clearContents()
     folder_path = self.input_file_path()
     print folder_path
     # filter = [".ma", ".mb"]
     all_assets = mc.getFileList(folder=folder_path, fs="*.ma")
     all_assets.extend(mc.getFileList(folder=folder_path, fs="*.mb"))
     i = 0
     if all_assets:
         self.tableWidget.setRowCount(len(all_assets))
     for _ in all_assets:
         label = _
         new_item = QtWidgets.QTableWidgetItem(label)
         new_item1 = QtWidgets.QTableWidgetItem(label.split(".")[0])
         new_item2 = QtWidgets.QTableWidgetItem("1")
         self.tableWidget.setItem(i, 0, new_item)
         self.tableWidget.setItem(i, 1, new_item1)
         self.tableWidget.setItem(i, 2, new_item2)
         i += 1
     return True
Esempio n. 27
0
    def get_scripts(self):
        uad = cmds.internalVar(uad=True)
        scripts_standalone = "{uad}scripts/ncTools/tools/standalone".format(
            uad=uad)
        files = cmds.getFileList(fld=scripts_standalone, fs="*.py")
        files.remove("__init__.py")
        G.standalones.scripts = []

        for script in files:
            script = script.rpartition(".")[0]
            G.standalones.scripts.append(script)
Esempio n. 28
0
    def XMDBatchConvert(self, fbxpath, xmdpath):

        fbxfiles = cmds.getFileList(folder=fbxpath, filespec='*.fbx')

        if len(fbxfiles) < 1:
            print "Error: There are no FBX/MA files in this directory, Please select one that does"
        else:
            for i in fbxfiles:

                self.XMDSingleConvert(fbxpath + '/' + i, xmdpath)

            print 'Exporting Finished!'
Esempio n. 29
0
    def get_seq_texture(path):
        fileNames = path.split(".")
        filePath = os.path.dirname(path)
        fileName = os.path.basename(path)
        fileName_spl = os.path.splitext(fileName)
        buffers = mc.getFileList(filespec=(os.path.dirname(path) + "/*"))
        re_num = re.compile('[_.]\d+')
        if not re_num.search(fileName_spl[0]): return [path]
        map_bnm = re_num.sub('', fileName_spl[0])
        return ["{}/{}".format(filePath, eamap) for eamap in buffers if eamap.find(map_bnm) != -1 and eamap.split('.')[-1] == fileName_spl[-1].split('.')[-1]]

#changenNetworkPath().changenNetworkPathUI()
Esempio n. 30
0
def add_random_textures():

    # A path to each .tx file in the sourceimages directory is stored in a list.
    texture_path = cmds.workspace(q=True, rootDirectory=True) + "sourceimages/"
    texture_names = cmds.getFileList(folder=texture_path, filespec='*.tx')

    # To make sure the full path to the texture us correct, the path to the workspace is appended to the front.
    length = len(texture_names)
    for i in range(0, length):
        texture_names[i] = texture_path + texture_names[i]

    # The paths are then assigned to each member of the group.
    add_map("map", texture_names)
Esempio n. 31
0
def jpmAW_populateFileList(alpha):
    ##get the path information
    ##clear the file list
    ##get a list of all files in the path
    ##add each file to the appropriate file list

    path = cmds.optionVar(q="jpmAWpath") + "/"
    cmds.optionVar(iv=("jpmAWalpha", alpha))

    if path == 0:
        jpmAW_setPathDialog()
    nmFiles = []
    pszFiles = []
    slcFiles = []
    cmds.textScrollList("jpmAW_animFileList", e=1, ra=1)
    cmds.textScrollList("jpmAW_poseFileList", e=1, ra=1)
    cmds.textScrollList("jpmAW_selFileList", e=1, ra=1)

    nmFiles = cmds.getFileList(fld=path, fs="*.nm8")
    pszFiles = cmds.getFileList(fld=path, fs="*.psz")
    slcFiles = cmds.getFileList(fld=path, fs="*.slc")

    if alpha:
        if len(nmFiles) > 1:
            nmFiles.sort()
        if len(pszFiles) > 1:
            pszFiles.sort()
        if len(slcFiles) > 1:
            slcFiles.sort()

    if nmFiles != "":
        for nm in nmFiles:
            cmds.textScrollList("jpmAW_animFileList", e=1, a=nm)
    if pszFiles != "":
        for psz in pszFiles:
            cmds.textScrollList("jpmAW_poseFileList", e=1, a=psz)
    if slcFiles != "":
        for slc in slcFiles:
            cmds.textScrollList("jpmAW_selFileList", e=1, a=slc)
Esempio n. 32
0
def creaLayout(parentL=""):
    posesEnM = mc.getFileList(folder="M:\PH_SCRIPTS\ICONS\POSES",
                              filespec='*.png')
    posesEnM.sort()
    indice = 0
    mc.rowColumnLayout(numberOfColumns=3, p=parentL)
    for i in range(len(posesEnM)):
        mc.iconTextButton(style='iconOnly',
                          image1='M:\PH_SCRIPTS\ICONS\POSES\\' + posesEnM[i],
                          width=150,
                          height=150,
                          c=partial(cargaPose, posesEnM[i][:-4]),
                          dcc=partial(cargaPose, posesEnM[i][:-4], 1),
                          ann=posesEnM[i][:-4].replace("_", " "))
Esempio n. 33
0
def batch_import(type=''):
	'''Import all files of the same type from a specified folder'''
	if file_type == '':
		file_type = "obj"

	folder_path_list = cmds.fileDialog2(fm=3)
	folder_path = folder_path_list[0] + '/'

	files = cmds.getFileList(folder=folder_path, filespec='*.%s' % file_type)
	if len(files) == 0:
	    cmds.warning("No files found")
	else:
	    for f in files:
	        cmds.file(folder_path + f, i=True)
Esempio n. 34
0
def clear(*args):
    posesel=[]
    seltab = mc.shelfTabLayout('tabs',q=1,st=1)
    seltab1= mc.shelfTabLayout(seltab,q=1,st=1)
    seltab2= mc.shelfLayout(seltab1,q=1,ca=1)
    
    if seltab2==None :
        NoTab(seltab)
    else:
        confirm=mc.confirmDialog(message='Do you want to delete all '+seltab+' in the selected tab ?', 
            ma='center', button=['Yes','No'] ,defaultButton='Yes',cancelButton='No',dismissString='No')
        if confirm=='Yes':
            seltab1= mc.shelfTabLayout(seltab,q=1,st=1)
            #seltab2= mc.shelfLayout(seltab1,q=1,ca=1)
            posesel= mc.shelfLayout(seltab1,q=1,ca=1)
            for i in range (len(posesel)):
                    print posesel[i]            
                    mc.deleteUI(posesel[i])
                #return
            deletefold=savepathini+'savepose/'+seltab+'/'+seltab1+'/'
            seltab1= mc.shelfTabLayout(seltab,q=1,st=1)
            list_in=mc.getFileList(fld=deletefold)
            for i in range(len(list_in)):
                mc.sysFile(deletefold+list_in[i],delete=1)
def BatchAnimExport():
    '''
    алгоритм работы скрипта, который создает ref позы для персонажей
    проверяет, существует ли ref .fbx
    если да 
        копирует .fbx в работу папку
    если нет
        создает .fbx
        копирует в рабочую папку
    '''
    
    # coding=1251
    
    import maya.cmds as cmds
    import maya.mel as mel
    import os
    import re
    import sys
    
    # вызываю окно, куда вписываю имя рабочей папки, 'case_dialogue'
    result = cmds.promptDialog(
    		title='working dir name',
    		message='add working dir',
    		button=['OK', 'Cancel'],
    		defaultButton='OK',
    		cancelButton='Cancel',
    		dismissString='Cancel')
    
    if result == 'OK':
        workingName = cmds.promptDialog(query=True, text=True)
        workingDirName = workingName.upper() + '\\'
    
    if result == 'Cancel':
        sys.exit('Cancelled')
    
    # задаю рабочий каталог
    workDirPath = 'e:\SH8\.dialogues\\'
    # задаю рабочий каталог для настроеных персонажей
    animChrPath = 'e:\SH8\.dialogues\.crhs\\'
    # задаю рабочий каталог для настроеных персонажей
    refFbxDir = 'e:\SH8\.dialogues\.crhs\.fbx_ref\\'
    # задаю путь, где хранятся .fbx анимации
    animFBXDir = 'anims_FBX\\'
    # задаю путь, где хранятся .fbx анимации
    animMBDir = 'anims_MB\\'
    # задаю приставку для названия ref анимаций
    refPrefix = '_face_10_fr_ref.fbx'
    
    log = '\n---------- export log:----------\n'
    
    # папкарабочего диалога
    animListDir = workDirPath + workingDirName
    # путь к файлу, где содержится список анимаций
    animListName = animListDir + workingName + '_anim_list.txt'
    # путь к папке .fbx анимаций рабочего диалога
    animFBXPath = workDirPath + workingDirName + animFBXDir
    # путь к папке .mb анимаций рабочего диалога
    animMBPath = workDirPath + workingDirName + animMBDir
    # составляю список из файлов, настроеных chr templates
    chrMBList = cmds.getFileList(fs = '*.mb', fld = animChrPath) 
    # составляю список из файлов, .fbx ref анимаций chr templates
    refAnimList = cmds.getFileList(fs = '*.fbx', fld = refFbxDir) 
    # составляю список из файлов, .fbx ref анимаций chr templates
    animMBList = cmds.getFileList(fs = '*.mb', fld = animMBPath) 
    # создаю список для лицевых контроллеров
    ctrlsList = cmds.ls('*_ctrl')
    
    # получаю длину списка анимаций для проверки кол-ва выполненых действий
    animListForLen = open(animListName,'r')
    animLenLines = animListForLen.readlines()
    animListLen = len(animLenLines)
    animListForLen.close()
    
    # функция, которая определяет, какие персонажи используются в диалоге по anim_list.txt и списку chr templates
    def CompareLists(searchInList, searchForList):
        searchList = ''
        for searchInString in searchInList:
            for searchForString in searchForList:
                searchForString = searchForString.split('.')
                if searchForString[0].lower() in searchInString:
                    if not searchForString[0].lower() in searchList:
                        if searchList == '':
                            searchList += searchForString[0].lower()
                        else:
                            searchList += ' ' + searchForString[0].lower()
        return searchList
    
    # сохраняю результат в переменную
    crhsInDialogue = CompareLists(animLenLines, chrMBList)
    
    # копирую в рабочу .fbx папку .fbx ref anims
    for chr in crhsInDialogue.split(' '):
        if os.path.exists(refFbxDir + chr + refPrefix):
            cmds.sysFile(refFbxDir + chr + refPrefix, cp = animFBXPath + chr + refPrefix)
        # если .fbx ref anim не сущетсвует, создаю его
        if not os.path.exists(refFbxDir + chr + refPrefix):
            cmds.file(animChrPath + chr + '.mb', o = True, f = True)
            # запекаю анимации на timeline для всех костей
            fullSkeletonList = cmds.ls(type = 'joint')
            cmds.select(fullSkeletonList)
            cmds.cutKey()
            cmds.bakeResults(fullSkeletonList, t=(0,10), simulation=True, sb=1) 
            # делаю экспорт выделенных костей в .fbx с именем файла
            cmds.select(fullSkeletonList)
            mel.eval('string $refFbxDir = `python "refFbxDir"`;')
            mel.eval('string $chrName = `python "chr"`;')
            mel.eval('string $refPrefix = `python "refPrefix"`;')
            mel.eval('FBXExportConstraints -v 0')
            mel.eval('FBXLoadExportPresetFile -f "c:/Users/user/Documents/maya/FBX/Presets/2014.1/export/AnimationOnly.fbxexportpreset"')
            mel.eval('FBXExport -f ($refFbxDir + $chrName + $refPrefix) -s')
            cmds.sysFile(refFbxDir + chr + refPrefix, cp = animFBXPath + chr + refPrefix)        
    
    
    # export animation
    for animMB in animMBList:
        if '_face_' in animMB:
            animFBX = animMB[:-3]
            if not os.path.exists(animFBXPath + animFBX + '.fbx'):
                cmds.file(animMBPath + animMB, o = True, f = True)
                # отделяю имя анимации от пути и расширенния и имени персонажа
                fullPathName = cmds.file(q = True, exn = True)
                fullPathName = fullPathName.split('/')
                fileName = fullPathName[-1]
                fileName = fileName[:-3] 
                
                # создаю переменные, где храню значение начала и конца timeline
                currEndTime = cmds.playbackOptions( q=True, maxTime=True )
                currStartTime = cmds.playbackOptions( q=True, minTime=True )
                endTimeScaled = round(currEndTime/2)
                
                cmds.select('*_ctrl')
                cmds.currentTime(currStartTime, edit=True) 
                cmds.setKeyframe('*_ctrl')
                cmds.currentTime(currEndTime, edit=True)
                cmds.setKeyframe('*_ctrl')
        
                # сжимаю анимацию в два раза, чтобы она соответствовала реальному времени
                cmds.select('*_ctrl')
                cmds.scaleKey(iub = False, ts = 0.5, tp = 1, fs = 0.5, fp = 1, vs = 1, vp = 0)
                cmds.playbackOptions(maxTime = int(endTimeScaled))
        
        
                # Удаляю группу и локаторы костей языка
                # Временно, пока не настроил их
                if cmds.objExists('tongue_1_GRP'):
                    cmds.delete('tongue_1_GRP', 'tongue_2_GRP')
            
        
        
                # выделяю все лицевые контроллеры
                cmds.select('*_ctrl')
                
                # смещаю ключи на 10 кадров вперед относительно их позиции
                cmds.keyframe(edit=True, relative = True, timeChange = (0 + 10))
        
                # задаю новые границы timeline
                currEndTime = cmds.playbackOptions( q=True, maxTime=True )
                currEndTime += 20
                cmds.playbackOptions( minTime=0, maxTime=currEndTime )
        
                # создаю функцию, которая обнуляю все каналы объектов из списка
                def SetKeysToZero():
                    cmds.select('*_ctrl')
                    ctrlsList = cmds.ls(sl = True)
                    for ctrl in ctrlsList:
                        attrs = cmds.listAttr(ctrl, k=True) #создает список атрибутов для каждого из выделенных объектов
                        for attr in attrs: #для каждого атрибута из списка атрибутов
                            if attr != "visibility": #если он не называется 
                                cmds.setAttr(ctrl + "." + attr, 0) #имя объекта+точка+название атрибута равняется нулю
        
                # ставлю нулевые ключи лицевых контроллеров вначале и конце timeline
                cmds.currentTime(currStartTime, edit=True) 
                SetKeysToZero()
                cmds.currentTime(currEndTime, edit=True)
                SetKeysToZero()
        
                # запекаю анимации на timeline для всех костей
                fullSkeletonList = cmds.ls(type = 'joint')
                cmds.select(fullSkeletonList)
                cmds.bakeResults(fullSkeletonList, t=(currStartTime,currEndTime), simulation=True, sb=1) 
        
                # перевожу переменные pytjon в mel
                mel.eval('string $animName = `python "fileName"`;')
                mel.eval('string $animFBXPath = `python "animFBXPath"`;')
                
                # делаю экспорт выделенных костей в .fbx с именем файла
                fullSkeletonList = cmds.ls(type = 'joint')
                cmds.select(fullSkeletonList)
                mel.eval('FBXExportConstraints -v 0')
                mel.eval('FBXLoadExportPresetFile -f "c:/Users/user/Documents/maya/FBX/Presets/2014.1/export/AnimationOnly.fbxexportpreset"')
                mel.eval('FBXExport -f ($animFBXPath + $animName + ".fbx") -s')
        
                # создаю лог работы
                
                if os.path.exists(animFBXPath + fileName + '.fbx'):
                    log += fileName + '.fbx exported \n'
                else:
                    log += fileName + '.fbx NOT exported \n'
    
    print log
__author__ = 'zklinger'

import maya.cmds as cmds
import sys
sys.path.append(r'C:\Users\zklinger\Documents\maya\scripts\maya-python-imageCard\scripts')
import gravModTools as gMT
from PIL import Image


imageFolder = 'C:\Users\zklinger\Documents\maya\scripts\maya-python-imageCard\example\layers\\'
imageFileList = cmds.getFileList(folder=imageFolder, filespec='*.png')

cardList = list()

#createRenderLayer -name "layer1" -number 1 -noRecurse `ls -selection`;
zDepthRenderLayer = cmds.createRenderLayer(empty=True,
                                           name='zDepthRenderLayer',
                                           number=1, noRecurse=True)

#createRenderLayer -name "layer1" -number 1 -noRecurse `ls -selection`;
AORenderLayer = cmds.createRenderLayer(empty=True,
                                           name='AORenderLayer',
                                           number=2, noRecurse=True)

#createRenderLayer -name "layer1" -number 1 -noRecurse `ls -selection`;
positionRenderLayer = cmds.createRenderLayer(empty=True,
                                           name='positionRenderLayer',
                                           number=2, noRecurse=True)

for i in range(len(imageFileList)):
    im = Image.open(imageFolder + imageFileList[i])
animMBDir = 'anims_MB\\'
# задаю приставку для названия ref анимаций
refPrefix = '_face_10_fr_ref.fbx'

log = '\n---------- export log:----------\n'

# папкарабочего диалога
animListDir = workDirPath + workingDirName
# путь к файлу, где содержится список анимаций
animListName = animListDir + workingName + '_anim_list.txt'
# путь к папке .fbx анимаций рабочего диалога
animFBXPath = workDirPath + workingDirName + animFBXDir
# путь к папке .mb анимаций рабочего диалога
animMBPath = workDirPath + workingDirName + animMBDir
# составляю список из файлов, настроеных chr templates
chrMBList = cmds.getFileList(fs = '*.mb', fld = animChrPath) 
# составляю список из файлов, .fbx ref анимаций chr templates
refAnimList = cmds.getFileList(fs = '*.fbx', fld = refFbxDir) 
# составляю список из файлов, .fbx ref анимаций chr templates
animMBList = cmds.getFileList(fs = '*.mb', fld = animMBPath) 
# создаю список для лицевых контроллеров
ctrlsList = cmds.ls('*_ctrl')

# получаю длину списка анимаций для проверки кол-ва выполненых действий
animListForLen = open(animListName,'r')
animLenLines = animListForLen.readlines()
animListLen = len(animLenLines)
animListForLen.close()

# функция, которая определяет, какие персонажи используются в диалоге по anim_list.txt и списку chr templates
def CompareLists(searchInList, searchForList):
Esempio n. 38
0
def AnimPoseLib():
    global tabs,Animation,Poses,pathfolders,pathfolder,savepathini,User_Name,tmpfile,seltabs,seltab
    if mc.window ('MainWin',q=True,exists =1):
        mc.deleteUI ('MainWin')
    if mc.windowPref ('MainWin',q=True,exists = 1):
        mc.windowPref ('MainWin',remove = 1)
    posewin=mc.window('MainWin',menuBar=True, title="SR_AnimPoseLib",width=400,mxb=0)
    User_Name = os.getenv('USERNAME')
    savepathini='C:/Documents and Settings/'+ User_Name + '/My Documents/'
    mc.menu( label='File', tearOff=True )
    mc.menuItem( label='Open Savepose Folder',c=lambda event:openfolder(savepathini))
    mc.menuItem( label='Refresh',c=lambda event:Refresh_UI(savepathini))
    mc.menu( label='Tabs', tearOff=True )
    mc.menuItem( label='New Tab',c=partial(Newtab)) 
    mc.menuItem( label='Delete Tab',c=partial(deletetab))
    mc.menuItem( label='Rename Tab',c=partial(renametab))
    mc.menuItem( label='Clear All ',c=partial(clear))
    mc.menu('chgFld',label='Folder',tearOff=True)
    mc.menuItem(label='Change Savepose Folder ',c=lambda event:savefolder(savepathini))
    mc.menuItem(d=True)
    newpath=[savepathini]
    mc.menuItem( label='My Douments ',c=partial(changepath,newpath))       
    mc.menu( label='Help', helpMenu=True,tearOff=True )
    mc.menuItem( label='About..!' ,c=partial(About))
    mc.frameLayout( label='',fn='boldLabelFont', borderStyle='etchedIn')
    mc.separator(style='none',height = 2 )
    mc.rowColumnLayout(numberOfColumns=5,cw=[(1,70),(2,60),(3,70),(4,40),(5,125)],cs=[(1,30),(5,40)])
    mc.text('ST',label='Start frame:')
    Start_F = mc.floatField('Start_F',precision=2)
    mc.text( 'ET',label='End frame:')
    End_F   = mc.floatField('End_F',precision=2)
    mc.floatField('Start_F', edit=True, enterCommand=('mc.setFocus(\"' + End_F + '\")') )
    mc.floatField('End_F', edit=True, enterCommand=('mc.setFocus(\"' + Start_F + '\")') )
    mc.button(label='Save (Anim/Pose)',c=partial(savepose),h=35 )
    mc.setParent( '..' )
    mc.rowColumnLayout(numberOfColumns=2,cw=[(1,130)])
    mc.text(label='Location : ',align='right',fn='boldLabelFont')
    mc.text('Path',label=' Local Folder',align='left',fn='smallFixedWidthFont') 
    mc.setParent( '..' )
    form = mc.formLayout()
    tabs = mc.shelfTabLayout('tabs',innerMarginWidth=5, innerMarginHeight=5,cc=partial(vis))
    mc.formLayout(form,edit=True, attachForm=((tabs, 'top', 0), (tabs, 'left', 15), (tabs, 'bottom', 15), (tabs, 'right', 15)) )
    Animation = mc.shelfTabLayout('Animation',innerMarginWidth=5, innerMarginHeight=5,bgc=(0.3,0.3,0.3),h=237)
    mc.setParent('..')
    Poses = mc.shelfTabLayout('Poses',innerMarginWidth=5, innerMarginHeight=5,bgc=(0.3,0.3,0.3),h=237,p=tabs)
    mc.setParent('..')
    mc.setParent('..')
    mc.setParent('..')    
    mc.text(l='Sreekanth.S.R  ',fn="smallBoldLabelFont",al='right')
    mc.window (posewin,e=1,wh=(500,410))
    mc.showWindow()
    shelfpath=[]
    posepath=[]
    savepath =(savepathini + 'SavePose/')
    mc.sysFile(savepath, makeDir=True )
    shelfpath= mc.getFileList (folder=savepath)
    Anim_count=shelfpath.count('Animation')
    Pose_count=shelfpath.count('Poses')
    Tmp_count =shelfpath.count('tmp.anim')
    if not Tmp_count:
        tmpfile=savepath+'tmp.anim'
        field=open(tmpfile,'w')
        field.write('Currnt dir \n'+savepathini)
        field.close()
    if Tmp_count:
        tmpfile=savepath+'tmp.anim'
        field=open(tmpfile,'r+')
        line=field.readline()
        if line[0:3]=='Cur' :
            line=field.readline()
            savepathini=line.strip()
            line=field.readline()
            if line[0:3]=='Run':
                line=field.readline()
                while(line != '}'):
                    mc.menuItem(label=line.strip(),p='chgFld',c=partial(savedpath,line))    
                    line=field.readline()
                field.close()
    Refresh_UI(savepathini)
Esempio n. 39
0
def Refresh_UI(savepathini,*args):
    mc.text('Path',e=1,l=savepathini)
    S_val=mc.playbackOptions(q=1,min=1)
    E_val=mc.playbackOptions(q=1,max=1)
    mc.floatField('End_F',e=1,v=E_val)
    mc.floatField('Start_F',e=1,v=S_val)
    savepath =(savepathini + 'SavePose/')
    #imgpath  = savepath + 'tmp_images/'
    mc.sysFile(savepath, makeDir=True )    
    posepath = (savepath + 'Animation/')
    posepath1= (savepath + 'Poses/')
    shelfpath= mc.getFileList (folder=savepath)
    Anim_count=shelfpath.count('Animation')
    Pose_count=shelfpath.count('Poses')
    if Anim_count==0 or Pose_count==0:
        mc.confirmDialog (title='Warning',message='No saved poses exist. A Default folders will\n    be created when you save for the first time', button='OK',defaultButton='Yes')
    tabsanim,tabsanim1=[],[]
    tabsanim=mc.getFileList(folder=posepath)
    tabsanim1=mc.getFileList(folder=posepath1)
    Anim_tabs=mc.shelfTabLayout('Animation',q=1,ca=1) 
    Pose_tabs=mc.shelfTabLayout('Poses',q=1,ca=1)
    if Anim_tabs or Pose_tabs :
        mc.deleteUI(Anim_tabs,Pose_tabs) 
    if tabsanim:
        for each in tabsanim:
            sh=mc.shelfLayout(each,p=Animation,st="iconAndTextVertical")
            mc.setParent('..')
            posetabs=(posepath + each + "/")
            poses = mc.getFileList (fld =posetabs,fs="*.anim")
#            imges = mc.getFileList (fld =posetabs,fs="*.bmp")
            icon_name='ghost.xpm'
            for j in range(len(poses)):
                butname = poses[j].replace(".anim","")
                img_name=poses[j].replace(".anim",".bmp")
                icon_name=posetabs + img_name
                posefile = posetabs + poses[j]
                mc.setParent()                
                mc.shelfButton(i1=icon_name,w=110,h=80,l=butname,bgc=(.2,.6,.3),st='iconAndTextVertical',p=each,c=partial(Importanim,posefile))
                mc.popupMenu()
                mc.menuItem(l='Import anim',en=1,c=partial(Importanim,posefile))
                mc.menuItem(d=True)
                mc.menuItem(l='Rename anim',en=1,c=partial(Renameanim,posefile))
                mc.menuItem(d=True)
                mc.menuItem(l='Delete anim',en=1,c=partial(Deleteanim,posefile))
                mc.setParent('..')   
    else:
        if mc.shelfLayout('Default',q=True,exists=True):
            mc.deleteUI ('Default')    
        shelftmp = mc.shelfLayout('Default',w=450,h=200,bgc=(0.3,0.3,0.3),p=Animation)
        mc.sysFile(posepath+'Default/', makeDir=True )         
    if tabsanim1:
        for each in tabsanim1:
            sh=mc.shelfLayout(each,p=Poses,st="iconAndTextVertical")
            mc.setParent('..')
            posetabs1 = (posepath1 + each + "/")
            poses1 = mc.getFileList (fld =posetabs1,fs="*.anim")
            icon_name1='ghostOff.xpm'
            for j in range(len(poses1)):
                butname1 = poses1[j].replace(".anim","")
                img_name1= poses1[j].replace(".anim",".bmp")
                icon_name1=posetabs1 + img_name1
                posefile1 = posetabs1 + poses1[j]
                mc.setParent()
                mc.shelfButton(i1=icon_name1,w=110,h=80,l=butname1,fn=  "fixedWidthFont" ,bgc=(.9, .4, .0),st='iconAndTextVertical',p=each,c=partial(Pose_rtn,posefile1))
                mc.popupMenu()
                mc.menuItem(l='Import Pose',en=1,c=partial(Pose_rtn,posefile1))
                mc.menuItem(d=True)
                mc.menuItem(l='Rename Pose',en=1,c=partial(Renamepose,posefile1))
                mc.menuItem(d=True)
                mc.menuItem(l='Delete Pose',en=1,c=partial(Deletepose,posefile1))
                mc.setParent('..')
    else:
        if mc.shelfLayout('Default1',q=True,exists=True):
            mc.deleteUI ('Default1') 
        shelftmp1 = mc.shelfLayout('Default1',w=450,h=200,bgc=(0.3,0.3,0.3),p=Poses)
        mc.sysFile(posepath1+'Default1/', makeDir=True )
Esempio n. 40
0
def setupScene():
    global util
    errormsgs = []
    util = Utils.utils()
    
    chks = ['keychk', 'rimchk','colchk','occchk','rgbachk','gshchk','matchk']
    chkstats = [mc.checkBox(x, q = True, v = True) for x in chks]
    if not 1 in chkstats:
        mc.confirmDialog(t='Warning', m = 'No layers are selected', b='OK', ma = "center")
        return    
    
    #get dict of assets in their respective render layer groups
    
    grpDict = findGrpDict()
    layergrps = grpDict.keys()
    layergrps.sort()
    
    
    #find the path of the file, check naming of file and query the timeline
 
    filepath = mc.file(q = True, sn = True)
    filename = os.path.basename(filepath)
    fildir = os.path.dirname(filepath)
    refcut = mc.checkBox("refchk", q = True, v = True)
    try:
        shotname = filename.split("_")[1]
    except:
        mc.confirmDialog(t='Warning', m = 'Scene name is not correct', b='OK', ma = "center")
        return
    shstart = mc.playbackOptions(q = True, ast = True)
    shend = mc.playbackOptions(q = True, aet = True)
    
    
    #query the camera and the camera group
    
    cam = mc.optionMenu('camlite', q = True, v = True)
    
    #setup the name of the new files
    
    clfile = filename[:-9] + "cl" + filename[-7:]
    #check the file exists, then change to vesion folder
    curr_path = fildir+'/'
    clfilepath=curr_path+clfile
    if mc.file(clfilepath,q=1,ex=1):
        Overrite = mc.confirmDialog(
                title='Confirm ',
                message='Overwrite the existing file? ',
                button=['Yes', 'No'],
                defaultButton='Yes',
                cancelButton='No',
                dismissString='No') 
        if Overrite =='No':   
            return
        
    chkpath=mc.getFileList (folder=curr_path)
    ver_count=chkpath.count('ver')
    verpath= curr_path+'ver/'
    if not ver_count:
        mc.sysFile(verpath,makeDir=1)      
#    else:
#        verpath= curr_path+'ver/'
    files = [ f for f in os.listdir(verpath) if (os.path.isfile (os.path.join(verpath,f))) and f[len(f)-3:len(f)]=='.ma']
    if files:
        ver = str(len(files)+1)
    else:
        ver='01'
    newpath=verpath+clfile
    mc.sysFile(filepath,copy=newpath)
    newname=clfile[:19]+'%s.ma'%ver.zfill(2)
    chgname=verpath+newname
    mc.sysFile(newpath,rename=chgname)
    
    #select all the assets specified in the setup window to export to a new file
    
    selasts = []
    refcutmiss = []
    for each in layergrps:
        for ast in grpDict[each]:
            selasts.append(ast)
    
            
    #add the camera to the selection
    
    selasts.append(cam)
    
    
    #add the ground and matte groups to the selection if they exist, else warn that they have not been setup
    
    gndmteobjs = ["Grp_Ground", "Grp_Matte"]
    if mc.objExists("Grp_Ground"):
            gndmteobjs.pop(gndmteobjs.index("Grp_Ground"))
            selasts.append("Grp_Ground")
    if mc.objExists("Grp_Matte"):
            gndmteobjs.pop(gndmteobjs.index("Grp_Matte"))
            selasts.append("Grp_Matte")
    if gndmteobjs:
        gndmtemsg = "\n".join(gndmteobjs)
        rslt = mc.confirmDialog(t='Warning', m="Ground/Matte Objects dont\nexist or havent been set up", b=['Continue', 'Cancel'], db='Continue', cb='Cancel', ds='Cancel', ma = 'center')
        if rslt == 'Cancel':
            return
        else:
            pass
            
    mc.select(selasts, r = True)
    
    

    #cmfile = filename[:-9] + "cm" + filename[-7:]
    

    #export all selected assets, cameras and ground/matte groups to a new _cl_v00 file
    
    mc.file((fildir + "/" + clfile), op = "v=0", typ = "mayaAscii", pr = True, es = True, f=True )

    #force open the new _cl_v00 file without saving the old one
    
    mc.file((fildir + "/" + clfile), op = "v=0", typ = "mayaAscii", lrd = "all", o = True, f = True)
    
    #select camera and export selected camera to a new _cm_v00 file
    
    #mc.select(cam, r = True) 
    #mc.file((fildir + "/" + cmfile), op = "v=0", typ = "mayaAscii", pr = True, es = True)
    mc.select(cl = True)
    
    #set the timeline and render globals, and move assets to their respective groups
    
    mc.playbackOptions(e = True, ast = shstart)
    mc.playbackOptions(e = True, aet = shend)
    setrendglobals(shotname, shstart, shend)
    try:
        Utils.moveAssetsToGrps()
    except:
        pass
    
        
    #setup the useBackground shader and assign it to the ground/matte objects if they exist
    
    gndusebg = "groundmatteuseBGshader"
    if mc.objExists(gndusebg):
        mc.delete(gndusebg)
    gndusebg = mc.shadingNode("useBackground", asShader = True, n = gndusebg)
    mc.setAttr((gndusebg + ".specularColor"), 0, 0, 0, type = "double3")
    mc.setAttr((gndusebg + ".reflectivity"), 0)
    mc.setAttr((gndusebg + ".reflectionLimit"), 0)
    mc.setAttr((gndusebg + ".shadowMask"), 0)
    if mc.objExists("Grp_Ground"):
        mc.select("Grp_Ground", r = True)
        mc.hyperShade(assign = gndusebg)
    if mc.objExists("Grp_Matte"):
        mc.select("Grp_Matte", r = True)
        mc.hyperShade(assign = gndusebg)
        
    
    #query the rim/key light required and import the relevant light file from /assets/lighting
    locquery  = mc.optionMenu('Location', q = True, v = True)
    rmkylight = mc.optionMenu('Time', q = True, v = True)
    camquery  = mc.optionMenu('camlite', q = True, v = True)
    rmkyfile = "%s/%s/Location/%s/%s_rimkey.ma"%(util.path, util.litePath,locquery,rmkylight)
    rimliteL = "%s:rimL"%rmkylight
    rimliteR = "%s:rimR"%rmkylight
    #refdoom  = "%s:ref_doom"%rmkylight
    keylite  = "%s:key"%rmkylight
    #fillite  = "%s:fill"%rmkylight
    #eyespec  = "%s:eyespc"%rmkylight
    if os.path.exists(rmkyfile):
        if mc.objExists(rimliteL):
            mc.delete(rimliteL)
        if mc.objExists(rimliteR):
            mc.delete(rimliteR)
        #if mc.objExists(fillite):
            #mc.delete(fillite)
        if mc.objExists(keylite):
            mc.delete(keylite)   
        mc.file(rmkyfile, i = True, typ = "mayaAscii", ra = True, ns = rmkylight, op = "v=0;p=17", pr = True)
    else:
        mc.confirmDialog(t='Warning', m = '%s file is not accessible'%rmkylight, b='OK', ma = "center")
        return
        
    #find the names of the imported rim/key lights in the scene and parent them to the 'Rim_key' group
    
    if mc.objExists("LIGHTS"):
            mc.delete("LIGHTS")
            
    sclites = mc.ls(type = "light")
    for each in sclites:
        if ":rimL" in each:
            rimliteL = mc.listRelatives(each, p = True)[0]
        elif ":rimR" in each:
            rimliteR = mc.listRelatives(each, p = True)[0]
        #elif ":fill" in each:
            #fillite  = mc.listRelatives(each, p = True)[0]
        elif ":key" in each:
            keylite = mc.listRelatives(each, p = True)[0]
    keygrp = "%s:key_set"%rmkylight
    mc.group(n = "LIGHTS", em = True)
    mc.parent(keygrp,"LIGHTS" )
                    
    #query common lights required and import the relevant light file from /assets/lighting/commonlights
    
    commonfile = "%s/%s/common_lights/common_lights.ma"%(util.path, util.litePath)
    commonlight="commonlight"
    #litequery=mc.optionMenu('amblite',q=True,v=True) 
    #GIrAMB = "%s:%s"%(commonlight,litequery)
    if os.path.exists(commonfile):
        if mc.objExists(commonlight):
            mc.delete(commonlight)
        mc.file(commonfile, i = True, typ = "mayaAscii", ra = True, ns = commonlight, op = "v=0;p=17", pr = True)
    else:
        mc.confirmDialog(t='Warning', m = '%s file is not accessible'%commonlight, b='OK', ma = "center")
        return        
  
    #mc.parent("commonlight:commonLight_sets","LIGHTS" )
    #spclite_parnt=mc.parent(spclite,camquery)
    #find shape node of key light
    
    if mc.objExists(keylite):
        keyliteshp = mc.listRelatives(keylite, c = True, s = True)
    
        
    #setup the mat shaders
    
    rgbashaders = rgbashader(shotname)
    mc.select(cl = True)
    myShader = mc.shadingNode('lambert', asShader=True)
    mc.setAttr (myShader+".colorR", 0.886)
    mc.setAttr (myShader+".colorG" ,0.961)
    mc.setAttr (myShader+".colorB" ,0.961)
    
    # assign cam folder 
    
    if camquery[14:] =='Ct':
        camname = "Center"
    elif camquery[14:]=='Lt':
        camname = "Left"
    else:
        camname = "Right"
    
    #remove all existing render layers
    
    mc.editRenderLayerGlobals(crl = "defaultRenderLayer")
    renlyrs = mc.ls(type = "renderLayer")
    for each in renlyrs:
        if not "defaultRenderLayer" in each:
            mc.delete(each)
    
            
    #cut the references of all assets if marked so in the light setup options            
    
    for each in layergrps:
        for ast in grpDict[each]:
            if refcut:
                try:
                    cutref(ast)
                except:
                    refcutmiss.append(ast)
    
                    
    #main loop for creating all the render layers with their respective settings working on each render layer group per loop                

    sqname = shotname[:5]
    shname = shotname[5:]    
    matindex = 0
    for lyr in layergrps:
        asts = grpDict[lyr]
        
          
        #create key layer, add key light
        
        if mc.checkBox("keychk", q = True, v = True):
            keylayer = (lyr + 'key')
            mc.select(asts, r = True)
            mc.select(keylite, add = True)
            #mc.select(refdoom, add = True)
            #mc.select(eyespec, add = True)
            if mc.objExists("Grp_Ground"):
                mc.select("Grp_Ground", add = True)
            if mc.objExists("Grp_Matte"):
                mc.select("Grp_Matte", add = True)
            mc.createRenderLayer(mc = True, n = keylayer)
            mc.editRenderLayerAdjustment(gndusebg + ".shadowMask")
            mc.setAttr(gndusebg + ".miOcclusionMask", 0)
            mc.connectAttr(keylayer+'.renderPass', 'diff.owner',nextAvailable=True)
            mc.connectAttr(keylayer+'.renderPass', 'amb.owner', nextAvailable=True)
            mc.connectAttr(keylayer+'.renderPass', 'sha.owner', nextAvailable=True)
            mc.connectAttr(keylayer+'.renderPass', 'spc.owner', nextAvailable=True)
            mc.connectAttr(keylayer+'.renderPass', 'inc.owner',nextAvailable=True)
            fileprefix = "%s/%s/%s/ch/%s/<RenderLayer>/<RenderPass>/%s%s_<RenderLayer>_<RenderPass>_v01"%(sqname,shname,camname,lyr,sqname,shname)
            mc.editRenderLayerAdjustment ("defaultRenderGlobals.imageFilePrefix")            
            mc.setAttr("defaultRenderGlobals.imageFilePrefix", fileprefix, type = "string")
            mc.editRenderLayerAdjustment('miDefaultOptions.rayTracing')
            mc.setAttr('miDefaultOptions.rayTracing',1)            
            mc.editRenderLayerAdjustment( 'miDefaultOptions.maxReflectionRays' )
            mc.setAttr('miDefaultOptions.maxReflectionRays', 3)
            mc.editRenderLayerAdjustment( 'miDefaultOptions.maxRefractionRays' )
            mc.setAttr('miDefaultOptions.maxRefractionRays', 0)
            mc.editRenderLayerAdjustment( 'miDefaultOptions.maxRayDepth')
            mc.setAttr('miDefaultOptions.maxRayDepth',20)            
            
        #create rim layer, add rimlight
        
        if mc.checkBox("rimchk", q = True, v = True):
            rimlayer = (lyr + 'rim')
            mc.select(asts, r = True)
            mc.select(rimliteL, add = True)
            mc.select(rimliteR, add = True)
            mc.createRenderLayer(mc = True, n = rimlayer)
            rimsh='%s:Rimshader'%commonlight
            #mc.shadingNode("lambert", asShader = True, n = rimsh )
            #mc.setAttr((rimsh+'.color'),1, 1, 1, type = "double3")
            #mc.setAttr((rimsh+'.diffuse'),1)
            mc.select(rimsh)
            mel.eval('hookShaderOverride("%s","","%s")'%(rimlayer,rimsh))
            fileprefix = "%s/%s/%s/ch/%s/<RenderLayer>/%s%s_<RenderLayer>_v01"%(sqname, shname,camname,lyr, sqname, shname)
            mc.editRenderLayerAdjustment ("defaultRenderGlobals.imageFilePrefix")            
            mc.setAttr("defaultRenderGlobals.imageFilePrefix", fileprefix, type = "string")
            mc.editRenderLayerAdjustment('miDefaultOptions.rayTracing')
            mc.setAttr('miDefaultOptions.rayTracing',0)
            
        #create col layer,add amb light
        
        if mc.checkBox("colchk",q= True,v = True):
            collayer= (lyr+ 'col')
            mc.select(asts, r = True)
            Col_light='%s:colLight'%commonlight 
            mc.select(Col_light,add=True)
            mc.createRenderLayer(mc = True, n = collayer)
            mc.editRenderLayerAdjustment ("defaultRenderGlobals.imageFilePrefix")            
            mc.setAttr("defaultRenderGlobals.imageFilePrefix", fileprefix, type = "string")
      
        #create occ layer
        
        if mc.checkBox("occchk",q=True,v=True):
            occlayer = (lyr + 'occ')
            mc.select(asts,r=True)
            if mc.objExists("Grp_Ground"):
                mc.select("Grp_Ground", add = True)
            if mc.objExists("Grp_Matte"):
                mc.select("Grp_Matte", add = True)
            mc.createRenderLayer(mc = True, n = occlayer)
            mel.eval("renderLayerBuiltinPreset occlusion %s "%occlayer)
            ShaderList=mc.ls (sl=1)
            Mib_Amb=mc.listConnections(ShaderList,t='mib_amb_occlusion')
            mc.setAttr(Mib_Amb[0]+'.samples',64)
            mc.setAttr(Mib_Amb[0]+'.spread',0.8)
            mc.setAttr(Mib_Amb[0]+'.max_distance',20)
            fileprefix = "%s/%s/%s/ch/%s/<RenderLayer>/%s%s_<RenderLayer>_v01"%(sqname, shname,camname,lyr, sqname, shname)
            mc.editRenderLayerAdjustment ("defaultRenderGlobals.imageFilePrefix")            
            mc.setAttr("defaultRenderGlobals.imageFilePrefix", fileprefix, type = "string")
            
            
        #create mat layer and assign r, g and b shaders in turn using matindex, turn off raytracing using layer override
        
        if mc.checkBox("rgbachk", q = True, v = True):
            rgbalayer = (lyr + 'rgba')
            mc.select(asts, r = True)
            mc.createRenderLayer(mc = True, n = rgbalayer)
            for i in range(len(asts)):
                shindex = matindex%4
                matindex += 1
                mc.select(asts[i], r = True)
                mc.hyperShade(assign = rgbashaders[shindex])
            fileprefix = "%s/%s/%s/ch/%s/<RenderLayer>/%s%s_<RenderLayer>_v01"%(sqname, shname,camname,lyr, sqname, shname)
            mc.editRenderLayerAdjustment ("defaultRenderGlobals.imageFilePrefix")            
            mc.setAttr("defaultRenderGlobals.imageFilePrefix", fileprefix, type = "string")
            mc.setAttr('miDefaultOptions.rayTracing',0)
            
        #create ground shadow layer, add key light and turn on shadow mask of useBG shader using layer override
        
        if mc.checkBox("gshchk", q = True, v = True):
            gshlayer = (lyr + 'gsh')
            mc.select(asts, r = True)
            mc.select(keylite, add = True)        
            if mc.objExists("Grp_Ground"):
                mc.select("Grp_Ground", add = True)
            if mc.objExists("Grp_Matte"):
                mc.select("Grp_Matte", add = True)
            mc.createRenderLayer(mc = True, n = gshlayer)
            mc.editRenderLayerAdjustment(gndusebg + ".shadowMask")
            mc.setAttr(gndusebg + ".shadowMask", 1)
            fileprefix = "%s/%s/%s/ch/%s/<RenderLayer>/%s%s_<RenderLayer>_v01"%(sqname, shname,camname,lyr, sqname, shname)
            mc.editRenderLayerAdjustment ("defaultRenderGlobals.imageFilePrefix")            
            mc.setAttr("defaultRenderGlobals.imageFilePrefix", fileprefix, type = "string")
            mc.editRenderLayerAdjustment('miDefaultOptions.rayTracing')
            mc.setAttr('miDefaultOptions.rayTracing',1) 
            mc.editRenderLayerAdjustment( 'miDefaultOptions.maxReflectionRays' )
            mc.setAttr('miDefaultOptions.maxReflectionRays', 0)
            mc.editRenderLayerAdjustment( 'miDefaultOptions.maxRefractionRays' )
            mc.setAttr('miDefaultOptions.maxRefractionRays', 0)
            mc.editRenderLayerAdjustment( 'miDefaultOptions.maxRayDepth')
            mc.setAttr('miDefaultOptions.maxRayDepth',20)

            #turn off receive shadows and primary visibility of the all the assets using changespreadattr()
            for ast in asts:
                changespreadattr(ast, "receiveShadows", 0)
                changespreadattr(ast, "primaryVisibility", 0)
                
        #create mat layer
        
        if mc.checkBox("matchk",q= True, v = True):
            matlayer = (lyr + 'mat')
            mc.select(asts, r = True)
            Zdep='%s:Zdepthshader'%commonlight            
            mc.select(asts, r = True)
            mc.createRenderLayer(mc = True, n = matlayer)
            mc.select(Zdep)
            mel.eval('hookShaderOverride("%s","","%s")'%(matlayer,Zdep))
            mc.connectAttr(matlayer+'.renderPass', 'camnml.owner', nextAvailable=True)
            mc.connectAttr(matlayer+'.renderPass', 'nml.owner', nextAvailable=True)
            fileprefix = "%s/%s/%s/ch/%s/<RenderLayer>/<RenderPass>/%s%s_<RenderLayer>_<RenderPass>_v01"%(sqname,shname,camname,lyr,sqname,shname)
            mc.editRenderLayerAdjustment ("defaultRenderGlobals.imageFilePrefix")            
            mc.setAttr("defaultRenderGlobals.imageFilePrefix", fileprefix, type = "string")
            mc.editRenderLayerAdjustment('miDefaultOptions.rayTracing')
            mc.setAttr('miDefaultOptions.rayTracing',0) 
            mc.editRenderLayerAdjustment( 'miDefaultOptions.maxReflectionRays' )
            mc.setAttr('miDefaultOptions.maxReflectionRays', 1)
            mc.editRenderLayerAdjustment( 'miDefaultOptions.maxRefractionRays' )
            mc.setAttr('miDefaultOptions.maxRefractionRays', 1)
            mc.editRenderLayerAdjustment( 'miDefaultOptions.maxRayDepth')
            mc.setAttr('miDefaultOptions.maxRayDepth',1)                 
    mc.editRenderLayerGlobals(crl = "defaultRenderLayer")
    mc.setAttr("defaultRenderLayer.renderable",0)
    mc.select(cl = True)
    
#    mc.checkBoxGrp ('enableColorProfile',e=1,v1=1)
#    mc.optionMenuGrp('inputColorProfile',e=1,enable=1)
#    mc.optionMenuGrp('outputColorProfile',e=1,enable=1)
#    mc.optionMenuGrp('inputColorProfile',e=1 ,sl=1 )
#    mc.optionMenuGrp('outputColorProfile',e=1 ,sl=2)
#    mc.setAttr ("defaultRenderGlobals.inputColorProfile",1) 
#    mc.setAttr ("defaultRenderGlobals.outputColorProfile",2) 
    mc.confirmDialog(t='Message', m = 'Scene setup completed successfully', b='OK', ma = "center")
Esempio n. 41
0
        if start == False:
            start = cmds.playbackOptions(q=True, min=True)
        if end == False:
            end = cmds.playbackOptions(q=True, max=True)

        if file_or_dir:
            create(start, end, save_cache_to + "/" + dir, step, per=set_per)
        else:
            create(start, end, save_cache_to + "/" + file_or_dir_name.rstrip(".mb") + "/" + dir, step, per=set_per)

        cmds.warning("Cache saved to " + save_cache_to)


file_or_dir = file_or_dir.rstrip("/")
save_cache_to = save_cache_to.rstrip("/")

if not os.path.exists(file_or_dir):
    cmds.warning("File or dir " + file_or_dir + " doesn't exists")
    exit(0)

if os.path.isfile(file_or_dir):
    cmds.file(file_or_dir, o=True)
    batch(file_or_dir, set_names, save_cache_to, start, end)
    cmds.file(file_or_dir, mf=False)

if os.path.isdir(file_or_dir):
    for file in cmds.getFileList(folder=file_or_dir + "/"):
        cmds.file(file_or_dir + "/" + file, o=True)
        batch(file, set_names, save_cache_to, start, end, False)
        cmds.file(file_or_dir + "/" + file, mf=False)
def batch_render():
    del_pointcloud()
    #autoload Mental-Ray, from http://forums.cgsociety.org/archive/index.php/t-1001360.html
    #cmds.loadPlugin('Mayatomr', quiet=True)
    #cmds.setAttr('defaultRenderGlobals.ren', 'mentalRay', type='string')
    cmds.undoInfo(state=False)

    #imageFormat 32 means PNG, from here: http://www.oputo.com/html/blog/2010/06/12/defaultrenderglobals-imageformat/
    cmds.setAttr('defaultRenderGlobals.imageFormat', 32)
        
    #hide our TEMPLATE
    cmds.hide( "template_skin" )
    cmds.hide( "template_bone" )

    input_bones_list = cmds.getFileList(folder=path_of_files, filespec='bone*.obj')
    frames_rendered = 0
    for curr_bone in input_bones_list:
        #take off the .obj, then get the last four digits of the name of the file
        #split_name = curr_bone.split('.')
        #file_name = split_name[0]
        #curr_digits = file_name[-4:]
        #print curr_digits
        curr_digits, bone_name, frm_name = get_bone_digit(curr_bone)
        
        # Assign shader to objects
        if draw_mesh:
            cmds.file(path_of_files + bone_name, i=True)
            cmds.file(path_of_files + frm_name, i=True)
            cmds.sets("Mesh", edit=True, forceElement="boneShader")
            frm_mesh_name = "frm" + curr_digits + "_Mesh"
            cmds.sets(frm_mesh_name, edit=True, forceElement="skinShader")
            cmds.select('Mesh')
            cmds.polySoftEdge(a=soften_angle)
            cmds.select(frm_mesh_name)
            cmds.polySoftEdge(a=soften_angle)
        
        #load the point cloud
        if draw_points:
            point_cloud_file = path_of_files + "frm" + curr_digits + ".xyz"
            load_xyz( point_cloud_file )
        
        path_to_file = cmds.render()
        
        if path_to_file[-3:] != "png":
            print "Render is NOT outputting pngs! Quitting..."
            break

        #rename the rendered file
        output_name = "frame" + curr_digits + ".png"
        split_path = path_to_file.split('/')
        split_path[-1] = output_name
        new_path = "/".join(split_path)
        #os.rename(path_to_file, new_path)
        move(path_to_file, new_path)
        print 'RENDERED TO: ', new_path
        
        #delete the meshes
        if draw_mesh:
            cmds.select('Mesh')
            cmds.delete()
            frm_mesh_name = "frm" + curr_digits + "_Mesh"
            cmds.select(frm_mesh_name)
            cmds.delete()
        
        #delete the point cloud
        if draw_points:
            del_pointcloud()
        
        frames_rendered = frames_rendered + 1
        
        if frames_rendered > max_num_frames:
            break
        
    #show our templates
    cmds.showHidden( "template_skin" )
    cmds.showHidden( "template_bone" )
    load_xyz( path_of_files + "frm0000.xyz" )