def mkBakeExecution():
	Uiinfo				=		myclass()
	if Uiinfo.result == 0: # Apply
		imgFormat 			=		Uiinfo.dlg.getValue("formats")
		imgres				=		Uiinfo.dlg.getValue("resolution")
		surfShdr			=		Uiinfo.mkCreateCamNrml()
		TimeLine			=		Uiinfo.dlg.getValue("Frame range")
		TimeLine			=		TimeLine.split('-')
		startFrame			=		int(TimeLine[0])
		endFrame			=		int(TimeLine[1])
		cameraName			=		Uiinfo.dlg.getValue("Load camera")
		ShaderName			=		Uiinfo.dlg.getValue("Load shader")
		objectName			=		Uiinfo.dlg.getValue("Load object")
		fileImageName		=		Uiinfo.dlg.getValue("Image name")
		normalCheck			=		Uiinfo.dlg.getValue("Normal map")
		cmds.cameraView(camera=cameraName)
		cmds.currentTime( startFrame, edit=True )
		for i in range (startFrame,endFrame):
			mKcurentFrame	=		cmds.currentTime( query=True )
			intFrame		=		int(mKcurentFrame)
			intFrame		=		str(intFrame).zfill(4)
			cmds.convertSolidTx( ShaderName, objectName, fileImageName=fileImageName+"_"+intFrame+'.'+imgFormat, fil =imgFormat,rx= int(imgres), ry= int(imgres))
			if normalCheck== 1 :
				cmds.convertSolidTx( surfShdr['surface'],objectName, fileImageName= fileImageName+"_nrml."+intFrame+'.'+imgFormat, fil = imgFormat,rx= int(imgres), ry= int(imgres))
			cmds.currentTime( mKcurentFrame+1, edit=True )
示例#2
0
def convert_connection_to_image(shader, attribute, dest_file, overwrite, resolution=1024, pass_through=False):

    if os.path.exists(dest_file) and not overwrite:
        return dest_file

    dest_dir = os.path.split(dest_file)[0]

    create_dir(dest_dir)

    plug_name = shader + '.' + attribute

    if not cmds.objExists(plug_name):
        warning('error converting texture, no object named {0} exists'.format(plug_name))
    else:
        connection = cmds.listConnections(plug_name)
        if not connection:
            warning('nothing connected to {0}, skipping conversion'.format(plug_name))
        elif pass_through == True:
            warning('{0}: skipping conversion'.format(plug_name))
        else:
            cmds.hyperShade(objects=shader)
            connected_object = cmds.ls(sl=True)[0]
            cmds.convertSolidTx(connection[0] ,connected_object ,fileImageName=dest_file, antiAlias=True, bm=3, fts=True, sp=True, alpha=True, doubleSided=True, resolutionX=resolution, resolutionY=resolution)

        return dest_file
def SundayRenderToolsTextureConvert():
    file = 'file2'
    obj = 'PalmTreeA_HeadShape'
    fileSizeX = cmds.getAttr(file + '.outSizeX')
    fileSizeY = cmds.getAttr(file + '.outSizeY')
    newfileName = os.path.basename(cmds.getAttr('file2.fileTextureName'))
    curTexFile = cmds.convertSolidTx(file, obj, fileImageName = newfileName + '_High.png', fileFormat = 'png', alpha = True, rx = fileSizeX, ry = fileSizeY)
    curTexFile = cmds.convertSolidTx(file, obj, fileImageName = newfileName + '_Medium.png', fileFormat = 'png', alpha = True, rx = fileSizeX / 2, ry = fileSizeY / 2)
    curTexFile = cmds.convertSolidTx(file, obj, fileImageName = newfileName + '_Low.png', fileFormat = 'png', alpha = True, rx = fileSizeX / 4, ry = fileSizeY / 4)
    print curTexFile
示例#4
0
def convertConnectionToImage(shader, attribute, dest_file, resolution=1024):
    if not cmds.objExists(shader+'.'+attribute):
        print 'error converting texture, no object named {0} exists'.format(shader+'.'+attribute)
    else:
        connection = cmds.listConnections(shader+'.'+attribute)
        if not connection:
            print 'nothing connected to {0}'.format(plug_name)
        else:
            cmds.hyperShade(objects=shader)
            connected_object = cmds.ls(sl=True)[0]
            print connected_object
            cmds.convertSolidTx(connection[0] ,connected_object ,fileImageName=dest_file, antiAlias=True, bm=3, fts=True, sp=True, alpha=True, doubleSided=True, resolutionX=resolution, resolutionY=resolution)
            return dest_file
