def publishSetDressGPU(*args):
    scenePath = cmds.workspace(sn=True, q=True)
    scenePath = scenePath.replace(os.sep, '/')

    abcPublishPath = scenePath + '/abc'
    abcPublishFile = 'setDressGPU'

    # 1. Check if setdress group exists :
    if not cmds.objExists('setDress_grp'):
        cmds.warning('setDress_grp does not exist.')
        return

    # 2. Export
    sel = cmds.select('setDress_grp', r=True)

    # alembic publish
    cmds.gpuCache('setDress_grp', \
     startTime=1, \
     endTime=1, \
     optimize=True, \
     optimizationThreshold=100, \
     writeMaterials=False, \
     dataFormat='ogawa', \
     useBaseTessellation=True, \
     directory=abcPublishPath, \
     fileName=abcPublishFile)

    # 4. inview message
    print('// Result : ' + abcPublishPath + abcPublishFile)
    cmds.inViewMessage( \
     amg='Set Dress GPU publish successful', \
     pos='midCenter', \
     fade=True)
    def _export_gpu_abc_cache(self, task_settings, item, export_path):
        """
        This method is capable of exporting the scene in a gpu alembic cache.

        :param task_settings: Dictionary of Settings. The keys are strings, matching
            the keys returned in the settings property. The values are `Setting`
            instances.
        :param item: Item to process
        :param export_path: The output path to export files to

        """
        # find the animated frame range to use:
        start_frame, end_frame = _find_scene_animation_range()
        export_uv = task_settings["Export UVs"].value

        try:
            publish_folder = os.path.dirname(export_path)
            export_filename = os.path.splitext(
                os.path.basename(export_path))[0]

            cmds.refresh(suspend=True)
            cmds.gpuCache(startTime=start_frame,
                          endTime=end_frame,
                          allDagObjects=False,
                          dataFormat="ogawa",
                          directory=publish_folder,
                          fileName=export_filename,
                          saveMultipleFiles=False,
                          dumpHierarchy=True,
                          writeUVs=export_uv)
            cmds.refresh(suspend=False)
        except Exception as e:
            raise Exception("Failed to export Geometry: %s" % e)

        self.logger.debug("Exported scene geometry to '%s'." % export_path)
def mighty_GPU_generator():
    ## Definition of the variables
    #### Get the namespace
    selection_buffer = cmds.ls(sl=True)
    mighty_GPU_generator_selection = str(selection_buffer[0])
    nameSpaceString = (mighty_GPU_generator_selection.split(':'))[0]
    cacheName = (nameSpaceString + "_GPU_cache")

    if cmds.objExists(cacheName):
        cmds.delete(cacheName)
        print cacheName + " deleted"

    #### Get the filename as prefix
    current_file_name = cmds.file(sceneName=True, query=True, shortName=1)
    mighty_GPU_cache_prefix = (current_file_name.split('_animation_'))[0]

    #### Get the timeline range
    minTime = cmds.playbackOptions(q=1, minTime=1)
    maxTime = cmds.playbackOptions(q=1, maxTime=1)

    ## Generate GPU cache file name with Prefix
    GPUcacheFileName = (mighty_GPU_cache_prefix + "_" + nameSpaceString +
                        "_GPUcache")
    print "######## GPU Cache will be named " + GPUcacheFileName + " ########"

    ## GPU cache processing
    cmds.gpuCache(nameSpaceString + ":Geometries",
                  startTime=minTime,
                  endTime=maxTime,
                  optimize=1,
                  optimizationThreshold=40000,
                  directory="",
                  fileName=GPUcacheFileName)
    print "######## GPU Cache processed ########"

    # ==============
    # - Load Cache -
    # ==============
    ## cachePath concatenation
    homedir = os.environ['HOME']
    cachePath = (homedir + "/maya/projects/default/cache/alembic/" +
                 GPUcacheFileName + ".abc")
    print "######## GPU Cache generated as " + cachePath + " ########"

    # Create Cache Node
    cacheNodeName = (nameSpaceString + "_GPU_cacheShape")
    cacheNode = cmds.createNode('gpuCache', name=cacheNodeName)
    cacheParent = cmds.listRelatives(cacheNode, p=True, pa=True)
    cacheParent = cmds.rename(cacheParent, cacheName)
    # Load the GPU datas into the cacheNode
    cmds.setAttr(cacheNode + '.cacheFileName', cachePath, type='string')
    # ==============
    # - End Load Cache -
    # ==============
    ## Unload the referenced rig
    refString = "CHAR_" + nameSpaceString + "1RN"
    cmds.file(unloadReference="CHAR_" + nameSpaceString + "_1RN")
    print "######## Rig unloaded and GPU loaded ########"
Beispiel #4
0
def export_gpu(out_path, startFrame, endFrame):
    # Ensure alembic exporter is loaded
    cmds.loadPlugin("gpuCache", quiet=True)

    cmds.gpuCache(cmds.ls(sl=True, long=True),
                  startTime=startFrame,
                  endTime=endFrame,
                  optimize=True,
                  optimizationThreshold=40000,
                  writeMaterials=True,
                  writeUVs=True,
                  dataFormat="ogawa",
                  saveMultipleFiles=False,
                  directory=os.path.dirname(out_path),
                  fileName=os.path.splitext(os.path.basename(out_path))[0])
Beispiel #5
0
def export_gpu_cache(root,
                     directory,
                     filename,
                     start_time=1,
                     end_time=1,
                     save_multiple_files=True):
    mc.gpuCache(root,
                directory=directory,
                fileName=filename,
                optimize=1,
                writeMaterials=1,
                dataFormat="ogawa",
                startTime=start_time,
                endTime=end_time,
                saveMultipleFiles=save_multiple_files)
