Esempio n. 1
1
 def __init__(self, name, index):
     #these will need to be actual data, and update as you move the object in the world
     self.m_name = name
     self.m_index = index
     #self.m_scale = (1, 1, 0) #we shouldn't really work with scale
     #self.m_position = (0, 0, 0)
     #self.m_width = 100#we could instead use scale and just let them scale instead of drag vertex
     #self.m_height = 100#then we could just calcualte width and height from base w/h and multiple by scale
     #probably the better idea then to let them move around the vertecies
     tempCube = cmds.polyCube(n = name, w = 100, h = 100, d = 0)[0]
     cmds.rotate(0, 90, 0, r=True, os=True)
     self.m_cube = tempCube
     self.m_layout = []
     self.m_effectNumber = -1
     if 'Attack' in self.m_name:
         self.b_isAttack = True
         self.m_effectNumber = 0
     else:
         self.b_isAttack = False
     #self.addUI()
     #red or blue based off of type of box
     lambert = cmds.shadingNode('lambert', asShader=True) 
     cmds.select(self.m_cube)
     if "Attack" in self.m_name:
         cmds.setAttr ( (lambert + '.color'), 1.0, 0.0, 0.0, type = 'double3' )
     else :
         cmds.setAttr ( (lambert + '.color'), 0.0, 0.0, 1.0, type = 'double3' )
         
     cmds.setAttr ( (lambert + '.transparency'), 0.90,0.90,0.90, type= 'double3' )
     
     cmds.hyperShade( assign=lambert )
Esempio n. 2
0
def applyMaterialv2(obj, r, g, b):
    #if cmds.objExists(obj):
    mat = cmds.shadingNode('aiStandardSurface', name="mat", asShader=True)
    cmds.setAttr(mat + ".baseColor", r, g, b)
    cmds.setAttr(mat + ".emissionColor", r, g, b)
    cmds.select(obj)
    cmds.hyperShade(assign=mat)
Esempio n. 3
0
    def create_and_deform(self, *args):
        """
        This function creates a terrain and deforms it using the Generator object
        Parameters:
            *args (list): Used to keep the information sent by the UI elements
        """
        logger.debug("Create NEW Terrain")
        # Execute function for terrain creation
        self.terrainGenerator.create_terrain(
            grid_name=self.valueDictionary[self.terrainName],
            dimensions=self.valueDictionary[self.dimensionSlider],
            subdivisions=self.valueDictionary[self.subdivisionSlider])

        # Execute deformation
        deformation_index = self.deformOptions.index(
            self.valueDictionary[self.methodField])

        self.terrainGenerator.deform_terrain(deformation_index)

        # Assign material
        material = create_material(
            self.valueDictionary[self.terrainShaderName],
            self.valueDictionary[self.terrainColorIcon],
            self.valueDictionary[self.terrainNormalIcon],
            self.valueDictionary[self.terrainSpecularIcon])

        cmds.select(self.terrainGenerator.gridObject)
        cmds.hyperShade(assign=material)
Esempio n. 4
0
  def generate(cls, *args):
    components = []
    width = cmds.intSliderGrp(cls.get_prefix() + Labels["width_label"], query=True, value=True)
    height = cmds.intSliderGrp(cls.get_prefix() + Labels["height_label"], query=True, value=True)
    depth = cmds.intSliderGrp(cls.get_prefix() + Labels["depth_label"], query=True, value=True)
    rgb = cmds.colorSliderGrp(cls.get_prefix() + Labels["color_label"], query=True, rgbValue=True)

    block_width = width * Constants["block_width_unit"]
    block_height = height * Constants["block_height_unit"]
    block_depth = depth * Constants["block_depth_unit"]

    #stubs
    for x in range(0, width):
      for z in range(0, depth):
        stub = cmds.polyCylinder(name=get_unique_name(cls.get_prefix(), "Stub"), radius=Constants["stub_radius"], height = Constants["stub_height"])
        components.append(stub[0])
        cmds.move(Constants["block_width_unit"] * x + half(Constants["block_width_unit"]), half(Constants["block_height_unit"]) * height + half(Constants["stub_height"]), Constants["block_depth_unit"] * z + half(Constants["block_depth_unit"]), stub[0])

    cube = cmds.polyCube(name=get_unique_name(cls.get_prefix(), "block"), width=block_width, height=block_height, depth=block_depth)
    components.append(cube[0])
    cmds.move(half(width * Constants["block_width_unit"]), 0, half(depth * Constants["block_depth_unit"]), cube)
    if components.count > 1:
      final = cmds.polyUnite(components, name=get_unique_name(cls.get_prefix(), ""))
    else:
      final = components[0]

    shader = cmds.shadingNode('blinn', asShader=True, name=get_unique_name(cls.get_prefix(),"mat"))
    cmds.setAttr(shader + ".color", rgb[0],rgb[1],rgb[2], type='double3')
    cmds.select(final[0], r=True)
    cmds.hyperShade(assign=shader)
Esempio n. 5
0
  def generate(cls, *args):
    components = []
    boolean = []
    width = cmds.intSliderGrp(cls.get_prefix() + Labels["width_label"], query=True, value=True)
    rgb = cmds.colorSliderGrp(cls.get_prefix() + Labels["color_label"], query=True, rgbValue=True)

    block_width = width * Constants["block_width_unit"]
    block_height = Constants["block_height_unit"]
    block_depth = Constants["block_depth_unit"]

    for x in range(0, width):
      stub = cmds.polyCylinder(name=get_unique_name(cls.get_prefix(), "Stub"), radius=Constants["stub_radius"], height = Constants["stub_height"])
      components.append(stub[0])
      cmds.move(Constants["block_width_unit"] * x + half(Constants["block_width_unit"]), half(Constants["block_height_unit"]) + half(Constants["stub_height"]), half(Constants["block_depth_unit"]), stub[0])
      
    for x in range(0, width-1):
      hole = cmds.polyCylinder(name=get_unique_name(cls.get_prefix(), "Hole"), radius=Constants["perforation_radius"], height=Constants["block_depth_unit"] + 0.2)
      boolean.append(hole[0])
      cmds.rotate('90deg', 0, 0, hole[0])
      cmds.move(Constants["block_width_unit"] * x + Constants["block_width_unit"], 0, half(Constants["block_depth_unit"]), hole[0])

    cube = cmds.polyCube(sx=5,sy=2,sz=2,name=get_unique_name(cls.get_prefix(), "block"), width=block_width, height=block_height, depth=block_depth)
    components.append(cube[0])
    cmds.move(half(width * Constants["block_width_unit"]), 0, half(Constants["block_depth_unit"]), cube)
    solid = cmds.polyUnite(components, name=get_unique_name(cls.get_prefix(), ""))
    boolean_group = cmds.polyUnite(boolean, name=get_unique_name(cls.get_prefix(),"boolean"))
    final = cmds.polyBoolOp( solid[0], boolean_group[0], op=2, n=get_unique_name(cls.get_prefix(), "") )

    shader = cmds.shadingNode('blinn', asShader=True, name=get_unique_name(cls.get_prefix(),"mat"))
    cmds.setAttr(shader + ".color", rgb[0],rgb[1],rgb[2], type='double3')
    cmds.select(final[0], r=True)
    cmds.hyperShade(assign=shader)
def Merge(nsTmp):
    combine = cmds.checkBoxGrp('merge', q=True, v1=True)
    rgb = cmds.colorSliderGrp('chainColour', q=True, rgbValue=True)

    if combine == True:
        myShader = cmds.shadingNode('lambert', asShader=True, name="blckMat")
        cmds.setAttr(nsTmp + ":blckMat.color",
                     rgb[0],
                     rgb[1],
                     rgb[2],
                     typ='double3')

        cmds.polyUnite((nsTmp + ":*"), n=nsTmp, ch=False)
        cmds.delete(ch=True)

        cmds.hyperShade(assign=(nsTmp + ":blckMat"))
        cmds.namespace(removeNamespace=":" + nsTmp,
                       mergeNamespaceWithParent=True)
    else:
        myShader = cmds.shadingNode('lambert', asShader=True, name="blckMat")
        cmds.setAttr(nsTmp + ":blckMat.color",
                     rgb[0],
                     rgb[1],
                     rgb[2],
                     typ='double3')

        cmds.group((nsTmp + ":*"), n=nsTmp)

        cmds.hyperShade(assign=(nsTmp + ":blckMat"))
        cmds.namespace(removeNamespace=":" + nsTmp,
                       mergeNamespaceWithParent=True)
Esempio n. 7
0
 def combineShader( shaderList ):
     
     cmds.undoInfo( ock=1 )
     
     targetObjs = []
     for shader in shaderList:
         cmds.hyperShade( objects = shader )
         targetObjs += cmds.ls( sl=1 )
     shadingEngines = cmds.listConnections( shaderList, s=0, d=1, type='shadingEngine' )
     if not shadingEngines: return None
     shadingEngines = list( set( shadingEngines ) )
     targetShadingEngine = shadingEngines[0]
     
     cmds.sets( targetObjs, e=1, forceElement = targetShadingEngine )
     
     cmds.delete( shadingEngines[1:] )
     for shader in shaderList:
         shadingEngines = cmds.listConnections( shader, s=0, d=1, type='shadingEngine' )
         if not shadingEngines:
             cmds.delete( shader )
         elif not targetShadingEngine in shadingEngines:
             cmds.delete( shader, shadingEngines )
     
     Window_global.nodeInfomation = {}
     
     cmds.undoInfo( cck=1 )
