Ejemplo n.º 1
0
    def process_reference(self, context, name, namespace, data):

        asset_name = context['asset']["name"]
        print("---", namespace)

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

        print(">>>", namespace)

        # Pre-run check
        if not cmds.objExists("vraySettings"):
            cmds.createNode("VRaySettingsNode", name="vraySettings")

        # Add namespace
        cmds.namespace(set=":")
        cmds.namespace(add=namespace)
        cmds.namespace(set=namespace)

        with lib.maintained_selection():
            nodes = self.create_vray_proxy(name)

        self[:] = nodes

        # Make sure to restore the default namespace, or anything imported or
        # refereced after this gets added to this namespace
        cmds.namespace(set=":")

        return nodes
Ejemplo n.º 2
0
    def load(self, context, name, namespace, options):

        import maya.cmds as cmds
        import avalon.maya.lib as lib
        from avalon.maya.pipeline import containerise
        import mtoa.ui.arnoldmenu
        import pymel.core as pm

        version = context['version']
        version_data = version.get("data", {})

        self.log.info("version_data: {}\n".format(version_data))

        frameStart = version_data.get("frameStart", None)

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

        # cmds.loadPlugin("gpuCache", quiet=True)

        # Root group
        label = "{}:{}".format(namespace, name)
        root = pm.group(name=label, empty=True)

        presets = config.get_presets(project=os.environ['AVALON_PROJECT'])
        colors = presets['plugins']['maya']['load']['colors']

        c = colors.get('ass')
        if c is not None:
            cmds.setAttr(root + ".useOutlinerColor", 1)
            cmds.setAttr(root + ".outlinerColor", c[0], c[1], c[2])

        # Create transform with shape
        transform_name = label + "_ASS"
        # transform = pm.createNode("transform", name=transform_name,
        #                             parent=root)

        standinShape = pm.PyNode(mtoa.ui.arnoldmenu.createStandIn())
        standin = standinShape.getParent()
        standin.rename(transform_name)

        pm.parent(standin, root)

        # Set the standin filepath
        standinShape.dso.set(self.fname)
        if frameStart is not None:
            standinShape.useFrameExtension.set(1)

        nodes = [root, standin]
        self[:] = nodes

        return containerise(name=name,
                            namespace=namespace,
                            nodes=nodes,
                            context=context,
                            loader=self.__class__.__name__)
Ejemplo n.º 3
0
    def load(self, context, name, namespace, data):

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

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

        # Ensure V-Ray for Maya is loaded.
        cmds.loadPlugin("vrayformaya", quiet=True)

        with lib.maintained_selection():
            cmds.namespace(addNamespace=namespace)
            with namespaced(namespace, new=False):
                nodes = self.create_vray_proxy(name, filename=self.fname)

        self[:] = nodes
        if not nodes:
            return

        return containerise(name=name,
                            namespace=namespace,
                            nodes=nodes,
                            context=context,
                            loader=self.__class__.__name__)
Ejemplo n.º 4
0
    def load(self, context, name=None, namespace=None, data=None):
        import maya.cmds as cmds

        from avalon import maya
        from avalon.maya import lib

        choice = self.display_warning()
        if choice is False:
            return

        asset = context['asset']

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

        with maya.maintained_selection():
            cmds.file(self.fname,
                      i=True,
                      namespace=namespace,
                      returnNewNodes=True,
                      groupReference=True,
                      groupName="{}:{}".format(namespace, name))

        # We do not containerize imported content, it remains unmanaged
        return
Ejemplo n.º 5
0
    def load(self, context, name, namespace, data):

        from avalon.maya.pipeline import containerise
        from avalon.maya import lib

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

        from colorbleed import setdress_api

        containers = setdress_api.load_package(filepath=self.fname,
                                               name=name,
                                               namespace=namespace)

        self[:] = containers

        # Only containerize if any nodes were loaded by the Loader
        nodes = self[:]
        if not nodes:
            return

        return containerise(name=name,
                            namespace=namespace,
                            nodes=nodes,
                            context=context,
                            loader=self.__class__.__name__)