示例#5
0
def BakeTexture(*args):

    ### get output path and correct it
    outputOrig = mc.textField('outputTextField', query=True, text=True)

    subPath = outputOrig + '/' + subFolder
    subSubPath = subPath + '/' + subSubFolder

    if not os.path.exists(outputOrig):
        os.makedirs(outputOrig)
    if not os.path.exists(subPath):
        os.makedirs(subPath)
    if not os.path.exists(subSubPath):
        os.makedirs(subSubPath)

    outputStr = str(outputOrig)
    outputDir = outputStr.replace('\\', '/')
    ### other settings
    padding = 4
    resX = 1024
    resY = 1024
    fileFormat = 'jpg'
    geo = mc.ls(sl=True)

    for t in range(currentMin, currentMax + 1, 1):
        ## get padding
        numberExt = ''
        mc.currentTime(t, e=1)
        currentFrame = t
        currentFramePad = len(str(currentFrame))

        if currentFramePad < padding:
            pad = padding - currentFramePad
            i = 1
            while i <= pad:
                numberExt += '0'
                i += 1

        numberExt += str(t)
        ## bake starts here
        imageName = (objectName + '_' + shaderName + '.' + numberExt + '.' +
                     fileFormat)
        imageDir = (outputDir + '/' + subFolder + '/' + subSubFolder + '/' +
                    imageName)
        file = mc.convertSolidTx(bakeShader,
                                 bakeGeo,
                                 antiAlias=0,
                                 bm=1,
                                 fts=1,
                                 sp=0,
                                 sh=0,
                                 alpha=0,
                                 doubleSided=0,
                                 componentRange=0,
                                 resolutionX=resX,
                                 resolutionY=resY,
                                 fileFormat=fileFormat,
                                 fileImageName=imageDir)
        mc.delete(file)
示例#6
0
def convert_connection_to_image(shader,
                                attribute,
                                dest_file,
                                overwrite,
                                resolution=1024,
                                pass_through=False):

    if os.path.exists(dest_file) and not overwrite:
        return dest_file

    dest_dir = os.path.split(dest_file)[0]

    create_dir(dest_dir)

    plug_name = shader + '.' + attribute

    if not cmds.objExists(plug_name):
        warning('error converting texture, no object named {0} exists'.format(
            plug_name))
    else:
        connection = cmds.listConnections(plug_name)
        if not connection:
            warning('nothing connected to {0}, skipping conversion'.format(
                plug_name))
        elif pass_through == True:
            warning('{0}: skipping conversion'.format(plug_name))
        else:
            cmds.hyperShade(objects=shader)
            connected_object = cmds.ls(sl=True)[0]
            cmds.convertSolidTx(connection[0],
                                connected_object,
                                fileImageName=dest_file,
                                antiAlias=True,
                                bm=3,
                                fts=True,
                                sp=True,
                                alpha=True,
                                doubleSided=True,
                                resolutionX=resolution,
                                resolutionY=resolution)

        return dest_file
def	bake_texture_range_v001	(	_resXY	):
	# get shape from selection to get texture later
	_geo		=	cmds.ls			(selection		=	True)[0]
	_shape		=	cmds.pickWalk	(direction		=	'down')[0]
	_scene		=	Scene()
	_path		=	_scene.project	+	'sourceImages/'	+	_scene.name	+	'_textureBake/'
	
	# get texture from geo from shading group connections
	_shadingGroup	= cmds.listConnections	(_shape			+	'.instObjGroups[0]',	source		=	True)[0]
	_shader			= cmds.listConnections	(_shadingGroup	+	'.surfaceShader',		destination	=	True)[0]
	
	if	cmds.nodeType	(_shader)	==	'surfaceShader':
		_texture	=	cmds.listConnections	(_shader	+	'.outColor',	destination	=	True)[0]
	else:
		_texture	=	cmds.listConnections	(_shader	+	'.color',		destination	=	True)[0]
	
	# get the current UV set to bake into
	_UVset			=	cmds.polyUVSet		(_geo,	query	=	True,	currentUVSet	=	True)[0]
	_bakeRange		=	_scene.animationEndFrame	-	_scene.animationStartFrame	+	1
	
	if	not	os.path.isdir	(_path):
		os.mkdir	(_path)
	
	# bake textures in frame range
	for	_k	in	range	(_bakeRange):
		_currentFrame	=	int	(cmds.currentTime	(_k	+	_scene.animationStartFrame)	)
		_currentFrame	=	('0000'	+	str	(_currentFrame)	)[-4:]
		_fileName		=	_path	+	_scene.name	+	'_'	+	_geo	+	'_'	+	_texture	+	'_'	+	_UVset	+	'.'	+	_currentFrame	+	'.tga'
		
		# do bake
		cmds.convertSolidTx		(_texture,	_geo,	antiAlias	=	False,	alpha		=	False,
								doubleSided	=	False,	force	=	False,	fileFormat	=	'tga',
								fileImageName	=	_fileName,
								resolutionX		=	_resXY,	resolutionY	=	_resXY,
								shadows			=	False,	backgroundMode	=	'shader',
								fillTextureSeams	=	False,	uvSetName	=	_UVset)

		print	_fileName

	# delete imported file textures from scene
	mm.eval				(	'hyperShadePanelMenuCommand("hyperShadePanel1", "deleteUnusedNodes");'	)