Esempio n. 8
0
def SundayRenderToolsChangeTextureResolution(object, level):
    sel = cmds.ls(selection = True)
    if object == 'selected':
        if len(sel) == 0:
            SundayDialogPy.SundayDialogConfirm('ERROR                       ', 'Nothing selected.', 'OK')
        else:
            cmds.hyperShade('', shaderNetworksSelectMaterialNodes = True)
            selShader = cmds.ls(selection = True)
            for curSelShader in selShader:
                notes = cmds.hyperShade(listUpstreamNodes = curSelShader)
                for note in notes:
                    if cmds.nodeType(note) == 'file' or cmds.nodeType(note) == 'psdFileTex':
                        cmds.select(note)
                        SundayRenderToolsChangeTextureResolutionSet(level, note)
                        continue
                
            
    elif object == 'global':
        notes = cmds.ls(type = 'file')
        for note in notes:
            cmds.select(note)
            SundayRenderToolsChangeTextureResolutionSet(level, note)
        
    
    
    try:
        cmds.select(sel)
    except:
        pass
def getObjMaterials():
    global remapAndLuminaceNodes
    shadingType = ['blinn', 'phong', 'RedshiftArchitectural', 'aiStandard']
    displacementShading = ['RedshiftDisplacement', 'displacementShader']
    duplicateMaterials = list()
    selObjsList = cmds.ls(sl = 1, tr = 1)
    if not selObjsList: assert 'No object is selected!'
    obj = selObjsList[0]
    duplicateNodes = list()
    cmds.select(obj, r = 1)
    cmds.hyperShade(smn = 1)
    selObjsDuplicateMaterials = cmds.duplicate(un = 1)
    for item in selObjsDuplicateMaterials:
        dupliMater = cmds.rename(item, '%s_duplicate'%(item))
        duplicateNodes.append(dupliMater)
    for item in duplicateNodes:
        if cmds.nodeType(item) in shadingType:
            duplicateShading = cmds.sets(r = 1, nss = 1, em = 1, n = '%s_SG'%item)
            cmds.connectAttr('%s.outColor'%item, '%s.surfaceShader'%duplicateShading, f = 1)
            duplicateMaterials.append(item)
        elif cmds.nodeType(item) == 'RedshiftDisplacement':
            conInfo = cmds.connectionInfo('%s.displacementShader'%duplicateShading, sfd = 1)
            if not conInfo:
                cmds.connectAttr('%s.out'%item, '%s.displacementShader'%duplicateShading, f = 1)
        elif cmds.nodeType(item) == 'displacementShader':
            conInfo = cmds.connectionInfo('%s.displacementShader'%duplicateShading, sfd = 1)
            if not conInfo:
                cmds.connectAttr('%s.displacement'%item, '%s.displacementShader'%duplicateShading, f = 1)
    cmds.sets(obj, e = 1, fe = duplicateShading)
    cmds.select(selObjsList, r = 1)
    return list(set(duplicateMaterials))
Esempio n. 10
0
def remove_material_duplicates(mats, compare_func):
    node2Node = list()
    needDelete = list()

    for i in xrange(0, len(mats)):
        for j in xrange(0, i):
            if compare_func(mats[i], mats[j]):
                node2Node.append(mats[i])
                node2Node.append(mats[j])
                needDelete.append(mats[i])

                cmds.hyperShade(objects=mats[i])
                sel = cmds.ls(sl=True)
                if sel != None and sel != []:
                    cmds.hyperShade(assign=mats[j])
                break

    for each in needDelete:
        listSG = cmds.listConnections(each, type="shadingEngine")
        cmds.delete(each)
        if listSG != None:
            for sg in listSG:
                if cmds.listConnections(sg, d=False) != None:
                    cmds.delete(sg)

    return len(needDelete)
Esempio n. 11
0
    def test_flat_orange(self):
        cmds.file(new=1, f=1)

        activeEditor = cmds.playblast(activeEditor=1)

        # Note that we use the default viewport2 renderer, because we're not testing
        # whether hdmaya works with this test - just whether we can make a snapshot

        cmds.modelEditor(activeEditor, e=1, rendererName='vp2Renderer')
        cmds.modelEditor(activeEditor, e=1, rendererOverrideName="")

        cube = cmds.polyCube()[0]
        shader = cmds.shadingNode("surfaceShader", asShader=1)
        cmds.select(cube)
        cmds.hyperShade(assign=shader)

        COLOR = (.75, .5, .25)
        cmds.setAttr('{}.outColor'.format(shader), type='float3', *COLOR)

        cmds.setAttr('persp.rotate', 0, 0, 0, type='float3')
        cmds.setAttr('persp.translate', 0, .25, .7, type='float3')

        self.assertSnapshotEqual("flat_orange.png")
        self.assertRaises(AssertionError, self.assertSnapshotEqual,
                          "flat_orange_bad.png")
        self.assertSnapshotClose("flat_orange_bad.png", 17515 / 163200000.0)
Esempio n. 12
0
def assignShaders(shadersName):
    
    shaderPath="Y:/TRABAJOS/PECERA_MALVINAS/1_Shot_Related/_ASSETS_GENERALES/04_SHADING/2_EXPORTS/shaders/"    
    #print shadersName
    
    objSelected=cmds.ls(sl=True)
    objFiltered=maya.cmds.listRelatives(objSelected, allDescendents=True, noIntermediate=True, fullPath=True, type="mesh")
    
    for obj in objFiltered:
        
        objName=cmds.listRelatives(obj, parent=True)
        #print objName
        obj= obj.rsplit('|', 1)
        obj=obj[0]
        #print obj[0]
        if '|' in obj[0]:
            obj=obj[1: ]
            attrName=cmds.getAttr("%s.objIdName"%(obj))
            #print attrName.split("_")[0]            
            for shader in shadersName:                
                
                if ".json" in shader and attrName.split("_")[0] in shader:
                    
                    json_data=open(shaderPath+shader).read()
                    jsonList = json.loads(json_data)
                    shaderName= jsonList[attrName]
                    cmds.select(obj)
                    shaderName=shaderName["shader"]
                    cmds.hyperShade(assign=shaderName)
    cmds.select(objSelected)
Esempio n. 13
0
def convert_area_light(area_light, attributes):
    # create and initialise material for object
    light_material = cmds.createNode("ms_appleseed_material", n=area_light + "_material")
    cmds.setAttr(light_material + ".enable_back_material", 0)
    cmds.setAttr(light_material + ".duplicate_front_attributes_on_back", 0)

    # create and initialise surface shader
    light_surface_shader = ms_commands.create_shading_node("constant_surface_shader", area_light + "_surface_shader")
    cmds.setAttr(light_surface_shader + ".alpha_multiplier", 0, 0, 0, type="double3")

    # create and initialise edf
    light_edf = ms_commands.create_shading_node("diffuse_edf", area_light + "_edf")
    cmds.setAttr(
        light_edf + ".exitance", attributes["color"][0], attributes["color"][1], attributes["color"][2], type="double3"
    )
    cmds.setAttr(
        light_edf + ".exitance_multiplier",
        attributes["multiplier"],
        attributes["multiplier"],
        attributes["multiplier"],
        type="double3",
    )

    # assign material and connect up nodes
    cmds.select(area_light)
    cmds.hyperShade(assign=light_material)
    cmds.connectAttr(light_edf + ".outColor", light_material + ".EDF_front_color", f=True)
    cmds.connectAttr(light_surface_shader + ".outColor", light_material + ".surface_shader_front_color", f=True)
Esempio n. 14
0
    def abcInFn(self):
        name = self.sg_name_text.text()
        path = self.sg_path_text.text()
        self.absolute_path = path + '\\' + name
        cmd.file(self.absolute_path + "_shader.ma", i=True, applyTo=":")
        print "shader is in"
        cmd.file(self.absolute_path + ".abc", i=True, applyTo=":")
        print "abc is in"

        #dir_file = open('D:\CS\cs_he\ca.json', 'r')
        dir_file = open(self.absolute_path + '.json', 'r')
        sg_file = json.load(dir_file)
        print "json is load"
        for i in sg_file:
            for f in sg_file[i]:
                try:

                    print f
                    cmd.select(f)
                except:
                    print "no"
                    pass
                else:
                    cmd.hyperShade(assign=i)

        dir_file.close()
        print "Abc Is In"