Ejemplo n.º 6
0
    def load(self, context, name, namespace, data):

        start_frame = cmds.playbackOptions(query=True, min=True)
        sound_node = cmds.sound(
            file=context["representation"]["data"]["path"], offset=start_frame
        )
        cmds.timeControl(
            mel.eval("$tmpVar=$gPlayBackSlider"),
            edit=True,
            sound=sound_node,
            displaySound=True
        )

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

        return containerise(
            name=name,
            namespace=namespace,
            nodes=[sound_node],
            context=context,
            loader=self.__class__.__name__
        )
Ejemplo n.º 7
0
    def load(self, context, name=None, namespace=None, data=None):

        import os
        from avalon.maya import lib
        from avalon.maya.pipeline import containerise

        assert os.path.exists(self.fname), "%s does not exist." % self.fname

        asset = context['asset']

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

        self.process_reference(context=context,
                               name=name,
                               namespace=namespace,
                               data=data)

        # Only containerize if any nodes were loaded by the Loader
        nodes = self[:]
        if not nodes:
            return

        return containerise(name=name,
                            namespace=namespace,
                            nodes=nodes,
                            context=context,
                            loader=self.__class__.__name__)
Ejemplo n.º 8
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__)
Ejemplo n.º 9
0
    def load(self, context, name=None, namespace=None, data=None):
        import maya.cmds as cmds

        from avalon import maya
        from avalon.maya import lib
        from avalon.maya.pipeline import containerise

        asset = context['asset']
        namespace = namespace or lib.unique_namespace(
            asset["name"] + "_",
            prefix="_" if asset["name"][0].isdigit() else "",
            suffix="_",
        )
        with maya.maintained_selection():
            nodes = cmds.file(self.fname,
                              i=True,
                              namespace=namespace,
                              returnNewNodes=True,
                              groupReference=True,
                              groupName="{}:{}".format(namespace, name))
        # Only containerize if any nodes were loaded by the Loader
        if not nodes:
            return
        self[:] = nodes
        return containerise(name=name,
                            namespace=namespace,
                            nodes=nodes,
                            context=context,
                            loader=self.__class__.__name__)
    def load(self, context, name=None, namespace=None, data=None):

        from maya import cmds
        import avalon.maya.lib as lib
        from avalon.maya.pipeline import containerise

        assert os.path.exists(self.fname), ("Path does not exist: %s" %
                                            self.fname)

        # Check if the plugin for redshift is available on the pc
        try:
            cmds.loadPlugin("redshift4maya", quiet=True)
        except Exception as exc:
            self.log.error("Encountered exception:\n%s" % exc)
            return

        # Check if viewport drawing engine is Open GL Core (compat)
        render_engine = None
        compatible = "OpenGL"
        if cmds.optionVar(exists="vp2RenderingEngine"):
            render_engine = cmds.optionVar(query="vp2RenderingEngine")

        if not render_engine or not render_engine.startswith(compatible):
            raise RuntimeError("Current scene's settings are incompatible."
                               "See Preferences > Display > Viewport 2.0 to "
                               "set the render engine to '%s<type>'" %
                               compatible)

        asset = context['asset']

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

        # Root group
        label = "{}:{}".format(namespace, name)
        root = cmds.group(name=label, empty=True)

        # Create VR
        volume_node = cmds.createNode("RedshiftVolumeShape",
                                      name="{}Shape".format(root),
                                      parent=root)

        self._apply_settings(volume_node, path=self.fname)

        nodes = [root, volume_node]
        self[:] = nodes

        return containerise(name=name,
                            namespace=namespace,
                            nodes=nodes,
                            context=context,
                            loader=self.__class__.__name__)
Ejemplo n.º 11
0
    def load(
        self,
        context,
        name=None,
        namespace=None,
        options=None
    ):

        import os
        from avalon.maya import lib
        from avalon.maya.pipeline import containerise

        assert os.path.exists(self.fname), "%s does not exist." % self.fname

        asset = context['asset']
        loaded_containers = []

        count = options.get("count") or 1
        for c in range(0, count):
            namespace = namespace or lib.unique_namespace(
                asset["name"] + "_",
                prefix="_" if asset["name"][0].isdigit() else "",
                suffix="_",
            )

            # Offset loaded subset
            if "offset" in options:
                offset = [i * c for i in options["offset"]]
                options["translate"] = offset

            self.log.info(options)

            self.process_reference(
                context=context,
                name=name,
                namespace=namespace,
                options=options
            )

            # Only containerize if any nodes were loaded by the Loader
            nodes = self[:]
            if not nodes:
                return

            loaded_containers.append(containerise(
                name=name,
                namespace=namespace,
                nodes=nodes,
                context=context,
                loader=self.__class__.__name__
            ))

            c += 1
            namespace = None
        return loaded_containers
