Ejemplo n.º 1
0
def noiseReset(fx):
    """
    Turn off and reset noise parameters to their defaults
    Args:
        fx (MNPR_FX): MNPR_FX object coming from the caller
    """
    # get node names of operation
    sfxNodes = getNodeNames(fx, 0)

    lib.printInfo("Recompiling material")

    # reset each material
    materials = getMaterials()
    for mat in materials:

        # turn off procedural noise
        stateId = getId(mat, sfxNodes.stateNodeName)
        cmds.shaderfx(sfxnode=mat, edit_bool=(stateId, "value", False))

        sfxNodes.refreshIds(mat)
        # reset attributes
        cmds.shaderfx(sfxnode=mat, edit_float=(sfxNodes.scale, "value", 1.0))
        cmds.shaderfx(sfxnode=mat,
                      edit_float=(sfxNodes.intensity, "value", 10.0))
        cmds.shaderfx(sfxnode=mat, edit_float=(sfxNodes.shift, "value", 0.0))
        cmds.shaderfx(sfxnode=mat, edit_bool=(sfxNodes.scale, "value", True))

    lib.printInfo("{0} procedural control has been reset".format(
        fx.description))
Ejemplo n.º 2
0
def createPBSPlus(
    args=None,
    args1=None,
    args2=None,
):
    for name, mesh, texture in zip(args, args1, args2):
        name = 'M_' + name + '_LOD0'
        for i in texture:
            num = texture.index(i)
            print i[0]
            print i[1]
            print i[2]
            shader = mc.shadingNode('StingrayPBS', asShader=True, name=name)
            mc.shaderfx(sfxnode=shader, initShaderAttributes=True)
            shading_group = mc.sets(renderable=True,
                                    noSurfaceShader=True,
                                    empty=True,
                                    name=name + 'SG')
            mc.connectAttr(shader + '.outColor',
                           shading_group + '.surfaceShader')

            ao = mc.shadingNode('file',
                                at=True,
                                name=name.replace('M', 'T') + '_AO')
            mc.setAttr(ao + '.fileTextureName', i[0], type='string')

            cm = mc.shadingNode('file',
                                at=True,
                                name=name.replace('M', 'T') + '_B')
            mc.setAttr(cm + '.fileTextureName', i[1], type='string')

            nm = mc.shadingNode('file',
                                at=True,
                                name=name.replace('M', 'T') + '_N')
            mc.setAttr(nm + '.fileTextureName', i[2], type='string')

            # mm = mc.shadingNode('file', at=True, name=name.replace('M', 'T')+'_M')
            # mc.setAttr(mm + '.fileTextureName', i[3], type='string')

            # rm = mc.shadingNode('file', at=True, name=name.replace('M', 'T')+'_R')
            # mc.setAttr(rm + '.fileTextureName', i[4], type='string')

            # em = mc.shadingNode('file', at=True, name=name.replace('M', 'T')+'_E')
            # mc.setAttr(em + '.fileTextureName', i[5], type='string')
            #
            mc.setAttr(shader + '.use_color_map', 1)
            mc.setAttr(shader + '.use_normal_map', 1)
            # mc.setAttr(shader+'.use_metallic_map', 1)
            # mc.setAttr(shader+'.use_roughness_map', 1)
            # mc.setAttr(shader+'.use_emissive_map', 1)
            mc.setAttr(shader + '.use_ao_map', 1)
            #
            mc.connectAttr(cm + '.outColor', shader + '.TEX_color_map')
            mc.connectAttr(nm + '.outColor', shader + '.TEX_normal_map')
            # # mc.connectAttr(mm+'.outColor', shader+'.TEX_metallic_map')
            # # mc.connectAttr(rm+'.outColor', shader+'.TEX_roughness_map')
            # # mc.connectAttr(em+'.outColor', shader+'.TEX_emissive_map')
            mc.connectAttr(ao + '.outColor', shader + '.TEX_ao_map')
            #
            mc.sets('%s' % mesh[num], e=True, fe='%s' % shading_group)
Ejemplo n.º 3
0
def create_material(name, graph_dir="", custom_graph=""):
    """
    Create a shaderFX material
    Args:
        name (unicode): Name of the new material
        graph_dir (unicode): Directory of where custom graphs are located
        custom_graph (unicode): Name of custom_graph

    Returns:
        (unicode): Name of new material
    """
    graph = ""
    if graph_dir and custom_graph:
        graph_path = clib.Path(graph_dir).child(custom_graph)
        if graph_path.exists():
            graph = graph_path.path
        else:
            clib.print_error("No custom graph was found in {}".format(graph_path.path))
    # resolve name clashes with SFX
    if cmds.objExists(name):
        if "_SFX" not in name:
            name += "_SFX"
    # create node and load custom_graph if available
    shader = cmds.shadingNode('ShaderfxShader', asShader=True, name=name)
    if graph:
        cmds.shaderfx(sfxnode=shader, loadGraph=graph)
    return shader