Esempio n. 15
0
def get_undeformed_mesh():
    import maya.cmds as cmds

    SelectedObj = cmds.ls(sl=True, sn=True)

    if SelectedObj:
        #get material
        SelectedObj = cmds.ls(sl=True, dag=True, s=True)
        shadeEng = cmds.listConnections(SelectedObj, type="shadingEngine")
        SelectedObjMaterial = cmds.ls(cmds.listConnections(shadeEng),
                                      materials=True)
        print SelectedObjMaterial[0]
        #duplicate object and switch it to original shape node
        cmds.duplicate(n="{}Blendshape".format(SelectedObj[0]))
        cmds.setAttr(
            "{}BlendshapeShapeOrig.intermediateObject".format(SelectedObj[0]),
            0)
        cmds.delete("{}BlendshapeShape".format(SelectedObj[0]))
        #assign material
        cmds.select('{}Blendshape'.format(SelectedObj[0]))
        cmds.select(SelectedObjMaterial[0], add=True)
        SelectedObjShaderGroup = cmds.listConnections(SelectedObjMaterial[0])
        print SelectedObjShaderGroup[0]
        cmds.hyperShade(assign='aiStandardSurface1SG')
        #unlock translate attrs
        axis = ['X', 'Y', 'Z']
        attrs = ['translate', 'rotate', 'scale']
        for ax in axis:
            for attr in attrs:
                cmds.setAttr('{}Blendshape'.format(SelectedObj[0]) + '.' +
                             attr + ax,
                             lock=0)
 def setMaterals(self, material=None, tmpShader=None, materialsMap=None):
     self.faceList = []
     #~ get every face a material
     try:
         tmpModel = cmds.getAttr(material + '.model')
     except:
         self.erroRaise()
         return
     modelList = []
     for item in tmpModel.split(','):
         modelList.append(item)
     for item in modelList:
         try:
             longObjectName = materialsMap[item]
         except:
             self.erroRaise()
             continue
         tmp_faceList = item.split('.')
         if len(tmp_faceList) == 2:
             faceList = longObjectName[0] + '.' + tmp_faceList[-1]
             self.faceList.append(faceList)
         elif len(tmp_faceList) == 1:
             faceList = longObjectName[0]
             self.faceList.append(faceList)
         else:
             pass
         if tmpShader != None:
             cmds.select(faceList)
             cmds.hyperShade(assign=tmpShader)
     return self.faceList
Esempio n. 17
0
def chkFaceAssignedMat():
	'''
	Separate face by material main function.
	'''

	selObjLs = cmds.ls(sl = True)

	selGeoFaceMatLs = faceAssignedMat(selObjLs)

	faceAssignedMatGeoLs = []

	for mat in selGeoFaceMatLs:
		cmds.hyperShade(objects = mat)
		matAssignGeoLs = cmds.ls(sl = True)
		faces = cmds.filterExpand(matAssignGeoLs, ex = False, sm = 34)

		if faces:
			matAssignedFaceShapes = getShapesFromFaces(faces)

			for faceShp in matAssignedFaceShapes:
				trsf = cmds.listRelatives(faceShp, p = True)
				if trsf[0] in selObjLs:
					faceAssignedMatGeoLs.extend(trsf)

	if faceAssignedMatGeoLs:
		cmds.select(faceAssignedMatGeoLs, r = True)
		cmds.confirmDialog(title = 'Error', message = '선택된 오브젝트들이 Face 단위로 Material이 적용 되어 있습니다.\n오브젝트 단위로 Material을 적용하고 릴리즈를 재시도 해 주세요.')
		cmds.error()
Esempio n. 18
0
def assignMaterialWithDisplacement(origMaterial, targetMaterial, sels=None):
    assigned = False
    #get sgNode
    try:
        sgNodes = mc.listConnections(origMaterial,
                                     s=0,
                                     d=1,
                                     type='shadingEngine')
        if sgNodes is not None:
            assigned = True
        else:
            assigned = False
        sgNode = ''
        for temp in sgNodes:
            if 'particle' not in sgNode.lower():
                sgNode = temp
    except:
        print origMaterial + ' is not assigned,ignore'
    #get disNode
    if assigned:
        disNode = ''
        inputNodes = mc.listConnections(sgNode, s=1, d=0)
        for inputNode in inputNodes:
            attrs = mc.listConnections(inputNode, p=1, d=1, s=0)
            if attrs is not None:
                for attr in attrs:
                    if 'displacementShader' in attr:
                        disNode = inputNode
                        break
        #get object
        if sels is None:
            mc.hyperShade(objects=origMaterial)
            objects = mc.ls(sl=1)
        else:
            objects = sels

        #create newSgNode
        newSgNode = mc.sets(renderable=1, empty=1, name=targetMaterial + 'SG')
        #connect

        #if the targetMaterial is lambert1 ,
        #then the lambert1 is connected to the targetMaterial by default ,there will be error
        try:
            mc.connectAttr(targetMaterial + '.outColor',
                           newSgNode + '.surfaceShader',
                           f=1)
        except:
            pass
        if disNode is not '':
            try:
                mc.connectAttr(disNode + '.out',
                               newSgNode + '.displacementShader',
                               f=1)
            except:
                mc.connectAttr(disNode + '.displacement',
                               newSgNode + '.displacementShader',
                               f=1)
        #assign
        mc.sets(objects, e=1, forceElement=newSgNode)
        return newSgNode
def roundPlate():
    
    #get values from UI
    rgb = cmds.colorSliderGrp('brickColour', query=True, rgbValue=True)
    transparent = cmds.checkBox('makeTransparent', query = True, value = True)
    
    base = cmds.polyCylinder( h = 0.18, r = 0.3 )
    cmds.rotate( 90, rotateY = True )
    cmds.move( 0.18/2, moveY = True)
    
    wide = cmds.polyCylinder( h = 0.14, r = 0.4 )
    cmds.rotate( 90, rotateY = True )
    cmds.move( 0.18 + (0.14/2), moveY = True)
    
    stud = cmds.polyCylinder( h = 0.18, r = 0.24 )
    cmds.rotate( 90, rotateY = True )
    cmds.move( 0.18 + 0.14 + (0.18/2), moveY = True)
    
    rp = cmds.polyUnite( base, wide, stud )
    
    myShader = cmds.shadingNode( 'phong', asShader=True )
    cmds.setAttr( myShader+".color", rgb[0], rgb[1], rgb[2], type='double3')
    cmds.setAttr( myShader+".reflectivity", 0 )
    
    if( transparent == True ):
       cmds.setAttr( myShader+".transparency", 0.5, 0.5, 0.5, type = 'double3' ) 
    
    cmds.select( rp )
    cmds.hyperShade( assign = myShader )
    
    cmds.delete( ch = True )
Esempio n. 20
0
 def selectObjectByMaterials( shaderList ):
     
     targetObjs = []
     for shader in shaderList:
         cmds.hyperShade( objects = shader )
         targetObjs += cmds.ls( sl=1 )
     cmds.select( targetObjs )
def setupDomeMatteMaterial(applyToMeshName):
  import maya.cmds as cmds
  import maya.mel as mel  

  #Get the selected geometry
  object_selection = applyToMeshName

  domeShaderName = 'dome_crossbounce_matte_material'

  #Create the mia_material + shading group
  dome_mia_shader_group_name = cmds.sets( renderable=True, noSurfaceShader=True, empty=True, name=domeShaderName+'SG' )
  
  #Create a mia_material_x_passes shader
  dome_mia_shader_name = cmds.shadingNode( 'mia_material_x_passes', n=domeShaderName, asShader=True) 

  #Apply the shading group to the selected geometry
  if object_selection:
    print("Applying the "+dome_mia_shader_name+" surface material to:")
    cmds.select(object_selection)
    cmds.hyperShade(assign=dome_mia_shader_group_name)  

  # Set the mia_material to be a matte material
  cmds.setAttr(dome_mia_shader_name+".diffuse", 0.5, 0.5, 0.5, type="double3")
  cmds.setAttr(dome_mia_shader_name+".diffuse_roughness", 0)
  cmds.setAttr(dome_mia_shader_name+".diffuse_weight", 1)
  cmds.setAttr(dome_mia_shader_name+".refl_color", 1, 1, 1, type="double3")
  cmds.setAttr(dome_mia_shader_name+".reflectivity", 0)

  # Connect the mia_material shader to the shading group
  cmds.connectAttr(dome_mia_shader_name+'.message', dome_mia_shader_group_name+'.surfaceShader', f=True)
  cmds.connectAttr(dome_mia_shader_name+'.message', dome_mia_shader_group_name+'.miPhotonShader', f=True)
  cmds.connectAttr(dome_mia_shader_name+'.message', dome_mia_shader_group_name+'.miShadowShader', f=True)
  cmds.connectAttr(dome_mia_shader_name+'.message', dome_mia_shader_group_name+'.miMaterialShader', f=True)