Ejemplo n.º 12
0
    def load(self, context, name, namespace, data):

        import maya.cmds as cmds
        import avalon.maya.lib as lib
        from avalon.maya.pipeline import containerise

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

        cmds.loadPlugin("gpuCache", quiet=True)

        # Root group
        label = "{}:{}".format(namespace, name)
        root = cmds.group(name=label, empty=True)

        settings = get_project_settings(os.environ['AVALON_PROJECT'])
        colors = settings['maya']['load']['colors']
        c = colors.get('model')
        if c is not None:
            cmds.setAttr(root + ".useOutlinerColor", 1)
            cmds.setAttr(root + ".outlinerColor",
                         c[0], c[1], c[2])

        # Create transform with shape
        transform_name = label + "_GPU"
        transform = cmds.createNode("transform", name=transform_name,
                                    parent=root)
        cache = cmds.createNode("gpuCache",
                                parent=transform,
                                name="{0}Shape".format(transform_name))

        # Set the cache filepath
        cmds.setAttr(cache + '.cacheFileName', self.fname, type="string")
        cmds.setAttr(cache + '.cacheGeomPath', "|", type="string")    # root

        # Lock parenting of the transform and cache
        cmds.lockNode([transform, cache], lock=True)

        nodes = [root, transform, cache]
        self[:] = nodes

        return containerise(
            name=name,
            namespace=namespace,
            nodes=nodes,
            context=context,
            loader=self.__class__.__name__)
Ejemplo n.º 13
0
    def create_namespace(self, asset):
        """Create a unique namespace
        Args:
            asset (dict): asset information

        """

        asset_name = "{}_".format(asset)
        prefix = "_" if asset_name[0].isdigit() else ""
        namespace = avalon_lib.unique_namespace(asset_name,
                                                prefix=prefix,
                                                suffix="_")

        return namespace
Ejemplo n.º 14
0
    def load(self, context, name, namespace, data):

        from maya import cmds
        import avalon.maya.lib as lib
        from avalon.maya.pipeline import containerise

        # Check if viewport drawing engine is Open GL Core (compat)
        render_engine = None
        compatible = "OpenGLCoreProfileCompat"
        if cmds.optionVar(exists="vp2RenderingEngine"):
            render_engine = cmds.optionVar(query="vp2RenderingEngine")

        if not render_engine or render_engine != compatible:
            raise RuntimeError("Current scene's settings are incompatible."
                               "See Preferences > Display > Viewport 2.0 to "
                               "set the render engine to '%s'" % compatible)

        asset = context['asset']
        version = context["version"]

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

        # Root group
        label = "{}:{}".format(namespace, name)
        root = cmds.group(name=label, empty=True)

        # Create VR
        grid_node = cmds.createNode("VRayVolumeGrid",
                                    name="{}VVGShape".format(label),
                                    parent=root)

        # Set attributes
        cmds.setAttr("{}.inFile".format(grid_node), self.fname, type="string")
        cmds.setAttr("{}.inReadOffset".format(grid_node),
                     version["startFrames"])

        nodes = [root, grid_node]
        self[:] = nodes

        return containerise(name=name,
                            namespace=namespace,
                            nodes=nodes,
                            context=context,
                            loader=self.__class__.__name__)
Ejemplo n.º 15
0
    def load(self, context, name, namespace, data):

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

        try:
            family = context["representation"]["context"]["family"]
        except ValueError:
            family = "vrayproxy"

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

        # Ensure V-Ray for Maya is loaded.
        cmds.loadPlugin("vrayformaya", quiet=True)

        with lib.maintained_selection():
            cmds.namespace(addNamespace=namespace)
            with namespaced(namespace, new=False):
                nodes = self.create_vray_proxy(name,
                                               filename=self.fname)

        self[:] = nodes
        if not nodes:
            return

        presets = config.get_presets(project=os.environ['AVALON_PROJECT'])
        colors = presets['plugins']['maya']['load']['colors']

        c = colors.get(family)
        if c is not None:
            cmds.setAttr("{0}_{1}.useOutlinerColor".format(name, "GRP"), 1)
            cmds.setAttr("{0}_{1}.outlinerColor".format(name, "GRP"),
                         c[0], c[1], c[2])

        return containerise(
            name=name,
            namespace=namespace,
            nodes=nodes,
            context=context,
            loader=self.__class__.__name__)
