示例#1
0
    def load(self, context, name, namespace, data):

        from avalon.maya.pipeline import containerise
        # from pype.hosts.maya.lib import namespaced

        asset = context['asset']['name']
        namespace = namespace or lib.unique_namespace(
            asset + "_",
            prefix="_" if asset[0].isdigit() else "",
            suffix="_",
        )

        with open(self.fname, "r") as file:
            renderSetup.instance().decode(json.load(file),
                                          renderSetup.DECODE_AND_OVERWRITE,
                                          None)

        nodes = []
        null = cmds.sets(name="null_SET", empty=True)
        nodes.append(null)

        self[:] = nodes
        if not nodes:
            return

        return containerise(name=name,
                            namespace=namespace,
                            nodes=nodes,
                            context=context,
                            loader=self.__class__.__name__)
示例#2
0
    def get(self, renderer, layer):
        """Get expected files for given renderer and render layer.

        Args:
            renderer (str): Name of renderer
            layer (str): Name of render layer

        Returns:
            dict: Expected rendered files by AOV

        Raises:
            :exc:`UnsupportedRendererException`: If requested renderer
                is not supported. It needs to be implemented by extending
                :class:`AExpectedFiles` and added to this methods ``if``
                statement.

        """
        renderSetup.instance().switchToLayerUsingLegacyName(layer)

        if renderer.lower() == "arnold":
            return self._get_files(ExpectedFilesArnold(layer))
        elif renderer.lower() == "vray":
            return self._get_files(ExpectedFilesVray(layer))
        elif renderer.lower() == "redshift":
            return self._get_files(ExpectedFilesRedshift(layer))
        elif renderer.lower() == "mentalray":
            return self._get_files(ExpectedFilesMentalray(layer))
        elif renderer.lower() == "renderman":
            return self._get_files(ExpectedFilesRenderman(layer))
        else:
            raise UnsupportedRendererException(
                "unsupported {}".format(renderer)
            )
    def renderSetupAdded(self):
        """Called just after the render setup node has been added."""
        renderSetup.instance().addActiveLayerObserver(
            self.onRenderLayerChanged)

        # We might be called as a result of file open.  Make sure we
        # observe attribute changes.
        self.onRenderLayerChanged()
示例#4
0
def get_renderable_layers():
    renderable_layers = [
        layer for layer in renderSetup.instance().getRenderLayers()
        if layer.isRenderable()
    ]
    defaultLayer = renderSetup.instance().getDefaultRenderLayer()
    if defaultLayer.isRenderable():
        renderable_layers.append(defaultLayer)
    return renderable_layers
示例#5
0
    def setData(self, value, role):
        if self._model is None:
            super(SceneProxyItem, self).setData(value, role)
            return

        if role == NODE_VISIBLE and value:
            renderSetupModel.instance().switchToLayer(self._model)
        if role == NODE_RENDERABLE:
            self._model.setRenderable(value)
        else:
            super(SceneProxyItem, self).setData(value, role)
示例#6
0
def getTotalNumberOperations(model):
    import maya.app.renderSetup.model.renderSetup as renderSetupModel
    newLayer = model
    oldLayer = renderSetupModel.instance().getVisibleRenderLayer()
    totalTopNumberOperations = 0
    if(oldLayer and not oldLayer == renderSetupModel.instance().getDefaultRenderLayer()):
        totalTopNumberOperations += _recursiveSearch(oldLayer.getCollections())
    if(newLayer and not newLayer == renderSetupModel.instance().getDefaultRenderLayer() and newLayer != oldLayer):
        totalTopNumberOperations += _recursiveSearch(newLayer.getCollections())
    totalTopNumberOperations += 3
    return totalTopNumberOperations
    def process(self, instance):

        rs = renderSetup.instance()
        master_layer = rs.getDefaultRenderLayer()
        rs.switchToLayer(master_layer)

        self.log.info("SCENE SAVE")

        if instance.context.data.get('ftrackData'):
            if instance.context.data['ftrackData']['Project']['code'] == 'hbt':
                self.log.info("Switching texures to PROXY")
                import hbt_switch_tex as hbtSw
                reload(hbtSw)

                nhbtData=hbtSw.switchTexture()

                nhbtData.option = 2
                nhbtData.highest = False
                nhbtData.limit = 1600
                nhbtData.validatorCheck()
                nhbtData.fast = False

                nhbtData.all = True
                nhbtData.switch()
                pm.refresh(f = True)

                self.log.info("Switched to PROXY before save")

        self.log.info('saving scene')
        maya.cmds.file(s=True)