Ejemplo n.º 4
0
def noiseShift(fx, widget):
    """
    Noise shift, will shift the procedural noise of an effect
    Args:
        fx (MNPR_FX): MNPR_FX object coming from the caller
        widget (RelativeSlider): RelativeSlider object that is calling this function
    """
    # get value to enter
    valueDiff = widget.relValue()
    valueDiff /= 100.0  # shift between [-1:1]

    # get node names
    sfxNodes = getNodeNames(fx, 0)

    # shift each material
    materials = getMaterials()
    for mat in materials:
        # turn on procedural noise if turned off
        stateId = getId(mat, sfxNodes.stateNodeName)
        if not cmds.shaderfx(sfxnode=mat, getPropertyValue=(stateId, "value")):
            cmds.shaderfx(sfxnode=mat, edit_bool=(stateId, "value", True))

        # set attribute
        prevValue = cmds.getAttr("{0}.{1}".format(mat, sfxNodes.shiftNodeName))
        newValue = prevValue + valueDiff
        lib.setAttr(mat, sfxNodes.shiftNodeName, newValue)
Ejemplo n.º 5
0
def createMatcapMaterial(material_name, matcap_image_name):
    """
    matcapのマテリアルをshaderFXから作る
    matcap_image_name : imageファイルの名前
    return : マテリアルの名前
    """
    selection = cmds.ls(sl=True)
    if not cmds.pluginInfo("shaderFXPlugin", q=True, loaded=True):
        cmds.loadPlugin("shaderFXPlugin")
        cmds.pluginInfo("shaderFXPlugin", e=True, autoload=True)

    cmds.shadingNode("ShaderfxShader", asShader=True, n=material_name)
    # shaderfxグラフを読み込む
    graph_path = os.path.join(CURRENT_PATH, "matcap_mat.sfx")

    cmds.shaderfx(sfxnode=material_name, loadGraph=graph_path)

    node_name = "TextureMap"
    node_id = cmds.shaderfx(sfx_node=material_name, getNodeIDByName=node_name)
    texture_path = os.path.join(CURRENT_PATH, "matcaps", matcap_image_name)
    # テクスチャアサイン
    cmds.shaderfx(sfxnode=material_name, edit_string=[
                  node_id, "texturepath_MyTexture", texture_path])
    cmds.select(selection)
    return material_name
Ejemplo n.º 6
0
 def create(cls, name):
     """
     Create a new shader and return the ShaderNetwork that wraps it.
     """
     sfx_shader = cmds.shadingNode('ShaderfxShader', asShader=True, name=name)
     cmds.shaderfx(sfxnode=sfx_shader, initShaderAttributes=True)
     network = cls(sfx_shader)
     return network
Ejemplo n.º 7
0
def createMaterial(objs,
                   name="mnprMat_SFX",
                   prototype="shaderFX",
                   graph="mnpr_uber"):
    """
    Create and assign material to all objs
    Args:
        name (str): Name of new material
        objs (list): List of objects to assign new material into
        prototype (str): "shaderFX" or "prototypeC"
    Returns: Material name (str)
    """
    logger.debug("Creating new material for {0}".format(objs))

    # get shader file
    shaderFile = os.path.join(mnpr_info.environment, "shaders",
                              "{0}.sfx".format(graph))
    if prototype != "shaderFX":
        if os.name == 'nt' and mnpr_info.backend == 'dx11':
            shaderFile = os.path.join(mnpr_info.environment, "shaders",
                                      "{0}.fx".format(prototype))
            if not os.path.isfile(shaderFile):
                shaderFile = os.path.join(mnpr_info.environment, "shaders",
                                          "{0}.fxo".format(prototype))
        else:
            shaderFile = os.path.join(mnpr_info.environment, "shaders",
                                      "{0}.ogsfx".format(prototype))

    # check if objects are meshes
    shapes = lib.getShapes(objs)
    if not len(shapes):
        cmds.error(
            "{0} -> All selected objects need to be meshes".format(objs))

    # generate name of material
    newName = "{0}_{1}".format(name, mnpr_info.abbr)

    shader = ""
    if prototype == "shaderFX":
        shader = cmds.shadingNode('ShaderfxShader', asShader=True, name=name)
        cmds.shaderfx(sfxnode=shader, loadGraph=shaderFile)
    else:
        if os.name == 'nt' and mnpr_info.backend == 'dx11':
            shader = cmds.shadingNode('dx11Shader', asShader=True, n=newName)
        else:
            shader = cmds.shadingNode('GLSLShader', asShader=True, n=newName)

    # assign shader to selected
    cmds.select(objs, r=True)
    cmds.hyperShade(assign=shader)

    if prototype != "shaderFX":
        lib.setAttr(shader, "shader", shaderFile)
        lib.setAttr(shader, "xUseControl", False)

    return shader