Ejemplo n.º 16
0
    def load(self, context, name, namespace, data):

        import maya.cmds as cmds
        import avalon.maya.lib as lib
        from avalon.maya.pipeline import containerise
        import mtoa.ui.arnoldmenu
        import pymel.core as pm

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

        # cmds.loadPlugin("gpuCache", quiet=True)

        # Root group
        label = "{}:{}".format(namespace, name)
        root = pm.group(name=label, empty=True)

        # Create transform with shape
        transform_name = label + "_ASS"
        # transform = pm.createNode("transform", name=transform_name,
        #                             parent=root)

        standinShape = pm.PyNode(mtoa.ui.arnoldmenu.createStandIn())
        standin = standinShape.getParent()
        standin.rename(transform_name)

        pm.parent(standin, root)

        # Set the standin filepath
        standinShape.dso.set(self.fname)

        nodes = [root, standin]
        self[:] = nodes

        return containerise(name=name,
                            namespace=namespace,
                            nodes=nodes,
                            context=context,
                            loader=self.__class__.__name__)
Ejemplo n.º 17
0
    def load(self, context, name, namespace, data):

        import maya.cmds as cmds
        import avalon.maya.lib as lib
        from avalon.maya.pipeline import containerise

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

        cmds.loadPlugin("gpuCache", quiet=True)

        # Root group
        label = "{}:{}".format(namespace, name)
        root = cmds.group(name=label, empty=True)

        # Create transform with shape
        transform_name = label + "_GPU"
        transform = cmds.createNode("transform",
                                    name=transform_name,
                                    parent=root)
        cache = cmds.createNode("gpuCache",
                                parent=transform,
                                name="{0}Shape".format(transform_name))

        # Set the cache filepath
        cmds.setAttr(cache + '.cacheFileName', self.fname, type="string")
        cmds.setAttr(cache + '.cacheGeomPath', "|", type="string")  # root

        # Lock parenting of the transform and cache
        cmds.lockNode([transform, cache], lock=True)

        nodes = [root, transform, cache]
        self[:] = nodes

        return containerise(name=name,
                            namespace=namespace,
                            nodes=nodes,
                            context=context,
                            loader=self.__class__.__name__)
Ejemplo n.º 18
0
def namespaced(namespace, new=True):
    """Work inside namespace during context

    Args:
        new (bool): When enabled this will rename the namespace to a unique
            namespace if the input namespace already exists.

    Yields:
        str: The namespace that is used during the context

    """
    original = cmds.namespaceInfo(cur=True)
    if new:
        namespace = unique_namespace(namespace)
        cmds.namespace(add=namespace)

    try:
        cmds.namespace(set=namespace)
        yield namespace
    finally:
        cmds.namespace(set=original)
Ejemplo n.º 19
0
    def load(self, context, name, namespace, data):

        from maya import cmds
        import avalon.maya.lib as lib
        from avalon.maya.pipeline import containerise

        assert os.path.exists(self.fname), ("Path does not exist: %s" %
                                            self.fname)

        # Ensure V-ray is loaded
        if not cmds.pluginInfo("mtoa", query=True, loaded=True):
            cmds.loadPlugin("mtoa")

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

        # Root group
        label = "{}:{}".format(namespace, name)
        root = cmds.group(name=label, empty=True)

        # Create VRayVolumeGrid
        grid_node = cmds.createNode("aiVolume",
                                    name="{}Shape".format(root),
                                    parent=root)

        self._apply_settings(grid_node, path=self.fname)

        nodes = [root, grid_node]
        self[:] = nodes

        return containerise(name=name,
                            namespace=namespace,
                            nodes=nodes,
                            context=context,
                            loader=self.__class__.__name__)