Beispiel #6
0
def exportGPUCacheGrp(exportGrp, exportPath, abcName, time = 'still') :
    startFrame = 1.0
    endFrame = 1.0

    if time == 'still' :
        currentFrame = mc.currentTime(q = True)
        startFrame = currentFrame
        endFrame = currentFrame

    if time == 'animation' :
        startFrame = mc.playbackOptions(q = True, min = True)
        endFrame = mc.playbackOptions(q = True, max = True)

    # export objs
    if mc.objExists(exportGrp) :
        mc.select(exportGrp)
        result = mc.gpuCache(exportGrp,
                                startTime = startFrame,
                                endTime = endFrame,
                                optimize = True,
                                optimizationThreshold = 40000,
                                writeMaterials = True,
                                dataFormat = 'ogawa',
                                directory = exportPath,
                                fileName = abcName,
                                saveMultipleFiles = False
                                )

        gpupath = '%s/%s.abc' % (exportPath,abcName)

        return result
Beispiel #7
0
def exportGpuCache(objName , dest, filename):
	'''
	Export GPU cache

	Variable :
	@objName	: Object name
	@dest		: Directory destination
	@filename	: finemat without extension
	'''
	# Export GPU cache
	loadGpuCachePlugin()

	loadAbcExportPlugin()

	result = cmds.gpuCache(	objName,
					startTime	= 1,
					endTime		= 1,
					optimize 	= True,
					optimizationThreshold = 40000, 
					writeMaterials = True,
					dataFormat 	= "ogawa", 
					directory 	= dest,
					fileName 	= filename)

	return str(result)
def mExportGPUCache(ves_grp, playbackRange, gpuName):
	"""
	輸出 GPU cache, 目前為多檔案輸出
	多檔案輸出時, saveMultipleFiles= True, 以及使用 filePrefix
	單檔案輸出時, saveMultipleFiles= False, 使用 fileName
	"""
	ves_member = cmds.listRelatives(ves_grp, c= 1)
	st = playbackRange[0]
	et = playbackRange[1]
	dirPath = os.path.dirname(gpuName)
	single = ''
	prefix = os.path.basename(gpuName)
	result = cmds.gpuCache(ves_member, startTime= st, endTime= et,
						optimize= 1, optimizationThreshold= 40000,
						writeMaterials= 1, dataFormat= 'ogawa',
						saveMultipleFiles= True,
						directory= dirPath,
						filePrefix= prefix, fileName= single)
	return result
Beispiel #9
0
def exportGPUCache(exportObjects, exportPath, abcName, time = 'still') :
    startFrame = 1.0
    endFrame = 1.0

    if time == 'still' :
        currentFrame = mc.currentTime(q = True)
        startFrame = currentFrame
        endFrame = currentFrame

    if time == 'animation' :
        startFrame = mc.playbackOptions(q = True, min = True)
        endFrame = mc.playbackOptions(q = True, max = True)

    # export objs
    validObjs = [a for a in exportObjects if mc.objExists(a)]
    objNotExists = [a for a in exportObjects if not mc.objExists(a)]

    if validObjs :
        mc.select(validObjs)
        result = mc.gpuCache(exportObjects,
                                startTime = startFrame,
                                endTime = endFrame,
                                optimize = True,
                                optimizationThreshold = 40000,
                                writeMaterials = True,
                                dataFormat = 'ogawa',
                                directory = exportPath,
                                fileName = abcName,
                                saveMultipleFiles = False
                                )

        gpupath = '%s/%s.abc' %(exportPath,abcName)

        if objNotExists :
            mm.eval('warning "%s not exists and will not be exported";' % objNotExists)

        return result

    else :
        mm.eval('warning "Objects not exists";' % objNotExists)
        return False
Beispiel #10
0
def generate_gpu_cache(geo_node, cache_name, start, end, rig_node, lock=False):
    """ Generates a GPU representation for shapes found under the geo_node

    Args:
        geo_node (str): geometry group transform node containing the shapes to
                        cache
        cache_name (str): file name to use for the gpu cache file
        start (float): start frame to use
        end (float): end frame to use
        rig_node (str): Rig root node containing the geo_node
        lock (bool): Whether or not the gpu cache node should be locked
    """

    # checks for plugin load
    check_gpu_plugin()

    # gets cache destination path
    cache_destination = get_cache_destination_path()

    try:
        file_name = re.sub('[^\w_.)( -]', '_', cache_name)
        file_name += "_{}".format(get_time_stamp())
        # Runs the GPU cache generation
        gpu_file = cmds.gpuCache("{}".format(geo_node),
                                 startTime=start,
                                 endTime=end,
                                 optimize=True,
                                 optimizationThreshold=4000,
                                 writeMaterials=True,
                                 directory=cache_destination,
                                 fileName=file_name,
                                 showStats=True,
                                 useBaseTessellation=False,
                                 saveMultipleFiles=True)

        # loads gpu cache
        return load_gpu_cache(cache_name, gpu_file[0], rig_node, lock)

    except Exception as e:
        raise e
Beispiel #11
0
def mExportGPUCache(ves_grp, playbackRange, gpuName):
    """
	輸出 GPU cache, 目前為多檔案輸出
	多檔案輸出時, saveMultipleFiles= True, 以及使用 filePrefix
	單檔案輸出時, saveMultipleFiles= False, 使用 fileName
	"""
    ves_member = cmds.listRelatives(ves_grp, c=1)
    st = playbackRange[0]
    et = playbackRange[1]
    dirPath = os.path.dirname(gpuName)
    single = ''
    prefix = os.path.basename(gpuName)
    result = cmds.gpuCache(ves_member,
                           startTime=st,
                           endTime=et,
                           optimize=1,
                           optimizationThreshold=40000,
                           writeMaterials=1,
                           dataFormat='ogawa',
                           saveMultipleFiles=True,
                           directory=dirPath,
                           filePrefix=prefix,
                           fileName=single)
    return result