示例#8
0
def getRenderLayerNameList():
    layer_objects = renderSetup.instance().getRenderLayers(
    )  # get layer object list
    layer_list = []
    for i in layer_objects:
        layer_list.append(i.name())  # (object).name() return object name
    return layer_list
示例#9
0
    def get(self, renderer, layer):
        renderSetup.instance().switchToLayerUsingLegacyName(layer)

        if renderer.lower() == "arnold":
            return self._get_files(ExpectedFilesArnold(layer))
        elif renderer.lower() == "vray":
            return self._get_files(ExpectedFilesVray(layer))
        elif renderer.lower() == "redshift":
            return self._get_files(ExpectedFilesRedshift(layer))
        elif renderer.lower() == "mentalray":
            return self._get_files(ExpectedFilesMentalray(layer))
        elif renderer.lower() == "renderman":
            return self._get_files(ExpectedFilesRenderman(layer))
        else:
            raise UnsupportedRendererException(
                "unsupported {}".format(renderer))
    def set_layer(self, name_):

        rs = renderSetup.instance()
        for i in range(len(self.hdr_paths)):
            _layer = rs.getRenderLayer('Scene' + str(i))
            human_collection = _layer.getCollectionByName("human" + str(i))
            human_collection.getSelector().staticSelection.set([name_])
示例#11
0
def getProxy(node):
    # Don't import at module level, otherwise import will fail in batch mode.
    import maya.app.renderSetup.views.proxy.renderSetup as renderSetupProxy
    import maya.app.renderSetup.views.renderSetup as renderSetupUI

    return renderSetupUI.renderSetupWindow.centralWidget.renderSetupView.model() \
        if node == renderSetup.instance() else renderSetupProxy.getProxy(node)
示例#12
0
def make_random_color_rsl(geo_list, lyr_name, seed=0):
    """Make randomColor renderSetuplayer

    Args:
        geo_list (pyNode list): list of geometries affected by the layer
        lyr_name (str): Layer name
        seed (int, optional): Random Seed
    """
    try:
        pm.undoInfo(openChunk=True)

        rs = renderSetup.instance()
        rs.clearAll()
        mel.eval('MLdeleteUnused;')

        rl = rs.createRenderLayer(CRANK_RENDER_LAYER_NAME)
        for geo in geo_list:
            mtl = make_random_color_mtl(seedStr=str(geo), seedOffset=seed)
            clct = rl.createCollection("clct")
            clct.getSelector().setPattern(geo)
            shOv = clct.createOverride('shOv', typeIDs.shaderOverride)
            shOv.setShader(mtl)

        rs.switchToLayer(rl)
    finally:
        pm.undoInfo(closeChunk=True)
示例#13
0
 def _beforeExport(self, clientData):
     import maya.app.renderSetup.model.renderSetup as renderSetup
     rs = renderSetup.instance()
     self._enabledLocalOverrides = [] if rs.getDefaultRenderLayer().isVisible() else \
         filter(lambda ov: ov.isLocalRender() and ov.isEnabled(), utils.getOverridesRecursive(rs.getVisibleRenderLayer()))
     self._exporting = True
     _toggle(self._enabledLocalOverrides)
示例#14
0
 def _updateCollections(self):
     if renderSetup.hasInstance():
         lightName = om.MFnDagNode(self.mayaHandle.object()).name()
         renderLayers = renderSetup.instance().getRenderLayers()
         for renderLayer in renderLayers:
             col = LightSource._findLightCollection(renderLayer, lightName)
             if col:
                 col.getSelector().setStaticSelection(self.getShapeName())
示例#15
0
def getCollectionItems():
    layer_name = 'charaA'  # any layer name
    collection_name = 'visibilityOff'  # any collection name
    target_collection = renderSetup.instance().getRenderLayer(
        layer_name).getCollectionByName(collection_name)
    objects_in_collection = target_collection.getSelector(
    ).staticSelection.asList()
    return objects_in_collection
示例#16
0
def setMayaObjectToCollection():
    sel = cmds.ls(sl=True)  # it must be list even if it is a single object
    layer_name = 'charaA'  # any layer name
    collection_name = 'visibilityOff'  # any collection name
    target_collection = renderSetup.instance().getRenderLayer(
        layer_name).getCollectionByName(collection_name)
    target_collection.getSelector().staticSelection.set(
        sel)  # set maya object to collection
示例#17
0
def getCollectionsNameFromLayerName():
    layer_name = 'charaA'  # any name
    render_layer = renderSetup.instance().getRenderLayer(layer_name)
    collection_objects = render_layer.getCollections()
    collection_names = []
    for i in collection_objects:
        collection_names.append(i.name())
    return collection_names