Ejemplo n.º 8
0
def createPBS(name='a', num=0, textures=None, model=[]):
    name = 'M_' + name + '_LOD0'
    print name
    for i in range(num):
        shader = mc.shadingNode('StingrayPBS', asShader=True, name=name)
        mc.shaderfx(sfxnode=shader, initShaderAttributes=True)
        shading_group = mc.sets(renderable=True,
                                noSurfaceShader=True,
                                empty=True,
                                name=name + 'SG')
        mc.connectAttr(shader + '.outColor', shading_group + '.surfaceShader')

        ao = mc.shadingNode('file',
                            at=True,
                            name=name.replace('M', 'T') + '_AO')
        mc.setAttr(ao + '.fileTextureName', textures[i][0], type='string')

        cm = mc.shadingNode('file',
                            at=True,
                            name=name.replace('M', 'T') + '_B')
        mc.setAttr(cm + '.fileTextureName', textures[i][1], type='string')

        nm = mc.shadingNode('file',
                            at=True,
                            name=name.replace('M', 'T') + '_N')
        mc.setAttr(nm + '.fileTextureName', textures[i][2], type='string')

        # mm = mc.shadingNode('file', at=True, name=name.replace('M', 'T')+'_M')
        # mc.setAttr(mm+'.fileTextureName', textures[3][i], type='string')

        # rm = mc.shadingNode('file', at=True, name=name.replace('M', 'T')+'_R')
        # mc.setAttr(rm+'.fileTextureName', textures[4][i], type='string')

        # em = mc.shadingNode('file', at=True, name=name.replace('M', 'T')+'_E')
        # mc.setAttr(em+'.fileTextureName', textures[5][i], type='string')

        mc.setAttr(shader + '.use_color_map', 1)
        mc.setAttr(shader + '.use_normal_map', 1)
        # mc.setAttr(shader+'.use_metallic_map', 1)
        # mc.setAttr(shader+'.use_roughness_map', 1)
        # mc.setAttr(shader+'.use_emissive_map', 1)
        mc.setAttr(shader + '.use_ao_map', 1)

        mc.connectAttr(cm + '.outColor', shader + '.TEX_color_map')
        mc.connectAttr(nm + '.outColor', shader + '.TEX_normal_map')
        # mc.connectAttr(mm+'.outColor', shader+'.TEX_metallic_map')
        # mc.connectAttr(rm+'.outColor', shader+'.TEX_roughness_map')
        # mc.connectAttr(em+'.outColor', shader+'.TEX_emissive_map')
        mc.connectAttr(ao + '.outColor', shader + '.TEX_ao_map')

        mc.sets('%s' % model[i], e=True, fe='%s' % shading_group)
Ejemplo n.º 9
0
def refresh_materials(objects=None):
    """ Forces an update of assigned shaderFX materials """
    if objects:
        materials = cmat.get_materials(objects)
    else:
        materials = cmds.ls(type="ShaderfxShader")
    selection = cmds.ls(sl=True, l=True)
    restore_selection = False
    for mat in materials:
        if cmds.objectType(mat) == 'ShaderfxShader':
            cmds.select(mat, r=True)  # needs to be selected
            restore_selection = True
            cmds.shaderfx(sfxnode=mat, update=True)
    if restore_selection:
        cmds.select(selection, r=True)
Ejemplo n.º 10
0
 def refreshIds(self, mat):
     """
         Store the node IDs of the FX nodes
     Args:
         mat (str): Material name to get node ids from
     """
     self.scale = cmds.shaderfx(sfxnode=mat,
                                getNodeIDByName=self.scaleNodeName)
     self.intensity = cmds.shaderfx(sfxnode=mat,
                                    getNodeIDByName=self.intensityNodeName)
     self.shift = cmds.shaderfx(sfxnode=mat,
                                getNodeIDByName=self.shiftNodeName)
     self.state = cmds.shaderfx(sfxnode=mat,
                                getNodeIDByName=self.stateNodeName)
     self.type = cmds.shaderfx(sfxnode=mat,
                               getNodeIDByName=self.typeNodeName)
Ejemplo n.º 11
0
def get_node_value(material, unique_node_name, quiet=False):
    """
    Utility function to get the node value within a shaderFX material
    Args:
        material (unicode): Material to get node id from
        unique_node_name (unicode): Unique node name in ShaderFX
        quiet (bool): If warnings should print or not
    """
    value = None
    node_id = get_id(material, unique_node_name, quiet)
    if node_id:
        if "value" in cmds.shaderfx(sfxnode=material, listProperties=node_id):
            value = cmds.shaderfx(sfxnode=material, getPropertyValue=(node_id, "value"))
        else:
            value = cmds.shaderfx(sfxnode=material, getPropertyValue=(node_id, "options"))[-1]
    return value
Ejemplo n.º 12
0
def get_node_name(material, node_id):
    """
    Get the name of a node based on its id
    Args:
        material (unicode): Material to get node name from
        node_id (int): Node id to get name of
    """
    return cmds.shaderfx(sfxnode=material, getPropertyValue=(node_id, "name"))
Ejemplo n.º 13
0
def list_node_ids(material, node_type=None):
    """
    List nodes of a certain type
    Args:
        material (unicode): Name of the shaderFX material
        node_type (unicode): Type to list (Type names correspond to names in ShaderFX node panel)
    """
    node_count = cmds.shaderfx(sfxnode=material, getNodeCount=True)
    ids = []
    for node_id in range(node_count):
        if node_type is None:
            ids.append(node_id)
        else:
            class_name = cmds.shaderfx(sfxnode=material, getNodeClassName=node_id)
            if node_type == class_name:
                ids.append(node_id)
    return ids