Esempio n. 22
0
    def arnoldShaderSetup(self, mesh, keepShaderValue, udimValue,
                          DisplacementFile):

        MaxBound = max([self.MinLuma, self.MaxLuma], key=abs)

        if keepShaderValue == "False":
            shader = cmds.shadingNode("aiStandard",
                                      name=mesh + "_aiStandard",
                                      asShader=True)
            shading_group = cmds.sets(name=mesh + "SG",
                                      renderable=True,
                                      noSurfaceShader=True,
                                      empty=True)
            cmds.connectAttr('%s.outColor' % shader,
                             '%s.surfaceShader' % shading_group)

        else:
            shape = cmds.listRelatives(mesh, shapes=True)
            shading_group = cmds.listConnections(shape, type='shadingEngine')

        displacement_shader = cmds.shadingNode("displacementShader",
                                               name=mesh +
                                               "_displacementShader",
                                               asShader=True)
        file_node = cmds.shadingNode("file",
                                     name=mesh + "_displacement_File",
                                     asTexture=True,
                                     isColorManaged=True)
        uv = cmds.shadingNode("place2dTexture", asUtility=True)

        cmds.setAttr(file_node + ".filterType", 0)
        cmds.setAttr(file_node + ".fileTextureName",
                     DisplacementFile,
                     type="string")
        cmds.setAttr(file_node + ".colorSpace", "Raw", type="string")
        cmds.setAttr(mesh + ".aiDispPadding", MaxBound)

        if udimValue == "True":
            cmds.setAttr(file_node + ".uvTilingMode", 3)
            cmds.setAttr(file_node + ".uvTileProxyQuality", 4)

        if keepShaderValue == "False":
            cmds.connectAttr('%s.displacement' % displacement_shader,
                             '%s.displacementShader' % shading_group,
                             force=True)
        else:
            cmds.connectAttr('%s.displacement' % displacement_shader,
                             '%s.displacementShader' % str(shading_group[0]),
                             force=True)

        cmds.defaultNavigation(connectToExisting=True,
                               source=uv,
                               destination=file_node)

        cmds.connectAttr('%s.outColorR' % file_node,
                         '%s.displacement' % displacement_shader)
        cmds.select(cmds.listRelatives(mesh, shapes=True))

        if keepShaderValue == "False":
            cmds.hyperShade(assign=shading_group)
def importAbcFile():
    importFilePath=pm.textField('path_ABC2', q=True, text=True)
    #.abc를 없애준다
    filePathDeletAbc = importFilePath.replace('.abc','')

    pm.importFile( filePathDeletAbc+'.ma' )
    importAbc( filePathDeletAbc+'.abc' )
    connectionsTxtFile_open = open(filePathDeletAbc+'.txt')
    import pickle
    lst = pickle.load(connectionsTxtFile_open)
    print lst
    for geo, shd, aiShd,disShd in lst:
        cmds.select( geo )
        cmds.hyperShade( assign=shd )
        node=pm.ls(geo)[0]
        shape = node.getShape()
        shadingGrps = shape.outputs( type='shadingEngine' )
        print shadingGrps[0]
        shader=pm.ls(aiShd)[0]
        print shader
        try:
            print 'good'
            pm.connectAttr(shader.outColor,shadingGrps[0].aiSurfaceShader) 
        except:
            print 'false'
        try:
            disShader=pm.ls(disShd)[0]
            pm.connectAttr(disShader.outColor,shadingGrps[0]..displacementShader) 
        except:
            print 'no dis'
Esempio n. 24
0
  def generate(cls, *args):
    components = []
    radius = cmds.intSliderGrp(cls.get_prefix() + Labels["radius_label"], query=True, value=True)
    height = cmds.intSliderGrp(cls.get_prefix() + Labels["height_label"], query=True, value=True)
    subdivs = cmds.intSliderGrp(cls.get_prefix() + Labels["subdivs_label"], query=True, value=True)
    rgb = cmds.colorSliderGrp(cls.get_prefix() + Labels["color_label"], query=True, rgbValue=True)
    wheel_radius = radius * Constants["wheel_radius_unit"]
    wheel_height = height * Constants["wheel_height_unit"]
    
    wheel_component = cmds.polyPipe(name=get_unique_name(cls.get_prefix(), "cylender"), sh=4, sc=subdivs, h=wheel_height, r=wheel_radius)
    wheel_extrusion_faces = []
    cmds.select(r=True)

    for i in range(0, subdivs):
      if i % 2 == 1:
        facet_title = wheel_component[0] + ".f[" + str(i) + "]"
        wheel_extrusion_faces.append(facet_title)

    #cmds.polyExtrudeFacet(wheel_extrusion_faces, ltz=Constants["wheel_ridge_depth"])
    cmds.delete(ch=1)
    cmds.lattice(wheel_component[0],divisions=[2,3,2], name=get_unique_name(cls.get_prefix(),"lattice"), cp=wheel_component[0])
    shader = cmds.shadingNode('blinn', asShader=True, name=get_unique_name(cls.get_prefix(),"mat"))
    cmds.setAttr(shader + ".color", rgb[0],rgb[1],rgb[2], type='double3')
    cmds.select(wheel_component[0], r=True)
    cmds.hyperShade(assign=shader)
Esempio n. 25
0
    def doAnimRig(self):
        path = str(self.ui.path_lineEdit.text())
        texturePath = '%s/textures' % path
        animRes = str(self.ui.animRes_comboBox.currentText())

        facialCore.path = texturePath
        facialCore.animRes = animRes

        if mc.objExists(self.renderHeadName):
            previewHead = mc.duplicate(self.renderHeadName,
                                       n=self.previewHeadName)[0]

            # render node
            ltNode = facialCore.makeAnimFacial(
                facialCore.renderLayerTextureName)

            # create lambert
            if not mc.objExists(self.animNode):
                mtl = mc.shadingNode('lambert', asShader=True, n=self.animNode)

            # connect
            mc.connectAttr('%s.outColor' % ltNode, '%s.color' % mtl, f=True)

            # assign
            mc.select(previewHead)
            mc.hyperShade(assign=mtl)

            self.messageBox('Success', 'Set Anim Node Complete')
Esempio n. 26
0
def consolidateShaders(mainMat_sel):

    mainMatSG = None
    matList = cmds.ls(materials=True, r=True)

    mainMatSplit = mainMat_sel.split(":")
    mainMat = mainMatSplit[-1]
    try:
        tmpList = cmds.listConnections(mainMat_sel)
        
        mainSplit = mainMat_sel.split(":")
        matVal = mainSplit[-1]
            
        for t in tmpList:
            if re.search("SG",t):
                mainMatSG = t
                break
                
        matList.sort()
        
        if mainMatSG != None:
            for m in matList:
                if m.split(":")[-1] == matVal:
                    cmds.select(m)
                    cmds.hyperShade(objects="")
                    cmds.sets( e=True, forceElement= mainMatSG )
                    
                    if m != mainMat_sel:
                        cmds.delete(m)
    except:
        pass
Esempio n. 27
0
def B_BakeC(*args):
    
    selection = mc.ls(sl = True, fl = True, dag = True, type= 'stroke')
         
    
    for each in selection:
        sel1 = mc.ls(sl= True, fl = True, dag = True)
        sel2 = mc.listConnections(sel1)
        sel2 = mc.listConnections(sel1, type= 'stroke')
        sel3 = mc.listConnections(sel1, type= 'transform')
        import maya.mel as mel    
        mel.eval('doPaintEffectsToPoly(1,0,1,1,100000);')
        mel.eval('polyMultiLayoutUV -lm 1 -sc 1 -rbf 0 -fr 1 -ps 0.05 -l 2 -gu 1 -gv 1 -psc 1 -su 1 -sv 1 -ou 0 -ov 0;')
        mc.delete(ch= True)
        mc.parent(w= True)
        sel4 = mc.ls("birchLimb*MeshGroup")
        mc.delete(sel1)
        mc.delete(sel2)
        mc.delete(sel3)
        mc.delete(sel4)
        mc.CenterPivot()
        mc.hyperShade( a= "lambert1")
        selected_objects = mc.ls(selection=True)
        newname = "Cable_"
        for number, object in enumerate(selected_objects):
            print 'Old Name:', object
            print 'New Name:', '%s%02d' % (newname, number)
            mc.rename(object, ('%s%02d' % (newname, number)))
            
    print "Done"
Esempio n. 28
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 Cnvert_BTN_Fun(self):
        sel = cmds.ls(sl=True, fl=True)

        for obj in sel:

            shapeNode = cmds.listRelatives(obj, children=True, shapes=True)

            SGNodeList = cmds.listConnections(shapeNode[0],
                                              type="shadingEngine")

            SGNodeList = list(set(SGNodeList))

            for SGNode in SGNodeList:

                shader = cmds.listConnections(SGNode + ".surfaceShader")

                cmds.select(cl=True)

                cmds.hyperShade(objects=shader[0])

                cmds.ConvertSelectionToFaces()

                faceList = cmds.ls(sl=True, fl=True)

                cmds.sets(cl=(shader[0] + "SG"))

                for face in faceList:
                    if obj == face.split('.')[0]:
                        cmds.select(face)
                        cmds.sets(add=(shader[0] + "SG"))

        mel.eval("maintainActiveChangeSelectMode " + sel[-1] + ";")
        cmds.select(cl=True)
        cmds.headsUpMessage(u'转换成功')
        self.Save_Json_Fun()