示例#18
0
def createRenderSetttingoverride():
    layer_name = 'charaA'  # any layer
    render_layer = renderSetup.instance().createRenderLayer(layer_name)
    set_colle = render_layer.renderSettingsCollectionInstance()
    attr_name = 'AASamples'
    override = set_colle.createAbsoluteOverride('defaultArnoldRenderOptions',
                                                attr_name)
    override.setAttrValue(5)
    override.setName(layer_name + '_' + attr_name)
示例#19
0
    def process(self):
        """Entry point."""
        exists = cmds.ls(self.name)
        if exists:
            cmds.warning("%s already exists." % exists[0])
            return

        use_selection = self.options.get("useSelection")
        with lib.undo_chunk():
            self._create_render_settings()
            instance = super(CreateRender, self).process()
            # create namespace with instance
            index = 1
            namespace_name = "_{}".format(str(instance))
            try:
                cmds.namespace(rm=namespace_name)
            except RuntimeError:
                # namespace is not empty, so we leave it untouched
                pass

            while (cmds.namespace(exists=namespace_name)):
                namespace_name = "_{}{}".format(str(instance), index)
                index += 1

            namespace = cmds.namespace(add=namespace_name)

            cmds.setAttr("{}.machineList".format(instance), lock=True)
            self._rs = renderSetup.instance()
            layers = self._rs.getRenderLayers()
            if use_selection:
                print(">>> processing existing layers")
                sets = []
                for layer in layers:
                    print("  - creating set for {}:{}".format(
                        namespace, layer.name()))
                    render_set = cmds.sets(
                        n="{}:{}".format(namespace, layer.name()))
                    sets.append(render_set)
                cmds.sets(sets, forceElement=instance)

            # if no render layers are present, create default one with
            # asterix selector
            if not layers:
                render_layer = self._rs.createRenderLayer('Main')
                collection = render_layer.createCollection("defaultCollection")
                collection.getSelector().setPattern('*')

            renderer = cmds.getAttr(
                'defaultRenderGlobals.currentRenderer').lower()
            # handle various renderman names
            if renderer.startswith('renderman'):
                renderer = 'renderman'

            cmds.setAttr(self._image_prefix_nodes[renderer],
                         self._image_prefixes[renderer],
                         type="string")
示例#20
0
def getLayerObjectFromLayerName():
    # if the specified layer does not exist, renderSetup returns error
    # so using try statement
    layer_name = 'charaA'  # any layer name
    try:
        render_layer = renderSetup.instance().getRenderLayer(layer_name)
        return render_layer
    except:
        print 'not exists'
        return False
示例#21
0
def clear_all_rsl():
    """Clear all renderSetupLayers
    """
    try:
        pm.undoInfo(openChunk=True)
        rs = renderSetup.instance()
        rs.clearAll()
        mel.eval('MLdeleteUnused;')
    finally:
        pm.undoInfo(closeChunk=True)
示例#22
0
def get_all_rsl():
    """get all the render setup layers names

    Yields:
        str: the names of all the rsl layers
    """
    rs = renderSetup.instance()
    render_layers = rs.getRenderLayers()
    for x in render_layers:
        yield x.name()
示例#23
0
def RenderLayerShadow():
    if not pm.objExists('Shadow_RL'):
        rs = renderSetup.instance()
        # Extract Name from Transform
        GetName = 'Shadow'

        # Extract Name LigtRig
        SelectionLights = pm.listRelatives(type='transform')
        for selection in SelectionLights:
            if selection.endswith('LIGHTRIG'):
                pass
        # Create and append the render layer
        RsRenderLayer = rs.createRenderLayer(GetName + '_' + 'RL')
        ColectionAll = RsRenderLayer.createCollection('Env' + '_' + GetName +
                                                      '_' + 'COL')
        ColectionLightRig = RsRenderLayer.createCollection('LightRig' + '_' +
                                                           GetName + '_' +
                                                           'COL')
        ColectionGeoMesh = RsRenderLayer.createCollection('Characters' + '_' +
                                                          GetName + '_' +
                                                          'COL')
        ColectionCharacter = RsRenderLayer.createCollection(
            'CharacterShadows' + '_' + GetName + '_' + 'COL')

        EnvOverride = ColectionAll.createOverride(
            'EnvOverrideShadow',
            OpenMaya.MTypeId(0x58000386))  #---->ShaderOverride
        EnvOverridePy = pm.PyNode("EnvOverrideShadow")
        # ShaderEnvGrp= pm.sets(name= "Env_OverrideShadow_SG", empty=True, renderable=True, noSurfaceShader=True)
        ShaderShadow = pm.shadingNode('RedshiftMatteShadowCatcher',
                                      name="Env_OverrideShadow_SH",
                                      asShader=True)

        #Connect Shader to ShadingGroup

        # ShaderShadow.outColor >> ShaderEnvGrp.surfaceShader

        #Connect Material to OverrideRL
        ShaderShadow.outColor >> EnvOverridePy.attrValue

        ##Switch Create RenderLayer
        rs.switchToLayer(RsRenderLayer)

        pm.select(clear=True)

        ##Build Message Done
        pm.inViewMessage(amg='<hl>Shadow_RL_Done!!</hl>.',
                         pos='midCenter',
                         fade=True)

    else:
        pm.select('LightFx_RL')
        pm.inViewMessage(amg='<hl>Shadow_RenderLayer_Exist!!</hl>.',
                         pos='midCenter',
                         fade=True)