Ejemplo n.º 14
0
def noiseSlide(fx, widget):
    """
    Noise slide, will modify the procedural noise of an effect
    Args:
        fx (MNPR_FX): MNPR_FX object coming from the caller
        widget (LabeledSlider): LabeledSlider object that is calling this function
    """
    # get index of sliding operation
    idx = 0  # default scale index
    if widget.label != "scale":
        idx = fx.procOptions.index(widget.label)

    # get node names of operation
    sfxNodes = getNodeNames(fx, idx)

    # get value to enter
    valueDiff = widget.slider.relValue()
    if widget.label == "scale":
        valueDiff /= 100.0
    else:
        valueDiff /= 5.0

    materials = getMaterials()

    for mat in materials:
        # turn on procedural noise if turned off
        stateId = getId(mat, sfxNodes.stateNodeName)
        if not cmds.shaderfx(sfxnode=mat, getPropertyValue=(stateId, "value")):
            lib.printInfo("Recompiling material")
            cmds.shaderfx(sfxnode=mat, edit_bool=(stateId, "value", True))

        # get attribute name
        attr = ""
        if widget.label != "scale":
            attr = sfxNodes.intensityNodeName
        else:
            attr = sfxNodes.scaleNodeName

        # set attribute
        attribute = "{0}.{1}".format(mat, attr)
        prevValue = cmds.getAttr(attribute)
        newValue = prevValue + valueDiff
        lib.setAttr(mat, attr, newValue)
Ejemplo n.º 15
0
def setMaterialAttrs(mat, matAttrs, options={}):
    """
    Sets material attributes found in matAttrs (e.g., settings, procedural settings, attributes and textures)
    Args:
        mat (str): name of material
        matAttrs (dict): dictionary of material attributes
        options (dict): dictionary of options to set
    """
    if not options:
        # coming from update, set all to true
        options["textures"] = True
        options["noiseFX"] = True

    # set settings
    settings = matAttrs['settings']
    for setting in settings:
        nodeId = cmds.shaderfx(sfxnode=mat, getNodeIDByName=setting)
        if "value" in cmds.shaderfx(sfxnode=mat, listProperties=nodeId):
            type = cmds.shaderfx(sfxnode=mat,
                                 getPropertyType=(nodeId, "value"))
            eval(
                "cmds.shaderfx(sfxnode=mat, edit_{0}=(nodeId, 'value', settings[setting]))"
                .format(type))
        else:
            cmds.shaderfx(sfxnode=mat,
                          edit_stringlist=(nodeId, "options",
                                           int(settings[setting])))
    # set procedural settings
    if options["noiseFX"]:
        procSettings = matAttrs['procSettings']
        for setting in procSettings:
            try:
                nodeId = cmds.shaderfx(sfxnode=mat, getNodeIDByName=setting)
                cmds.shaderfx(sfxnode=mat,
                              edit_bool=(nodeId, "value",
                                         procSettings[setting]))
            except RuntimeError:
                #traceback.print_exc()
                print "Setting of {0} procedural node has failed".format(
                    setting)
                continue
    # set all attributes
    if mnpr_system.updateAE():
        attributes = matAttrs['attributes']
        for attr in attributes:
            lib.setAttr(mat, attr, attributes[attr], True)
        # set all textures
        if options["textures"]:
            textures = matAttrs['textures']
            for texture in textures:
                lib.setAttr(mat, texture, textures[texture], True)
Ejemplo n.º 16
0
def getId(mat, uniqueNodeName):
    """
    Utility function to get the id of uniqueNodeName within mat
    Args:
        mat (str): Material to get node id from
        uniqueNodeName (str): Unique node name in ShaderFX
    Returns:
        (int): Node id in ShaderFX graph
    """
    nodeId = cmds.shaderfx(sfxnode=mat, getNodeIDByName=uniqueNodeName)

    return nodeId
Ejemplo n.º 17
0
def getMaterialAttrs(mat, dictionary):
    """
    Adds material attributes to dictionary (e.g., settings, procedural settings, attributes and textures)
    Args:
        mat (str): name of material
        dictionary (dict): dictionary of material attributes
    """
    # get graph name
    nodeId = cmds.shaderfx(sfxnode=mat, getNodeIDByName="graphName")
    dictionary["graph"] = str(
        cmds.shaderfx(sfxnode=mat, getPropertyValue=(nodeId, "value")))
    # get settings
    settings = {}
    for settingNode in settingNodes:
        try:
            nodeId = cmds.shaderfx(sfxnode=mat, getSettingNodeID=settingNode)
        except RuntimeError:
            continue
        if "value" in cmds.shaderfx(sfxnode=mat, listProperties=nodeId):
            settings[settingNode] = cmds.shaderfx(sfxnode=mat,
                                                  getPropertyValue=(nodeId,
                                                                    "value"))
        else:
            settings[settingNode] = cmds.shaderfx(
                sfxnode=mat, getPropertyValue=(nodeId, "options"))[-1]
    dictionary['settings'] = settings
    # get procedural settings
    procSettings = {}
    for settingNode in procSettingNodes:
        try:
            nodeId = cmds.shaderfx(sfxnode=mat, getNodeIDByName=settingNode)
        except RuntimeError:
            continue
        procSettings[settingNode] = cmds.shaderfx(sfxnode=mat,
                                                  getPropertyValue=(nodeId,
                                                                    "value"))
    dictionary['procSettings'] = procSettings
    # get attributes and textures
    setAttrs = cmds.listAttr(mat, k=True)
    setTextures = cmds.listAttr(mat, uf=True)
    attributes = {}
    for attr in setAttrs:
        attributes[attr] = cmds.getAttr("{0}.{1}".format(mat, attr))
    dictionary['attributes'] = attributes
    textures = {}
    for texture in setTextures:
        textures[texture] = cmds.getAttr("{0}.{1}".format(mat, texture))
    dictionary['textures'] = textures