Ejemplo n.º 20
0
def load(Loader,
         representation,
         name=None,
         namespace=None,
         data=None):
    """Load asset via database

    Deprecated; this functionality is replaced by `api.load()`

    Arguments:
        Loader (api.Loader): The loader to process in host Maya.
        representation (dict, io.ObjectId or str): Address to representation
        name (str, optional): Use pre-defined name
        namespace (str, optional): Use pre-defined namespace
        data (dict, optional): Additional settings dictionary

    """

    from avalon.vendor import six
    from avalon import io
    from avalon.maya import lib
    from avalon.maya.pipeline import containerise

    assert representation is not None, "This is a bug"

    if isinstance(representation, (six.string_types, io.ObjectId)):
        representation = io.find_one({"_id": io.ObjectId(str(representation))})

    version, subset, asset, project = io.parenthood(representation)

    assert all([representation, version, subset, asset, project]), (
        "This is a bug"
    )

    context = {
        "project": project,
        "asset": asset,
        "subset": subset,
        "version": version,
        "representation": representation,
    }

    # Ensure data is a dictionary when no explicit data provided
    if data is None:
        data = dict()
    assert isinstance(data, dict), "Data must be a dictionary"

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

    # TODO(roy): add compatibility check, see `tools.cbloader.lib`

    Loader.log.info(
        "Running '%s' on '%s'" % (Loader.__name__, asset["name"])
    )

    try:
        loader = Loader(context)

        with lib.maintained_selection():
            loader.process(name, namespace, context, data)

    except OSError as e:
        log.info("WARNING: %s" % e)
        return list()

    # Only containerize if any nodes were loaded by the Loader
    nodes = loader[:]
    if not nodes:
        return

    return containerise(
        name=name,
        namespace=namespace,
        nodes=loader[:],
        context=context,
        loader=Loader.__name__)
Ejemplo n.º 21
0
    def load(self, context, name=None, namespace=None, data=None):

        from maya import cmds
        import avalon.maya.lib as lib
        from avalon.maya.pipeline import containerise

        try:
            family = context["representation"]["context"]["family"]
        except ValueError:
            family = "vdbcache"

        # Check if the plugin for redshift is available on the pc
        try:
            cmds.loadPlugin("redshift4maya", quiet=True)
        except Exception as exc:
            self.log.error("Encountered exception:\n%s" % exc)
            return

        # Check if viewport drawing engine is Open GL Core (compat)
        render_engine = None
        compatible = "OpenGL"
        if cmds.optionVar(exists="vp2RenderingEngine"):
            render_engine = cmds.optionVar(query="vp2RenderingEngine")

        if not render_engine or not render_engine.startswith(compatible):
            raise RuntimeError("Current scene's settings are incompatible."
                               "See Preferences > Display > Viewport 2.0 to "
                               "set the render engine to '%s<type>'" %
                               compatible)

        asset = context['asset']

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

        # Root group
        label = "{}:{}".format(namespace, name)
        root = cmds.group(name=label, empty=True)

        presets = config.get_presets(project=os.environ['AVALON_PROJECT'])
        colors = presets['plugins']['maya']['load']['colors']

        c = colors.get(family)
        if c is not None:
            cmds.setAttr(root + ".useOutlinerColor", 1)
            cmds.setAttr(root + ".outlinerColor", c[0], c[1], c[2])

        # Create VR
        volume_node = cmds.createNode("RedshiftVolumeShape",
                                      name="{}RVSShape".format(label),
                                      parent=root)

        cmds.setAttr("{}.fileName".format(volume_node),
                     self.fname,
                     type="string")

        nodes = [root, volume_node]
        self[:] = nodes

        return containerise(name=name,
                            namespace=namespace,
                            nodes=nodes,
                            context=context,
                            loader=self.__class__.__name__)
Ejemplo n.º 22
0
    def load(self, context, name, namespace, data):

        from maya import cmds
        import avalon.maya.lib as lib
        from avalon.maya.pipeline import containerise

        try:
            family = context["representation"]["context"]["family"]
        except ValueError:
            family = "vdbcache"

        # Check if viewport drawing engine is Open GL Core (compat)
        render_engine = None
        compatible = "OpenGLCoreProfileCompat"
        if cmds.optionVar(exists="vp2RenderingEngine"):
            render_engine = cmds.optionVar(query="vp2RenderingEngine")

        if not render_engine or render_engine != compatible:
            raise RuntimeError("Current scene's settings are incompatible."
                               "See Preferences > Display > Viewport 2.0 to "
                               "set the render engine to '%s'" % compatible)

        asset = context['asset']
        version = context["version"]

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

        # Root group
        label = "{}:{}".format(namespace, name)
        root = cmds.group(name=label, empty=True)

        presets = config.get_presets(project=os.environ['AVALON_PROJECT'])
        colors = presets['plugins']['maya']['load']['colors']

        c = colors.get(family)
        if c is not None:
            cmds.setAttr(root + ".useOutlinerColor", 1)
            cmds.setAttr(root + ".outlinerColor", c[0], c[1], c[2])

        # Create VR
        grid_node = cmds.createNode("VRayVolumeGrid",
                                    name="{}VVGShape".format(label),
                                    parent=root)

        # Set attributes
        cmds.setAttr("{}.inFile".format(grid_node), self.fname, type="string")
        cmds.setAttr("{}.inReadOffset".format(grid_node),
                     version["startFrames"])

        nodes = [root, grid_node]
        self[:] = nodes

        return containerise(name=name,
                            namespace=namespace,
                            nodes=nodes,
                            context=context,
                            loader=self.__class__.__name__)