示例#8
0
def convertConnectionToImage(shader, attribute, dest_file, resolution=1024, pass_through=False):
    
    dest_dir = os.path.split(dest_file)[0]
    if not os.path.exists(dest_dir):
        os.makedirs(dest_dir)

    if not cmds.objExists(shader+'.'+attribute):
        print 'error converting texture, no object named {0} exists'.format(shader+'.'+attribute)
    else:
        connection = cmds.listConnections(shader+'.'+attribute)
        if not connection:
            print 'nothing connected to {0}, skipping conversion'.format(plug_name)
        elif pass_through == True:
            print '{0}: skipping conversion'.format(plug_name)
        else:
            cmds.hyperShade(objects=shader)
            connected_object = cmds.ls(sl=True)[0]
            print connected_object
            cmds.convertSolidTx(connection[0] ,connected_object ,fileImageName=dest_file, antiAlias=True, bm=3, fts=True, sp=True, alpha=True, doubleSided=True, resolutionX=resolution, resolutionY=resolution)
        
        return dest_file
示例#9
0
	def bakeIt(self, sel_geo, shader, sizex, sizey, sel_format, renderPath, imageName, frameNumber ):
		''' bake the image '''

		fileNode = cmds.convertSolidTx(sel_geo, shader, 
									antiAlias=1, bm=1, fts=1, sp=0, sh=0, alpha=0, 
									doubleSided=0, componentRange=0, 
									resolutionX=sizex, resolutionY=sizey, 
									fileFormat=sel_format, 
									fin=renderPath+"/"+imageName+"."+frameNumber+"."+sel_format);

		cmds.clearCache(fileNode)
		cmds.delete(fileNode)
示例#10
0
def mkBakeExecution():
    Uiinfo = myclass()
    if Uiinfo.result == 0:  # Apply
        imgFormat = Uiinfo.dlg.getValue("formats")
        imgres = Uiinfo.dlg.getValue("resolution")
        surfShdr = Uiinfo.mkCreateCamNrml()
        TimeLine = Uiinfo.dlg.getValue("Frame range")
        TimeLine = TimeLine.split('-')
        startFrame = int(TimeLine[0])
        endFrame = int(TimeLine[1])
        cameraName = Uiinfo.dlg.getValue("Load camera")
        ShaderName = Uiinfo.dlg.getValue("Load shader")
        objectName = Uiinfo.dlg.getValue("Load object")
        fileImageName = Uiinfo.dlg.getValue("Image name")
        normalCheck = Uiinfo.dlg.getValue("Normal map")
        cmds.cameraView(camera=cameraName)
        cmds.currentTime(startFrame, edit=True)
        for i in range(startFrame, endFrame):
            mKcurentFrame = cmds.currentTime(query=True)
            intFrame = int(mKcurentFrame)
            intFrame = str(intFrame).zfill(4)
            cmds.convertSolidTx(ShaderName,
                                objectName,
                                fileImageName=fileImageName + "_" + intFrame +
                                '.' + imgFormat,
                                fil=imgFormat,
                                rx=int(imgres),
                                ry=int(imgres))
            if normalCheck == 1:
                cmds.convertSolidTx(surfShdr['surface'],
                                    objectName,
                                    fileImageName=fileImageName + "_nrml." +
                                    intFrame + '.' + imgFormat,
                                    fil=imgFormat,
                                    rx=int(imgres),
                                    ry=int(imgres))
            cmds.currentTime(mKcurentFrame + 1, edit=True)