Esempio n. 30
0
	def doAnimRig(self) : 
		path = str(self.ui.path_lineEdit.text())
		texturePath = '%s/textures' % path 
		animRes = str(self.ui.animRes_comboBox.currentText())

		facialCore.path = texturePath
		facialCore.animRes = animRes

		if mc.objExists(self.renderHeadName) : 
			previewHead = mc.duplicate(self.renderHeadName, n = self.previewHeadName)[0]

			# render node 
			ltNode = facialCore.makeAnimFacial(facialCore.renderLayerTextureName)

			# create lambert 
			if not mc.objExists(self.animNode) : 
				mtl = mc.shadingNode('lambert', asShader = True, n = self.animNode)

			# connect 
			mc.connectAttr('%s.outColor' % ltNode, '%s.color' % mtl, f = True)

			# assign 
			mc.select(previewHead)
			mc.hyperShade(assign = mtl)

			self.messageBox('Success', 'Set Anim Node Complete')
def setupDomeMatteMaterial(applyToMeshName):
  import maya.cmds as cmds
  import maya.mel as mel  

  #Get the selected geometry
  object_selection = applyToMeshName

  domeShaderName = 'dome_crossbounce_matte_material'

  #Create the mia_material + shading group
  dome_mia_shader_group_name = cmds.sets( renderable=True, noSurfaceShader=True, empty=True, name=domeShaderName+'SG' )
  
  #Create a mia_material_x_passes shader
  dome_mia_shader_name = cmds.shadingNode( 'mia_material_x_passes', n=domeShaderName, asShader=True) 

  #Apply the shading group to the selected geometry
  if object_selection:
    print("Applying the "+dome_mia_shader_name+" surface material to:")
    cmds.select(object_selection)
    cmds.hyperShade(assign=dome_mia_shader_group_name)  

  # Set the mia_material to be a matte material
  cmds.setAttr(dome_mia_shader_name+".diffuse", 0.5, 0.5, 0.5, type="double3")
  cmds.setAttr(dome_mia_shader_name+".diffuse_roughness", 0)
  cmds.setAttr(dome_mia_shader_name+".diffuse_weight", 1)
  cmds.setAttr(dome_mia_shader_name+".refl_color", 1, 1, 1, type="double3")
  cmds.setAttr(dome_mia_shader_name+".reflectivity", 0)

  # Connect the mia_material shader to the shading group
  cmds.connectAttr(dome_mia_shader_name+'.message', dome_mia_shader_group_name+'.surfaceShader', f=True)
  cmds.connectAttr(dome_mia_shader_name+'.message', dome_mia_shader_group_name+'.miPhotonShader', f=True)
  cmds.connectAttr(dome_mia_shader_name+'.message', dome_mia_shader_group_name+'.miShadowShader', f=True)
  cmds.connectAttr(dome_mia_shader_name+'.message', dome_mia_shader_group_name+'.miMaterialShader', f=True)
Esempio n. 32
0
def CreateWeld():
    selection = mc.ls(sl=True, fl=True, dag=True, type='stroke')

    for each in selection:
        sel1 = mc.ls(sl=True, fl=True, dag=True, )
        sel2 = mc.listConnections(sel1)
        sel3 = mc.listConnections(sel1, type='brush')
        selAll = sel1 + sel3
        import maya.mel as mel
        mel.eval('doPaintEffectsToPoly(1,0,1,1,100000);')
        mel.eval('polyMultiLayoutUV -lm 1 -sc 1 -rbf 0 -fr 1 -ps 0.05 -l 2 -gu 1 -gv 1 -psc 1 -su 1 -sv 1 -ou 0 -ov 0;')
        mc.delete(ch=True)
        mc.parent(w=True)
        sel4 = mc.ls("birchLimb*MeshGroup")
        mc.delete(selAll)
        mc.delete(sel4)
        mc.CenterPivot()
        mc.hyperShade(a="Welder_shd")
        selected_objects = mc.ls(selection=True)
        mc.toggleDisplacement()
        newname = "Weld_"
        for number, object in enumerate(selected_objects):
            print 'Old Name:', object
            print 'New Name:', '%s%02d' % (newname, number)
            mc.setAttr(object + ".aiSubdivType", 1)
            mc.setAttr(object + ".aiSubdivIterations", 2)
            mc.rename(object, ('%s%02d' % (newname, number)))
Esempio n. 33
0
def showShaderAttr():
    """ Select material and show in attribute editor """
    if cmds.ls(sl=True):
        cmds.hyperShade(smn=True)
        mel.eval("openAEWindow")
    else:
        cmds.warning("Select object with shader")
def getObjMaterials():
    global remapAndLuminaceNodes
    shadingType = ["blinn", "phong", "RedshiftArchitectural", "aiStandard"]
    displacementShading = ["RedshiftDisplacement", "displacementShader"]
    duplicateMaterials = list()
    selObjsList = cmds.ls(sl=1, tr=1)
    if not selObjsList:
        assert "No object is selected!"
    for obj in selObjsList:
        duplicateNodes = list()
        cmds.select(obj, r=1)
        cmds.hyperShade(smn=1)
        selObjsDuplicateMaterials = cmds.duplicate(un=1)
        for item in selObjsDuplicateMaterials:
            dupliMater = cmds.rename(item, "%s_duplicate" % (item))
            duplicateNodes.append(dupliMater)
        for item in duplicateNodes:
            if cmds.nodeType(item) in shadingType:
                duplicateShading = cmds.sets(r=1, nss=1, em=1, n="%s_SG" % item)
                cmds.connectAttr("%s.outColor" % item, "%s.surfaceShader" % duplicateShading, f=1)
                duplicateMaterials.append(item)
            elif cmds.nodeType(item) == "RedshiftDisplacement":
                conInfo = cmds.connectionInfo("%s.displacementShader" % duplicateShading, sfd=1)
                if not conInfo:
                    cmds.connectAttr("%s.out" % item, "%s.displacementShader" % duplicateShading, f=1)
            elif cmds.nodeType(item) == "displacementShader":
                conInfo = cmds.connectionInfo("%s.displacementShader" % duplicateShading, sfd=1)
                if not conInfo:
                    cmds.connectAttr("%s.displacement" % item, "%s.displacementShader" % duplicateShading, f=1)
        cmds.sets(obj, e=1, fe=duplicateShading)
    cmds.select(selObjsList, r=1)
    return list(set(duplicateMaterials))
Esempio n. 35
0
def get_undeformed_mesh():
    selected_obj = cmds.ls(selection=True, shortNames=True)

    if selected_obj:
    # get material
        selected_obj = cmds.ls(selection=True, dag=True, shape=True)[0]
        shade_eng = cmds.listConnections(selected_obj , type="shadingEngine")
        selected_obj_material = cmds.ls(cmds.listConnections(shade_eng), materials=True)
        print selected_obj_material[0]
    # duplicate object and switch it to original shape node
        cmds.duplicate(name="{}Blendshape".format(selected_obj))
        cmds.setAttr("{}BlendshapeShapeOrig.intermediateObject".format(selected_obj), 0)
        cmds.delete("{}BlendshapeShape".format(selected_obj))
    # assign material
        cmds.select('{}Blendshape'.format(selected_obj[0]))
        cmds.select(selected_obj_material[0], add=True)
        selected_obj_shadergroup = cmds.listConnections(selected_obj_material[0])
        print selected_obj_shadergroup[0]
        cmds.hyperShade( assign='aiStandardSurface1SG')
    # unlock translate attrs
        axis = ['X', 'Y', 'Z']
        attrs = ['translate', 'rotate', 'scale']
        for ax in axis:
            for attr in attrs:
               cmds.setAttr('{}Blendshape.{}{}'.format(selected_obj, attr, ax), lock=True)
Esempio n. 36
0
def RightBlock():

    firstBlockDepth = cmds.intSliderGrp('firstAngleDepth',
                                        query=True,
                                        value=True)
    secondBlockDepth = cmds.intSliderGrp('secondAngleDepth',
                                         query=True,
                                         value=True)
    rgb = cmds.colorSliderGrp('angled90BlockColour', query=True, rgbValue=True)

    cmds.select(clear=True)

    cubeDimY = 1 * 0.96
    cubeDimZ = firstBlockDepth * 0.8

    firstBlock = makeRoundHoleBlock(firstBlockDepth)
    secondBlock = makeRoundHoleBlock(secondBlockDepth)
    cmds.move((cubeDimZ / 2.0), moveZ=True)
    cmds.move((cubeDimZ / 2.0), moveY=True)
    cmds.rotate('90deg', 0, 0, secondBlock[0])
    finalShape = cmds.polyCBoolOp(firstBlock[0], secondBlock[0], op=1)

    # Adding on the colour
    myShader = cmds.shadingNode('lambert', asShader=True, name="blockMaterial")
    cmds.setAttr(myShader + ".color", rgb[0], rgb[1], rgb[2], type='double3')
    cmds.select(finalShape, r=True)
    cmds.hyperShade(assign=myShader)
    cmds.namespace(set=":")