Ejemplo n.º 23
0
    def load(self, context, name, namespace, data):
        import pymel.core as pm

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

        # Get camera from user selection.
        camera = None
        default_cameras = ["frontShape", "perspShape", "sideShape", "topShape"]
        cameras = [
            x for x in pm.ls(type="camera") if x.name() not in default_cameras
        ]
        camera_names = {x.getParent().name(): x for x in cameras}
        camera_names["Create new camera."] = "create_camera"
        window = CameraWindow(camera_names.keys())
        window.exec_()
        camera = camera_names[window.camera]

        if camera == "create_camera":
            camera = pm.createNode("camera")

        if camera is None:
            return

        try:
            camera.displayResolution.set(1)
            camera.farClipPlane.set(image_plane_depth * 10)
        except RuntimeError:
            pass

        # Create image plane
        image_plane_transform, image_plane_shape = pm.imagePlane(
            camera=camera, showInAllViews=False)
        image_plane_shape.depth.set(image_plane_depth)

        image_plane_shape.imageName.set(
            context["representation"]["data"]["path"])

        start_frame = pm.playbackOptions(q=True, min=True)
        end_frame = pm.playbackOptions(q=True, max=True)

        image_plane_shape.frameOffset.set(1 - start_frame)
        image_plane_shape.frameIn.set(start_frame)
        image_plane_shape.frameOut.set(end_frame)
        image_plane_shape.frameCache.set(end_frame)
        image_plane_shape.useFrameExtension.set(1)

        movie_representations = ["mov", "preview"]
        if context["representation"]["name"] in movie_representations:
            # Need to get "type" by string, because its a method as well.
            pm.Attribute(image_plane_shape + ".type").set(2)

        # Ask user whether to use sequence or still image.
        if context["representation"]["name"] == "exr":
            # Ensure OpenEXRLoader plugin is loaded.
            pm.loadPlugin("OpenEXRLoader.mll", quiet=True)

            message = ("Hold image sequence on first frame?"
                       "\n{} files available.".format(
                           len(context["representation"]["files"])))
            reply = QtWidgets.QMessageBox.information(
                None, "Frame Hold.", message, QtWidgets.QMessageBox.Ok,
                QtWidgets.QMessageBox.Cancel)
            if reply == QtWidgets.QMessageBox.Ok:
                pm.delete(
                    image_plane_shape.listConnections(type="expression")[0])
                image_plane_shape.frameExtension.set(start_frame)

        new_nodes.extend([
            image_plane_transform.longName().split("|")[-1],
            image_plane_shape.longName().split("|")[-1]
        ])

        for node in new_nodes:
            pm.rename(node, "{}:{}".format(namespace, node))

        return containerise(name=name,
                            namespace=namespace,
                            nodes=new_nodes,
                            context=context,
                            loader=self.__class__.__name__)