示例#24
0
    def set(self, value):
        # value can be a RenderLayer object, the name of a render layer, or None
        # to switch to the default layer.
        rs = renderSetup.instance()    
        if value is None:
            value = rs.getDefaultRenderLayer()
        elif not isinstance(value, renderLayer.RenderLayer):
            # This throws a generic Exception if 
            value = rs.getRenderLayer(value)

        rs.switchToLayer(value)
示例#25
0
def createAbsoluteOverride():
    layer_name = 'charaA'  # any layer name
    collection_name = 'visibilityOff'  # any collection name
    target_collection = renderSetup.instance().getRenderLayer(
        layer_name).getCollectionByName(collection_name)
    cmds.polyCube(n='dummyObj')
    abs_override = target_collection.createAbsoluteOverride(
        'dummyObjShape', 'primaryVisibility')
    abs_override.setName(layer_name + '_visibleOff')
    abs_override.setAttrValue(0)
    cmds.delete('dummyObj')
示例#26
0
    def _onRenderLayerChangeCB(self):
        # This access to render setup instance is safe since this callback
        # is only used when render setup is active
        visibleRenderLayer = renderSetup.instance().getVisibleRenderLayer()
        defaultRenderLayer = renderSetup.instance().getDefaultRenderLayer()

        # If default layer is visible we always go to global mode. Otherwise we check if the layer
        # has a lights collection, and if so we leave the mode unchanged.
        # This means that we never go to layer mode automatically when a layer is made visible but we do
        # go the other way, back into global mode when default layer is made visible or the layer has no
        # lights collection.
        # This is because we don't want to be in layer mode without being able to create overrides.
        # And we must be able to be in global mode but still with another layer active.
        mode = self.EDITOR_GLOBAL_MODE if (
            visibleRenderLayer == defaultRenderLayer
            or not visibleRenderLayer.hasLightsCollectionInstance()
        ) else self.editorMode
        self.setEditorMode(mode, visibleRenderLayer)
        self.visibilityChanged.emit()
        self.centralWidget.scheduleRefresh()
示例#27
0
    def _isMemberOfVisibleLayer(self):
        """ Check if the light source is a member of the visible layer. """

        # If no render setuo active the light is always visible
        if not renderSetup.hasInstance():
            return True

        visibleLayer = renderSetup.instance().getVisibleRenderLayer()

        # All lights are always members of default layer
        if visibleLayer is renderSetup.instance().getDefaultRenderLayer():
            return True

        legacyLayerName = visibleLayer._getLegacyNodeName()
        legacyLayerPlug = commonUtils.nameToPlug(legacyLayerName +
                                                 ".renderInfo")
        if not legacyLayerPlug:
            return True

        # The light source is a member if the shape node or any parent node is
        # connected to the legacy render layer plug
        #
        # NOTE:
        # Lights does not support instancing so we don't need to travers all
        # dag paths here. If we ever add support for instancing light sources
        # this needs to change.
        #
        path = om.MDagPath.getAPathTo(self.shapeHandle.object())
        while (path.length() > 0):
            # Check if the node is connected to the render layer
            fnNode = om.MFnDependencyNode(path.node())
            arrayPlug = fnNode.findPlug("renderLayerInfo", False)
            numElements = arrayPlug.evaluateNumElements()
            for i in range(numElements):
                elemPlug = arrayPlug.elementByLogicalIndex(i)
                if elemPlug.isDestination and elemPlug.source(
                ) == legacyLayerPlug:
                    return True
            # Move to parent node
            path.pop(1)
        return False