Esempio n. 37
0
    def linkShaders(self, *args):

        links = self.getLinksFromDB()

        if links == None:
            return

        selection = cmds.ls(sl=True)
        if len(selection) > 0:
            selection = cmds.listRelatives(selection,
                                           allDescendents=True,
                                           noIntermediate=True)

        # If shader file is available import it
        shaderPath = cmds.textFieldButtonGrp("tfbShaderPath", q=True, tx=True)
        if len(shaderPath) > 0:
            cmds.file(shaderPath, i=True)
            cmds.textFieldButtonGrp("tfbShaderPath", e=True, tx="")

        # Link shaders
        for link in links:
            mesh = link[0]
            shader = link[1]

            if cmds.checkBox("cbSubstring", q=True, value=True):
                substring = cmds.textField("tfSubstring", q=True, text=True)
                mesh = substring + mesh

            if cmds.objExists(mesh):
                cmds.select(mesh)
                cmds.hyperShade(assign=shader)
                print "'" + mesh + "' linked"

        print "Finished linking."
Esempio n. 38
0
def assignShader(shadeFile, edlFile, namespace):

    missGeo = ''

    mc.file(shadeFile, i=True, loadReferenceDepth="all", pr=True, options ="v=0")

    f = open(edlFile,'r')
    txt = f.read()
    f.close()

    for t in txt.split('\r\n'):
        geo = []
        if t.split(' ')[1:]:
            mc.select(cl=True)
            for face in t.split(' ')[1:]:
                if not face[:4] == '%s:' % namespace:
                    face = face.split('|')
                    face = ('|%s:' % namespace).join(face)
                    face = '%s:%s' % (namespace, face)
                try:
                    mc.select(face ,r=True)
                    geo.append(face)

                except:
                    # face
                    missGeo += '%s\n' % (face)
            if geo: 
                mc.select(geo,r=True)
                mc.hyperShade(assign=t.split(' ')[0] )  
            mc.select(cl=True)
    print '\n___________________________________\nGeo is missing.\n___________________________________\n%s' % missGeo
Esempio n. 39
0
	def linkShaders(self, *args):

		links = self.getLinksFromDB()

		if links == None:
			return

		selection = cmds.ls(sl=True)
		if len(selection) > 0:
			selection = cmds.listRelatives(selection, allDescendents=True, noIntermediate=True)

		# If shader file is available import it
		shaderPath = cmds.textFieldButtonGrp("tfbShaderPath", q=True, tx=True)
		if len(shaderPath) > 0:
			cmds.file(shaderPath, i=True)
			cmds.textFieldButtonGrp("tfbShaderPath", e=True, tx="")

		# Link shaders
		for link in links:
			mesh = link[0]
			shader = link[1]

			if cmds.checkBox("cbSubstring", q=True, value=True):
				substring = cmds.textField("tfSubstring", q=True, text=True)
				mesh = substring + mesh

			if cmds.objExists(mesh):
				cmds.select(mesh)
				cmds.hyperShade(assign=shader)
				print "'" + mesh + "' linked"

		print "Finished linking."
Esempio n. 40
0
def joinTypeMaterials(meshShape, typeNode):
    transformList = cmds.listRelatives(meshShape, parent=True, fullPath=True)

    cmds.setAttr(meshShape + '.displayColors', 0)
    shaderType = cmds.optionMenuGrp('typeToolShaderType', q=True, v=True)

    shader = cmds.shadingNode(shaderType, asShader=True, n="typeShader#")
    defaultColour = [(1, 1, 1)]
    try:
        cmds.setAttr(shader + '.color',
                     defaultColour[0][0],
                     defaultColour[0][1],
                     defaultColour[0][2],
                     type="double3")
    except:
        pass

    shadingGroup = cmds.sets(n=shader + 'SG',
                             renderable=True,
                             noSurfaceShader=True,
                             empty=True)
    cmds.connectAttr('%s.outColor' % shader, '%s.surfaceShader' % shadingGroup)

    #assign the shader
    cmds.select(transformList[0])
    cmds.hyperShade(assign=shader)

    cmds.evalDeferred("maya.mel.eval('updateAE " + typeNode + "')")
    cmds.select(transformList[0])
def getObjMaterials():
    global remapAndLuminaceNodes
    index = 0
    shadingType = ["blinn", "phong", "RedshiftArchitectural", "aiStandard"]
    displacementShading = ["RedshiftDisplacement", "displacementShader"]
    duplicateMaterials = list()
    selObjsList = cmds.ls(sl=1, tr=1)
    if not selObjsList:
        assert "No object is selected!"
    for obj in selObjsList:
        duplicateNodes = list()
        cmds.select(obj, r=1)
        cmds.hyperShade(smn=1)
        selObjsDuplicateMaterials = cmds.duplicate(un=1)
        for item in selObjsDuplicateMaterials:
            dupliMater = cmds.rename(item, "%s_duplicate" % (item))
            duplicateNodes.append(dupliMater)
        remapAndLuminaceNodes.append(duplicateNodes[1])
        remapAndLuminaceNodes.append(duplicateNodes[2])
        remapAndLuminaceNodes.extend(duplicateNodes)
        for item in duplicateNodes:
            if cmds.nodeType(item) == "shadingEngine":
                duplicateShading = item
            if cmds.nodeType(item) in shadingType:
                duplicateMaterials.append(item)
            #     duplicateMaterials.append(item)
            #     remapAndLuminaceNodes.remove(item)
            # if cmds.nodeType(item) == displacementShading:
            #     if index >= 1: continue
            #     cmds.connectAttr('%s.displacement'%item, '%s.displacementShader'%duplicateShading, f = 1)
            #     index += 1
            # remapAndLuminaceNodes.remove(item)
        cmds.sets(obj, e=1, fe=duplicateShading)
    cmds.select(selObjsList, r=1)
    return list(set(duplicateMaterials))
Esempio n. 42
0
def SLiBBrowserImport(type):
    selected = cmds.ls(selection = True)
    if cmds.iconTextRadioCollection('slAssetCollection', query = True, select = True) == 'NONE':
        SLiBDialogConfirm('Error while ' + type + '                              ', 'Please select the Shader you want to Import!', 'OK')
        return None

    assetPath = os.path.dirname(cmds.iconTextRadioButton(cmds.iconTextRadioCollection('slAssetCollection', query = True, select = True), query = True, label = True))
    importFile = cmds.iconTextRadioButton(cmds.iconTextRadioCollection('slAssetCollection', query = True, select = True), query = True, label = True)
    fileType = 'mayaAscii'
    aas = cmds.checkBox('SLiBAutoAssign', query = True, value = True)
    before = cmds.ls(materials=1)
    cmds.file(importFile, i = True, type = fileType, usingNamespaces = False, returnNewNodes = True, ignoreVersion = True)
    after  = cmds.ls(materials=1)
    imported = list(set(after)-set(before))
    cmds.scrollField('SLiB_TEXTFIELD_Info', edit = True, text = 'Import %s Successful !!!' % imported[0])
    cmds.select(selected)
    if aas:
        #cmds.sets(selected, e=1, forceElement=shader)
        cmds.hyperShade( a=imported[0])
        

    atf = cmds.checkBox('SLiBAutoTextureFix', query = True, value = True)
    if atf:
        import SLiBFixTexturePathSilentPy
        reload(SLiBFixTexturePathSilentPy)
        SLiBFixTexturePathSilentPy.SLiBFiXiTs()
        
    try:
        cmds.select(selected)
    
    except:
        cmds.iconTextRadioCollection('slAssetCollection', query = True, select = True) == 'NONE'
        cmds.select(clear = True)
Esempio n. 43
0
def _hookup_shaders(reference_node):
    """
    Reconnects published shaders to the corresponding mesh.
    :return:
    """

    # find all shader hookup script nodes and extract the mesh object info
    hookup_prefix = "SHADER_HOOKUP_"
    shader_hookups = {}
    for node in cmds.ls(type="script"):
        node_parts = node.split(":")
        node_base = node_parts[-1]
        node_namespace = ":".join(node_parts[:-1])
        if not node_base.startswith(hookup_prefix):
            continue
        obj_pattern = node_base.replace(hookup_prefix, "") + "\d*"
        obj_pattern = "^" + obj_pattern + "$"
        shader = cmds.scriptNode(node, query=True, beforeScript=True)
        shader_hookups[obj_pattern] = node_namespace + ":" + shader

    # if the object name matches an object in the file, connect the shaders
    for node in (cmds.ls(references=True, transforms=True) or []):
        for (obj_pattern, shader) in shader_hookups.iteritems():
            # get rid of namespacing
            node_base = node.split(":")[-1]
            if re.match(obj_pattern, node_base, re.IGNORECASE):
                # assign the shader to the object
                cmds.select(node, replace=True)
                cmds.hyperShade(assign=shader)