Ejemplo n.º 18
0
def noiseTypeClicked(fx):
    """
    Toggle between noise types (3D or 2D)
    Args:
        fx (MNPR_FX): MnprFx object coming from the caller
    """
    materials = getMaterials()

    # get node names of operation
    sfxNodes = getNodeNames(fx, 0)

    lib.printInfo("Recompiling material")
    typeId = getId(
        materials[0],
        sfxNodes.typeNodeName)  # base toggle on first material state
    state = cmds.shaderfx(sfxnode=materials[0],
                          getPropertyValue=(typeId, "value"))
    for mat in materials:
        cmds.shaderfx(sfxnode=mat, edit_bool=(typeId, "value", not state))
    if state:
        lib.printInfo("NoiseFX for {0} is now in 2D".format(fx.description))
    else:
        lib.printInfo("NoiseFX for {0} is now in 3D".format(fx.description))
Ejemplo n.º 19
0
def enableVtxCtrl(shapes):
    """
    Enable vertex color control on shapes
    Args:
        shapes (list): List of shapes (str) to enable vertex control to
    """
    # enable ctrl in material
    selected = cmds.ls(sl=True, l=True)
    cmds.hyperShade(smn=True)
    mats = cmds.ls(sl=True, l=True, mat=True)
    for mat in mats:
        if cmds.nodeType(mat) == "ShaderfxShader":
            nodeId = getId(mat, "vtxControls")
            cmds.shaderfx(sfxnode=mat, edit_bool=(nodeId, "value", True))
        else:
            if cmds.attributeQuery("xUseControl", node=mat, ex=True):
                lib.setAttr(mat, "xUseControl", True)
            if cmds.attributeQuery("Color0_Source", node=mat, ex=True):
                lib.setAttr(mat, "Color0_Source", "color:controlSetA")
            if cmds.attributeQuery("Color1_Source", node=mat, ex=True):
                lib.setAttr(mat, "Color1_Source", "color:controlSetB")
            if cmds.attributeQuery("Color2_Source", node=mat, ex=True):
                lib.setAttr(mat, "Color2_Source", "color:controlSetC")
    cmds.select(selected, r=True)

    # create vtx control sets
    for shape in shapes:
        colorSets = cmds.polyColorSet(shape, query=True, allColorSets=True)
        if not colorSets:
            colorSets = []
        if "controlSetC" not in colorSets:
            logger.debug("Creating control sets for {0}".format(shape))
            # create color sets
            cmds.polyColorSet(shape, cs='controlSetA', create=True)
            cmds.polyColorSet(shape, cs='controlSetB', create=True)
            cmds.polyColorSet(shape, cs='controlSetC', create=True)
            defaultVertexColors(shape)
Ejemplo n.º 20
0
def updateShaderFX():
    """ Updates shaderFX shaders"""
    shaderDir = systemDir("shaders")
    materials = cmds.ls(type="ShaderfxShader")

    counter = 0
    for mat in materials:
        counter += 1
        # get materials attributes
        matAttrs = {}
        mnpr_matPresets.getMaterialAttrs(mat, matAttrs)

        # load new graph
        shaderFile = os.path.join(shaderDir,
                                  "{0}.sfx".format(matAttrs["graph"]))
        cmds.shaderfx(sfxnode=mat, loadGraph=shaderFile)

        # set attributes
        mnpr_matPresets.setMaterialAttrs(mat, matAttrs)

        print("{0} has been updated to the latest version".format(mat))
        print("{0}/{1} materials updated".format(counter, len(materials)))

    lib.printInfo('Shaders updated')
Ejemplo n.º 21
0
def noiseToggleClicked(fx):
    """
    Toggle procedural effect (On or Off)
    Args:
        fx (MNPR_FX): MnprFx object coming from the caller
    """
    materials = getMaterials()

    # get node names of operation
    sfxNodes = getNodeNames(fx, 0)

    lib.printInfo("Recompiling material")
    stateId = getId(
        materials[0],
        sfxNodes.stateNodeName)  # base toggle on first material state
    state = cmds.shaderfx(sfxnode=materials[0],
                          getPropertyValue=(stateId, "value"))
    for mat in materials:
        stateId = getId(mat, sfxNodes.stateNodeName)
        cmds.shaderfx(sfxnode=mat, edit_bool=(stateId, "value", not state))
    if state:
        lib.printInfo("NoiseFX for {0} is off".format(fx.description))
    else:
        lib.printInfo("NoiseFX for {0} is on".format(fx.description))