示例#28
0
def CharacterOne():

    rs = renderSetup.instance()
    selection = pm.ls(selection=True)
    if selection:
        if len(selection) == 1:

            # Extract Name from Transform
            Selection = pm.ls(type='transform', selection=True)
            GetName = Selection[0]

            # Extract Name LigtRig
            SelectionLights = pm.listRelatives(type='transform')
            for selection in SelectionLights:
                if selection.endswith('LIGHTRIG'):
                    pass
            # Create and append the render layer
            RsRenderLayer = rs.createRenderLayer(GetName + '_' + 'RL')
            ColectionEnvironment = RsRenderLayer.createCollection('Env' + '_' +
                                                                  GetName +
                                                                  '_' + 'COL')
            ColectionLightRig = RsRenderLayer.createCollection('LightRig' +
                                                               '_' + GetName +
                                                               '_' + 'COL')
            ColectionGeoMesh = RsRenderLayer.createCollection(GetName + '_' +
                                                              GetName + '_' +
                                                              'COL')
            ColectionCharacter = RsRenderLayer.createCollection(
                'CharacterShadows' + '_' + GetName + '_' + 'COL')

            ##Append Colection
            # ColectionGeoMesh.getSelector().staticSelection.add(cmds.ls(Selection, long =True))
            ColectionGeoMesh.getSelector().staticSelection.add(
                cmds.ls(Selection, long=True))
            # ColectionLightRig.getSelector().setPattern(GetName + '_' + 'LIGHTRIG*')

            ##Switch Create RenderLayer
            rs.switchToLayer(RsRenderLayer)

            ##Build Message Done
            pm.inViewMessage(amg='<hl>CharacterOne_RL_Done!!</hl>.',
                             pos='midCenter',
                             fade=True)

        else:
            pm.inViewMessage(amg='<hl>Select One Group!!</hl>.',
                             pos='midCenter',
                             fade=True)

    else:
        pm.inViewMessage(amg='<hl>Noting is Selected, Select GRP!!</hl>.',
                         pos='midCenter',
                         fade=True)
示例#29
0
def dropOnto(nodeName, mimeData, row):
    # Note: If nodeName is None, then we are dropping onto the RenderSetup model.
    if nodeName != renderSetupModel.instance().name():
        n = utils.nameToUserNode(nodeName)
        nProxy = n.getOpaqueData(renderSetupProxy.PROXY_OPAQUE_DATA)()
    rsProxy = renderSetupUI.renderSetupWindow.centralWidget.renderSetupView.model()

    rsProxy.dropMimeDataFailure = False # Indicates if the drop was accepted
    rsProxy.dropMimeData(
        mimeData, QtCore.Qt.DropAction.MoveAction, row, 0, QtCore.QModelIndex() if nodeName==renderSetupModel.instance().name() else nProxy.index())
    
    return not rsProxy.dropMimeDataFailure
示例#30
0
def deleteLayer(layerName):
    layer = renderSetup.instance().getRenderLayer(layerName)
    if layer.isVisible():
        renderSetup.instance().switchToLayer(
            renderSetup.instance().getDefaultRenderLayer())
    renderSetup.instance().detachRenderLayer(layer)
    renderLayer.delete(layer)
示例#31
0
def importRenderSetup(filePath):
    currentLayers = map(lambda layer: layer.name(),
                        renderSetup.instance().getRenderLayers())

    with open(filePath, "r") as file:
        data = json.load(file)

        if type(data) == dict:
            importedLayers = map(
                lambda layer: layer["renderSetupLayer"]["name"],
                data['renderSetup']['renderLayers'])
            if currentLayers:
                #take backup of exisiting render setup in the scene file dir
                sceneFileName = getSceneFileName()
                bckupFilePath = os.path.join(
                    os.path.dirname(
                        os.path.abspath(cmds.file(q=1,
                                                  sceneName=1))), "RS_Bckup_" +
                    sceneFileName[:sceneFileName.find(".")] + ".json")
                with open(bckupFilePath, "w+") as file:
                    json.dump(renderSetup.instance().encode(None),
                              fp=file,
                              indent=2,
                              sort_keys=True)

                #delete layers from render setup that are there in the imported file
                [
                    deleteLayer(layer) for layer in importedLayers
                    if layer in currentLayers
                ]

            #import render setup
            renderSetup.instance().decode(data, renderSetup.DECODE_AND_MERGE,
                                          None)

        else:
            raise TypeError(
                "Can't perform import on the file which wasn't exported using Render Layer Setup"
            )