Esempio n. 44
0
 def createImpactHelper(self):
     '''
     Creates IS Sphere Helper
     '''
     mImpact = cmds.sphere(r = 0.00001, n = 'IS_Impact')
     mImpactShape = cmds.listRelatives(mImpact[0])[0]
     
     self._mVoroImpactTrs = mImpact[0]
     self._mVoroImpactShape = mImpact[1]
     
     cmds.setAttr(mImpact[0] + '.visibility', False)
     cmds.setAttr(mImpact[0] + '.overrideEnabled', True)
     cmds.setAttr(mImpact[0] + '.overrideColor', 14)
     cmds.setAttr(mImpact[1] + '.sections', 2)
     cmds.setAttr(mImpact[1] + '.spans', 2)
     cmds.setAttr(mImpactShape + '.curvePrecisionShaded', 20)
     
     self._mVoroImpactShader = cmds.shadingNode('lambert', name = 'IS_ImpactMat', asShader = True)
     cmds.setAttr(self._mVoroImpactShader + '.diffuse', 0.0)
     cmds.setAttr(self._mVoroImpactShader + '.translucence', 0.3)
     cmds.setAttr(self._mVoroImpactShader + '.translucenceDepth', 0.75)
     cmds.setAttr(self._mVoroImpactShader + '.color', 0.0, 1.0, 0.0, type = 'double3')
     cmds.setAttr(self._mVoroImpactShader + '.incandescence', 0.0, 0.15, 0.0, type = 'double3')
     cmds.setAttr(self._mVoroImpactShader + '.transparency', 0.55, 0.55, 0.55, type = 'double3')
     
     cmds.select(mImpact, replace = True)
     cmds.hyperShade(assign = self._mVoroImpactShader)
     mel.eval('hyperShadePanelMenuCommand("hyperShadePanel1", "deleteUnusedNodes")')
     
     if (cmds.attributeQuery('hiddenInOutliner', node = self._mVoroImpactTrs, exists = True)):
         cmds.setAttr(self._mVoroImpactTrs + '.hiddenInOutliner', True)
     
     cmds.select(clear = True)
     cmds.scriptEditorInfo (clearHistory = True)
def pieslice(pStAn, pEnAn, pR, pH=0.1):
    cyl = mc.polyCylinder(h=pH, r=pR)
    cx = mc.objectCenter(x=True)
    cy = mc.objectCenter(y=True)
    cz = mc.objectCenter(z=True)

    h = pH
    #cut the cylinder, and separate different parts
    cut = mc.polyCut(cyl,
                     cutPlaneCenter=[cx, h / 2, cz],
                     cutPlaneRotate=[0, pStAn, 0],
                     extractFaces=True,
                     extractOffset=[0, 0, 0])
    cut = mc.polyCut(cyl,
                     cutPlaneCenter=[cx, h / 2, cz],
                     cutPlaneRotate=[0, pEnAn, 0],
                     extractFaces=True,
                     extractOffset=[0, 0, 0])
    obj = mc.polySeparate(cyl)
    names = []
    for i in range(len(obj)):
        mc.rename(obj[i], 'part' + str(i))
        names.append('part' + str(i))

    #delete useless parts from the now separated cylinder
    mc.delete(names[0:2] + names[3:], s=True)
    #fill hole of the leftover pieslice
    mc.polyCloseBorder(names[2])
    #add and assign a material (which was deleted when delete was called)
    myBlinn = mc.shadingNode('blinn', asShader=True)
    mc.select(names[2])
    mc.hyperShade(assign=myBlinn)
    return names[2]
Esempio n. 46
0
 def ToMaterialFromFace(self):
     materials = []
     for name in self.names:
         cmds.select(name)
         cmds.hyperShade(smn=True)
         materials += cmds.ls(sl=True)
     return materials
Esempio n. 47
0
	def doRenderRig(self) : 
		path = str(self.ui.path_lineEdit.text())
		texturePath = '%s/textures' % path 
		renderRes = str(self.ui.renderRes_comboBox.currentText())

		facialCore.path = texturePath
		facialCore.res = renderRes

		if mc.objExists(self.defaultHeadName) : 
			# rename 
			mc.rename(self.defaultHeadName, self.renderHeadName)

			# group 
			group = mc.group(em = True, n = self.stillGroup)
			mc.parent(self.renderHeadName, group)

			# render node 
			ltNode = facialCore.makeRenderFacial()

			# create lambert 
			if not mc.objExists(self.renderNode) : 
				vrayMtl = mc.shadingNode('VRayMtl', asShader = True, n = self.renderNode)

			# connect 
			mc.connectAttr('%s.outColor' % ltNode, '%s.color' % vrayMtl, f = True)

			# assign 
			mc.select(self.renderHeadName)
			mc.hyperShade(assign = vrayMtl)

			self.messageBox('Success', 'Set Render Node Complete')

		else : 
			self.messageBox('Warning', '%s not Exists' % self.defaultHeadName)
Esempio n. 48
0
    def assignShadeToDefault(self, shaded_, default_):
        for sh in shaded_.shader_list:
            cmds.hyperShade(o=sh)

            sel_list = cmds.ls(sl=1, allPaths=1)
            if not sel_list:
                return

            clean_list = []

            if [x for x in sel_list if '.f[' in x]:
                print 'f mode'
                clean_list = [
                    x.replace(shaded_.full_name, default_.full_name)
                    for x in sel_list if shaded_.name
                ]
            else:
                print 'g mode'
                clean_list = [
                    x.replace(shaded_.full_shape, default_.full_shape)
                    for x in sel_list if shaded_.shape in x
                ]
            #print 'clean', clean_list
            cmds.select(clean_list)
            cmds.hyperShade(assign=sh)
Esempio n. 49
0
def hookup_shaders(reference_node):

    hookup_prefix = "SHADER_HOOKUP_"
    shader_hookups = {}
    for node in cmds.ls(type="script"):
        if not node.startswith(hookup_prefix):
            continue
        obj_pattern = node.replace(hookup_prefix, "") + "\d*"
        obj_pattern = "^" + obj_pattern + "$"
        shader = cmds.scriptNode(node, query=True, beforeScript=True)
        shader_hookups[obj_pattern] = shader

    for node in cmds.referenceQuery(reference_node, nodes=True):
        for (obj_pattern, shader) in shader_hookups.iteritems():
            if re.match(obj_pattern, node, re.IGNORECASE):
                # assign the shader to the object
                cmds.file(unloadReference=reference_node, force=True)
                cmds.setAttr(reference_node + ".locked", False)
                cmds.file(loadReference=reference_node)
                cmds.select(node, replace=True)
                cmds.hyperShade(assign=shader)
                cmds.file(unloadReference=reference_node)
                cmds.setAttr(reference_node + ".locked", True)
                cmds.file(loadReference=reference_node)
            else:
                print "NODE: " + node + " doesn't match " + obj_pattern
    def Transfer_BTN_Fun(self):
        sel = cmds.ls(sl=True, fl=True)

        shapeNode = cmds.listRelatives(sel[0], children=True, shapes=True)

        SGNodeList = cmds.listConnections(shapeNode[0], type="shadingEngine")

        SGNodeList = list(set(SGNodeList))

        for each in SGNodeList:
            cmds.hyperShade(objects=each)
            sel_mat_face = cmds.ls(sl=True)

            ##剔除不是本物体的面 (按材质组选的面,有可能选择其他物体)
            mat_face_use = []
            for each_face in sel_mat_face:
                if each_face.find(sel[0]) != -1:  ##没有找到就返回-1
                    print each_face
                    mat_face_use.append(each_face)
            print mat_face_use
            ##改为目标物体的面
            mat_face_obj = []
            for each_new in mat_face_use:
                mat_face_obj.append(each_new.replace(sel[0], sel[1]))

            cmds.select(mat_face_obj, r=True)
            cmds.hyperShade(assign=each)

        cmds.select(cl=True)
        cmds.headsUpMessage(u'传递成功')
        self.Save_Json_Fun()
 def applyRandomShaders(self, *args):
     selection = self.getSelectedMeshes()
         for mesh in selection:
             # Does a random material exist for this object?
             if not cmds.objExists(mesh + '_rand_shdr'):
                 # Material doesn't exist so create random value for hue, saturation, value
                 h = random.uniform(0, 1)
                 s = random.uniform(0, 0.5)
                 v = random.uniform(0, 1)
                 # Create a shader named accordingly to this mesh
                 my_shdr = cmds.shadingNode(
                     self.shaderType,
                     asShader = True,
                     name = mesh + '_rand_shdr')
                 cmds.setAttr(my_shdr + '.color', h, s, v)
                 cmds.select(mesh)
                 cmds.hyperShade(assign = mesh + '_rand_shdr')
             else:
                 # A random shader already exists for this mesh.
                 # Check if the existing shader is assigned to the mesh
                 the_nodes = cmds.ls(mesh, dagObjects = True, shapes = True)
                 shading_engine = cmds.listConnections(
                     the_nodes,
                     type = 'shadingEngine')
                 material = cmds.ls(cmds.listConnections(
                     shading_engine),
                     materials = True)
                 # If existing material is not assigned to this mesh, then assign it
                 if material != mesh + '_rand_shdr':
                     cmds.select(mesh)
                     cmds.hyperShade(assign = mesh + '_rand_shdr')