示例#11
0
 def bake(self):
     for shader, attr in self.shaders.items():
         t = initstats.emit('bake', True)
         assignation = attr[0]
         path = attr[1]
         texture = attr[2]
         Umin, Vmin = tdLib.getUDIM(assignation)
         with tdLib.UndoContext():
             assignation = self.extract_combine(assignation)
             dummyFile = cmds.convertSolidTx(texture + '.outColor', assignation, fileImageName=path, antiAlias=1, backgroundMode=2, resolutionX=512, resolutionY=512, fileFormat='tga', uvRange=[Umin, Umin+1, Vmin, Vmin+1])
         cmds.undo()
         self.reinitialise_texture()
         logger.info(self.create_high(path))
         logger.info(path)
         t.stop()
示例#12
0
 def bake(self):
     for shader, attr in self.shaders.items():
         t = initstats.emit('bake', True)
         assignation = attr[0]
         path = attr[1]
         texture = attr[2]
         Umin, Vmin = tdLib.getUDIM(assignation)
         with tdLib.UndoContext():
             assignation = self.extract_combine(assignation)
             dummyFile = cmds.convertSolidTx(
                 texture + '.outColor',
                 assignation,
                 fileImageName=path,
                 antiAlias=1,
                 backgroundMode=2,
                 resolutionX=512,
                 resolutionY=512,
                 fileFormat='tga',
                 uvRange=[Umin, Umin + 1, Vmin, Vmin + 1])
         cmds.undo()
         self.reinitialise_texture()
         logger.info(self.create_high(path))
         logger.info(path)
         t.stop()
def	bake_texture_range	(	_resXY,	_range	=	0,	_reopenRange	=	10	):
	# get scene name with path to reopen
	_scene			=	Scene()
	_reOpenName		=	_scene.path	+	_scene.name	+	'.mb'
#	_bakePath		=	_scene.project	+	'images/'	+	_scene.name	+	'_textureBake/'
	_bakePath		=	_scene.project	+	'images/'
	
	# create bake path if not exists
	if	not	os.path.isdir	(_bakePath):
		os.mkdir	(_bakePath)

	# get shape from selection to get texture
	_geo			=	cmds.ls			(selection		=	True)[0]
	_shape			=	cmds.pickWalk	(direction		=	'down')[0]

	# get texture from geo from shading group connections
	_shadingGroup	=	cmds.listConnections	(_shape	+	'.instObjGroups[0]',		source			=	True)[0]
	_shader			=	cmds.listConnections	(_shadingGroup	+	'.surfaceShader',		destination	=	True)[0]

	# decide node type for "color" if normal shader or "outcolor" for surface shader
	if	cmds.nodeType	(_shader)	==	'surfaceShader':
		_texture	=	cmds.listConnections	(_shader	+	'.outColor',	destination	=	True)[0]
	else:
		_texture	=	cmds.listConnections	(_shader	+	'.color',		destination	=	True)[0]
	
	# get the current UV set to bake into
	_UVset			=	cmds.polyUVSet			(_geo,	query	=	True,	currentUVSet	=	True)[0]

	# range = current frame only
	if	_range	==	0:
		_frame	=	int(_scene.getCurrentFrame())
#		_fileName		=	_bakePath	+	_scene.name	+	'_'	+	_geo	+	'_'	+	_texture	+	'_'	+	_UVset	+	'.'	+	('0000'	+	str	(_frame)	)[-4:]	+	'.iff'
		_fileName		=	_bakePath	+	_scene.name	+	'_footageBake.'	+	('0000'	+	str	(_frame)	)[-4:]	+	'.iff'
		
		#bake single frame
		cmds.convertSolidTx		(_texture,	_geo,	antiAlias	=	False,	alpha		=	False,
										doubleSided	=	False,	force	=	False,	fileFormat	=	'iff',
										fileImageName	=	_fileName,
										resolutionX		=	_resXY,	resolutionY	=	_resXY,
										shadows			=	False,	backgroundMode	=	'shader',
										fillTextureSeams	=	False,	uvSetName	=	_UVset)
										
		print _fileName
	
	else:
		if	_range	==	1:
			# get bake range from playBack range
			_startFrame		=	_scene.playBackStartFrame
			_endFrame		=	_scene.playBackEndFrame
			_bakeRange		=	_endFrame	-	_startFrame	+	1
			_reOpenTimes	=	(_bakeRange	/	_reopenRange)
			
			if _reOpenTimes	>	int(_reOpenTimes):
				_reOpenTimes	=	int(_reOpenTimes)	+	1
			else:
				_reOpenTimes	=	int(_reOpenTimes)
				
			_frame			=	_scene.playBackStartFrame
			_frame			=	int(_frame)
			
		else:
			# get bake range from playBack range
			_startFrame		=	_scene.renderStartFrame
			_endFrame		=	_scene.renderEndFrame
			_bakeRange		=	_endFrame	-	_startFrame	+	1
			_reOpenTimes	=	int(_bakeRange	/	_reopenRange)	+	1
			_frame			=	_scene.renderStartFrame
			_frame			=	int(_frame)
			
		for	_k	in	range	(_reOpenTimes):
			for	_l	in	range	(_reopenRange):
				if	_frame	<=	_endFrame:
					cmds.currentTime	(_frame)