Beispiel #12
0
def start_trans():

    get_frame_start = mc.intField("the_ST_ABC", q=True, v=True)
    get_frame_end = mc.intField("the_ET_ABC", q=True, v=True)
    write_UV = ["", "-uvWrite"]
    # world_Space = ["","-worldSpace"]
    ifUV = int(mc.checkBox("if_write_UV", q=True, v=True))
    # ifWP = 1
    daili = mc.optionMenu("the_dai", q=True, sl=True)
    get_cj_list = mc.textScrollList("the_cj_list", q=True, ai=True)
    if_comb = int(mc.checkBox("if_combine", q=True, v=True))
    get_final_out_path = mc.textField("thePath_to_out", q=True, tx=True)
    get_final_out_filename = mc.textField("the_out_file_name", q=True, tx=True)
    get_the_step = mc.floatField("the_EVA_every", q=True, v=True)
    dataType = int(mc.optionMenu("cacheData", q=True, sl=True))
    all_need_to_cache = mc.textScrollList("the_mod_list", q=True, ai=True)
    all_need_to_string = ""
    all_need_to_cache_string = ""
    all_need_to_cache_string_2 = ""
    #导出代理

    #输出缓存
    if if_comb == 1 and str(all_need_to_cache) != "None":
        for oneGroup in all_need_to_cache:
            Groups = mc.listRelatives(oneGroup, allParents=True)
            group_M = mc.ls(oneGroup, dag=True, ni=True, shapes=True)
            if len(group_M) > 1:
                objComb = mc.polyUnite(oneGroup,
                                       ch=True,
                                       mergeUVSets=True,
                                       name=oneGroup + "_comb")
                if Groups:
                    mc.parent(objComb[0], Groups[0])

            if len(group_M) == 1:
                oneObj = mc.listRelatives(group_M[0], allParents=True)
                mc.rename(oneObj, oneGroup + "_comb")
            all_need_to_string += "\"" + oneGroup + "_comb" + "\","

        if str(all_need_to_string) != 0:
            mc.textScrollList("the_mod_list", e=True, ra=True)
            exec("mc.textScrollList(\"the_mod_list\",e=True,append=(" +
                 all_need_to_string[0:-1] + "))")
    all_need_to_cache = mc.textScrollList("the_mod_list", q=True, ai=True)
    for one_cache in all_need_to_cache:
        all_need_to_cache_string += " -root " + one_cache
        all_need_to_cache_string_2 += one_cache + " "
    #导出ABC缓存
    if dataType == 1:
        get_cache_path = mc.workspace(en="cache")
        get_cache_paths = r'%s/alembic/' % get_cache_path
        if not os.path.isdir(get_cache_paths):
            os.makedirs(get_cache_paths)
        # mc.AbcExport(j="-frameRange "+str(get_frame_start)+" "+str(get_frame_end)+" "+"-step "+str(get_the_step)+" "+write_UV[ifUV]+" -worldSpace"+all_need_to_cache_string+" -file "+get_final_out_path+get_final_out_filename+".abc");
        mc.AbcExport(j="-frameRange " + str(get_frame_start) + " " +
                     str(get_frame_end) + " " + "-step " + str(get_the_step) +
                     " " + write_UV[ifUV] + " -worldSpace" +
                     all_need_to_cache_string + " -file " + get_cache_paths +
                     get_final_out_filename + ".abc")
        mc.delete(all_need_to_cache, ch=True)
        #mm.eval("AbcImport -mode import -connect \""+all_need_to_cache_string_2[0:-1]+"\" \""+get_final_out_path+get_final_out_filename+".abc"+"\"")
        mm.eval("AbcImport -mode import -connect \"" +
                all_need_to_cache_string_2[0:-1] + "\" \"" + get_cache_paths +
                get_final_out_filename + ".abc" + "\"")

    #导出GPU缓存
    if dataType == 2:
        get_cache_path = mc.workspace(en="cache")
        get_cache_paths = r'%s/alembic/' % get_cache_path
        if not os.path.isdir(get_cache_paths):
            os.makedirs(get_cache_paths)
        mc.select(all_need_to_cache, r=True)
        # mc.gpuCache(all_need_to_cache, startTime  = get_frame_start, endTime  = get_frame_end, saveMultipleFiles = False, optimize = False, writeMaterials = False, dataFormat = "ogawa", wuv = ifUV, directory= get_final_out_path, fileName  = get_final_out_filename)
        mc.gpuCache(all_need_to_cache,
                    startTime=get_frame_start,
                    endTime=get_frame_end,
                    saveMultipleFiles=False,
                    optimize=False,
                    writeMaterials=False,
                    dataFormat="ogawa",
                    wuv=ifUV,
                    directory=get_cache_paths,
                    fileName=get_final_out_filename)
        for one_gpu in all_need_to_cache:
            mc.polyTriangulate(one_gpu)
        mc.delete(all_need_to_cache, ch=True)
        # mm.eval("AbcImport -mode import -connect \"" +all_need_to_cache_string_2[0:-1] + "\" -createIfNotFound " + " \"" +get_final_out_path+get_final_out_filename+".abc"+"\"")
        mm.eval("AbcImport -mode import -connect \"" +
                all_need_to_cache_string_2[0:-1] + "\" -createIfNotFound " +
                " \"" + get_cache_paths + get_final_out_filename + ".abc" +
                "\"")

    #导出几何体缓存
    if dataType == 3:
        all_need_to_cache_shape = mc.ls(all_need_to_cache,
                                        dagObjects=True,
                                        ni=True,
                                        shapes=True)
        cacheFiles = mc.cacheFile(r=True,
                                  sch=True,
                                  dtf=True,
                                  fm='OneFile',
                                  spm=1,
                                  smr=1,
                                  directory=get_final_out_path,
                                  fileName=get_final_out_filename,
                                  st=get_frame_start,
                                  et=get_frame_end,
                                  points=all_need_to_cache_shape)
        mc.delete(all_need_to_cache, ch=True)
        myswichList = []
        myswichNode = []
        myNewcacheObjects = []
        switchText = ''
        for each in all_need_to_cache_shape:
            switch = mm.eval('createHistorySwitch("%s",false)' % each)
            myNewcacheObjects.append(each)
            myswichNode.append(switch)
            switchText = '%s.inp[0]' % switch
            myswichList.append(switchText)
            mc.setAttr('%s.playFromCache' % switch, 1)
        mc.cacheFile(f=get_final_out_filename,
                     directory=get_final_out_path,
                     cnm=myNewcacheObjects,
                     ia=myswichList,
                     attachFile=True)

    #输出blend缓存
    if dataType == 4:
        mc.select(all_need_to_cache, r=True)
        mm.eval('x_bakeShape(%s,%s,%s, "%s", 0, 0)' %
                (get_frame_start, get_frame_end, get_the_step,
                 get_final_out_filename))
        mc.textScrollList("the_mod_list", e=True, ra=True)
        exec(
            "mc.textScrollList(\"the_mod_list\",e=True,append=(get_final_out_filename+'_bakeshape_gp'))"
        )
        mc.delete(all_need_to_cache, ch=True)
        mc.select(hi=True)
    #导出另存文件
    all_need_to_cache = mc.textScrollList("the_mod_list", q=True, ai=True)
    all_need_others = mc.textScrollList("the_others_list", q=True, ai=True)
    if str(all_need_others) != "None":
        mc.select(all_need_others + all_need_to_cache, r=True)
    else:
        mc.select(all_need_to_cache, r=True)
    maormb = mc.optionMenu("the_ma_mb", q=True, sl=True)
    MA_MB = ["mayaBinary", "mayaAscii"]
    ma_mb = [".mb", ".ma"]
    mm.eval("file -force -options \"v=0;\" -typ \"" + MA_MB[maormb - 1] +
            "\" -pr -es \"" + get_final_out_path + get_final_out_filename +
            ma_mb[maormb - 1] + "\"")