Ejemplo n.º 24
0
def load_package(filepath, name, namespace=None):
    """Load a package that was gathered elsewhere.

    A package is a group of published instances, possibly with additional data
    in a hierarchy.

    """

    if namespace is None:
        # Define a unique namespace for the package
        namespace = os.path.basename(filepath).split(".")[0]
        unique_namespace(namespace)
    assert isinstance(namespace, basestring)

    # Load the setdress package data
    with open(filepath, "r") as fp:
        data = json.load(fp)

    # Load the setdress alembic hierarchy
    #   We import this into the namespace in which we'll load the package's
    #   instances into afterwards.
    alembic = filepath.replace(".json", ".abc")
    hierarchy = cmds.file(alembic,
                          reference=True,
                          namespace=namespace,
                          returnNewNodes=True,
                          groupReference=True,
                          groupName="{}:{}".format(namespace, name),
                          typ="Alembic")

    # Get the top root node (the reference group)
    root = "{}:{}".format(namespace, name)

    containers = []
    all_loaders = api.discover(api.Loader)
    for representation_id, instances in data.items():

        # Find the compatible loaders
        loaders = api.loaders_from_representation(all_loaders,
                                                  representation_id)

        for instance in instances:
            container = _add(instance=instance,
                             representation_id=representation_id,
                             loaders=loaders,
                             namespace=namespace,
                             root=root)
            containers.append(container)

    # TODO: Do we want to cripple? Or do we want to add a 'parent' parameter?
    # Cripple the original avalon containers so they don't show up in the
    # manager
    # for container in containers:
    #     cmds.setAttr("%s.id" % container,
    #                  "colorbleed.setdress.container",
    #                  type="string")

    # TODO: Lock all loaded nodes
    #   This is to ensure the hierarchy remains unaltered by the artists
    # for node in nodes:
    #      cmds.lockNode(node, lock=True)

    return containers + hierarchy
Ejemplo n.º 25
0
    def load(self, context, name, namespace, data):
        new_nodes = []
        image_plane_depth = 1000
        asset = context['asset']['name']
        namespace = namespace or lib.unique_namespace(
            asset + "_",
            prefix="_" if asset[0].isdigit() else "",
            suffix="_",
        )

        # Getting camera from selection.
        selection = pc.ls(selection=True)

        if len(selection) > 1:
            QtWidgets.QMessageBox.critical(
                None, "Error!",
                "Multiple nodes selected. Please select only one.",
                QtWidgets.QMessageBox.Ok)
            return

        if len(selection) < 1:
            QtWidgets.QMessageBox.critical(None, "Error!",
                                           "No camera selected.",
                                           QtWidgets.QMessageBox.Ok)
            return

        relatives = pc.listRelatives(selection[0], shapes=True)
        if not pc.ls(relatives, type="camera"):
            QtWidgets.QMessageBox.critical(None, "Error!",
                                           "Selected node is not a camera.",
                                           QtWidgets.QMessageBox.Ok)
            return

        camera = selection[0]

        try:
            camera.displayResolution.set(1)
            camera.farClipPlane.set(image_plane_depth * 10)
        except RuntimeError:
            pass

        # Create image plane
        image_plane_transform, image_plane_shape = pc.imagePlane(
            camera=camera, showInAllViews=False)
        image_plane_shape.depth.set(image_plane_depth)

        image_plane_shape.imageName.set(
            context["representation"]["data"]["path"])

        start_frame = pc.playbackOptions(q=True, min=True)
        end_frame = pc.playbackOptions(q=True, max=True)

        image_plane_shape.frameOffset.set(1 - start_frame)
        image_plane_shape.frameIn.set(start_frame)
        image_plane_shape.frameOut.set(end_frame)
        image_plane_shape.useFrameExtension.set(1)

        if context["representation"]["name"] == "mov":
            # Need to get "type" by string, because its a method as well.
            pc.Attribute(image_plane_shape + ".type").set(2)

        # Ask user whether to use sequence or still image.
        if context["representation"]["name"] == "exr":
            # Ensure OpenEXRLoader plugin is loaded.
            pc.loadPlugin("OpenEXRLoader.mll", quiet=True)

            reply = QtWidgets.QMessageBox.information(
                None, "Frame Hold.", "Hold image sequence on first frame?",
                QtWidgets.QMessageBox.Ok, QtWidgets.QMessageBox.Cancel)
            if reply == QtWidgets.QMessageBox.Ok:
                pc.delete(
                    image_plane_shape.listConnections(type="expression")[0])
                image_plane_shape.frameExtension.set(start_frame)

        new_nodes.extend([
            image_plane_transform.longName().split("|")[-1],
            image_plane_shape.longName().split("|")[-1]
        ])

        for node in new_nodes:
            pc.rename(node, "{}:{}".format(namespace, node))

        return containerise(name=name,
                            namespace=namespace,
                            nodes=new_nodes,
                            context=context,
                            loader=self.__class__.__name__)