#					_fileName		=	_bakePath	+	_scene.name	+	'_'	+	_geo	+	'_'	+	_texture	+	'_'	+	_UVset	+	'.'	+	('0000'	+	str	(_frame)	)[-4:]	+	'.iff'
					_fileName		=	_bakePath	+	_scene.name	+	'_footageBake.'	+	('0000'	+	str	(_frame)	)[-4:]	+	'.iff'
					print	_fileName			
				
					# do bake
					cmds.convertSolidTx		(_texture,	_geo,	antiAlias	=	False,	alpha		=	False,
											doubleSided	=	False,	force	=	False,	fileFormat	=	'iff',
											fileImageName	=	_fileName,
											resolutionX		=	_resXY,	resolutionY	=	_resXY,
											shadows			=	False,	backgroundMode	=	'shader',
											fillTextureSeams	=	False,	uvSetName	=	_UVset)

					_frame	=	_frame	+	1

			# reopen scene to empty RAM
			if	_k	<	_reOpenTimes	-	1:
				cmds.file	(_reOpenName,	open	=	True,	force	=	True)
def	bake_texture_range	(	_resXY	):
	# get shape from selection to get texture later
	_geo				= cmds.ls		(selection		= True)[0]
	_shape				= cmds.pickWalk	(direction		= 'down')[0]
	
	# get texture from geo from shading group connections
	_shadingGroup		= cmds.listConnections	(_shape			+ '.instObjGroups[0]',	source		= True)[0]
	_shader				= cmds.listConnections	(_shadingGroup	+ '.surfaceShader',		destination	= True)[0]
	
	if	cmds.nodeType	(_shader)	==	'surfaceShader':
		_texture	= cmds.listConnections	(_shader	+ '.outColor',	destination	= True)[0]
	else:
		_texture	= cmds.listConnections	(_shader	+ '.color',		destination	= True)[0]
	
	# get the current UV set to bake into
	_UVset				= cmds.polyUVSet	(_geo,	query	= True,	currentUVSet	= True)[0]
	
	# bake frame rabge from playback slider
	_bakeStartFrame		= int	(cmds.playbackOptions	(query	= True,	minTime	= True)	)
	_bakeEndFrame		= int	(cmds.playbackOptions	(query	= True,	maxTime	= True)	)
	_bakeRange			= _bakeEndFrame	- _bakeStartFrame	+ 1
	
	# get scene name
	_sceneName			=	cmds.file	(	query	=	True,	sceneName	=	True,	shortName	=	True	)[:-3]
	
	# get scene path and set image directory to /spurceImages/<scenename>
	_path				=	cmds.file	(	query	=	True,	expandName	=	True	)
	_k					=	_path.rfind	(	'/'	)
	_path				=	_path[:_k]
	_k					=	_path.rfind	(	'/'	)
	_path				=	_path[:_k]
	_path				=	_path	+	'/sourceImages/'	+	_sceneName	+	'_textureBake/'
	
	# create image directory if not exists
	if	not	os.path.isdir	(	_path	):
		os.mkdir	(	_path	)
	
	# bake textures in framea range
	for	_k	in	range	(	_bakeRange	):
	
		# set current frame and store for file name
		_currentFrame	=	int	(	cmds.currentTime	(	_k	+	_bakeStartFrame	)	)
		_currentFrame	=		(	'0000'	+	str	(	_currentFrame	)	)[-4:]
		
		# compose filename
		_fileName		=	_path	+	_sceneName	+	'_'	+	_geo	+	'_'	+	_texture	+	'_'	+	_UVset	+	'.'	+	_currentFrame	+	'.tga'
		
		# do bake
		cmds.convertSolidTx		(_texture,	_geo,
								antiAlias			=	False,
								alpha				=	False,
								doubleSided			=	False,
								force				=	False,
								fileFormat			=	'tga',
								fileImageName		=	_fileName,
								resolutionX			=	_resXY,
								resolutionY			=	_resXY,
								shadows				=	False,
								backgroundMode		=	'shader',
								fillTextureSeams	=	False,
								uvSetName			=	_UVset	)
								
		# print filename in script editor
		print _fileName

	# delete imported file textures from scene
	mm.eval				(	'hyperShadePanelMenuCommand("hyperShadePanel1", "deleteUnusedNodes");'	)
	
	# select geo
	cmds.select			(	_geo,	replace	=	True	)