Beispiel #13
0
def BG_ASM_SET():
    trs = pymel.core.ls( tr=1 )
    
    topNodes = []
    for tr in trs:
        if tr.getParent(): continue
        children = tr.listRelatives( c=1 )
        proxyExists = False
        for child in children:
            if child[0] == 'V':
                proxyExists = True
                break
        if proxyExists: topNodes.append( tr )
    
    targets = []
    
    pymel.core.makeIdentity( topNodes, apply=1, t=1, r=1, s=1, n=0, pn=1 )
    
    for topNode in topNodes:
        children = topNode.listRelatives( c=1 )
        for child in children:
            if child.find( 'V3' ) != -1: 
                targets.append( topNode )
                continue
            pymel.core.delete( child )
    
    for target in targets:
        children = target.listRelatives( c=1, ad=1 )
        for child in children:
            pymel.core.showHidden( child, a=1 )
        
        reducedObj = sgCmds.combineMultiShapes( target )
        pymel.core.polyReduce( reducedObj, ver=1, trm=0, p=90, vct=0, tct=0, shp=0, keepBorder=1, keepMapBorder=1, 
                               keepColorBorder=1, keepFaceGroupBorder=1, keepHardEdge=1, keepCreaseEdge=1, keepBorderWeight=0.5, 
                               keepMapBorderWeight=0.5, keepColorBorderWeight=0.5, keepFaceGroupBorderWeight=0.5, keepHardEdgeWeight=0.5, 
                               keepCreaseEdgeWeight=0.5, useVirtualSymmetry=0, symmetryTolerance=0.01, sx=0, sy=1, sz=0, sw=0, preserveTopology=1, keepQuadsWeight=1, vertexMapName="",
                               replaceOriginal=1, cachingReduce=1, ch=1 )
        reducedObj.rename( target.shortName() + '_reduced' )
        pymel.core.select( reducedObj )
        cmds.DeleteHistory()
        
        bb = pymel.core.exactWorldBoundingBox( target )    
        bbmin = bb[:3]
        bbmax = bb[-3:]
        points = [[] for i in range(8)]
        points[0] = [bbmin[0], bbmin[1], bbmax[2]]
        points[1] = [bbmax[0], bbmin[1], bbmax[2]]
        points[2] = [bbmin[0], bbmax[1], bbmax[2]]
        points[3] = [bbmax[0], bbmax[1], bbmax[2]]
        points[4] = [bbmin[0], bbmax[1], bbmin[2]]
        points[5] = [bbmax[0], bbmax[1], bbmin[2]]
        points[6] = [bbmin[0], bbmin[1], bbmin[2]]
        points[7] = [bbmax[0], bbmin[1], bbmin[2]]
        
        boundingBoxObj = pymel.core.polyCube( ch=1, o=1, cuv=4, n= target.shortName() + '_gpu' )[0]
        boundingBoxObjShape = boundingBoxObj.getShape()
        boundingBoxObjShape.overrideEnabled.set( 1 )
        boundingBoxObjShape.overrideDisplayType.set( 2 )
        
        newLambert = pymel.core.shadingNode( 'lambert', asShader=1 )
        newLambertSG = pymel.core.sets( renderable=1, noSurfaceShader=1, empty=1, name= newLambert + 'SG' )
        newLambert.outColor >> newLambertSG.surfaceShader
        newLambert.transparency.set( 1,1,1 )
        cmds.sets( boundingBoxObj.name(), e=1, forceElement=newLambertSG.name() )
        
        for i in range( 8 ):
            pymel.core.move( points[i][0], points[i][1], points[i][2], boundingBoxObj + '.vtx[%d]' % i )
        
        sceneName = cmds.file( q=1, sceneName=1 )
        gpuPath = os.path.dirname( sceneName )
        
        pymel.core.select( target )
        mel.eval( 'displaySmoothness -divisionsU 0 -divisionsV 0 -pointsWire 4 -pointsShaded 1 -polygonObject 1;' )
        
        targetParents = cmds.listRelatives( target.name(), p=1, f=1 )
        targetPos = cmds.getAttr( target+ '.m' )
        cmds.xform( target.name(), os=1, matrix= sgCmds.getListFromMatrix( OpenMaya.MMatrix() ) )
        abcPath = cmds.gpuCache( target.name(), startTime=1, endTime=1, optimize=1, optimizationThreshold=1000, writeMaterials=0, dataFormat='ogawa',
                                 directory=gpuPath, fileName=target.replace( '|', '_' ), saveMultipleFiles=False )[0]
        cmds.xform( target.name(), os=1, matrix= targetPos )
        gpuObjName = target.split( '|' )[-1]+'_gpuOrig'
        gpuCacheNode = cmds.createNode( 'gpuCache' )
        gpuCacheObj = cmds.listRelatives( gpuCacheNode, p=1, f=1 )[0]
        gpuCacheObj = cmds.rename( gpuCacheObj, gpuObjName )
        gpuShapeName = cmds.listRelatives( gpuCacheObj, c=1,f=1 )[0]
        cmds.setAttr( gpuShapeName+'.cacheFileName', abcPath, type='string' )
        if targetParents:
            gpuCacheObj = cmds.parent( gpuCacheObj, targetParents[0] )
        cmds.xform( gpuCacheObj, os=1, matrix= targetPos )
        gpuCacheObj = pymel.core.ls( gpuCacheObj )[0]
        
        src = target
        gpuShape = gpuCacheObj.getShape()
        pymel.core.parent( gpuShape, boundingBoxObj, shape=1, add=1 )
        pymel.core.delete( gpuCacheObj )
        others = [reducedObj,boundingBoxObj]
        
        sceneName = cmds.file( q=1, sceneName=1 )
        fileName = sceneName.split( '/' )[-1].split( '.' )[0]
        targetPath = '.'.join( sceneName.split( '.' )[:-1] ) + '.mi'
        
        pymel.core.select( target )
        mel.eval( 'displaySmoothness -divisionsU 3 -divisionsV 3 -pointsWire 16 -pointsShaded 4 -polygonObject 3;' )
        
        pymel.core.select( src )
        cmds.file( targetPath, options='binary=1;compression=0;tabstop=8;perframe=0;padframe=0;perlayer=1;pathnames=3313323333;assembly=0;fragment=0;fragsurfmats=0;fragsurfmatsassign=0;fragincshdrs=0;fragchilddag=0;passcontrimaps=1;passusrdata=1;overrideAssemblyRootName=0;assemblyRootName=binary=1;compression=0;tabstop=8;perframe=0;padframe=0;perlayer=0;pathnames=3313333333;assembly=1;fragment=1;fragsurfmats=1;fragsurfmatsassign=1;fragincshdrs=1;fragchilddag=1;passcontrimaps=1;passusrdata=0;filter=00000011010000001101000;overrideAssemblyRootName=0;assemblyRootName=',
                   typ='mentalRay', pr=1, es=1, force=1 )
        mel.eval( 'Mayatomr -mi  -exportFilter 721600 -active -binary -fe  -fem  -fma  -fis  -fcd  -pcm  -as  -asn "%s" -xp "3313333333" -file "%s"' % (fileName,targetPath) )
        
        for other in others:
            otherShape = other.getShape()
            if otherShape.nodeType() == 'mesh':
                otherShape.miUpdateProxyBoundingBoxMode.set(3)
                otherShape.miProxyFile.set( targetPath )
        
        target.rename( target + '_orig' )
        
        folderPath = os.path.dirname( cmds.file( q=1, sceneName=1 ) )
        fileName = cmds.file( q=1, sceneName=1 ).split( '/' )[-1].split( '.' )[0]
        if not cmds.pluginInfo( 'sceneAssembly', q=1, l=1 ):
            cmds.loadPlugin( 'sceneAssembly' )
        
        mel.eval( 'assemblyCreate assemblyDefinition' )
        asmNode = pymel.core.ls( type='assemblyDefinition' )[-1]
        asmNode.rename( 'ASM_' + fileName )
        reps = pymel.core.assembly( asmNode, q=1, listRepresentations=1 )
        if reps:
            for rep in reps:
                pymel.core.assembly( asmNode, e=1, deleteRepresentation=rep )
        
        index = 0
        repNames = []
        for sel in [boundingBoxObj,reducedObj,target]:
            selShape = sel.getShape()
            repName = sel.split( '_' )[-1]
            repNames.append( repName )
            if selShape:
                if selShape.nodeType() == 'gpuCache':
                    pymel.core.assembly( asmNode, edit=True, createRepresentation='Cache',
                      input=selShape.cacheFileName.get(), repName=repName )
                    asmNode.attr( 'representations' )[index].repLabel.set( repName )
                    index+=1
                    continue            
            pymel.core.select( sel )
            filePath = folderPath + '/ASMOBJ_' + sel.shortName() + '.mb'
            cmds.file( filePath, force=1, options="v=0;", typ="mayaBinary", pr=1, es=1 )    
            pymel.core.assembly( asmNode, edit=True, createRepresentation='Scene',
                      input=filePath, repName=repName )
            asmNode.attr( 'representations' )[index].repLabel.set( repName )
            index+=1
        
        scenePath = cmds.file( q=1, sceneName=1 )
        folderName = os.path.dirname( scenePath )
        fileName = scenePath.split( '/' )[-1].split( '.' )[0]
        exportPath = folderName + '/ASM_' + fileName + '.mb'
        
        pymel.core.select( asmNode )
        cmds.file( exportPath, force=1, options="v=0;", typ="mayaBinary", pr=1, es=1 )