Ejemplo n.º 22
0
def get_id(material, unique_node_name, quiet=False):
    """
    Utility function to get the id of uniqueNodeName within a shaderFX material
    Args:
        material (unicode): Material to get node id from
        unique_node_name (unicode): Unique node name in ShaderFX
        quiet (bool): If warnings should print or not

    Returns:
        (int): Node id in ShaderFX graph
    """
    node_id = 0
    if cmds.objectType(material) == 'ShaderfxShader':
        try:
            node_id = cmds.shaderfx(sfxnode=material, getNodeIDByName=unique_node_name)
        except RuntimeError:
            if not quiet:
                clib.print_warning("Node {0} was not found in the material {1}".format(unique_node_name, material))
    return node_id
Ejemplo n.º 23
0
    def generate_class_definitions(cls, shader, node_list):
        """
        helper method which generates class definitions for known node types. These are stable within maya versions
        but may change between them. Requires a shader node to run.  Create a node, then pass in one of the string lists
        in the pbsnodes or sfxnodes modules to this -- it will spit out a the text of all the classes for your version
        of Maya.
        """
        class_def = []
        errors = []

        for item in node_list.split('\n'):
            try:
                classname = item.replace(" ", "")
                id_code = cmds.shaderfx(sfxnode=shader, getNodeTypeByClassName=item)
                class_def.append(cls.SFX_NODE_TEMPLATE.format(classname, cls.__name__, item, id_code))
            except:
                errors.append(item)

        return class_def, errors
Ejemplo n.º 24
0
    def load(self, name, options):
        """
        Loads the specified attribute set
        Args:
            name (str): Name of the attribute set to import
        """
        # get data
        selection = cmds.ls(sl=True, l=True)
        mat, xform = getMaterial(selection)
        if not mat:
            cmds.error("Nothing was selected")

        # if not the same material type, create new material
        matType = cmds.objectType(mat)
        try:
            graph = self[name]['graph']
        except KeyError:
            graph = "mnpr_uber"

        prevGraph = "NA"
        if self[name]['type'] != matType:
            mat = createMaterial(xform, graph=graph)
        else:
            # shaderFX shader, get current graph name
            try:
                nodeId = cmds.shaderfx(sfxnode=mat,
                                       getNodeIDByName="graphName")
                prevGraph = cmds.shaderfx(sfxnode=mat,
                                          getPropertyValue=(nodeId, "value"))
            except RuntimeError:
                pass
            # if a new material is desired, create anyways
            if options["newMaterial"]:
                mat = createMaterial([xform[0]], graph=graph)
            elif graph != prevGraph:
                shaderFile = os.path.join(mnpr_info.environment, "shaders",
                                          "{0}.sfx".format(graph))
                cmds.shaderfx(sfxnode=mat, loadGraph=shaderFile)

        # default lighting in case there are no lights
        defaultLighting()

        shapes = lib.getShapes(xform)
        # if colorSets are present, enable control to avoid wrong vertex stylization inputs
        if cmds.polyColorSet(shapes, query=True, allColorSets=True):
            mnpr_pFX.enableVtxCtrl(shapes)
        # disable/enable shadows when proxy geometry is involved
        if graph == "mnpr_geoproxy":
            for shape in shapes:
                lib.setAttr(shape, "castsShadows", False)
                lib.setAttr(shape, "receiveShadows", False)
        elif prevGraph == "mnpr_geoproxy":
            for shape in shapes:
                lib.setAttr(shape, "castsShadows", True)
                lib.setAttr(shape, "receiveShadows", True)

        # set material settings and attributes
        if matType == 'ShaderfxShader':
            setMaterialAttrs(mat, self[name], options)
        else:
            # set attributes in material
            print "->{0} will be replaced".format(mat)
            attrs = self[name]['attributes']
            for attr in attrs:
                lib.setAttr(mat, attr, attrs[attr])
            cmds.select(mat, r=True)