示例#15
0
    currentFrame = t
    currentFramePad = len(str(currentFrame))

    if currentFramePad < padding:
        pad = padding - currentFramePad
        i = 1
        while i <= pad:
            numberExt += '0'
            i += 1

    numberExt += str(t)
    ## bake starts here
    for eachGeo in geo:
        imageName = (name + '_' + shaderName + '.' + numberExt + '.' +
                     fileFormat)
        imageDir = (outputDir + '/' + imageName)
        file = mc.convertSolidTx(shader,
                                 eachGeo,
                                 antiAlias=1,
                                 bm=1,
                                 fts=1,
                                 sp=0,
                                 sh=0,
                                 alpha=0,
                                 doubleSided=0,
                                 componentRange=0,
                                 resolutionX=resX,
                                 resolutionY=rexY,
                                 fileFormat=fileFormat,
                                 fileImageName=imageDir)
        cmds.delete(file)
示例#16
0
    def getOutput(self, GirlName, shaderNode, shaderName, meshName, components,
                  setCount):
        self.GirlName = GirlName
        self.shaderNode = shaderNode
        self.shaderName = shaderName

        texName, inputStr = self.detectInput('float')

        #if self.inputFound:
        #	self.prependToOutput( inputStr )
        #	self.exportName = '%s.%s' % (texName, self.plugName)
        #else:

        self.addToOutput('Texture "%s.%s"' % (self.shaderName, self.GirlName))
        AttrObject = '%s.%s' % (self.shaderName, self.GirlName)
        if self.GirlName == 'bumpmap':
            AttrObject = '%s.normalCamera' % self.shaderName

        if cmds.connectionInfo(AttrObject, isDestination=True):
            sourceNodePath = cmds.connectionInfo(AttrObject,
                                                 sourceFromDestination=True)
            [sourceNode, ooo] = sourceNodePath.split(".")

            sourceNodePath = cmds.connectionInfo(AttrObject,
                                                 sourceFromDestination=True)
            [sourceNode, ooo] = sourceNodePath.split(".")
            """
			Bake the shader
			"""
            print meshName
            areaSize = cmds.getAttr('%s.as' % meshName)
            maxAreaSize = cmds.getAttr('Girl_settings.mas')
            maxTexRes = cmds.getAttr('Girl_settings.mts')
            texRes = math.sqrt(areaSize / maxAreaSize) * maxTexRes

            textureFileFormat = "png"
            fileExt = "png"

            if cmds.nodeType(sourceNode,
                             api=False) == 'bump2d' or cmds.nodeType(
                                 sourceNode, api=False) == 'bump3d':
                sourceNodePath = cmds.connectionInfo(
                    "%s.%s" % (sourceNode, "bumpValue"),
                    sourceFromDestination=True)
                texRes = maxTexRes

            ambientColor = cmds.getAttr('%s.ambientColor' % shaderName)
            [aR, aG, aB] = ambientColor[0]
            cmds.setAttr('%s.ambientColor' % shaderName,
                         1,
                         1,
                         1,
                         type="double3")

            sceneFilePath = cmds.getAttr('Girl_settings.scene_file_path')
            sceneFileName = cmds.getAttr('Girl_settings.scene_filename')
            bakedShaderPath = sceneFilePath + sceneFileName
            if (os.access(bakedShaderPath, os.F_OK) == False):
                os.mkdir(bakedShaderPath)
            bakedShaderPath = bakedShaderPath + '/' + self.shaderName
            if (os.access(bakedShaderPath, os.F_OK) == False):
                os.mkdir(bakedShaderPath)

            #if( cmds.nodeType(sourceNodePath, api=False) ==  'file' ):
            #[sourceNode,ooo] = sourceNodePath.split(".")
            #tmpPath = sourceNode + ".fileTextureName"
            #tmpSourcePath = cmds.getAttr( tmpPath )
            #bakedAttrFilePath = cmds.workspace( en=tmpSourcePath )
            #sourceFilePath = cmds.workspace( en=tmpSourcePath )
            #[zzz, ext] = tmpSourcePath.split(".")
            #bakedAttrFilePath = '%s/%s.%s' % (bakedShaderPath, self.GirlName, ext)

            #print bakedAttrFilePath
            #print sourceFilePath

            #os.system( "copy %s %s" % (sourceFilePath, bakedAttrFilePath) )
            #else:
            bakedAttrFilePath = '%s\\%s.%s' % (bakedShaderPath, self.GirlName,
                                               fileExt)
            selection = OpenMaya.MSelectionList()
            OpenMaya.MGlobal.getActiveSelectionList(selection)
            cmds.select(cl=True)

            faceName = ""
            lastIndices0 = -1
            lastIndices1 = -1
            currentIndex = -1
            pathName = meshName

            haveAFace = 0
            minU = 100
            maxU = -100
            minV = 100
            maxV = -100
            faceU = OpenMaya.MFloatArray()
            faceV = OpenMaya.MFloatArray()

            components.reset()
            while not components.isDone():
                if (lastIndices0 == -1):
                    lastIndices0 = components.index()
                    lastIndices1 = components.index()
                else:
                    currentIndex = components.index()
                    if (currentIndex > lastIndices1 + 1):
                        faceName = (pathName + ".f[" + "%d" % lastIndices0 +
                                    ":" + "%d" % lastIndices1 + "] ")
                        #cmds.select( faceName, add=True )
                        lastIndices0 = currentIndex
                        lastIndices1 = currentIndex
                    else:
                        lastIndices1 = currentIndex
                haveAFace = 1

                components.getUVs(faceU, faceV)
                for i in range(faceU.length()):
                    if (faceU[i] < minU):
                        minU = faceU[i]
                    if (faceU[i] > maxU):
                        maxU = faceU[i]
                for i in range(faceV.length()):
                    if (faceV[i] < minV):
                        minV = faceV[i]
                    if (faceV[i] > maxV):
                        maxV = faceV[i]

                components.next()

            if (haveAFace == 1):
                faceName = (pathName + ".f[" + "%d" % lastIndices0 + ":" +
                            "%d" % lastIndices1 + "] ")
                #cmds.select( faceName, add=True )

            if (setCount == 1):
                minU = 0
                maxU = 1
                minV = 0
                maxV = 1

            print "%f %f %f %f" % (minU, maxU, minV, maxV)
            bakedFileNode = cmds.convertSolidTx(
                sourceNodePath,
                meshName,
                antiAlias=1,
                bm=1,
                fts=1,
                sp=0,
                sh=0,
                alpha=0,
                doubleSided=0,
                uvr=[minU, maxU, minV, maxV],
                resolutionX=texRes,
                resolutionY=texRes,
                fileFormat=textureFileFormat,
                fileImageName=bakedAttrFilePath)

            self.addToOutput('\t"color" "imagemap"')
            bakedAttrFilePath = bakedAttrFilePath.replace('\\', '/')
            self.addToOutput('\t\t"string filename" ["%s"]' %
                             bakedAttrFilePath)
            cmds.setAttr('%s.ambientColor' % shaderName,
                         aR,
                         aG,
                         aB,
                         type="double3")

            if cmds.nodeType(sourceNode,
                             api=False) == 'bump2d' or cmds.nodeType(
                                 sourceNode, api=False) == 'bump3d':
                bumpDepth = cmds.getAttr(sourceNode + ".bumpDepth")
                self.addToOutput('\t\t"float bumpDepth" ["%f"]' % bumpDepth)
            """
			Bake the shader
			
			print meshName
			areaSize = cmds.getAttr( '%s.as' % meshName )
			maxAreaSize = cmds.getAttr( 'Girl_settings.mas' )
			maxTexRes = cmds.getAttr( 'Girl_settings.mts' )
			texRes = math.sqrt(areaSize / maxAreaSize) * maxTexRes
			
			if cmds.nodeType( sourceNode, api=False ) == 'bump2d' or cmds.nodeType( sourceNode, api=False ) == 'bump3d':
				sourceNodePath = cmds.connectionInfo("%s.%s" % (sourceNode, "bumpValue"), sourceFromDestination=True)
				texRes = maxTexRes
			ambientColor = cmds.getAttr('%s.ambientColor' % shaderName )
			[aR, aG, aB] = ambientColor[0]
			cmds.setAttr('%s.ambientColor' % shaderName, 1, 1, 1, type="double3" )
			
			sceneFilePath = cmds.getAttr( 'Girl_settings.scene_file_path' )
			sceneFileName = cmds.getAttr( 'Girl_settings.scene_filename' )
			bakedShaderPath = sceneFilePath + sceneFileName
			if( os.access(bakedShaderPath, os.F_OK) == False ): 
			    os.mkdir(bakedShaderPath)					
			bakedShaderPath = bakedShaderPath + '\\' + self.shaderName
			if( os.access(bakedShaderPath, os.F_OK) == False ): 
			    os.mkdir(bakedShaderPath)					
			bakedAttrFilePath = '%s\\%s.png' % (bakedShaderPath, self.GirlName)
			bakedFileNode = cmds.convertSolidTx(sourceNodePath, meshName, antiAlias=1, bm=1, fts=1, sp=0, sh=0, alpha=0, doubleSided=0, componentRange=0, resolutionX=texRes, resolutionY=texRes, fileFormat="png", fileImageName=bakedAttrFilePath)
			
			self.addToOutput( '\t"color" "imagemap"' )
			bakedAttrFilePath = bakedAttrFilePath.replace('\\', '/')
			self.addToOutput( '\t\t"string filename" ["%s"]' % bakedAttrFilePath)
			
			cmds.setAttr('%s.ambientColor' % shaderName, aR, aG, aB, type="double3");
			"""
            #cmds.setAttr('%s.ambientColor' % shaderName, ambientColor[0], ambientColor[1], ambientColor[2], type="double3" )
        else:
            floatPlug = shaderNode.findPlug(self.plugName)
            floatValue = floatPlug.asFloat() * self.aPreScale

            if self.aInvert:
                floatValue = 1 - floatValue

            if self.aRecip:
                floatValue = 1.0 / floatValue

            floatValue *= self.aPostScale

            self.addToOutput('\t"float" "constant"')
            self.addToOutput('\t\t"float value" [%f]' % floatValue)

        return self.outputString