Beispiel #14
0
def create_gpu_cache(objName='',gpuDirname='',gpuBasename=''):
    # gpuCache -startTime 1 -endTime 1 -optimize -optimizationThreshold 40000 -writeMaterials -dataFormat ogawa -directory "C:/Users/vanef/Dropbox/media_server/project/asset/prop/general/glass/prePublish" -fileName "glass_gpu" Md_Geo_Grp;
    return mc.gpuCache(objName,startTime=1,endTime=1,optimize=True,optimizationThreshold=40000,writeMaterials=True,dataFormat="ogawa",fileName=gpuBasename,directory=gpuDirname)
Beispiel #15
0
def publish_gpu(*args, **kwargs):
    """ 上传模型abc文件
        args: entity_type, entity_id, attr_id
    """

    _task_id, _output_attr_id = args

    _output_attr_handle = zfused_api.attr.Output(_output_attr_id)
    _file_format = _output_attr_handle.format()
    _suffix = _output_attr_handle.suffix()
    _attr_code = _output_attr_handle.code()

    _task = zfused_api.task.Task(_task_id)
    _production_path = _task.production_path()
    _project_entity_production_path = _task.project_entity().production_path()
    _temp_path = _task.temp_path()
    _file_code = _task.file_code()
    if kwargs.get("fix_version"):
        _file_index = "{:0>4d}".format(_task.last_version_index(0))
    else:
        _file_index = "{:0>4d}".format(_task.last_version_index() + 1)

    _production_file = "{}/{}/{}.{}{}".format(_production_path, _attr_code,
                                              _file_code, _file_index, _suffix)
    _cover_file = "{}/{}/{}{}".format(_production_path, _attr_code, _file_code,
                                      _suffix)
    _publish_file = "{}/{}/{}.{}{}".format(_temp_path, _attr_code, _file_code,
                                           _file_index, _suffix)
    _publish_file_dir = os.path.dirname(_publish_file)
    if not os.path.isdir(_publish_file_dir):
        os.makedirs(_publish_file_dir)

    _file_name = "{}.{}".format(_file_code, _file_index)

    try:
        # 添加顶点色

        # change shading color
        _engines = shadingengine.get_shading_engines()
        #
        for _index, _engine in enumerate(_engines):
            _color = shadingengine.get_node_shading_color(_engine)
            # 可能会出问题
            if _color:
                shadingengine.set_node_shading_color(_engine, _color)
        shadingengine.switch_color_shader(_engines)

        # get rendering group
        _is_rendering = renderinggroup.nodes()
        _rendering_groups = " ".join(_is_rendering)

        _alembic_nodes = cmds.ls(type="AlembicNode")
        if _alembic_nodes:
            _start_time = cmds.playbackOptions(q=True, min=True)
            _end_time = cmds.playbackOptions(q=True, max=True)
            cmds.gpuCache(_rendering_groups,
                          useBaseTessellation=True,
                          startTime=_start_time,
                          endTime=_end_time,
                          writeMaterials=True,
                          directory=_publish_file_dir,
                          fileName=_file_name)  #allDagObjects = True)
        else:
            # will reduce mesh
            # get gpu reduce percentage
            _reduce_percentage = _task.project_entity().xattr(
                "gpu_reduce_percentage")
            if _reduce_percentage == "100":
                cmds.gpuCache(_rendering_groups,
                              useBaseTessellation=True,
                              startTime=1,
                              endTime=1,
                              writeMaterials=True,
                              directory=_publish_file_dir,
                              fileName=_file_name)  #allDagObjects = True)
            else:
                reducemesh.reduce_mesh(float(_reduce_percentage),
                                       _publish_file_dir, _file_name)

    except Exception as e:
        logger.error(e)
        return False

    # publish file
    _result = filefunc.publish_file(_publish_file, _production_file)
    _result = filefunc.publish_file(_publish_file, _cover_file)

    # record in file
    _file_info = zfile.get_file_info(_publish_file, _production_file)
    _cover_file_info = zfile.get_file_info(_cover_file, _cover_file)
    zfused_api.task.new_production_file([_file_info, _cover_file_info],
                                        _task_id, _output_attr_id,
                                        int(_file_index))

    return True