Ejemplo n.º 25
0
def dx112sfx(graph="mnpr_uber"):
    """
    Converts dx11 materials to shaderFX materials
    Args:
        graph (str): ShaderFX graph name (filename)
    """
    check()
    dx11Shaders = cmds.ls(type="dx11Shader")
    prototypeCNodes = []
    for dx11Shader in dx11Shaders:
        shaderPath = cmds.getAttr("{0}.shader".format(dx11Shader))
        if "rototypeC" not in shaderPath:
            continue
        prototypeCNodes.append(dx11Shader)

        print("Converting {0} shader".format(dx11Shader))
        # get all attributes
        attributes = cmds.listAttr(dx11Shader, ud=True, st="x*", k=True)
        print(attributes)
        # get all connected nodes
        connectedNodes = cmds.listConnections(dx11Shader, t="file", c=True)
        print(connectedNodes)
        # get all shapes
        cmds.select(dx11Shader, r=True)
        cmds.hyperShade(objects="")
        shapes = cmds.ls(sl=True)
        print(shapes)

        # create shaderFX shader
        shader = cmds.shadingNode('ShaderfxShader',
                                  asShader=True,
                                  name="{0}".format(
                                      dx11Shader.replace("_WC", "_SFX")))
        cmds.select(shapes, r=True)
        cmds.hyperShade(assign=shader)
        shaderFile = os.path.join(mnpr_info.environment, "shaders",
                                  "{0}.sfx".format(graph))
        cmds.shaderfx(sfxnode=shader, loadGraph=shaderFile)
        print(">>> Shader {0} created".format(shader))
        # assign settings
        vtxControl = bool(
            cmds.getAttr("{0}.{1}".format(dx11Shader, "xUseControl")))
        if vtxControl:
            nodeId = cmds.shaderfx(sfxnode=shader,
                                   getNodeIDByName="vtxControls")
            cmds.shaderfx(sfxnode=shader,
                          edit_bool=(nodeId, "value", vtxControl))
        shadows = bool(
            cmds.getAttr("{0}.{1}".format(dx11Shader, "xUseShadows")))
        if not shadows:
            nodeId = cmds.shaderfx(sfxnode=shader, getNodeIDByName="Shadow")
            cmds.shaderfx(sfxnode=shader, edit_bool=(nodeId, "value", shadows))
        specularity = bool(
            cmds.getAttr("{0}.{1}".format(dx11Shader, "xSpecular")))
        if specularity:
            nodeId = cmds.shaderfx(sfxnode=shader,
                                   getNodeIDByName="Specularity")
            cmds.shaderfx(sfxnode=shader,
                          edit_bool=(nodeId, "value", specularity))
        # assign attributes
        print("Setting attributes for {0}".format(shader))
        for attr in attributes:
            value = cmds.getAttr("{0}.{1}".format(dx11Shader, attr))
            if attr in dx2sfxAttr:
                lib.setAttr(shader, dx2sfxAttr[attr], value)
        # assign textures
        if connectedNodes:
            for i in range(0, len(connectedNodes), 2):
                textureDir = cmds.getAttr("{0}.{1}".format(
                    connectedNodes[i + 1], "fileTextureName"))
                attr = connectedNodes[i].split(".")[1]
                lib.setAttr(shader, dx2sfxAttr[attr], textureDir)

    # delete prototypeC shaders
    cmds.delete(prototypeCNodes)