示例#17
0
    def convert(self, start_frame=None, end_frame=None):
        # Validate settings fields.
        if not self.validate():
            return cmds.warning('Missing required settings.')

        start_frame = start_frame or int(
            cmds.playbackOptions(q=True, minTime=True))
        end_frame = end_frame or int(
            cmds.playbackOptions(q=True, maxTime=True) + 1)

        # Check whether the alleged attribute has a map assigned.
        path_map = self.get_assigned_map()
        if not path_map:
            return cmds.warning(
                'No map is currently assigned to the channel selected.')

        path_map = '/paintmaps/%s' % self.attr.id
        path = '%s/%s/' % (xg.descriptionPath(self.collection,
                                              self.description), path_map)
        path_bake = '%s%s.ptx' % (path, self.emitter)

        # Prepare the ui.
        self.project.ui_progress.set_max_value(end_frame).set_progress(
            start_frame)

        # And the attribute wrapper.
        self.attr.clear().append_line(
            '# This script has been generated by xgen animated maps script.'
        ).append_line(
            "# You're free to modify it as you please, just remember to do that with care."
        ).append_line(
            '# You may be surprised by the enormous size of the script, considering the alleged ability to'
        ).append_line(
            '# assign multiple expression variables within strings, yet this is the safest way of'
        ).append_line(
            '# providing animated maps to xgen channels.').append_line()

        is_file = cmds.objectType(self.sequence) == 'file'

        # Bake it.
        for frame in range(start_frame, end_frame):
            # Set current time.
            cmds.currentTime(frame)

            # Make sure source sequence can be baked.
            bake_node = self.sequence
            if not is_file:
                bake_node = cmds.convertSolidTx(bake_node,
                                                self.emitter,
                                                alpha=False,
                                                antiAlias=False,
                                                bm=2,
                                                fts=True,
                                                sp=False,
                                                sh=False,
                                                ds=False,
                                                cr=False,
                                                rx=self.tpu,
                                                ry=self.tpu,
                                                fil='iff',
                                                fileImageName='xgenBakeTemp')
                if len(bake_node):
                    bake_node = bake_node[0]

            cmds.ptexBake(inMesh=self.emitter,
                          o=path,
                          bt=bake_node,
                          tpu=self.tpu)

            if not is_file:
                cmds.delete(bake_node)

            if os.path.isfile(path_bake):
                shutil.copy2(path_bake,
                             '%s%s.%s.ptx' % (path, self.emitter, frame))

            # Append a new frame reference to the attribute.
            if not frame == end_frame:
                self.attr.append_line(
                    '%s ($frame <= %s) {' %
                    ('if' if frame == start_frame else 'else if', frame))
            else:
                self.attr.append_line('else {')

            self.attr.append_line(
                '\t$a=map(\'${DESC}%s/%s.%s.ptx\');' %
                (path_map, self.emitter, frame)).append_line('}')

            # Increase progress bar position.
            self.project.ui_progress.set_step()

        # Set the attribute script.
        self.attr.append_line(self.expression).commit()