Beispiel #16
0
        pymel.core.move(points[i][0], points[i][1], points[i][2],
                        boundingBoxObj + '.vtx[%d]' % i)

    sceneName = cmds.file(q=1, sceneName=1)
    gpuPath = os.path.dirname(sceneName)

    targetParents = cmds.listRelatives(target.name(), p=1, f=1)
    targetPos = cmds.getAttr(target + '.m')
    cmds.xform(target.name(),
               os=1,
               matrix=sgCmds.matrixToList(OpenMaya.MMatrix()))
    abcPath = cmds.gpuCache(target.name(),
                            startTime=1,
                            endTime=1,
                            optimize=1,
                            optimizationThreshold=1000,
                            writeMaterials=0,
                            dataFormat='ogawa',
                            directory=gpuPath,
                            fileName=target.replace('|', '_'),
                            saveMultipleFiles=False)[0]
    cmds.xform(target.name(), os=1, matrix=targetPos)
    gpuObjName = target.split('|')[-1] + '_gpu'
    gpuCacheNode = cmds.createNode('gpuCache')
    gpuCacheObj = cmds.listRelatives(gpuCacheNode, p=1, f=1)[0]
    gpuCacheObj = cmds.rename(gpuCacheObj, gpuObjName)
    gpuShapeName = cmds.listRelatives(gpuCacheObj, c=1, f=1)[0]
    cmds.setAttr(gpuShapeName + '.cacheFileName', abcPath, type='string')
    if targetParents:
        gpuCacheObj = cmds.parent(gpuCacheObj, targetParents[0])
    cmds.xform(gpuCacheObj, os=1, matrix=targetPos)
    gpuCacheObj = pymel.core.ls(gpuCacheObj)[0]