Ejemplo n.º 26
0
def createPBS(name, direcotory=os.path.join(MayaProjectDir, 'sourceimages')):
    '''
    创建pbs
    :param name: 名字
    :param direcotory: 贴图文件夹,默认项目文件夹sourceimages
    :return:
    '''
    if cmds.ls(sl=True, type='dagNode'):
        meshName = cmds.ls(sl=True, type='dagNode')[0]
    else:
        cmds.warning(u'未选择模型')
        return
    for i in os.listdir(MayaProjectDir):
        # 使用simplygon减面
        if i.endswith('AmbientOcclusion.png'):
            im = Image.open(os.path.join(MayaProjectDir, i))
            im = im.resize((512, 512), Image.ANTIALIAS)
            im.save(os.path.join(direcotory, 'T_%s_ao.png' % name))
            os.remove(os.path.join(MayaProjectDir, i))
        if i.endswith('Diffuse.png'):
            im = Image.open(os.path.join(MayaProjectDir, i))
            im = im.resize((2048, 2048), Image.ANTIALIAS)
            im.save(os.path.join(direcotory, 'T_%s_b.png' % name))

            os.remove(os.path.join(MayaProjectDir, i))

        if i.endswith('Normals.png'):
            im = Image.open(os.path.join(MayaProjectDir, i))
            im = im.resize((2048, 2048), Image.ANTIALIAS)
            im.save(os.path.join(direcotory, 'T_%s_n.png' % name))

            os.remove(os.path.join(MayaProjectDir, i))

    shaderName = 'M_' + name + '_w'
    if cmds.objExists(shaderName):
        cmds.delete(shaderName)
    shader = cmds.shadingNode('StingrayPBS', asShader=True, name=shaderName)
    cmds.shaderfx(sfxnode=shader, initShaderAttributes=True)  # 初始化pbs

    shading_group_name = shaderName + 'SG'
    if cmds.objExists(shading_group_name):
        cmds.delete(shading_group_name)
    shading_group = cmds.sets(renderable=True,
                              noSurfaceShader=True,
                              empty=True,
                              name=shading_group_name)
    cmds.connectAttr(shader + '.outColor', shading_group + '.surfaceShader')

    imges = os.listdir(direcotory)
    for img in imges:
        if img.endswith('%s_b.png' % name):
            baseTex = os.path.join(direcotory, img)
            imageSaveAs(baseTex, (2048, 2048))
            tb = 'T_' + name + '_b'
            if cmds.objExists(tb):
                cmds.delete(tb)
            baseColor = cmds.shadingNode('file', at=True, name=tb)
            cmds.setAttr(shader + '.use_color_map', 1)
            cmds.connectAttr(baseColor + '.outColor',
                             shader + '.TEX_color_map')
            cmds.setAttr(baseColor + '.fileTextureName',
                         baseTex,
                         type='string')

        if img.endswith('%s_n.png' % name):
            noramlTex = os.path.join(direcotory, img)
            imageSaveAs(noramlTex, (2048, 2048))

            tn = 'T_' + name + '_n'
            if cmds.objExists(tn):
                cmds.delete(tn)
            normal = cmds.shadingNode('file', at=True, name=tn)
            cmds.setAttr(shader + '.use_normal_map', 1)
            cmds.connectAttr(normal + '.outColor', shader + '.TEX_normal_map')
            cmds.setAttr(normal + '.fileTextureName', noramlTex, type='string')

        if img.endswith('%s_ao.png' % name):
            aoTex = os.path.join(direcotory, img)
            imageSaveAs(aoTex, (512, 512))

            tao = 'T_' + name + '_ao'
            if cmds.objExists(tao):
                cmds.delete(tao)
            ambientOcclusion = cmds.shadingNode('file', at=True, name=tao)
            cmds.setAttr(shader + '.use_ao_map', 1)
            cmds.connectAttr(ambientOcclusion + '.outColor',
                             shader + '.TEX_ao_map')
            cmds.setAttr(ambientOcclusion + '.fileTextureName',
                         aoTex,
                         type='string')

        if img.endswith('%s_r.png' % name):
            roughnessTex = os.path.join(direcotory, img)
            imageSaveAs(roughnessTex, (512, 512))

            tr = 'T_' + name + '_r'
            if cmds.objExists(tr):
                cmds.delete(tr)
            roughness = cmds.shadingNode('file', at=True, name=tr)
            cmds.setAttr(shader + '.use_roughness_map', 1)
            cmds.connectAttr(roughness + '.outColor',
                             shader + '.TEX_roughness_map')
            cmds.setAttr(roughness + '.fileTextureName',
                         roughnessTex,
                         type='string')

        else:
            cmds.setAttr(shader + '.roughness', 0.5)

        if img.endswith('%s_m.png' % name):
            metallicTex = os.path.join(direcotory, img)
            imageSaveAs(metallicTex, (512, 512))

            tm = 'T_' + name + '_m'
            if cmds.objExists(tm):
                cmds.delete(tm)
            metallic = cmds.shadingNode('file', at=True, name=tm)
            cmds.setAttr(shader + '.use_metallic_map', 1)
            cmds.connectAttr(metallic + '.outColor',
                             shader + '.TEX_metallic_map')
            cmds.setAttr(metallic + '.fileTextureName',
                         metallicTex,
                         type='string')

        if img.endswith('%s_e.png' % name):
            emissiveTex = os.path.join(direcotory, img)
            imageSaveAs(emissiveTex, (512, 512))

            te = 'T_' + name + '_e'
            if cmds.objExists(te):
                cmds.delete(te)
            emissive = cmds.shadingNode('file', at=True, name=te)
            cmds.setAttr(shader + '.use_emissive_map', 1)
            cmds.connectAttr(emissive + '.outColor',
                             shader + '.TEX_emissive_map')
            cmds.setAttr(emissive + '.fileTextureName',
                         emissiveTex,
                         type='string')

    cmds.sets(meshName, e=True, fe=shading_group)
    cmds.select(meshName)
    return meshName
Ejemplo n.º 27
0
 def create(cls, name):
     sfx_shader = cmds.shadingNode('StingrayPBS', asShader=True, name=name)
     cmds.shaderfx(sfxnode=sfx_shader, initShaderAttributes=True)
     network = cls(sfx_shader)
     return network
Ejemplo n.º 28
0
def set_node_value(material, unique_node_name, value, quiet=False):
    """
    Utility function to set the node value within a shaderFX material
    Args:
        material (unicode): Material to get node id from
        unique_node_name (unicode): Unique node name in ShaderFX
        value (any): Value to set into node
        quiet (bool): If warnings should print or not
    """
    node_id = get_id(material, unique_node_name, quiet)
    if node_id:
        selection = cmds.ls(sl=True, l=True)
        cmds.select(material, r=True)  # triggers and scripts are only made if material is selected
        if "value" in cmds.shaderfx(sfxnode=material, listProperties=node_id):
            v = cmds.shaderfx(sfxnode=material, getPropertyValue=(node_id, "value"))
            if v is not value:
                if isinstance(value, bool):
                    cmds.shaderfx(sfxnode=material, edit_bool=(node_id, "value", value))
                elif isinstance(value, float):
                    cmds.shaderfx(sfxnode=material, edit_float=(node_id, "value", value))
                elif isinstance(value, int):
                    cmds.shaderfx(sfxnode=material, edit_int=(node_id, "value", value))
        else:
            v = cmds.shaderfx(sfxnode=material, getPropertyValue=(node_id, "options"))[-1]
            if v is not value:
                cmds.shaderfx(sfxnode=material, edit_stringlist=(node_id, "options", int(value)))
        cmds.select(selection, r=True)
    else:
        if not quiet:
            clib.print_warning("Setting of {0} node to {1} has failed".format(unique_node_name, value))
    return node_id