Esempio n. 52
0
def unused_materials(delete=None, material_type=None):
    """Deletes unused materials.
        @PARAMS:
            delete: boolean, True deletes materials.
            material_type: string, "phong".
        :NOTE: Delete unused Nodes in Maya seems to fail for some reason.
        Also, instead of wrapping try/except in here, wrap this function in
        a try/except using the epic logger.
    """
    # globals
    deleted_materials = list()
    ignore_materials = ["lambert1", "particleCloud1"]

    # find materials
    materials = cmds.ls(type=material_type)
    if not material_type:
        materials = cmds.ls(mat=True)

    # remove unused materials
    for material in materials:
        if material in ignore_materials:
            continue
        cmds.hyperShade(objects=material)
        assigned_geo = cmds.ls(sl=True)
        if not assigned_geo:
            if delete:
                cmds.delete(material)
            deleted_materials.append(material)
    return deleted_materials
Esempio n. 53
0
    def selectObjectByMaterials(shaderList):

        targetObjs = []
        for shader in shaderList:
            cmds.hyperShade(objects=shader)
            targetObjs += cmds.ls(sl=1)
        cmds.select(targetObjs)
Esempio n. 54
0
    def assign(self):
        """選択したmatcapでマテリアルを作成して
        選択したオブジェクトに適用する
        すでに同じ名前のマテリアルが存在するときは入れ替える
        """
        selection = cmds.ls(sl=True)
        # すでに同じ名前のマテリアルが割り当てられたオブジェクトがあるなら入れ替える
        matcap_objects = cmds.ls(sl=True)
        cmds.hyperShade(objects=MATERIAL_NAME)
        sel = cmds.ls(sl=True)
        if sel:
            matcap_objects += sel
        if not matcap_objects:
            return

        cmds.select(matcap_objects)

        mat = cmds.ls(MATERIAL_NAME)
        if mat:
            cmds.delete(mat)
            SG = mat[0]+"SG"
            print(SG)
            cmds.delete(SG)

        shader_name = createMatcapMaterial(MATERIAL_NAME, self.getImagePath())
        assignMatcapMaterial(shader_name)
        cmds.select(selection)
Esempio n. 55
0
    def combineShader(shaderList):

        cmds.undoInfo(ock=1)

        targetObjs = []
        for shader in shaderList:
            cmds.hyperShade(objects=shader)
            targetObjs += cmds.ls(sl=1)
        shadingEngines = cmds.listConnections(shaderList,
                                              s=0,
                                              d=1,
                                              type='shadingEngine')
        if not shadingEngines: return None
        shadingEngines = list(set(shadingEngines))
        targetShadingEngine = shadingEngines[0]

        cmds.sets(targetObjs, e=1, forceElement=targetShadingEngine)

        cmds.delete(shadingEngines[1:])
        for shader in shaderList:
            shadingEngines = cmds.listConnections(shader,
                                                  s=0,
                                                  d=1,
                                                  type='shadingEngine')
            if not shadingEngines:
                cmds.delete(shader)
            elif not targetShadingEngine in shadingEngines:
                cmds.delete(shader, shadingEngines)

        Window_global.nodeInfomation = {}

        cmds.undoInfo(cck=1)
    def hfSplitBadShaded(self, engines):
        modifiedShapes = []
        for sg in engines:
            print('checking shading group: '+sg)
            cmds.hyperShade(objects=sg)
            components = cmds.ls(sl=1)
            uniqueShapes = []
            for entry in components:
                uniqueShapes.append(entry.split('.')[0])
                # remove whole shapes (not components) from the list.
                if entry.rfind('.f') == -1:
                    components.remove(entry)
            if len(components) > 0:
                components.sort()
                # remove duplicates from uniqueShapes.
                uniqueShapes = list(set(uniqueShapes))
                modifiedShapes.extend(uniqueShapes)
                # print('\nunique shapes under shading group: ')
                # print(uniqueShapes)
                for shape in uniqueShapes:
                    cmds.select(cl=1)
                    # get the total num of faces for the shape for later use.
                    totalFaces = cmds.polyEvaluate(shape, f=1)
                    for comp in components:
                        testStr = shape+'.f['
                        if testStr in comp:
                            # the current component is a member of the current mesh we're splitting and it has the shader we want.
                            cmds.select(comp, add=1)
                    selFaces = cmds.ls(sl=1)
                    # print 'selection:'
                    # print selFaces
                    # extract the selected faces if we aren't selecting every face of the current mesh.
                    if len(selFaces) < int(totalFaces) and len(selFaces) > 0:
                        cmds.polyChipOff(selFaces, kft=1, dup=0)
                        cmds.delete(shape,ch=1)
                    # now the mesh is broken into shells. separate it if possible.
                    if cmds.polyEvaluate(shape, s=1) > 1:
                        newObjects = cmds.polySeparate(shape, ch=0)
                        modifiedShapes.extend(newObjects)
                        # print('split new shapes: ')
                        # print(newObjects)
                        cmds.select(newObjects)
                        # print(cmds.ls(sl=1))
                        cmds.delete(ch=1)
        cmds.select(cl=1)
        # now in order to return all the new meshes we made, we should sort through uniqueShapes and remove anything that no longer
        # exists. anything that's been split, etc.
        modifiedShapes = list(set(modifiedShapes))
        returnShapes = []
        for shape in modifiedShapes:
            if cmds.objExists(shape) == 0:
                modifiedShapes.remove(shape)
            else:
                meshNodes = cmds.listRelatives(shape, s=1)
                if meshNodes != None:
                # if we are not testing an xform, meshNodes will be a 'NoneType' object so we should include an exception.
                    returnShapes.extend(meshNodes)

        return returnShapes
Esempio n. 57
0
def duplicateShaderToOther( first, second ):
    
    import maya.mel as mel
    import sgBFunction_dag
    
    if not cmds.objExists( first ): return None
    if not cmds.objExists( second ): return None
    
    first = sgBFunction_dag.getTransform( first )
    second = sgBFunction_dag.getTransform( second )
    firstShape = sgBFunction_dag.getShape( first )
    secondShape = sgBFunction_dag.getShape( second )
    
    engines = cmds.listConnections( firstShape, type='shadingEngine' )
    
    if not engines: return None
    
    engines = list( set( engines ) )
    
    for engine in engines:
        shaders = cmds.listConnections( engine+'.surfaceShader', s=1, d=0 )
        
        engine = cmds.duplicate( engine, n= 'du_'+engine )[0]
        
        if shaders:
            shader = shaders[0]
            
            cmds.hyperShade( objects = shader )
            selObjs = cmds.ls( sl=1, l=1 )
            
            targetObjs = []
            for selObj in selObjs:
                if selObj.find( '.' ) != -1:
                    trNode, components = selObj.split( '.' )
                    if trNode == first:
                        targetObjs.append( second+'.'+components )
                elif selObj == firstShape:
                    targetObjs.append( secondShape )
            
            cmds.select( shader )
            mel.eval( 'hyperShadePanelMenuCommand("hyperShadePanel1", "duplicateShadingNetwork")' )
            shader = cmds.ls( sl=1 )[0]
            cmds.connectAttr( shader+'.outColor', engine+'.surfaceShader' )
        
        aiShaders = cmds.listConnections( engine+'.aiSurfaceShader', s=1, d=0 )

        if aiShaders:
            aiShader = aiShaders[0]
            
            cmds.hyperShade( objects = aiShader )
            selObjs = cmds.ls( sl=1, l=1 )
            
            cmds.select( aiShader )
            mel.eval( 'hyperShadePanelMenuCommand("hyperShadePanel1", "duplicateShadingNetwork")' )
            aiShader = cmds.ls( sl=1 )[0]
            cmds.connectAttr( aiShader+'.outColor', engine+'.aiSurfaceShader' )
        
        for targetObj in targetObjs:
            cmds.sets( targetObj, e=1, forceElement=engine )
Esempio n. 58
0
File: ao.py Progetto: matheushrr/rl
def reAdd(samplesField, spreadField, maxDistanceField):
	# switch to the ao render layer
	cmds.editRenderLayerGlobals(currentRenderLayer='ao')
	objects = cmds.ls(g=True)
	cmds.select(objects)
	cmds.hyperShade(a='amb_occl_surf_shader')
	
	changeAOSettings(samplesField, spreadField, maxDistanceField)
Esempio n. 59
0
	def assign(self):
		"""assign shader to selection"""
		sel = mn.ls( sl = True )
		if sel:
			#if not self.exists:
			shadCount = self.importShader()
			mc.select( sel )
			mc.hyperShade( a = self.name + str( shadCount ) + ':' + self.name )
Esempio n. 60
0
def deleteShaders(*args):
    previewShaders = cmds.select("PREV_*", allDagObjects=False, noExpand=True)

    meshes = cmds.hyperShade(objects="")
    cmds.hyperShade(assign= 'lambert1' )
    cmds.select(cl =1)
    previewShaders = cmds.select("PREV_*", allDagObjects=False, noExpand=True)
    cmds.delete()