Beispiel #17
0
def BG_ASM_SET():
    trs = pymel.core.ls(tr=1)

    topNodes = []
    for tr in trs:
        if tr.getParent(): continue
        children = tr.listRelatives(c=1)
        proxyExists = False
        for child in children:
            if child[0] == 'V':
                proxyExists = True
                break
        if proxyExists: topNodes.append(tr)

    targets = []

    pymel.core.makeIdentity(topNodes, apply=1, t=1, r=1, s=1, n=0, pn=1)

    for topNode in topNodes:
        children = topNode.listRelatives(c=1)
        for child in children:
            if child.find('V3') != -1:
                targets.append(topNode)
                continue
            pymel.core.delete(child)

    for target in targets:
        children = target.listRelatives(c=1, ad=1)
        for child in children:
            pymel.core.showHidden(child, a=1)

        reducedObj = sgCmds.combineMultiShapes(target)
        pymel.core.polyReduce(reducedObj,
                              ver=1,
                              trm=0,
                              p=90,
                              vct=0,
                              tct=0,
                              shp=0,
                              keepBorder=1,
                              keepMapBorder=1,
                              keepColorBorder=1,
                              keepFaceGroupBorder=1,
                              keepHardEdge=1,
                              keepCreaseEdge=1,
                              keepBorderWeight=0.5,
                              keepMapBorderWeight=0.5,
                              keepColorBorderWeight=0.5,
                              keepFaceGroupBorderWeight=0.5,
                              keepHardEdgeWeight=0.5,
                              keepCreaseEdgeWeight=0.5,
                              useVirtualSymmetry=0,
                              symmetryTolerance=0.01,
                              sx=0,
                              sy=1,
                              sz=0,
                              sw=0,
                              preserveTopology=1,
                              keepQuadsWeight=1,
                              vertexMapName="",
                              replaceOriginal=1,
                              cachingReduce=1,
                              ch=1)
        reducedObj.rename(target.shortName() + '_reduced')
        pymel.core.select(reducedObj)
        cmds.DeleteHistory()

        bb = pymel.core.exactWorldBoundingBox(target)
        bbmin = bb[:3]
        bbmax = bb[-3:]
        points = [[] for i in range(8)]
        points[0] = [bbmin[0], bbmin[1], bbmax[2]]
        points[1] = [bbmax[0], bbmin[1], bbmax[2]]
        points[2] = [bbmin[0], bbmax[1], bbmax[2]]
        points[3] = [bbmax[0], bbmax[1], bbmax[2]]
        points[4] = [bbmin[0], bbmax[1], bbmin[2]]
        points[5] = [bbmax[0], bbmax[1], bbmin[2]]
        points[6] = [bbmin[0], bbmin[1], bbmin[2]]
        points[7] = [bbmax[0], bbmin[1], bbmin[2]]

        boundingBoxObj = pymel.core.polyCube(ch=1,
                                             o=1,
                                             cuv=4,
                                             n=target.shortName() + '_gpu')[0]
        boundingBoxObjShape = boundingBoxObj.getShape()
        boundingBoxObjShape.overrideEnabled.set(1)
        boundingBoxObjShape.overrideDisplayType.set(2)

        newLambert = pymel.core.shadingNode('lambert', asShader=1)
        newLambertSG = pymel.core.sets(renderable=1,
                                       noSurfaceShader=1,
                                       empty=1,
                                       name=newLambert + 'SG')
        newLambert.outColor >> newLambertSG.surfaceShader
        newLambert.transparency.set(1, 1, 1)
        cmds.sets(boundingBoxObj.name(), e=1, forceElement=newLambertSG.name())

        for i in range(8):
            pymel.core.move(points[i][0], points[i][1], points[i][2],
                            boundingBoxObj + '.vtx[%d]' % i)

        sceneName = cmds.file(q=1, sceneName=1)
        gpuPath = os.path.dirname(sceneName)

        pymel.core.select(target)
        mel.eval(
            'displaySmoothness -divisionsU 0 -divisionsV 0 -pointsWire 4 -pointsShaded 1 -polygonObject 1;'
        )

        targetParents = cmds.listRelatives(target.name(), p=1, f=1)
        targetPos = cmds.getAttr(target + '.m')
        cmds.xform(target.name(),
                   os=1,
                   matrix=sgCmds.getListFromMatrix(OpenMaya.MMatrix()))
        abcPath = cmds.gpuCache(target.name(),
                                startTime=1,
                                endTime=1,
                                optimize=1,
                                optimizationThreshold=1000,
                                writeMaterials=0,
                                dataFormat='ogawa',
                                directory=gpuPath,
                                fileName=target.replace('|', '_'),
                                saveMultipleFiles=False)[0]
        cmds.xform(target.name(), os=1, matrix=targetPos)
        gpuObjName = target.split('|')[-1] + '_gpuOrig'
        gpuCacheNode = cmds.createNode('gpuCache')
        gpuCacheObj = cmds.listRelatives(gpuCacheNode, p=1, f=1)[0]
        gpuCacheObj = cmds.rename(gpuCacheObj, gpuObjName)
        gpuShapeName = cmds.listRelatives(gpuCacheObj, c=1, f=1)[0]
        cmds.setAttr(gpuShapeName + '.cacheFileName', abcPath, type='string')
        if targetParents:
            gpuCacheObj = cmds.parent(gpuCacheObj, targetParents[0])
        cmds.xform(gpuCacheObj, os=1, matrix=targetPos)
        gpuCacheObj = pymel.core.ls(gpuCacheObj)[0]

        src = target
        gpuShape = gpuCacheObj.getShape()
        pymel.core.parent(gpuShape, boundingBoxObj, shape=1, add=1)
        pymel.core.delete(gpuCacheObj)
        others = [reducedObj, boundingBoxObj]

        sceneName = cmds.file(q=1, sceneName=1)
        fileName = sceneName.split('/')[-1].split('.')[0]
        targetPath = '.'.join(sceneName.split('.')[:-1]) + '.mi'

        pymel.core.select(target)
        mel.eval(
            'displaySmoothness -divisionsU 3 -divisionsV 3 -pointsWire 16 -pointsShaded 4 -polygonObject 3;'
        )

        pymel.core.select(src)
        cmds.file(
            targetPath,
            options=
            'binary=1;compression=0;tabstop=8;perframe=0;padframe=0;perlayer=1;pathnames=3313323333;assembly=0;fragment=0;fragsurfmats=0;fragsurfmatsassign=0;fragincshdrs=0;fragchilddag=0;passcontrimaps=1;passusrdata=1;overrideAssemblyRootName=0;assemblyRootName=binary=1;compression=0;tabstop=8;perframe=0;padframe=0;perlayer=0;pathnames=3313333333;assembly=1;fragment=1;fragsurfmats=1;fragsurfmatsassign=1;fragincshdrs=1;fragchilddag=1;passcontrimaps=1;passusrdata=0;filter=00000011010000001101000;overrideAssemblyRootName=0;assemblyRootName=',
            typ='mentalRay',
            pr=1,
            es=1,
            force=1)
        mel.eval(
            'Mayatomr -mi  -exportFilter 721600 -active -binary -fe  -fem  -fma  -fis  -fcd  -pcm  -as  -asn "%s" -xp "3313333333" -file "%s"'
            % (fileName, targetPath))

        for other in others:
            otherShape = other.getShape()
            if otherShape.nodeType() == 'mesh':
                otherShape.miUpdateProxyBoundingBoxMode.set(3)
                otherShape.miProxyFile.set(targetPath)

        target.rename(target + '_orig')

        folderPath = os.path.dirname(cmds.file(q=1, sceneName=1))
        fileName = cmds.file(q=1, sceneName=1).split('/')[-1].split('.')[0]
        if not cmds.pluginInfo('sceneAssembly', q=1, l=1):
            cmds.loadPlugin('sceneAssembly')

        mel.eval('assemblyCreate assemblyDefinition')
        asmNode = pymel.core.ls(type='assemblyDefinition')[-1]
        asmNode.rename('ASM_' + fileName)
        reps = pymel.core.assembly(asmNode, q=1, listRepresentations=1)
        if reps:
            for rep in reps:
                pymel.core.assembly(asmNode, e=1, deleteRepresentation=rep)

        index = 0
        repNames = []
        for sel in [boundingBoxObj, reducedObj, target]:
            selShape = sel.getShape()
            repName = sel.split('_')[-1]
            repNames.append(repName)
            if selShape:
                if selShape.nodeType() == 'gpuCache':
                    pymel.core.assembly(asmNode,
                                        edit=True,
                                        createRepresentation='Cache',
                                        input=selShape.cacheFileName.get(),
                                        repName=repName)
                    asmNode.attr('representations')[index].repLabel.set(
                        repName)
                    index += 1
                    continue
            pymel.core.select(sel)
            filePath = folderPath + '/ASMOBJ_' + sel.shortName() + '.mb'
            cmds.file(filePath,
                      force=1,
                      options="v=0;",
                      typ="mayaBinary",
                      pr=1,
                      es=1)
            pymel.core.assembly(asmNode,
                                edit=True,
                                createRepresentation='Scene',
                                input=filePath,
                                repName=repName)
            asmNode.attr('representations')[index].repLabel.set(repName)
            index += 1

        scenePath = cmds.file(q=1, sceneName=1)
        folderName = os.path.dirname(scenePath)
        fileName = scenePath.split('/')[-1].split('.')[0]
        exportPath = folderName + '/ASM_' + fileName + '.mb'

        pymel.core.select(asmNode)
        cmds.file(exportPath,
                  force=1,
                  options="v=0;",
                  typ="mayaBinary",
                  pr=1,
                  es=1)