Skip to content

lib

Standalone helper functions

RigSetsNotExistError

Bases: RuntimeError

Raised when required rig sets for animation instance are missing.

This is raised from create_rig_animation_instance when the required out_SET or controls_SET are missing.

Source code in client/ayon_maya/api/lib.py
85
86
87
88
89
90
91
class RigSetsNotExistError(RuntimeError):
    """Raised when required rig sets for animation instance are missing.

    This is raised from `create_rig_animation_instance` when the required
    `out_SET` or `controls_SET` are missing.
    """
    pass

delete_after

Bases: object

Context Manager that will delete collected nodes after exit.

This allows to ensure the nodes added to the context are deleted afterwards. This is useful if you want to ensure nodes are deleted even if an error is raised.

Examples:

with delete_after() as delete_bin: cube = maya.cmds.polyCube() delete_bin.extend(cube) # cube exists

cube deleted

Source code in client/ayon_maya/api/lib.py
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
class delete_after(object):
    """Context Manager that will delete collected nodes after exit.

    This allows to ensure the nodes added to the context are deleted
    afterwards. This is useful if you want to ensure nodes are deleted
    even if an error is raised.

    Examples:
        with delete_after() as delete_bin:
            cube = maya.cmds.polyCube()
            delete_bin.extend(cube)
            # cube exists
        # cube deleted

    """

    def __init__(self, nodes=None):

        self._nodes = list()

        if nodes:
            self.extend(nodes)

    def append(self, node):
        self._nodes.append(node)

    def extend(self, nodes):
        self._nodes.extend(nodes)

    def __iter__(self):
        return iter(self._nodes)

    def __enter__(self):
        return self

    def __exit__(self, type, value, traceback):
        if self._nodes:
            cmds.delete(self._nodes)

apply_attributes(attributes, nodes_by_id)

Alter the attributes to match the state when publishing

Apply attribute settings from the publish to the node in the scene based on the UUID which is stored in the cbId attribute.

Parameters:

Name Type Description Default
attributes list

list of dictionaries

required
nodes_by_id dict

collection of nodes based on UUID {uuid: [node, node]}

required
Source code in client/ayon_maya/api/lib.py
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
def apply_attributes(attributes, nodes_by_id):
    """Alter the attributes to match the state when publishing

    Apply attribute settings from the publish to the node in the scene based
    on the UUID which is stored in the cbId attribute.

    Args:
        attributes (list): list of dictionaries
        nodes_by_id (dict): collection of nodes based on UUID
                           {uuid: [node, node]}

    """

    for attr_data in attributes:
        nodes = nodes_by_id[attr_data["uuid"]]
        attr_value = attr_data["attributes"]
        for node in nodes:
            for attr, value in attr_value.items():
                if value is None:
                    log.warning(
                        f"Skipping setting {node}.{attr} with value 'None'")
                    continue

                set_attribute(attr, value, node)

apply_shaders(relationships, shadernodes, nodes)

Link shadingEngine to the right nodes based on relationship data

Relationship data is constructed of a collection of sets and attributes sets corresponds with the shaderEngines found in the lookdev. Each set has the keys name, members and uuid, the members hold a collection of node information name and uuid.

Parameters:

Name Type Description Default
relationships dict

relationship data

required
shadernodes list

list of nodes of the shading objectSets (includes

required
nodes list

list of nodes to apply shader to

required

Returns:

Type Description

None

Source code in client/ayon_maya/api/lib.py
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
def apply_shaders(relationships, shadernodes, nodes):
    """Link shadingEngine to the right nodes based on relationship data

    Relationship data is constructed of a collection of `sets` and `attributes`
    `sets` corresponds with the shaderEngines found in the lookdev.
    Each set has the keys `name`, `members` and `uuid`, the `members`
    hold a collection of node information `name` and `uuid`.

    Args:
        relationships (dict): relationship data
        shadernodes (list): list of nodes of the shading objectSets (includes
        VRayObjectProperties and shadingEngines)
        nodes (list): list of nodes to apply shader to

    Returns:
        None
    """

    attributes = relationships.get("attributes", [])
    shader_data = relationships.get("relationships", {})

    shading_engines = cmds.ls(shadernodes, type="objectSet", long=True)
    assert shading_engines, "Error in retrieving objectSets from reference"

    # region compute lookup
    nodes_by_id = defaultdict(list)
    for node in nodes:
        nodes_by_id[get_id(node)].append(node)

    shading_engines_by_id = defaultdict(list)
    for shad in shading_engines:
        shading_engines_by_id[get_id(shad)].append(shad)
    # endregion

    # region assign shading engines and other sets
    for data in shader_data.values():
        # collect all unique IDs of the set members
        shader_uuid = data["uuid"]
        member_uuids = [member["uuid"] for member in data["members"]]

        filtered_nodes = list()
        for m_uuid in member_uuids:
            filtered_nodes.extend(nodes_by_id[m_uuid])

        id_shading_engines = shading_engines_by_id[shader_uuid]
        if not id_shading_engines:
            log.error("No shader found with cbId "
                      "'{}'".format(shader_uuid))
            continue
        elif len(id_shading_engines) > 1:
            log.error("Skipping shader assignment. "
                      "More than one shader found with cbId "
                      "'{}'. (found: {})".format(shader_uuid,
                                                 id_shading_engines))
            continue

        if not filtered_nodes:
            log.warning("No nodes found for shading engine "
                        "'{0}'".format(id_shading_engines[0]))
            continue
        try:
            cmds.sets(filtered_nodes, forceElement=id_shading_engines[0])
        except RuntimeError as rte:
            log.error("Error during shader assignment: {}".format(rte))

    # endregion

    apply_attributes(attributes, nodes_by_id)

assign_look(nodes, product_name='lookMain')

Assigns a look to a node.

Optimizes the nodes by grouping by folder id and finding related product by name.

Parameters:

Name Type Description Default
nodes list

all nodes to assign the look to

required
product_name str

name of the product to find

'lookMain'
Source code in client/ayon_maya/api/lib.py
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
def assign_look(nodes, product_name="lookMain"):
    """Assigns a look to a node.

    Optimizes the nodes by grouping by folder id and finding
    related product by name.

    Args:
        nodes (list): all nodes to assign the look to
        product_name (str): name of the product to find
    """

    # Group all nodes per folder id
    grouped = defaultdict(list)
    for node in nodes:
        hash_id = get_id(node)
        if not hash_id:
            continue

        parts = hash_id.split(":", 1)
        grouped[parts[0]].append(node)

    project_name = get_current_project_name()
    product_entities = ayon_api.get_products(
        project_name, product_names=[product_name], folder_ids=grouped.keys()
    )
    product_entities_by_folder_id = {
        product_entity["folderId"]: product_entity
        for product_entity in product_entities
    }
    product_ids = {
        product_entity["id"]
        for product_entity in product_entities_by_folder_id.values()
    }
    last_version_entities_by_product_id = ayon_api.get_last_versions(
        project_name,
        product_ids
    )

    for folder_id, asset_nodes in grouped.items():
        product_entity = product_entities_by_folder_id.get(folder_id)
        if not product_entity:
            log.warning((
                "No product '{}' found for {}"
            ).format(product_name, folder_id))
            continue

        product_id = product_entity["id"]
        last_version = last_version_entities_by_product_id.get(product_id)
        if not last_version:
            log.warning((
                "Not found last version for product '{}' on folder with id {}"
            ).format(product_name, folder_id))
            continue

        families = last_version.get("attrib", {}).get("families") or []
        if "look" not in families:
            log.warning((
                "Last version for product '{}' on folder with id {}"
                " does not have look product type"
            ).format(product_name, folder_id))
            continue

        log.debug("Assigning look '{}' <v{:03d}>".format(
            product_name, last_version["version"]))

        assign_look_by_version(asset_nodes, last_version["id"])

assign_look_by_version(nodes, version_id)

Assign nodes a specific published look version by id.

This assumes the nodes correspond with the asset.

Parameters:

Name Type Description Default
nodes(list)

nodes to assign look to

required
version_id ObjectId

database id of the version

required

Returns:

Type Description

None

Source code in client/ayon_maya/api/lib.py
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
def assign_look_by_version(nodes, version_id):
    """Assign nodes a specific published look version by id.

    This assumes the nodes correspond with the asset.

    Args:
        nodes(list): nodes to assign look to
        version_id (bson.ObjectId): database id of the version

    Returns:
        None
    """

    project_name = get_current_project_name()

    # Get representations of shader file and relationships
    representations = list(ayon_api.get_representations(
        project_name=project_name,
        representation_names={"ma", "json"},
        version_ids=[version_id]
    ))
    look_representation = next(
        repre for repre in representations if repre["name"] == "ma")
    json_representation = next(
        repre for repre in representations if repre["name"] == "json")

    # See if representation is already loaded, if so reuse it.
    host = registered_host()
    representation_id = look_representation["id"]
    for container in host.ls():
        if (container['loader'] == "LookLoader" and
                container['representation'] == representation_id):
            log.info("Reusing loaded look ..")
            container_node = container['objectName']
            break
    else:
        log.info("Using look for the first time ..")

        # Load file
        _loaders = discover_loader_plugins()
        loaders = loaders_from_representation(_loaders, representation_id)
        Loader = next((i for i in loaders if i.__name__ == "LookLoader"), None)
        if Loader is None:
            raise RuntimeError("Could not find LookLoader, this is a bug")

        # Reference the look file
        with maintained_selection():
            container_node = load_container(Loader, look_representation)

    # Get container members
    shader_nodes = get_container_members(container_node)

    # Load relationships
    shader_relation = get_representation_path(json_representation)
    with open(shader_relation, "r") as f:
        relationships = json.load(f)

    # Assign relationships
    apply_shaders(relationships, shader_nodes, nodes)

attribute_values(attr_values)

Remaps node attributes to values during context.

Parameters:

Name Type Description Default
attr_values dict

Dictionary with (attr, value)

required
Source code in client/ayon_maya/api/lib.py
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
@contextlib.contextmanager
def attribute_values(attr_values):
    """Remaps node attributes to values during context.

    Arguments:
        attr_values (dict): Dictionary with (attr, value)

    """

    original = [(attr, cmds.getAttr(attr)) for attr in attr_values]
    try:
        for attr, value in attr_values.items():
            if isinstance(value, str):
                cmds.setAttr(attr, value, type="string")
            else:
                cmds.setAttr(attr, value)
        yield
    finally:
        for attr, value in original:
            if isinstance(value, str):
                cmds.setAttr(attr, value, type="string")
            elif value is None and cmds.getAttr(attr, type=True) == "string":
                # In some cases the maya.cmds.getAttr command returns None
                # for string attributes but this value cannot assigned.
                # Note: After setting it once to "" it will then return ""
                #       instead of None. So this would only happen once.
                cmds.setAttr(attr, "", type="string")
            else:
                cmds.setAttr(attr, value)

bake(nodes, frame_range=None, step=1.0, simulation=True, preserve_outside_keys=False, disable_implicit_control=True, shape=True)

Bake the given nodes over the time range.

This will bake all attributes of the node, including custom attributes.

Parameters:

Name Type Description Default
nodes list

Names of transform nodes, eg. camera, light.

required
frame_range list

frame range with start and end frame. or if None then takes timeSliderRange

None
simulation bool

Whether to perform a full simulation of the attributes over time.

True
preserve_outside_keys bool

Keep keys that are outside of the baked range.

False
disable_implicit_control bool

When True will disable any constraints to the object.

True
shape bool

When True also bake attributes on the children shapes.

True
step float

The step size to sample by.

1.0

Returns:

Type Description

None

Source code in client/ayon_maya/api/lib.py
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
def bake(nodes,
         frame_range=None,
         step=1.0,
         simulation=True,
         preserve_outside_keys=False,
         disable_implicit_control=True,
         shape=True):
    """Bake the given nodes over the time range.

    This will bake all attributes of the node, including custom attributes.

    Args:
        nodes (list): Names of transform nodes, eg. camera, light.
        frame_range (list): frame range with start and end frame.
            or if None then takes timeSliderRange
        simulation (bool): Whether to perform a full simulation of the
            attributes over time.
        preserve_outside_keys (bool): Keep keys that are outside of the baked
            range.
        disable_implicit_control (bool): When True will disable any
            constraints to the object.
        shape (bool): When True also bake attributes on the children shapes.
        step (float): The step size to sample by.

    Returns:
        None

    """

    # Parse inputs
    if not nodes:
        return

    assert isinstance(nodes, (list, tuple)), "Nodes must be a list or tuple"

    # If frame range is None fall back to time slider playback time range
    if frame_range is None:
        frame_range = [cmds.playbackOptions(query=True, minTime=True),
                       cmds.playbackOptions(query=True, maxTime=True)]

    # If frame range is single frame bake one frame more,
    # otherwise maya.cmds.bakeResults gets confused
    if frame_range[1] == frame_range[0]:
        frame_range[1] += 1

    # Bake it
    with keytangent_default(in_tangent_type='auto',
                            out_tangent_type='auto'):
        cmds.bakeResults(nodes,
                         simulation=simulation,
                         preserveOutsideKeys=preserve_outside_keys,
                         disableImplicitControl=disable_implicit_control,
                         shape=shape,
                         sampleBy=step,
                         time=(frame_range[0], frame_range[1]))

bake_to_world_space(nodes, frame_range=None, simulation=True, preserve_outside_keys=False, disable_implicit_control=True, shape=True, step=1.0)

Bake the nodes to world space transformation (incl. other attributes)

Bakes the transforms to world space (while maintaining all its animated attributes and settings) by duplicating the node. Then parents it to world and constrains to the original.

Other attributes are also baked by connecting all attributes directly. Baking is then done using Maya's bakeResults command.

See bake for the argument documentation.

Returns:

Name Type Description
list

The newly created and baked node names.

Source code in client/ayon_maya/api/lib.py
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
def bake_to_world_space(nodes,
                        frame_range=None,
                        simulation=True,
                        preserve_outside_keys=False,
                        disable_implicit_control=True,
                        shape=True,
                        step=1.0):
    """Bake the nodes to world space transformation (incl. other attributes)

    Bakes the transforms to world space (while maintaining all its animated
    attributes and settings) by duplicating the node. Then parents it to world
    and constrains to the original.

    Other attributes are also baked by connecting all attributes directly.
    Baking is then done using Maya's bakeResults command.

    See `bake` for the argument documentation.

    Returns:
         list: The newly created and baked node names.

    """
    @contextlib.contextmanager
    def _unlock_attr(attr):
        """Unlock attribute during context if it is locked"""
        if not cmds.getAttr(attr, lock=True):
            # If not locked, do nothing
            yield
            return
        try:
            cmds.setAttr(attr, lock=False)
            yield
        finally:
            cmds.setAttr(attr, lock=True)

    def _get_attrs(node):
        """Workaround for buggy shape attribute listing with listAttr

        This will only return keyable settable attributes that have an
        incoming connections (those that have a reason to be baked).

        Technically this *may* fail to return attributes driven by complex
        expressions for which maya makes no connections, e.g. doing actual
        `setAttr` calls in expressions.

        Arguments:
            node (str): The node to list attributes for.

        Returns:
            list: Keyable attributes with incoming connections.
                The attribute may be locked.

        """
        attrs = cmds.listAttr(node,
                              write=True,
                              scalar=True,
                              settable=True,
                              connectable=True,
                              keyable=True,
                              shortNames=True) or []
        valid_attrs = []
        for attr in attrs:
            node_attr = '{0}.{1}'.format(node, attr)

            # Sometimes Maya returns 'non-existent' attributes for shapes
            # so we filter those out
            if not cmds.attributeQuery(attr, node=node, exists=True):
                continue

            # We only need those that have a connection, just to be safe
            # that it's actually keyable/connectable anyway.
            if cmds.connectionInfo(node_attr,
                                   isDestination=True):
                valid_attrs.append(attr)

        return valid_attrs

    transform_attrs = {"t", "r", "s",
                       "tx", "ty", "tz",
                       "rx", "ry", "rz",
                       "sx", "sy", "sz"}

    world_space_nodes = []
    with contextlib.ExitStack() as stack:
        delete_bin = stack.enter_context(delete_after())
        # Create the duplicate nodes that are in world-space connected to
        # the originals
        for node in nodes:

            # Duplicate the node
            short_name = node.rsplit("|", 1)[-1]
            new_name = "{0}_baked".format(short_name)
            new_node = cmds.duplicate(node,
                                      name=new_name,
                                      renameChildren=True)[0]  # noqa

            # Parent new node to world
            if cmds.listRelatives(new_node, parent=True):
                new_node = cmds.parent(new_node, world=True)[0]

            # Temporarily unlock and passthrough connect all attributes
            # so we can bake them over time
            # Skip transform attributes because we will constrain them later
            attrs = set(_get_attrs(node)) - transform_attrs
            for attr in attrs:
                orig_node_attr = "{}.{}".format(node, attr)
                new_node_attr = "{}.{}".format(new_node, attr)

                # unlock during context to avoid connection errors
                stack.enter_context(_unlock_attr(new_node_attr))
                cmds.connectAttr(orig_node_attr,
                                 new_node_attr,
                                 force=True)

            # If shapes are also baked then also temporarily unlock and
            # passthrough connect all shape attributes for baking
            if shape:
                children_shapes = cmds.listRelatives(new_node,
                                                     children=True,
                                                     fullPath=True,
                                                     shapes=True)
                if children_shapes:
                    orig_children_shapes = cmds.listRelatives(node,
                                                              children=True,
                                                              fullPath=True,
                                                              shapes=True)
                    for orig_shape, new_shape in zip(orig_children_shapes,
                                                     children_shapes):
                        attrs = _get_attrs(orig_shape)
                        for attr in attrs:
                            orig_node_attr = "{}.{}".format(orig_shape, attr)
                            new_node_attr = "{}.{}".format(new_shape, attr)

                            # unlock during context to avoid connection errors
                            stack.enter_context(_unlock_attr(new_node_attr))
                            cmds.connectAttr(orig_node_attr,
                                             new_node_attr,
                                             force=True)

            # Constraint transforms
            for attr in transform_attrs:
                transform_attr = "{}.{}".format(new_node, attr)
                stack.enter_context(_unlock_attr(transform_attr))
            delete_bin.extend(cmds.parentConstraint(node, new_node, mo=False))
            delete_bin.extend(cmds.scaleConstraint(node, new_node, mo=False))

            world_space_nodes.append(new_node)

        bake(world_space_nodes,
             frame_range=frame_range,
             step=step,
             simulation=simulation,
             preserve_outside_keys=preserve_outside_keys,
             disable_implicit_control=disable_implicit_control,
             shape=shape)

    return world_space_nodes

collect_animation_defs(fps=False, create_context=None)

Get the basic animation attribute definitions for the publisher.

Parameters:

Name Type Description Default
fps bool

Whether to include fps attribute definition.

False
create_context CreateContext | None

When provided the context of publisher will be used to define the defaults for the attributes. Depending on project settings this may then use the entity's frame range and FPS instead of the current scene values.

None

Returns:

Type Description

List[NumberDef]: List of number attribute definitions.

Source code in client/ayon_maya/api/lib.py
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
def collect_animation_defs(fps=False, create_context=None):
    """Get the basic animation attribute definitions for the publisher.

    Arguments:
        fps (bool): Whether to include `fps` attribute definition.
        create_context (CreateContext | None): When provided the context of
            publisher will be used to define the defaults for the attributes.
            Depending on project settings this may then use the entity's frame
            range and FPS instead of the current scene values.

    Returns:
        List[NumberDef]: List of number attribute definitions.

    """

    use_entity_frame_range = False
    if create_context is not None:
        project_settings = create_context.get_current_project_settings()
        use_entity_frame_range: bool = project_settings["maya"]["create"].get(
            "use_entity_attributes_as_defaults", False)

    if create_context is not None and use_entity_frame_range:
        task_entity = create_context.get_current_task_entity()
        frame_start = task_entity["attrib"]["frameStart"]
        frame_end = task_entity["attrib"]["frameEnd"]
        handle_start = task_entity["attrib"]["handleStart"]
        handle_end = task_entity["attrib"]["handleEnd"]
        default_fps = task_entity["attrib"]["fps"]
    else:
        # get scene values as defaults
        frame_start = cmds.playbackOptions(query=True, minTime=True)
        frame_end = cmds.playbackOptions(query=True, maxTime=True)
        frame_start_handle = cmds.playbackOptions(
            query=True, animationStartTime=True)
        frame_end_handle = cmds.playbackOptions(
            query=True, animationEndTime=True)

        handle_start = frame_start - frame_start_handle
        handle_end = frame_end_handle - frame_end
        default_fps = mel.eval('currentTimeUnitToFPS()')

    # build attributes
    defs = [
        NumberDef("frameStart",
                  label="Frame Start",
                  default=frame_start,
                  decimals=0),
        NumberDef("frameEnd",
                  label="Frame End",
                  default=frame_end,
                  decimals=0),
        NumberDef("handleStart",
                  label="Handle Start",
                  default=handle_start,
                  decimals=0),
        NumberDef("handleEnd",
                  label="Handle End",
                  default=handle_end,
                  decimals=0),
        NumberDef("step",
                  label="Step size",
                  tooltip="A smaller step size means more samples and larger "
                          "output files.\n"
                          "A 1.0 step size is a single sample every frame.\n"
                          "A 0.5 step size is two samples per frame.\n"
                          "A 0.2 step size is five samples per frame.",
                  default=1.0,
                  decimals=3),
    ]

    if fps:
        fps_def = NumberDef(
            "fps", label="FPS", default=default_fps, decimals=5
        )
        defs.append(fps_def)

    return defs

convert_to_maya_fps(fps)

Convert any fps to supported Maya framerates.

Source code in client/ayon_maya/api/lib.py
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
def convert_to_maya_fps(fps):
    """Convert any fps to supported Maya framerates."""
    float_framerates = [
        23.976023976023978,
        # WTF is 29.97 df vs fps?
        29.97002997002997,
        47.952047952047955,
        59.94005994005994
    ]
    # 44100 fps evaluates as 41000.0. Why? Omitting for now.
    int_framerates = [
        2,
        3,
        4,
        5,
        6,
        8,
        10,
        12,
        15,
        16,
        20,
        24,
        25,
        30,
        40,
        48,
        50,
        60,
        75,
        80,
        90,
        100,
        120,
        125,
        150,
        200,
        240,
        250,
        300,
        375,
        400,
        500,
        600,
        750,
        1200,
        1500,
        2000,
        3000,
        6000,
        48000
    ]

    # If input fps is a whole number we'll return.
    if float(fps).is_integer():
        # Validate fps is part of Maya's fps selection.
        if int(fps) not in int_framerates:
            raise ValueError(
                "Framerate \"{}\" is not supported in Maya".format(fps)
            )
        return int(fps)
    else:
        # Differences to supported float frame rates.
        differences = []
        for i in float_framerates:
            differences.append(abs(i - fps))

        # Validate difference does not stray too far from supported framerates.
        min_difference = min(differences)
        min_index = differences.index(min_difference)
        supported_framerate = float_framerates[min_index]
        if min_difference > 0.1:
            raise ValueError(
                "Framerate \"{}\" strays too far from any supported framerate"
                " in Maya. Closest supported framerate is \"{}\"".format(
                    fps, supported_framerate
                )
            )

        return supported_framerate

create_rig_animation_instance(nodes, context, namespace, options=None, log=None)

Create an animation publish instance for loaded rigs.

See the RecreateRigAnimationInstance inventory action on how to use this for loaded rig containers.

Parameters:

Name Type Description Default
nodes list

Member nodes of the rig instance.

required
context dict

Representation context of the rig container

required
namespace str

Namespace of the rig container

required
options dict

Additional loader data

None
log Logger

Logger to log to if provided

None

Returns:

Type Description

None

Source code in client/ayon_maya/api/lib.py
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
def create_rig_animation_instance(
    nodes, context, namespace, options=None, log=None
):
    """Create an animation publish instance for loaded rigs.

    See the RecreateRigAnimationInstance inventory action on how to use this
    for loaded rig containers.

    Arguments:
        nodes (list): Member nodes of the rig instance.
        context (dict): Representation context of the rig container
        namespace (str): Namespace of the rig container
        options (dict, optional): Additional loader data
        log (logging.Logger, optional): Logger to log to if provided

    Returns:
        None

    """
    if options is None:
        options = {}
    name = context["representation"]["name"]
    output = next((node for node in nodes if
                   node.endswith("out_SET")), None)
    controls = next((node for node in nodes if
                     node.endswith("controls_SET")), None)
    if name != "fbx":
        if not output:
            raise RigSetsNotExistError(
                "No out_SET in rig. The loaded rig publish is lacking the "
                "out_SET required for animation instances.")
        if not controls:
            raise RigSetsNotExistError(
                "No controls_SET in rig. The loaded rig publish is lacking "
                "the controls_SET required for animation instances.")

    anim_skeleton = next((node for node in nodes if
                          node.endswith("skeletonAnim_SET")), None)
    skeleton_mesh = next((node for node in nodes if
                          node.endswith("skeletonMesh_SET")), None)

    # Find the roots amongst the loaded nodes
    roots = (
        cmds.ls(nodes, assemblies=True, long=True) or
        get_highest_in_hierarchy(nodes)
    )
    assert roots, "No root nodes in rig, this is a bug."

    folder_entity = context["folder"]
    product_entity = context["product"]
    product_type = product_entity["productType"]
    product_name = product_entity["name"]

    custom_product_name = options.get("animationProductName")
    if custom_product_name:
        formatting_data = {
            "folder": {
                "name": folder_entity["name"]
            },
            "product": {
                "type": product_type,
                "name": product_name,
            },
            "asset": folder_entity["name"],
            "subset": product_name,
            "family": product_type
        }
        namespace = get_custom_namespace(
            custom_product_name.format(**formatting_data)
        )

    if log:
        log.info("Creating product: {}".format(namespace))

    # Fill creator identifier
    creator_identifier = "io.openpype.creators.maya.animation"

    host = registered_host()
    create_context = CreateContext(host)
    # Create the animation instance
    rig_sets = [output, controls, anim_skeleton, skeleton_mesh]
    # Remove sets that this particular rig does not have
    rig_sets = [s for s in rig_sets if s is not None]
    with maintained_selection():
        cmds.select(rig_sets + roots, noExpand=True)
        create_context.create(
            creator_identifier=creator_identifier,
            variant=namespace,
            pre_create_data={"use_selection": True}
        )

displaySmoothness(nodes, divisionsU=0, divisionsV=0, pointsWire=4, pointsShaded=1, polygonObject=1)

Set the displaySmoothness during the context

Source code in client/ayon_maya/api/lib.py
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
@contextlib.contextmanager
def displaySmoothness(nodes,
                      divisionsU=0,
                      divisionsV=0,
                      pointsWire=4,
                      pointsShaded=1,
                      polygonObject=1):
    """Set the displaySmoothness during the context"""

    # Ensure only non-intermediate shapes
    nodes = cmds.ls(nodes,
                    dag=1,
                    shapes=1,
                    long=1,
                    noIntermediate=True)

    def parse(node):
        """Parse the current state of a node"""
        state = {}
        for key in ["divisionsU",
                    "divisionsV",
                    "pointsWire",
                    "pointsShaded",
                    "polygonObject"]:
            value = cmds.displaySmoothness(node, query=1, **{key: True})
            if value is not None:
                state[key] = value[0]
        return state

    originals = dict((node, parse(node)) for node in nodes)

    try:
        # Apply current state
        cmds.displaySmoothness(nodes,
                               divisionsU=divisionsU,
                               divisionsV=divisionsV,
                               pointsWire=pointsWire,
                               pointsShaded=pointsShaded,
                               polygonObject=polygonObject)
        yield
    finally:
        # Revert state
        _iteritems = getattr(originals, "iteritems", originals.items)
        for node, state in _iteritems():
            if state:
                cmds.displaySmoothness(node, **state)

empty_sets(sets, force=False)

Remove all members of the sets during the context

Source code in client/ayon_maya/api/lib.py
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
@contextlib.contextmanager
def empty_sets(sets, force=False):
    """Remove all members of the sets during the context"""

    assert isinstance(sets, (list, tuple))

    original = dict()
    original_connections = []

    # Store original state
    for obj_set in sets:
        members = cmds.sets(obj_set, query=True)
        original[obj_set] = members

    try:
        for obj_set in sets:
            cmds.sets(clear=obj_set)
            if force:
                # Break all connections if force is enabled, this way we
                # prevent Maya from exporting any reference nodes which are
                # connected with placeHolder[x] attributes
                plug = "%s.dagSetMembers" % obj_set
                connections = cmds.listConnections(plug,
                                                   source=True,
                                                   destination=False,
                                                   plugs=True,
                                                   connections=True) or []
                original_connections.extend(connections)
                for dest, src in pairwise(connections):
                    cmds.disconnectAttr(src, dest)
        yield
    finally:

        for dest, src in pairwise(original_connections):
            cmds.connectAttr(src, dest)

        # Restore original members
        _iteritems = getattr(original, "iteritems", original.items)
        for origin_set, members in _iteritems():
            cmds.sets(members, forceElement=origin_set)

evaluation(mode='off')

Set the evaluation manager during context.

Parameters:

Name Type Description Default
mode str

The mode to apply during context. "off": The standard DG evaluation (stable) "serial": A serial DG evaluation "parallel": The Maya 2016+ parallel evaluation

'off'
Source code in client/ayon_maya/api/lib.py
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
@contextlib.contextmanager
def evaluation(mode="off"):
    """Set the evaluation manager during context.

    Arguments:
        mode (str): The mode to apply during context.
            "off": The standard DG evaluation (stable)
            "serial": A serial DG evaluation
            "parallel": The Maya 2016+ parallel evaluation

    """

    original = cmds.evaluationManager(query=True, mode=1)[0]
    try:
        cmds.evaluationManager(mode=mode)
        yield
    finally:
        cmds.evaluationManager(mode=original)

fix_incompatible_containers()

Backwards compatibility: old containers to use new ReferenceLoader

Source code in client/ayon_maya/api/lib.py
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
def fix_incompatible_containers():
    """Backwards compatibility: old containers to use new ReferenceLoader"""
    old_loaders = {
        "MayaAsciiLoader",
        "AbcLoader",
        "ModelLoader",
        "CameraLoader",
        "RigLoader",
        "FBXLoader"
    }
    host = registered_host()
    for container in host.ls():
        loader = container['loader']
        if loader in old_loaders:
            log.info(
                "Converting legacy container loader {} to "
                "ReferenceLoader: {}".format(loader, container["objectName"])
            )
            cmds.setAttr(container["objectName"] + ".loader",
                         "ReferenceLoader", type="string")

force_shader_assignments_to_faces(shapes)

Replaces any non-face shader assignments with shader assignments to the faces during the context.

Parameters:

Name Type Description Default
shapes List[str]

The shapes to add into face sets for any component assignments of shading engine

required
Source code in client/ayon_maya/api/lib.py
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
@contextlib.contextmanager
def force_shader_assignments_to_faces(shapes):
    """Replaces any non-face shader assignments with shader assignments
    to the faces during the context.

    Args:
        shapes (List[str]): The shapes to add into face sets for any component
            assignments of shading engine
    """
    shapes = cmds.ls(shapes, shapes=True, type="mesh", long=True)
    if not shapes:
        # Do nothing
        yield
        return

    all_render_sets = set()
    for shape in shapes:
        render_sets = cmds.listSets(object=shape, t=1, extendToShape=False)
        if render_sets:
            all_render_sets.update(render_sets)

    shapes_lookup = set(shapes)

    # Maya has the tendency to return component assignment using the transform
    # name instead of the shape name, like `pCube1.f[1]` instead of
    # `pCube1Shape.f[1]` so we need to take those into consideration as members
    def get_parent(_shape: str) -> str:
        return _shape.rsplit("|", 1)[0]

    components_lookup = {f"{shape}." for shape in shapes}
    components_lookup.update(f"{get_parent(shape)}." for shape in shapes)
    components_lookup = tuple(components_lookup)  # support str.startswith

    original_assignments = {}
    override_assignments = defaultdict(list)
    for shading_engine in cmds.ls(list(all_render_sets), type="shadingEngine"):
        members = cmds.sets(shading_engine, query=True)
        if not members:
            continue

        members = cmds.ls(members, long=True)

        # Include ALL originals, even those not among our shapes
        original_assignments[shading_engine] = members

        has_conversions = False
        for member in members:
            # Only consider shapes from our inputs
            if (
                    member not in shapes_lookup
                    and not member.startswith(components_lookup)
            ):
                continue

            if "." not in member:
                # Convert to face assignments
                member = f"{member}.f[*]"
                if not cmds.objExists(member):
                    # It is possible for a mesh to have no faces at all
                    # for which we cannot convert to face assignments anyway.
                    # It is a `mesh` node type - it just would error on
                    # 'No object matches name' when trying to assign to the
                    # faces. So we skip the conversion
                    log.debug(
                        "Skipping face assignment conversion because "
                        f"no mesh faces were found: {member}")
                    continue

                has_conversions = True
            override_assignments[shading_engine].append(member)

        if not has_conversions:
            # We can skip this shading engine completely because
            # we have nothing to override
            original_assignments.pop(shading_engine, None)
            override_assignments.pop(shading_engine, None)

    try:
        # Apply overrides
        for shading_engine, override_members in override_assignments.items():
            # We force remove the members because this allows maya to take
            # out the mesh (also without the components)
            cmds.sets(clear=shading_engine)
            cmds.sets(override_members, forceElement=shading_engine)

        yield

    finally:
        # Revert to original assignments
        for shading_engine, original_members in original_assignments.items():
            cmds.sets(clear=shading_engine)
            cmds.sets(original_members, forceElement=shading_engine)

generate_capture_preset(instance, camera, path, start=None, end=None, capture_preset=None)

Function for getting all the data of preset options for playblast capturing

Parameters:

Name Type Description Default
instance Instance

instance

required
camera str

review camera

required
path str

filepath

required
start int

frameStart

None
end int

frameEnd

None
capture_preset dict

capture preset

None

Returns:

Name Type Description
dict

Resulting preset

Source code in client/ayon_maya/api/lib.py
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
def generate_capture_preset(instance, camera, path,
                            start=None, end=None, capture_preset=None):
    """Function for getting all the data of preset options for
    playblast capturing

    Args:
        instance (pyblish.api.Instance): instance
        camera (str): review camera
        path (str): filepath
        start (int): frameStart
        end (int): frameEnd
        capture_preset (dict): capture preset

    Returns:
        dict: Resulting preset
    """
    preset = load_capture_preset(data=capture_preset)

    preset["camera"] = camera
    preset["start_frame"] = start
    preset["end_frame"] = end
    preset["filename"] = path
    preset["overwrite"] = True
    preset["panel"] = instance.data["panel"]

    # Disable viewer since we use the rendering logic for publishing
    # We don't want to open the generated playblast in a viewer directly.
    preset["viewer"] = False

    # "isolate_view" will already have been applied at creation, so we'll
    # ignore it here.
    preset.pop("isolate_view")

    # Set resolution variables from capture presets
    width_preset = capture_preset["Resolution"]["width"]
    height_preset = capture_preset["Resolution"]["height"]

    # Set resolution variables from folder values
    folder_attributes = instance.data["folderEntity"]["attrib"]
    folder_width = folder_attributes.get("resolutionWidth")
    folder_height = folder_attributes.get("resolutionHeight")
    review_instance_width = instance.data.get("review_width")
    review_instance_height = instance.data.get("review_height")

    # Use resolution from instance if review width/height is set
    # Otherwise use the resolution from preset if it has non-zero values
    # Otherwise fall back to folder width x height
    # Else define no width, then `capture.capture` will use render resolution
    if review_instance_width and review_instance_height:
        preset["width"] = review_instance_width
        preset["height"] = review_instance_height
    elif width_preset and height_preset:
        preset["width"] = width_preset
        preset["height"] = height_preset
    elif folder_width and folder_height:
        preset["width"] = folder_width
        preset["height"] = folder_height

    # Isolate view is requested by having objects in the set besides a
    # camera. If there is only 1 member it'll be the camera because we
    # validate to have 1 camera only.
    if instance.data["isolate"] and len(instance.data["setMembers"]) > 1:
        preset["isolate"] = instance.data["setMembers"]

    # Override camera options
    # Enforce persisting camera depth of field
    camera_options = preset.setdefault("camera_options", {})
    camera_options["depthOfField"] = cmds.getAttr(
        "{0}.depthOfField".format(camera)
    )

    # Use Pan/Zoom from instance data instead of from preset
    preset.pop("pan_zoom", None)
    camera_options["panZoomEnabled"] = instance.data["panZoom"]

    # Override viewport options by instance data
    viewport_options = preset.setdefault("viewport_options", {})
    viewport_options["imagePlane"] = instance.data.get("imagePlane", True)

    # When using 'project settings' we preserve the capture preset that
    # was picked, then we do not override it with the instance data
    if instance.data["displayLights"] != "project_settings":
        viewport_options["displayLights"] = instance.data["displayLights"]

    # Override transparency if requested.
    transparency = instance.data.get("transparency", 0)
    if transparency != 0:
        preset["viewport2_options"]["transparencyAlgorithm"] = transparency

    # Update preset with current panel setting
    # if override_viewport_options is turned off
    if not capture_preset["ViewportOptions"]["override_viewport_options"]:
        panel_preset = capture.parse_view(preset["panel"])
        panel_preset.pop("camera")
        preset.update(panel_preset)

    return preset

generate_ids(nodes, folder_id=None)

Returns new unique ids for the given nodes.

Note: This does not assign the new ids, it only generates the values.

To assign new ids using this method:

nodes = ["a", "b", "c"] for node, id in generate_ids(nodes): set_id(node, id)

To also override any existing values (and assign regenerated ids):

nodes = ["a", "b", "c"] for node, id in generate_ids(nodes): set_id(node, id, overwrite=True)

Parameters:

Name Type Description Default
nodes list

List of nodes.

required
folder_id Optional[str]

Folder id to generate id for. When None provided current folder is used.

None

Returns:

Name Type Description
list

A list of (node, id) tuples.

Source code in client/ayon_maya/api/lib.py
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
def generate_ids(nodes, folder_id=None):
    """Returns new unique ids for the given nodes.

    Note: This does not assign the new ids, it only generates the values.

    To assign new ids using this method:
    >>> nodes = ["a", "b", "c"]
    >>> for node, id in generate_ids(nodes):
    >>>     set_id(node, id)

    To also override any existing values (and assign regenerated ids):
    >>> nodes = ["a", "b", "c"]
    >>> for node, id in generate_ids(nodes):
    >>>     set_id(node, id, overwrite=True)

    Args:
        nodes (list): List of nodes.
        folder_id (Optional[str]): Folder id to generate id for. When None
            provided current folder is used.

    Returns:
        list: A list of (node, id) tuples.

    """

    if folder_id is None:
        # Get the folder id based on current context folder
        project_name = get_current_project_name()
        folder_path = get_current_folder_path()
        if not folder_path:
            raise ValueError("Current folder path is not set")
        folder_entity = ayon_api.get_folder_by_path(
            project_name, folder_path, fields=["id"]
        )
        if not folder_entity:
            raise ValueError((
                "Current folder '{}' was not found on the server"
            ).format(folder_path))
        folder_id = folder_entity["id"]

    node_ids = []
    for node in nodes:
        _, uid = str(uuid.uuid4()).rsplit("-", 1)
        unique_id = "{}:{}".format(folder_id, uid)
        node_ids.append((node, unique_id))

    return node_ids

get_all_children(nodes, ignore_intermediate_objects=False)

Return all children of nodes including each instanced child. Using maya.cmds.listRelatives(allDescendents=True) includes only the first instance. As such, this function acts as an optimal replacement with a focus on a fast query.

Parameters:

Name Type Description Default
nodes iterable

List of nodes to get children for.

required
ignore_intermediate_objects bool

Ignore any children that are intermediate objects.

False

Returns:

Name Type Description
set

Children of input nodes.

Source code in client/ayon_maya/api/lib.py
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
def get_all_children(nodes, ignore_intermediate_objects=False):
    """Return all children of `nodes` including each instanced child.
    Using maya.cmds.listRelatives(allDescendents=True) includes only the first
    instance. As such, this function acts as an optimal replacement with a
    focus on a fast query.

    Args:
        nodes (iterable): List of nodes to get children for.
        ignore_intermediate_objects (bool): Ignore any children that
            are intermediate objects.

    Returns:
        set: Children of input nodes.

    """

    sel = OpenMaya.MSelectionList()
    traversed = set()
    iterator = OpenMaya.MItDag(OpenMaya.MItDag.kDepthFirst)
    fn_dag = OpenMaya.MFnDagNode()
    for node in nodes:

        if node in traversed:
            # Ignore if already processed as a child
            # before
            continue

        sel.clear()
        sel.add(node)
        dag = sel.getDagPath(0)

        iterator.reset(dag)
        # ignore self
        iterator.next()  # noqa: B305
        while not iterator.isDone():

            if ignore_intermediate_objects:
                fn_dag.setObject(iterator.currentItem())
                if fn_dag.isIntermediateObject:
                    iterator.prune()
                    iterator.next()  # noqa: B305
                    continue

            path = iterator.fullPathName()

            if path in traversed:
                iterator.prune()
                iterator.next()  # noqa: B305
                continue

            traversed.add(path)
            iterator.next()  # noqa: B305

    return traversed

get_attr_in_layer(attr, layer, as_string=True)

Return attribute value in specified renderlayer.

Same as cmds.getAttr but this gets the attribute's value in a given render layer without having to switch to it.

Warning for parent attribute overrides

Attributes that have render layer overrides to their parent attribute are not captured correctly since they do not have a direct connection. For example, an override to sphere.rotate when querying sphere.rotateX will not return correctly!

This is much faster for Maya's renderLayer system, yet the code

does no optimized query for render setup.

Parameters:

Name Type Description Default
attr str

attribute name, ex. "node.attribute"

required
layer str

layer name

required
as_string bool

whether attribute should convert to a string value

True

Returns:

Type Description

The return value from maya.cmds.getAttr

Source code in client/ayon_maya/api/lib.py
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
def get_attr_in_layer(attr, layer, as_string=True):
    """Return attribute value in specified renderlayer.

    Same as cmds.getAttr but this gets the attribute's value in a
    given render layer without having to switch to it.

    Warning for parent attribute overrides:
        Attributes that have render layer overrides to their parent attribute
        are not captured correctly since they do not have a direct connection.
        For example, an override to sphere.rotate when querying sphere.rotateX
        will not return correctly!

    Note: This is much faster for Maya's renderLayer system, yet the code
        does no optimized query for render setup.

    Args:
        attr (str): attribute name, ex. "node.attribute"
        layer (str): layer name
        as_string (bool): whether attribute should convert to a string value

    Returns:
        The return value from `maya.cmds.getAttr`

    """

    try:
        if cmds.mayaHasRenderSetup():
            from . import lib_rendersetup
            return lib_rendersetup.get_attr_in_layer(
                attr, layer, as_string=as_string)
    except AttributeError:
        pass

    # Ignore complex query if we're in the layer anyway
    current_layer = cmds.editRenderLayerGlobals(query=True,
                                                currentRenderLayer=True)
    if layer == current_layer:
        return cmds.getAttr(attr, asString=as_string)

    connections = cmds.listConnections(attr,
                                       plugs=True,
                                       source=False,
                                       destination=True,
                                       type="renderLayer") or []
    connections = filter(lambda x: x.endswith(".plug"), connections)
    if not connections:
        return cmds.getAttr(attr)

    # Some value types perform a conversion when assigning
    # TODO: See if there's a maya method to allow this conversion
    # instead of computing it ourselves.
    attr_type = cmds.getAttr(attr, type=True)
    conversion = None
    if attr_type == "time":
        conversion = mel.eval('currentTimeUnitToFPS()')  # returns float
    elif attr_type == "doubleAngle":
        # Radians to Degrees: 180 / pi
        # TODO: This will likely only be correct when Maya units are set
        #       to degrees
        conversion = 57.2957795131
    elif attr_type == "doubleLinear":
        raise NotImplementedError("doubleLinear conversion not implemented.")

    for connection in connections:
        if connection.startswith(layer + "."):
            attr_split = connection.split(".")
            if attr_split[0] == layer:
                attr = ".".join(attr_split[0:-1])
                value = cmds.getAttr("%s.value" % attr)
                if conversion:
                    value *= conversion
                return value

    else:
        # When connections are present, but none
        # to the specific renderlayer than the layer
        # should have the "defaultRenderLayer"'s value
        layer = "defaultRenderLayer"
        for connection in connections:
            if connection.startswith(layer):
                attr_split = connection.split(".")
                if attr_split[0] == "defaultRenderLayer":
                    attr = ".".join(attr_split[0:-1])
                    value = cmds.getAttr("%s.value" % attr)
                    if conversion:
                        value *= conversion
                    return value

    return cmds.getAttr(attr, asString=as_string)

get_attribute(plug, asString=False, expandEnvironmentVariables=False, **kwargs)

Maya getAttr with some fixes based on pymel.core.general.getAttr().

Like Pymel getAttr this applies some changes to maya.cmds.getAttr - maya pointlessly returned vector results as a tuple wrapped in a list (ex. '[(1,2,3)]'). This command unpacks the vector for you. - when getting a multi-attr, maya would raise an error, but this will return a list of values for the multi-attr - added support for getting message attributes by returning the connections instead

Note that the asString + expandEnvironmentVariables argument naming convention matches the maya.cmds.getAttr arguments so that it can act as a direct replacement for it.

Parameters:

Name Type Description Default
plug str

Node's attribute plug as node.attribute

required
asString bool

Return string value for enum attributes instead of the index. Note that the return value can be dependent on the UI language Maya is running in.

False
expandEnvironmentVariables bool

Expand any environment variable and (tilde characters on UNIX) found in string attributes which are returned.

False
Kwargs

Supports the keyword arguments of maya.cmds.getAttr

Returns:

Name Type Description
object

The value of the maya attribute.

Source code in client/ayon_maya/api/lib.py
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
def get_attribute(plug,
                  asString=False,
                  expandEnvironmentVariables=False,
                  **kwargs):
    """Maya getAttr with some fixes based on `pymel.core.general.getAttr()`.

    Like Pymel getAttr this applies some changes to `maya.cmds.getAttr`
      - maya pointlessly returned vector results as a tuple wrapped in a list
        (ex.  '[(1,2,3)]'). This command unpacks the vector for you.
      - when getting a multi-attr, maya would raise an error, but this will
        return a list of values for the multi-attr
      - added support for getting message attributes by returning the
        connections instead

    Note that the asString + expandEnvironmentVariables argument naming
    convention matches the `maya.cmds.getAttr` arguments so that it can
    act as a direct replacement for it.

    Args:
        plug (str): Node's attribute plug as `node.attribute`
        asString (bool): Return string value for enum attributes instead
            of the index. Note that the return value can be dependent on the
            UI language Maya is running in.
        expandEnvironmentVariables (bool): Expand any environment variable and
            (tilde characters on UNIX) found in string attributes which are
            returned.

    Kwargs:
        Supports the keyword arguments of `maya.cmds.getAttr`

    Returns:
        object: The value of the maya attribute.

    """
    attr_type = cmds.getAttr(plug, type=True)
    if asString:
        kwargs["asString"] = True
    if expandEnvironmentVariables:
        kwargs["expandEnvironmentVariables"] = True
    try:
        res = cmds.getAttr(plug, **kwargs)
    except RuntimeError:
        if attr_type == "message":
            return cmds.listConnections(plug)

        node, attr = plug.split(".", 1)
        children = cmds.attributeQuery(attr, node=node, listChildren=True)
        if children:
            return [
                get_attribute("{}.{}".format(node, child))
                for child in children
            ]

        raise

    # Convert vector result wrapped in tuple
    if isinstance(res, list) and len(res):
        if isinstance(res[0], tuple) and len(res):
            if attr_type in {'pointArray', 'vectorArray'}:
                return res
            return res[0]

    return res

get_capture_preset(task_name, task_type, product_name, project_settings, log)

Get capture preset for playblasting.

Logic for transitioning from old style capture preset to new capture preset profiles.

Parameters:

Name Type Description Default
task_name str

Task name.

required
task_type str

Task type.

required
product_name str

Product name.

required
project_settings dict

Project settings.

required
log Logger

Logging object.

required
Source code in client/ayon_maya/api/lib.py
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
def get_capture_preset(
    task_name, task_type, product_name, project_settings, log
):
    """Get capture preset for playblasting.

    Logic for transitioning from old style capture preset to new capture preset
    profiles.

    Args:
        task_name (str): Task name.
        task_type (str): Task type.
        product_name (str): Product name.
        project_settings (dict): Project settings.
        log (logging.Logger): Logging object.
    """
    capture_preset = None
    filtering_criteria = {
        "task_names": task_name,
        "task_types": task_type,
        "product_names": product_name
    }

    plugin_settings = project_settings["maya"]["publish"]["ExtractPlayblast"]
    if plugin_settings["profiles"]:
        profile = filter_profiles(
            plugin_settings["profiles"],
            filtering_criteria,
            logger=log
        ) or {}
        capture_preset = profile.get("capture_preset")
    else:
        log.warning("No profiles present for Extract Playblast")

    # Backward compatibility for deprecated Extract Playblast settings
    # without profiles.
    if capture_preset is None:
        log.debug(
            "Falling back to deprecated Extract Playblast capture preset "
            "because no new style playblast profiles are defined or no "
            "profile matches for your current context."
        )
        capture_preset = plugin_settings.get("capture_preset")

    if capture_preset:
        # Create deepcopy of preset as we'll change the values
        capture_preset = copy.deepcopy(capture_preset)

        viewport_options = capture_preset["ViewportOptions"]
        # Change 'list' to 'dict' for 'capture.py'
        viewport_options["pluginObjects"] = {
            item["name"]: item["value"]
            for item in viewport_options["pluginObjects"]
        }
    return capture_preset or {}

get_color_management_preferences()

Get and resolve OCIO preferences.

Source code in client/ayon_maya/api/lib.py
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
def get_color_management_preferences():
    """Get and resolve OCIO preferences."""
    data = {
        # Is color management enabled.
        "enabled": cmds.colorManagementPrefs(
            query=True, cmEnabled=True
        ),
        "rendering_space": cmds.colorManagementPrefs(
            query=True, renderingSpaceName=True
        ),
        "output_transform": cmds.colorManagementPrefs(
            query=True, outputTransformName=True
        ),
        "output_transform_enabled": cmds.colorManagementPrefs(
            query=True, outputTransformEnabled=True
        ),
        "view_transform": cmds.colorManagementPrefs(
            query=True, viewTransformName=True
        )
    }

    # Split view and display from view_transform. view_transform comes in
    # format of "{view} ({display})".
    regex = re.compile(r"^(?P<view>.+) \((?P<display>.+)\)$")
    if int(cmds.about(version=True)) <= 2020:
        # view_transform comes in format of "{view} {display}" in 2020.
        regex = re.compile(r"^(?P<view>.+) (?P<display>.+)$")

    match = regex.match(data["view_transform"])
    if not match:
        raise ValueError(
            "Unable to parse view and display from Maya view transform: '{}' "
            "using regex '{}'".format(data["view_transform"], regex.pattern)
        )

    data.update({
        "display": match.group("display"),
        "view": match.group("view")
    })

    # Get config absolute path.
    path = cmds.colorManagementPrefs(
        query=True, configFilePath=True
    )

    # The OCIO config supports a custom <MAYA_RESOURCES> token.
    maya_resources_token = "<MAYA_RESOURCES>"
    maya_resources_path = OpenMaya.MGlobal.getAbsolutePathToResources()
    path = path.replace(maya_resources_token, maya_resources_path)

    data["config"] = path

    return data

get_container_members(container)

Returns the members of a container. This includes the nodes from any loaded references in the container.

Source code in client/ayon_maya/api/lib.py
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
def get_container_members(container):
    """Returns the members of a container.
    This includes the nodes from any loaded references in the container.
    """
    if isinstance(container, dict):
        # Assume it's a container dictionary
        container = container["objectName"]

    members = cmds.sets(container, query=True) or []
    members = cmds.ls(members, long=True, objectsOnly=True) or []
    all_members = set(members)

    # Include any referenced nodes from any reference in the container
    # This is required since we've removed adding ALL nodes of a reference
    # into the container set and only add the reference node now.
    for ref in cmds.ls(members, exactType="reference", objectsOnly=True):

        # Ignore any `:sharedReferenceNode`
        if ref.rsplit(":", 1)[-1].startswith("sharedReferenceNode"):
            continue

        # Ignore _UNKNOWN_REF_NODE_ (PLN-160)
        if ref.rsplit(":", 1)[-1].startswith("_UNKNOWN_REF_NODE_"):
            continue

        try:
            reference_members = cmds.referenceQuery(ref,
                                                    nodes=True,
                                                    dagPath=True)
        except RuntimeError:
            # Ignore reference nodes that are not associated with a
            # referenced file on which `referenceQuery` command fails
            if not is_valid_reference_node(ref):
                continue
            raise
        reference_members = cmds.ls(reference_members,
                                    long=True,
                                    objectsOnly=True)
        all_members.update(reference_members)

    return list(all_members)

get_container_transforms(container, members=None, root=False)

Retrieve the root node of the container content

When a container is created through a Loader the content of the file will be grouped under a transform. The name of the root transform is stored in the container information

Parameters:

Name Type Description Default
container dict

the container

required
members list

optional and convenience argument

None
root bool

return highest node in hierarchy if True

False

Returns:

Name Type Description
root list / str
Source code in client/ayon_maya/api/lib.py
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
def get_container_transforms(container, members=None, root=False):
    """Retrieve the root node of the container content

    When a container is created through a Loader the content
    of the file will be grouped under a transform. The name of the root
    transform is stored in the container information

    Args:
        container (dict): the container
        members (list): optional and convenience argument
        root (bool): return highest node in hierarchy if True

    Returns:
        root (list / str):
    """

    if not members:
        members = get_container_members(container)

    results = cmds.ls(members, type="transform", long=True)
    if root:
        root = get_highest_in_hierarchy(results)
        if root:
            results = root[0]

    return results

get_custom_namespace(custom_namespace)

Return unique namespace.

The input namespace can contain a single group of '#' number tokens to indicate where the namespace's unique index should go. The amount of tokens defines the zero padding of the number, e.g ### turns into 001.

Note that a namespace will always be

prefixed with a _ if it starts with a digit

Example

get_custom_namespace("myspace_##_")

myspace_01_

get_custom_namespace("##_myspace")

_01_myspace

get_custom_namespace("myspace##")

myspace01

Source code in client/ayon_maya/api/lib.py
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
def get_custom_namespace(custom_namespace):
    """Return unique namespace.

    The input namespace can contain a single group
    of '#' number tokens to indicate where the namespace's
    unique index should go. The amount of tokens defines
    the zero padding of the number, e.g ### turns into 001.

    Warning: Note that a namespace will always be
        prefixed with a _ if it starts with a digit

    Example:
        >>> get_custom_namespace("myspace_##_")
        # myspace_01_
        >>> get_custom_namespace("##_myspace")
        # _01_myspace
        >>> get_custom_namespace("myspace##")
        # myspace01

    """
    split = re.split("([#]+)", custom_namespace, 1)

    if len(split) == 3:
        base, padding, suffix = split
        padding = "%0{}d".format(len(padding))
    else:
        base = split[0]
        padding = "%02d"  # default padding
        suffix = ""

    return unique_namespace(
        base,
        format=padding,
        prefix="_" if not base or base[0].isdigit() else "",
        suffix=suffix
    )

get_fps_for_current_context()

Get fps that should be set for current context.

Todos
  • Skip project value.
  • Merge logic with 'get_frame_range' and 'reset_scene_resolution' -> all the values in the functions can be collected at one place as they have same requirements.

Returns:

Type Description

Union[int, float]: FPS value.

Source code in client/ayon_maya/api/lib.py
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
def get_fps_for_current_context():
    """Get fps that should be set for current context.

    Todos:
        - Skip project value.
        - Merge logic with 'get_frame_range' and 'reset_scene_resolution' ->
            all the values in the functions can be collected at one place as
            they have same requirements.

    Returns:
        Union[int, float]: FPS value.
    """
    task_entity = get_current_task_entity(fields={"attrib"})
    fps = task_entity.get("attrib", {}).get("fps")
    if not fps:
        project_name = get_current_project_name()
        folder_path = get_current_folder_path()
        folder_entity = ayon_api.get_folder_by_path(
            project_name, folder_path, fields={"attrib.fps"}
        ) or {}

        fps = folder_entity.get("attrib", {}).get("fps")
        if not fps:
            project_entity = ayon_api.get_project(
                project_name, fields=["attrib.fps"]
            ) or {}
            fps = project_entity.get("attrib", {}).get("fps")

            if not fps:
                fps = 25

    return convert_to_maya_fps(fps)

get_frame_range(include_animation_range=False)

Get the current task frame range and handles.

Parameters:

Name Type Description Default
include_animation_range bool

Whether to include animationStart and animationEnd keys to define the outer range of the timeline. It is excluded by default.

False

Returns:

Name Type Description
dict

Task's expected frame range values.

Source code in client/ayon_maya/api/lib.py
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
def get_frame_range(include_animation_range=False):
    """Get the current task frame range and handles.

    Args:
        include_animation_range (bool, optional): Whether to include
            `animationStart` and `animationEnd` keys to define the outer
            range of the timeline. It is excluded by default.

    Returns:
        dict: Task's expected frame range values.

    """

    # Set frame start/end
    project_name = get_current_project_name()
    folder_path = get_current_folder_path()
    task_name = get_current_task_name()

    folder_entity = ayon_api.get_folder_by_path(
        project_name,
        folder_path,
        fields={"id"})
    task_entity = ayon_api.get_task_by_name(
            project_name, folder_entity["id"], task_name
        )

    task_attributes = task_entity["attrib"]

    frame_start = task_attributes.get("frameStart")
    frame_end = task_attributes.get("frameEnd")

    if frame_start is None or frame_end is None:
        cmds.warning("No edit information found for '{}'".format(folder_path))
        return

    handle_start = task_attributes.get("handleStart") or 0
    handle_end = task_attributes.get("handleEnd") or 0

    frame_range = {
        "frameStart": frame_start,
        "frameEnd": frame_end,
        "handleStart": handle_start,
        "handleEnd": handle_end
    }
    if include_animation_range:
        # The animation range values are only included to define whether
        # the Maya time slider should include the handles or not.
        # Some usages of this function use the full dictionary to define
        # instance attributes for which we want to exclude the animation
        # keys. That is why these are excluded by default.

        settings = get_project_settings(project_name)

        task_type = task_entity["taskType"]

        include_handles_settings = settings["maya"]["include_handles"]

        animation_start = frame_start
        animation_end = frame_end

        include_handles = include_handles_settings["include_handles_default"]
        for item in include_handles_settings["per_task_type"]:
            if task_type in item["task_type"]:
                include_handles = item["include_handles"]
                break
        if include_handles:
            animation_start -= int(handle_start)
            animation_end += int(handle_end)

        frame_range["animationStart"] = animation_start
        frame_range["animationEnd"] = animation_end

    return frame_range

get_highest_in_hierarchy(nodes)

Return highest nodes in the hierarchy that are in the nodes list.

The "highest in hierarchy" are the nodes closest to world: top-most level.

Parameters:

Name Type Description Default
nodes list

The nodes in which find the highest in hierarchies.

required

Returns:

Name Type Description
list

The highest nodes from the input nodes.

Source code in client/ayon_maya/api/lib.py
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
def get_highest_in_hierarchy(nodes):
    """Return highest nodes in the hierarchy that are in the `nodes` list.

    The "highest in hierarchy" are the nodes closest to world: top-most level.

    Args:
        nodes (list): The nodes in which find the highest in hierarchies.

    Returns:
        list: The highest nodes from the input nodes.

    """

    # Ensure we use long names
    nodes = cmds.ls(nodes, long=True)
    lookup = set(nodes)

    highest = []
    for node in nodes:
        # If no parents are within the nodes input list
        # then this is a highest node
        if not any(n in lookup for n in iter_parents(node)):
            highest.append(node)

    return highest

get_id(node)

Get the cbId attribute of the given node.

Parameters:

Name Type Description Default
node str

the name of the node to retrieve the attribute from

required

Returns: str

Source code in client/ayon_maya/api/lib.py
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
def get_id(node):
    """Get the `cbId` attribute of the given node.

    Args:
        node (str): the name of the node to retrieve the attribute from
    Returns:
        str

    """
    if node is None:
        return

    sel = OpenMaya.MSelectionList()
    sel.add(node)

    api_node = sel.getDependNode(0)
    fn = OpenMaya.MFnDependencyNode(api_node)

    if not fn.hasAttribute("cbId"):
        return

    try:
        return fn.findPlug("cbId", False).asString()
    except RuntimeError:
        log.warning("Failed to retrieve cbId on %s", node)
        return

get_id_from_sibling(node, history_only=True)

Return first node id in the history chain that matches this node.

The nodes in history must be of the exact same node type and must be parented under the same parent.

Optionally, if no matching node is found from the history, all the siblings of the node that are of the same type are checked. Additionally to having the same parent, the sibling must be marked as 'intermediate object'.

Parameters:

Name Type Description Default
node str

node to retrieve the history from

required
history_only bool

if True and if nothing found in history, look for an 'intermediate object' in all the node's siblings of same type

True

Returns:

Type Description

str or None: The id from the sibling node or None when no id found on any valid nodes in the history or siblings.

Source code in client/ayon_maya/api/lib.py
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
def get_id_from_sibling(node, history_only=True):
    """Return first node id in the history chain that matches this node.

    The nodes in history must be of the exact same node type and must be
    parented under the same parent.

    Optionally, if no matching node is found from the history, all the
    siblings of the node that are of the same type are checked.
    Additionally to having the same parent, the sibling must be marked as
    'intermediate object'.

    Args:
        node (str): node to retrieve the history from
        history_only (bool): if True and if nothing found in history,
            look for an 'intermediate object' in all the node's siblings
            of same type

    Returns:
        str or None: The id from the sibling node or None when no id found
            on any valid nodes in the history or siblings.

    """

    node = cmds.ls(node, long=True)[0]

    # Find all similar nodes in history
    history = cmds.listHistory(node)
    node_type = cmds.nodeType(node)
    similar_nodes = cmds.ls(history, exactType=node_type, long=True)

    # Exclude itself
    similar_nodes = [x for x in similar_nodes if x != node]

    # The node *must be* under the same parent
    parent = get_node_parent(node)
    similar_nodes = [i for i in similar_nodes if get_node_parent(i) == parent]

    # Check all of the remaining similar nodes and take the first one
    # with an id and assume it's the original.
    for similar_node in similar_nodes:
        _id = get_id(similar_node)
        if _id:
            return _id

    if not history_only:
        # Get siblings of same type
        similar_nodes = cmds.listRelatives(parent,
                                           type=node_type,
                                           fullPath=True)
        similar_nodes = cmds.ls(similar_nodes, exactType=node_type, long=True)

        # Exclude itself
        similar_nodes = [x for x in similar_nodes if x != node]

        # Get all unique ids from siblings in order since
        # we consistently take the first one found
        sibling_ids = OrderedDict()
        for similar_node in similar_nodes:
            # Check if "intermediate object"
            if not cmds.getAttr(similar_node + ".intermediateObject"):
                continue

            _id = get_id(similar_node)
            if not _id:
                continue

            if _id in sibling_ids:
                sibling_ids[_id].append(similar_node)
            else:
                sibling_ids[_id] = [similar_node]

        if sibling_ids:
            first_id, found_nodes = next(iter(sibling_ids.items()))

            # Log a warning if we've found multiple unique ids
            if len(sibling_ids) > 1:
                log.warning(("Found more than 1 intermediate shape with"
                             " unique id for '{}'. Using id of first"
                             " found: '{}'".format(node, found_nodes[0])))

            return first_id

get_id_required_nodes(referenced_nodes=False, nodes=None, existing_ids=True)

Return nodes that should receive a cbId attribute.

This includes only mesh and curve nodes, parent transforms of the shape nodes, file texture nodes and object sets (including shading engines).

This filters out any node which is locked, referenced, read-only, intermediate object.

Parameters:

Name Type Description Default
referenced_nodes bool

set True to include referenced nodes

False
nodes (list, Optional)

nodes to consider

None
existing_ids bool

set True to include nodes with cbId attribute

True

Returns:

Name Type Description
nodes set

list of filtered nodes

Source code in client/ayon_maya/api/lib.py
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
def get_id_required_nodes(referenced_nodes=False,
                          nodes=None,
                          existing_ids=True):
    """Return nodes that should receive a `cbId` attribute.

    This includes only mesh and curve nodes, parent transforms of the shape
    nodes, file texture nodes and object sets (including shading engines).

    This filters out any node which is locked, referenced, read-only,
    intermediate object.

    Args:
        referenced_nodes (bool): set True to include referenced nodes
        nodes (list, Optional): nodes to consider
        existing_ids (bool): set True to include nodes with `cbId` attribute

    Returns:
        nodes (set): list of filtered nodes
    """

    if nodes is not None and not nodes:
        # User supplied an empty `nodes` list to check so all we can
        # do is return the empty result
        return set()

    def _node_type_exists(node_type):
        try:
            cmds.nodeType(node_type, isTypeName=True)
            return True
        except RuntimeError:
            return False

    def iterate(maya_iterator):
        while not maya_iterator.isDone():
            yield maya_iterator.thisNode()
            maya_iterator.next()

    # `readOnly` flag is obsolete as of Maya 2016 therefore we explicitly
    # remove default nodes and reference nodes
    default_camera_shapes = {
        "frontShape", "sideShape", "topShape", "perspShape"
    }

    # The filtered types do not include transforms because we only want the
    # parent transforms that have a child shape that we filtered to, so we
    # include the parents here
    types = ["mesh", "nurbsCurve", "nurbsSurface", "file", "objectSet"]

    # Check if plugin nodes are available for Maya by checking if the plugin
    # is loaded
    if cmds.pluginInfo("pgYetiMaya", query=True, loaded=True):
        types.append("pgYetiMaya")

    iterator_type = OpenMaya.MIteratorType()
    # This tries to be closest matching API equivalents of `types` variable
    iterator_type.filterList = [
        OpenMaya.MFn.kMesh,  # mesh
        OpenMaya.MFn.kNurbsSurface,  # nurbsSurface
        OpenMaya.MFn.kNurbsCurve,  # nurbsCurve
        OpenMaya.MFn.kFileTexture,  # file
        OpenMaya.MFn.kSet,  # objectSet
        OpenMaya.MFn.kPluginShape  # pgYetiMaya
    ]
    it = OpenMaya.MItDependencyNodes(iterator_type)

    fn_dep = OpenMaya.MFnDependencyNode()
    fn_dag = OpenMaya.MFnDagNode()
    result = set()

    def _should_include_parents(obj):
        """Whether to include parents of obj in output"""
        if not obj.hasFn(OpenMaya.MFn.kShape):
            return False

        fn_dag.setObject(obj)
        if fn_dag.isIntermediateObject:
            return False

        # Skip default cameras
        if (
            obj.hasFn(OpenMaya.MFn.kCamera) and
            fn_dag.name() in default_camera_shapes
        ):
            return False

        return True

    def _add_to_result_if_valid(obj):
        """Add to `result` if the object should be included"""
        fn_dep.setObject(obj)
        if (
                not existing_ids
                and fn_dep.hasAttribute("cbId")
                # May not be an empty value
                and fn_dep.findPlug("cbId", True).asString()
        ):
            return

        if not referenced_nodes and fn_dep.isFromReferencedFile:
            return

        if fn_dep.isDefaultNode:
            return

        if fn_dep.isLocked:
            return

        # Skip default cameras
        if (
            obj.hasFn(OpenMaya.MFn.kCamera) and
            fn_dep.name() in default_camera_shapes
        ):
            return

        if obj.hasFn(OpenMaya.MFn.kDagNode):
            # DAG nodes
            fn_dag.setObject(obj)

            # Skip intermediate objects
            if fn_dag.isIntermediateObject:
                return

            # DAG nodes can be instanced and thus may have multiple paths.
            # We need to identify each path
            paths = OpenMaya.MDagPath.getAllPathsTo(obj)
            for dag in paths:
                path = dag.fullPathName()
                result.add(path)
        else:
            # Dependency node
            path = fn_dep.name()
            result.add(path)

    for obj in iterate(it):
        # For any non-intermediate shape node always include the parent
        # even if we exclude the shape itself (e.g. when locked, default)
        if _should_include_parents(obj):
            fn_dag.setObject(obj)
            parents = [
                fn_dag.parent(index) for index in range(fn_dag.parentCount())
            ]
            for parent_obj in parents:
                _add_to_result_if_valid(parent_obj)

        _add_to_result_if_valid(obj)

    if not result:
        return result

    # Exclude some additional types
    exclude_types = []
    if _node_type_exists("ilrBakeLayer"):
        # Remove Turtle from the result if Turtle is loaded
        exclude_types.append("ilrBakeLayer")

    if exclude_types:
        exclude_nodes = set(cmds.ls(nodes, long=True, type=exclude_types))
        if exclude_nodes:
            result -= exclude_nodes

    # Filter to explicit input nodes if provided
    if nodes is not None:
        # The amount of input nodes to filter to can be large and querying
        # many nodes can be slow in Maya. As such we want to try and reduce
        # it as much as possible, so we include the type filter to try and
        # reduce the result of `maya.cmds.ls` here.
        nodes = set(cmds.ls(nodes, long=True, type=types + ["dagNode"]))
        if nodes:
            result &= nodes
        else:
            return set()

    return result

get_isolate_view_sets()

Return isolate view sets of all modelPanels.

Returns:

Name Type Description
list

all sets related to isolate view

Source code in client/ayon_maya/api/lib.py
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
def get_isolate_view_sets():
    """Return isolate view sets of all modelPanels.

    Returns:
        list: all sets related to isolate view

    """

    view_sets = set()
    for panel in cmds.getPanel(type="modelPanel") or []:
        view_set = cmds.modelEditor(panel, query=True, viewObjects=True)
        if view_set:
            view_sets.add(view_set)

    return view_sets

get_main_window()

Acquire Maya's main window

Source code in client/ayon_maya/api/lib.py
 94
 95
 96
 97
 98
 99
100
101
102
103
def get_main_window():
    """Acquire Maya's main window"""
    from qtpy import QtWidgets

    if self._parent is None:
        self._parent = {
            widget.objectName(): widget
            for widget in QtWidgets.QApplication.topLevelWidgets()
        }["MayaWindow"]
    return self._parent

get_namespace(node)

Return namespace of given node

Source code in client/ayon_maya/api/lib.py
367
368
369
370
371
372
373
def get_namespace(node):
    """Return namespace of given node"""
    node_name = node.rsplit("|", 1)[-1]
    if ":" in node_name:
        return node_name.rsplit(":", 1)[0]
    else:
        return ""

get_node_index_under_parent(node)

Return the index of a DAG node under its parent.

Parameters:

Name Type Description Default
node str

A DAG Node path.

required

Returns:

Name Type Description
int int

The DAG node's index under its parents or world

Source code in client/ayon_maya/api/lib.py
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
def get_node_index_under_parent(node: str) -> int:
    """Return the index of a DAG node under its parent.

    Arguments:
        node (str): A DAG Node path.

    Returns:
        int: The DAG node's index under its parents or world

    """
    node = cmds.ls(node, long=True)[0]  # enforce long names
    parent = node.rsplit("|", 1)[0]
    if not parent:
        return cmds.ls(assemblies=True, long=True).index(node)
    else:
        return cmds.listRelatives(parent,
                                  children=True,
                                  fullPath=True).index(node)

get_node_name(path)

Return maya node name without namespace or parents

Examples:

>>> get_node_name("|grp|node")
"node"
>>> get_node_name("|foobar:grp|foobar:child")
"child"
>>> get_node_name("|foobar:grp|lala:bar|foobar:test:hello_world")
"hello_world"
Source code in client/ayon_maya/api/lib.py
505
506
507
508
509
510
511
512
513
514
515
516
def get_node_name(path: str) -> str:
    """Return maya node name without namespace or parents

    Examples:
        >>> get_node_name("|grp|node")
        "node"
        >>> get_node_name("|foobar:grp|foobar:child")
        "child"
        >>> get_node_name("|foobar:grp|lala:bar|foobar:test:hello_world")
        "hello_world"
    """
    return path.rsplit("|", 1)[-1].rsplit(":", 1)[-1]

get_node_parent(node)

Return full path name for parent of node

Source code in client/ayon_maya/api/lib.py
2281
2282
2283
2284
def get_node_parent(node):
    """Return full path name for parent of node"""
    parents = cmds.listRelatives(node, parent=True, fullPath=True)
    return parents[0] if parents else None

get_reference_node(members, log=None)

Get the reference node from the container members Args: members: list of node names

Returns:

Name Type Description
str

Reference node name.

Source code in client/ayon_maya/api/lib.py
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
def get_reference_node(members, log=None):
    """Get the reference node from the container members
    Args:
        members: list of node names

    Returns:
        str: Reference node name.

    """

    # Collect the references without .placeHolderList[] attributes as
    # unique entries (objects only) and skipping the sharedReferenceNode.
    references = set()
    for ref in cmds.ls(members, exactType="reference", objectsOnly=True):

        # Ignore any `:sharedReferenceNode`
        if ref.rsplit(":", 1)[-1].startswith("sharedReferenceNode"):
            continue

        # Ignore _UNKNOWN_REF_NODE_ (PLN-160)
        if ref.rsplit(":", 1)[-1].startswith("_UNKNOWN_REF_NODE_"):
            continue

        if not is_valid_reference_node(ref):
            continue

        references.add(ref)

    if not references:
        return

    # Get highest reference node (least parents)
    highest = min(references,
                  key=lambda x: len(get_reference_node_parents(x)))

    # Warn the user when we're taking the highest reference node
    if len(references) > 1:
        if not log:
            log = logging.getLogger(__name__)

        log.warning("More than one reference node found in "
                    "container, using highest reference node: "
                    "%s (in: %s)", highest, list(references))

    return highest

get_reference_node_parents(ref)

Return all parent reference nodes of reference node

Parameters:

Name Type Description Default
ref str

reference node.

required

Returns:

Name Type Description
list

The upstream parent reference nodes.

Source code in client/ayon_maya/api/lib.py
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
def get_reference_node_parents(ref):
    """Return all parent reference nodes of reference node

    Args:
        ref (str): reference node.

    Returns:
        list: The upstream parent reference nodes.

    """
    def _get_parent(reference_node):
        """Return parent reference node, but ignore invalid reference nodes"""
        if not is_valid_reference_node(reference_node):
            return
        return cmds.referenceQuery(reference_node,
                                   referenceNode=True,
                                   parent=True)

    parent = _get_parent(ref)
    parents = []
    while parent:
        parents.append(parent)
        parent = _get_parent(parent)
    return parents

Return objectSets that are relationships for a look for node.

Filters out based on: - id attribute is NOT AVALON_CONTAINER_ID - shapes and deformer shapes (alembic creates meshShapeDeformed) - set name ends with any from a predefined list - set in not in viewport set (isolate selected for example)

Parameters:

Name Type Description Default
node str

name of the current node to check

required

Returns:

Name Type Description
list

The related sets

Source code in client/ayon_maya/api/lib.py
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
def get_related_sets(node):
    """Return objectSets that are relationships for a look for `node`.

    Filters out based on:
    - id attribute is NOT `AVALON_CONTAINER_ID`
    - shapes and deformer shapes (alembic creates meshShapeDeformed)
    - set name ends with any from a predefined list
    - set in not in viewport set (isolate selected for example)

    Args:
        node (str): name of the current node to check

    Returns:
        list: The related sets

    """

    sets = cmds.listSets(object=node, extendToShape=False)
    if not sets:
        return []

    # Fix 'no object matches name' errors on nodes returned by listSets.
    # In rare cases it can happen that a node is added to an internal maya
    # set inaccessible by maya commands, for example check some nodes
    # returned by `cmds.listSets(allSets=True)`
    sets = cmds.ls(sets)

    # Ids to ignore
    ignored = {
        AVALON_INSTANCE_ID,
        AVALON_CONTAINER_ID,
        AYON_INSTANCE_ID,
        AYON_CONTAINER_ID,
    }

    # Ignore `avalon.container`
    sets = [
        s for s in sets
        if (
           not cmds.attributeQuery("id", node=s, exists=True)
           or cmds.getAttr(f"{s}.id") not in ignored
        )
    ]
    if not sets:
        return sets

    # Exclude deformer sets (`type=2` for `maya.cmds.listSets`)
    exclude_sets = cmds.listSets(object=node,
                                 extendToShape=False,
                                 type=2) or []
    exclude_sets = set(exclude_sets)  # optimize lookup

    # Default nodes to ignore
    exclude_sets.update({"defaultLightSet", "defaultObjectSet"})

    # Filter out the sets to exclude
    sets = [s for s in sets if s not in exclude_sets]

    # Ignore when the set has a specific suffix
    ignore_suffices = ("out_SET", "controls_SET", "_INST", "_CON")
    sets = [s for s in sets if not s.endswith(ignore_suffices)]
    if not sets:
        return sets

    # Ignore viewport filter view sets (from isolate select and
    # viewports)
    view_sets = get_isolate_view_sets()
    sets = [s for s in sets if s not in view_sets]

    return sets

get_sequence(filepath, pattern='%04d')

Get sequence from filename.

This will only return files if they exist on disk as it tries to collect the sequence using the filename pattern and searching for them on disk.

Supports negative frame ranges like -001, 0000, 0001 and -0001, 0000, 0001.

Parameters:

Name Type Description Default
filepath str

The full path to filename containing the given

required
pattern str

The pattern to swap with the variable frame number.

'%04d'

Returns:

Type Description

Optional[list[str]]: file sequence.

Source code in client/ayon_maya/api/lib.py
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
def get_sequence(filepath, pattern="%04d"):
    """Get sequence from filename.

    This will only return files if they exist on disk as it tries
    to collect the sequence using the filename pattern and searching
    for them on disk.

    Supports negative frame ranges like -001, 0000, 0001 and -0001,
    0000, 0001.

    Arguments:
        filepath (str): The full path to filename containing the given
        pattern.
        pattern (str): The pattern to swap with the variable frame number.

    Returns:
        Optional[list[str]]: file sequence.

    """
    filename = os.path.basename(filepath)
    re_pattern = re.escape(filename)
    re_pattern = re_pattern.replace(re.escape(pattern), "-?[0-9]+")
    source_dir = os.path.dirname(filepath)
    files = [f for f in os.listdir(source_dir) if re.match(re_pattern, f)]
    if not files:
        # Files do not exist, this may not be a problem if e.g. the
        # textures were relative paths and we're searching across
        # multiple image search paths.
        return

    # clique.PATTERNS["frames"] supports only `.1001.exr` not `_1001.exr` so
    # we use a customized pattern.
    pattern = "[_.](?P<index>(?P<padding>0*)\\d+)\\.\\D+\\d?$"
    patterns = [pattern]
    collections, _remainder = clique.assemble(
        files,
        patterns=patterns,
        minimum_items=1)

    if len(collections) > 1:
        raise ValueError(
            f"Multiple collections found for {collections}. "
            "This is a bug.")

    return [
        os.path.join(source_dir, filename)
        for filename in collections[0]
    ]

get_shader_assignments_from_shapes(shapes, components=True)

Return the shape assignment per related shading engines.

Returns a dictionary where the keys are shadingGroups and the values are lists of assigned shapes or shape-components.

Since maya.cmds.sets returns shader members on the shapes as components on the transform we correct that in this method too.

For the 'shapes' this will return a dictionary like: { "shadingEngineX": ["nodeX", "nodeY"], "shadingEngineY": ["nodeA", "nodeB"] }

Parameters:

Name Type Description Default
shapes list

The shapes to collect the assignments for.

required
components bool

Whether to include the component assignments.

True

Returns:

Name Type Description
dict

The {shadingEngine: shapes} relationships

Source code in client/ayon_maya/api/lib.py
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
def get_shader_assignments_from_shapes(shapes, components=True):
    """Return the shape assignment per related shading engines.

    Returns a dictionary where the keys are shadingGroups and the values are
    lists of assigned shapes or shape-components.

    Since `maya.cmds.sets` returns shader members on the shapes as components
    on the transform we correct that in this method too.

    For the 'shapes' this will return a dictionary like:
        {
            "shadingEngineX": ["nodeX", "nodeY"],
            "shadingEngineY": ["nodeA", "nodeB"]
        }

    Args:
        shapes (list): The shapes to collect the assignments for.
        components (bool): Whether to include the component assignments.

    Returns:
        dict: The {shadingEngine: shapes} relationships

    """

    shapes = cmds.ls(shapes,
                     long=True,
                     shapes=True,
                     objectsOnly=True)
    if not shapes:
        return {}

    # Collect shading engines and their shapes
    assignments = defaultdict(list)
    for shape in shapes:

        # Get unique shading groups for the shape
        shading_groups = cmds.listConnections(shape,
                                              source=False,
                                              destination=True,
                                              plugs=False,
                                              connections=False,
                                              type="shadingEngine") or []
        shading_groups = list(set(shading_groups))
        for shading_group in shading_groups:
            assignments[shading_group].append(shape)

    if components:
        # Note: Components returned from maya.cmds.sets are "listed" as if
        # being assigned to the transform like: pCube1.f[0] as opposed
        # to pCubeShape1.f[0] so we correct that here too.

        # Build a mapping from parent to shapes to include in lookup.
        transforms = {shape.rsplit("|", 1)[0]: shape for shape in shapes}
        lookup = set(shapes) | set(transforms.keys())

        component_assignments = defaultdict(list)
        for shading_group in assignments.keys():
            members = cmds.ls(cmds.sets(shading_group, query=True), long=True)
            for member in members:

                node = member.split(".", 1)[0]
                if node not in lookup:
                    continue

                # Component
                if "." in member:

                    # Fix transform to shape as shaders are assigned to shapes
                    if node in transforms:
                        shape = transforms[node]
                        component = member.split(".", 1)[1]
                        member = "{0}.{1}".format(shape, component)

                component_assignments[shading_group].append(member)
        assignments = component_assignments

    return dict(assignments)

guess_colorspace(img_info)

Guess the colorspace of the input image filename. Note: Reference from makeTx.py Args: img_info (dict): Image info generated by :func:image_info Returns: str: color space name use in the --colorconvert option of maketx.

Source code in client/ayon_maya/api/lib.py
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
def guess_colorspace(img_info):
    # type: (dict) -> str
    """Guess the colorspace of the input image filename.
    Note:
        Reference from makeTx.py
    Args:
        img_info (dict): Image info generated by :func:`image_info`
    Returns:
        str: color space name use in the `--colorconvert`
             option of maketx.
    """
    from arnold import (
        AiTextureInvalidate,
        # types
        AI_TYPE_BYTE,
        AI_TYPE_INT,
        AI_TYPE_UINT
    )
    try:
        if img_info['bit_depth'] <= 16:
            if img_info['format'] in (AI_TYPE_BYTE, AI_TYPE_INT, AI_TYPE_UINT): # noqa
                return 'sRGB'
            else:
                return 'linear'
        # now discard the image file as AiTextureGetFormat has loaded it
        AiTextureInvalidate(img_info['filename'])       # noqa
    except ValueError:
        print(("[maketx] Error: Could not guess"
               "colorspace for {}").format(img_info["filename"]))
        return "linear"

image_info(file_path)

Based on the texture path, get its bit depth and format information. Take reference from makeTx.py in Arnold: ImageInfo(filename): Get Image Information for colorspace AiTextureGetFormat(filename): Get Texture Format AiTextureGetBitDepth(filename): Get Texture bit depth Args: file_path (str): Path to the texture file. Returns: dict: Dictionary with the information about the texture file.

Source code in client/ayon_maya/api/lib.py
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
def image_info(file_path):
    # type: (str) -> dict
    """Based on the texture path, get its bit depth and format information.
    Take reference from makeTx.py in Arnold:
        ImageInfo(filename): Get Image Information for colorspace
        AiTextureGetFormat(filename): Get Texture Format
        AiTextureGetBitDepth(filename): Get Texture bit depth
    Args:
        file_path (str): Path to the texture file.
    Returns:
        dict: Dictionary with the information about the texture file.
    """
    from arnold import (
        AiTextureGetBitDepth,
        AiTextureGetFormat
    )
    # Get Texture Information
    img_info = {'filename': file_path}
    if os.path.isfile(file_path):
        img_info['bit_depth'] = AiTextureGetBitDepth(file_path)  # noqa
        img_info['format'] = AiTextureGetFormat(file_path)  # noqa
    else:
        img_info['bit_depth'] = 8
        img_info['format'] = "unknown"
    return img_info

imprint(node, data)

Write data to node as userDefined attributes

Parameters:

Name Type Description Default
node str

Long name of node

required
data dict

Dictionary of key/value pairs

required
Example

from maya import cmds def compute(): ... return 6 ... cube, generator = cmds.polyCube() imprint(cube, { ... "regularString": "myFamily", ... "computedValue": lambda: compute() ... }) ... cmds.getAttr(cube + ".computedValue") 6

Source code in client/ayon_maya/api/lib.py
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
def imprint(node, data):
    """Write `data` to `node` as userDefined attributes

    Arguments:
        node (str): Long name of node
        data (dict): Dictionary of key/value pairs

    Example:
        >>> from maya import cmds
        >>> def compute():
        ...   return 6
        ...
        >>> cube, generator = cmds.polyCube()
        >>> imprint(cube, {
        ...   "regularString": "myFamily",
        ...   "computedValue": lambda: compute()
        ... })
        ...
        >>> cmds.getAttr(cube + ".computedValue")
        6

    """

    for key, value in data.items():

        if callable(value):
            # Support values evaluated at imprint
            value = value()

        if isinstance(value, bool):
            add_type = {"attributeType": "bool"}
            set_type = {"keyable": False, "channelBox": True}
        elif isinstance(value, str):
            add_type = {"dataType": "string"}
            set_type = {"type": "string"}
        elif isinstance(value, int):
            add_type = {"attributeType": "long"}
            set_type = {"keyable": False, "channelBox": True}
        elif isinstance(value, float):
            add_type = {"attributeType": "double"}
            set_type = {"keyable": False, "channelBox": True}
        elif isinstance(value, (list, tuple)):
            add_type = {"attributeType": "enum", "enumName": ":".join(value)}
            set_type = {"keyable": False, "channelBox": True}
            value = 0  # enum default
        else:
            raise TypeError("Unsupported type: %r" % type(value))

        cmds.addAttr(node, longName=key, **add_type)
        cmds.setAttr(node + "." + key, value, **set_type)

is_valid_reference_node(reference_node)

Return whether Maya considers the reference node a valid reference.

Maya might report an error when using maya.cmds.referenceQuery: Reference node 'reference_node' is not associated with a reference file.

Note that this does not check whether the reference node points to an existing file. Instead, it only returns whether maya considers it valid and thus is not an unassociated reference node

Parameters:

Name Type Description Default
reference_node str

Reference node name

required

Returns:

Name Type Description
bool

Whether reference node is a valid reference

Source code in client/ayon_maya/api/lib.py
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
def is_valid_reference_node(reference_node):
    """Return whether Maya considers the reference node a valid reference.

    Maya might report an error when using `maya.cmds.referenceQuery`:
    Reference node 'reference_node' is not associated with a reference file.

    Note that this does *not* check whether the reference node points to an
    existing file. Instead, it only returns whether maya considers it valid
    and thus is not an unassociated reference node

    Arguments:
         reference_node (str): Reference node name

    Returns:
        bool: Whether reference node is a valid reference

    """
    # maya 2022 is missing `isValidReference` so the check needs to be
    # done in different way.
    if int(cmds.about(version=True)) < 2023:
        try:
            cmds.referenceQuery(reference_node, filename=True)
            return True
        except RuntimeError:
            return False
    sel = OpenMaya.MSelectionList()
    sel.add(reference_node)
    depend_node = sel.getDependNode(0)

    return OpenMaya.MFnReference(depend_node).isValidReference()

is_visible(node, displayLayer=True, intermediateObject=True, parentHidden=True, visibility=True)

Is node visible?

Returns whether a node is hidden by one of the following methods: - The node exists (always checked) - The node must be a dagNode (always checked) - The node's visibility is off. - The node is set as intermediate Object. - The node is in a disabled displayLayer. - Whether any of its parent nodes is hidden.

Roughly based on: http://ewertb.soundlinker.com/mel/mel.098.php

Returns:

Name Type Description
bool

Whether the node is visible in the scene

Source code in client/ayon_maya/api/lib.py
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
def is_visible(node,
               displayLayer=True,
               intermediateObject=True,
               parentHidden=True,
               visibility=True):
    """Is `node` visible?

    Returns whether a node is hidden by one of the following methods:
    - The node exists (always checked)
    - The node must be a dagNode (always checked)
    - The node's visibility is off.
    - The node is set as intermediate Object.
    - The node is in a disabled displayLayer.
    - Whether any of its parent nodes is hidden.

    Roughly based on: http://ewertb.soundlinker.com/mel/mel.098.php

    Returns:
        bool: Whether the node is visible in the scene

    """

    # Only existing objects can be visible
    if not cmds.objExists(node):
        return False

    # Only dagNodes can be visible
    if not cmds.objectType(node, isAType='dagNode'):
        return False

    if visibility:
        if not cmds.getAttr('{0}.visibility'.format(node)):
            return False

    if intermediateObject and cmds.objectType(node, isAType='shape'):
        if cmds.getAttr('{0}.intermediateObject'.format(node)):
            return False

    if displayLayer:
        # Display layers set overrideEnabled and overrideVisibility on members
        if cmds.attributeQuery('overrideEnabled', node=node, exists=True):
            override_enabled = cmds.getAttr('{}.overrideEnabled'.format(node))
            override_visibility = cmds.getAttr('{}.overrideVisibility'.format(
                node))
            if override_enabled and not override_visibility:
                return False

    if parentHidden:
        parents = cmds.listRelatives(node, parent=True, fullPath=True)
        if parents:
            parent = parents[0]
            if not is_visible(parent,
                              displayLayer=displayLayer,
                              intermediateObject=False,
                              parentHidden=parentHidden,
                              visibility=visibility):
                return False

    return True

iter_parents(node)

Iter parents of node from its long name.

Note: The node must be the long node name.

Parameters:

Name Type Description Default
node str

Node long name.

required

Yields:

Name Type Description
str

All parent node names (long names)

Source code in client/ayon_maya/api/lib.py
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
def iter_parents(node):
    """Iter parents of node from its long name.

    Note: The `node` *must* be the long node name.

    Args:
        node (str): Node long name.

    Yields:
        str: All parent node names (long names)

    """
    while True:
        split = node.rsplit("|", 1)
        if len(split) == 1 or not split[0]:
            return

        node = split[0]
        yield node

iter_shader_edits(relationships, shader_nodes, nodes_by_id, label=None)

Yield edits as a set of actions.

Source code in client/ayon_maya/api/lib.py
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
def iter_shader_edits(relationships, shader_nodes, nodes_by_id, label=None):
    """Yield edits as a set of actions."""

    attributes = relationships.get("attributes", [])
    shader_data = relationships.get("relationships", {})

    shading_engines = cmds.ls(shader_nodes, type="objectSet", long=True)
    assert shading_engines, "Error in retrieving objectSets from reference"

    # region compute lookup
    shading_engines_by_id = defaultdict(list)
    for shad in shading_engines:
        shading_engines_by_id[get_id(shad)].append(shad)
    # endregion

    # region assign shading engines and other sets
    for data in shader_data.values():
        # collect all unique IDs of the set members
        shader_uuid = data["uuid"]
        member_uuids = [
            (member["uuid"], member.get("components"))
            for member in data["members"]]

        filtered_nodes = list()
        for _uuid, components in member_uuids:
            nodes = nodes_by_id.get(_uuid, None)
            if nodes is None:
                continue

            if components:
                # Assign to the components
                nodes = [".".join([node, components]) for node in nodes]

            filtered_nodes.extend(nodes)

        id_shading_engines = shading_engines_by_id[shader_uuid]
        if not id_shading_engines:
            log.error("{} - No shader found with cbId "
                      "'{}'".format(label, shader_uuid))
            continue
        elif len(id_shading_engines) > 1:
            log.error("{} - Skipping shader assignment. "
                      "More than one shader found with cbId "
                      "'{}'. (found: {})".format(label, shader_uuid,
                                                 id_shading_engines))
            continue

        if not filtered_nodes:
            log.warning("{} - No nodes found for shading engine "
                        "'{}'".format(label, id_shading_engines[0]))
            continue

        yield {"action": "assign",
               "uuid": data["uuid"],
               "nodes": filtered_nodes,
               "shader": id_shading_engines[0]}

    for data in attributes:
        nodes = nodes_by_id.get(data["uuid"], [])
        attr_value = data["attributes"]
        yield {"action": "setattr",
               "uuid": data["uuid"],
               "nodes": nodes,
               "attributes": attr_value}

iter_visible_nodes_in_range(nodes, start, end)

Yield nodes that are visible in start-end frame range.

  • Ignores intermediateObjects completely.
  • Considers animated visibility attributes + upstream visibilities.

This is optimized for large scenes where some nodes in the parent hierarchy might have some input connections to the visibilities, e.g. key, driven keys, connections to other attributes, etc.

This only does a single time step to start if current frame is not inside frame range since the assumption is made that changing a frame isn't so slow that it beats querying all visibility plugs through MDGContext on another frame.

Parameters:

Name Type Description Default
nodes list

List of node names to consider.

required
start (int, float)

Start frame.

required
end (int, float)

End frame.

required

Returns:

Name Type Description
list

List of node names. These will be long full path names so might have a longer name than the input nodes.

Source code in client/ayon_maya/api/lib.py
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
def iter_visible_nodes_in_range(nodes, start, end):
    """Yield nodes that are visible in start-end frame range.

    - Ignores intermediateObjects completely.
    - Considers animated visibility attributes + upstream visibilities.

    This is optimized for large scenes where some nodes in the parent
    hierarchy might have some input connections to the visibilities,
    e.g. key, driven keys, connections to other attributes, etc.

    This only does a single time step to `start` if current frame is
    not inside frame range since the assumption is made that changing
    a frame isn't so slow that it beats querying all visibility
    plugs through MDGContext on another frame.

    Args:
        nodes (list): List of node names to consider.
        start (int, float): Start frame.
        end (int, float): End frame.

    Returns:
        list: List of node names. These will be long full path names so
            might have a longer name than the input nodes.

    """
    # States we consider per node
    VISIBLE = 1  # always visible
    INVISIBLE = 0  # always invisible
    ANIMATED = -1  # animated visibility

    # Ensure integers
    start = int(start)
    end = int(end)

    # Consider only non-intermediate dag nodes and use the "long" names.
    nodes = cmds.ls(nodes, long=True, noIntermediate=True, type="dagNode")
    if not nodes:
        return

    with maintained_time():
        # Go to first frame of the range if the current time is outside
        # the queried range so can directly query all visible nodes on
        # that frame.
        current_time = cmds.currentTime(query=True)
        if not (start <= current_time <= end):
            cmds.currentTime(start)

        visible = cmds.ls(nodes, long=True, visible=True)
        for node in visible:
            yield node
        if len(visible) == len(nodes) or start == end:
            # All are visible on frame one, so they are at least visible once
            # inside the frame range.
            return

    # For the invisible ones check whether its visibility and/or
    # any of its parents visibility attributes are animated. If so, it might
    # get visible on other frames in the range.
    def memodict(f):
        """Memoization decorator for a function taking a single argument.

        See: http://code.activestate.com/recipes/
             578231-probably-the-fastest-memoization-decorator-in-the-/
        """

        class memodict(dict):
            def __missing__(self, key):
                ret = self[key] = f(key)
                return ret

        return memodict().__getitem__

    @memodict
    def get_state(node):
        plug = node + ".visibility"
        connections = cmds.listConnections(plug,
                                           source=True,
                                           destination=False)
        if connections:
            return ANIMATED
        else:
            return VISIBLE if cmds.getAttr(plug) else INVISIBLE

    visible = set(visible)
    invisible = [node for node in nodes if node not in visible]
    always_invisible = set()
    # Iterate over the nodes by short to long names to iterate the highest
    # in hierarchy nodes first. So the collected data can be used from the
    # cache for parent queries in next iterations.
    node_dependencies = dict()
    for node in sorted(invisible, key=len):

        state = get_state(node)
        if state == INVISIBLE:
            always_invisible.add(node)
            continue

        # If not always invisible by itself we should go through and check
        # the parents to see if any of them are always invisible. For those
        # that are "ANIMATED" we consider that this node is dependent on
        # that attribute, we store them as dependency.
        dependencies = set()
        if state == ANIMATED:
            dependencies.add(node)

        traversed_parents = list()
        for parent in iter_parents(node):

            if parent in always_invisible or get_state(parent) == INVISIBLE:
                # When parent is always invisible then consider this parent,
                # this node we started from and any of the parents we
                # have traversed in-between to be *always invisible*
                always_invisible.add(parent)
                always_invisible.add(node)
                always_invisible.update(traversed_parents)
                break

            # If we have traversed the parent before and its visibility
            # was dependent on animated visibilities then we can just extend
            # its dependencies for to those for this node and break further
            # iteration upwards.
            parent_dependencies = node_dependencies.get(parent, None)
            if parent_dependencies is not None:
                dependencies.update(parent_dependencies)
                break

            state = get_state(parent)
            if state == ANIMATED:
                dependencies.add(parent)

            traversed_parents.append(parent)

        if node not in always_invisible and dependencies:
            node_dependencies[node] = dependencies

    if not node_dependencies:
        return

    # Now we only have to check the visibilities for nodes that have animated
    # visibility dependencies upstream. The fastest way to check these
    # visibility attributes across different frames is with Python api 2.0
    # so we do that.
    @memodict
    def get_visibility_mplug(node):
        """Return api 2.0 MPlug with cached memoize decorator"""
        sel = OpenMaya.MSelectionList()
        sel.add(node)
        dag = sel.getDagPath(0)
        return OpenMaya.MFnDagNode(dag).findPlug("visibility", True)

    @contextlib.contextmanager
    def dgcontext(mtime):
        """MDGContext context manager"""
        context = OpenMaya.MDGContext(mtime)
        try:
            previous = context.makeCurrent()
            yield context
        finally:
            previous.makeCurrent()

    # We skip the first frame as we already used that frame to check for
    # overall visibilities. And end+1 to include the end frame.
    scene_units = OpenMaya.MTime.uiUnit()
    for frame in range(start + 1, end + 1):
        mtime = OpenMaya.MTime(frame, unit=scene_units)

        # Build little cache so we don't query the same MPlug's value
        # again if it was checked on this frame and also is a dependency
        # for another node
        frame_visibilities = {}
        with dgcontext(mtime):
            for node, dependencies in list(node_dependencies.items()):
                for dependency in dependencies:
                    dependency_visible = frame_visibilities.get(dependency,
                                                                None)
                    if dependency_visible is None:
                        mplug = get_visibility_mplug(dependency)
                        dependency_visible = mplug.asBool()
                        frame_visibilities[dependency] = dependency_visible

                    if not dependency_visible:
                        # One dependency is not visible, thus the
                        # node is not visible.
                        break

                else:
                    # All dependencies are visible.
                    yield node
                    # Remove node with dependencies for next frame iterations
                    # because it was visible at least once.
                    node_dependencies.pop(node)

        # If no more nodes to process break the frame iterations..
        if not node_dependencies:
            break

keytangent_default(in_tangent_type='auto', out_tangent_type='auto')

Set the default keyTangent for new keys during this context

Source code in client/ayon_maya/api/lib.py
817
818
819
820
821
822
823
824
825
826
827
828
829
830
@contextlib.contextmanager
def keytangent_default(in_tangent_type='auto',
                       out_tangent_type='auto'):
    """Set the default keyTangent for new keys during this context"""

    original_itt = cmds.keyTangent(query=True, g=True, itt=True)[0]
    original_ott = cmds.keyTangent(query=True, g=True, ott=True)[0]
    cmds.keyTangent(g=True, itt=in_tangent_type)
    cmds.keyTangent(g=True, ott=out_tangent_type)
    try:
        yield
    finally:
        cmds.keyTangent(g=True, itt=original_itt)
        cmds.keyTangent(g=True, ott=original_ott)

len_flattened(components)

Return the length of the list as if it was flattened.

Maya will return consecutive components as a single entry when requesting with maya.cmds.ls without the flatten flag. Though enabling flatten on a large list (e.g. millions) will result in a slow result. This command will return the amount of entries in a non-flattened list by parsing the result with regex.

Parameters:

Name Type Description Default
components list

The non-flattened components.

required

Returns:

Name Type Description
int

The amount of entries.

Source code in client/ayon_maya/api/lib.py
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
def len_flattened(components):
    """Return the length of the list as if it was flattened.

    Maya will return consecutive components as a single entry
    when requesting with `maya.cmds.ls` without the `flatten`
    flag. Though enabling `flatten` on a large list (e.g. millions)
    will result in a slow result. This command will return the amount
    of entries in a non-flattened list by parsing the result with
    regex.

    Args:
        components (list): The non-flattened components.

    Returns:
        int: The amount of entries.

    """
    assert isinstance(components, (list, tuple))
    n = 0

    pattern = re.compile(r"\[(\d+):(\d+)\]")
    for c in components:
        match = pattern.search(c)
        if match:
            start, end = match.groups()
            n += int(end) - int(start) + 1
        else:
            n += 1
    return n

list_looks(project_name, folder_id)

Return all look products for the given folder.

This assumes all look products start with "look*" in their names.

Returns:

Type Description

list[dict[str, Any]]: List of look products.

Source code in client/ayon_maya/api/lib.py
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
def list_looks(project_name, folder_id):
    """Return all look products for the given folder.

    This assumes all look products start with "look*" in their names.

    Returns:
        list[dict[str, Any]]: List of look products.

    """
    return list(ayon_api.get_products(
        project_name, folder_ids=[folder_id], product_types={"look"}
    ))

load_capture_preset(data)

Convert AYON Extract Playblast settings to capture arguments

Input data is the settings from

project_settings/maya/publish/ExtractPlayblast/capture_preset

Parameters:

Name Type Description Default
data dict

Capture preset settings from AYON settings

required

Returns:

Name Type Description
dict

capture.capture compatible keyword arguments

Source code in client/ayon_maya/api/lib.py
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
def load_capture_preset(data):
    """Convert AYON Extract Playblast settings to `capture` arguments

    Input data is the settings from:
        `project_settings/maya/publish/ExtractPlayblast/capture_preset`

    Args:
        data (dict): Capture preset settings from AYON settings

    Returns:
        dict: `capture.capture` compatible keyword arguments

    """

    options = dict()
    viewport_options = dict()
    viewport2_options = dict()
    camera_options = dict()

    # Straight key-value match from settings to capture arguments
    options.update(data["Codec"])
    options.update(data["Generic"])
    options.update(data["Resolution"])

    camera_options.update(data["CameraOptions"])
    viewport_options.update(data["Renderer"])

    # DISPLAY OPTIONS
    disp_options = {}
    for key, value in data["DisplayOptions"].items():
        if key.startswith("background"):
            # Convert background, backgroundTop, backgroundBottom colors

            if len(value) == 4:
                # Ignore alpha + convert RGB to float
                value = [
                    float(value[0]) / 255,
                    float(value[1]) / 255,
                    float(value[2]) / 255
                ]
            disp_options[key] = value
        elif key == "displayGradient":
            disp_options[key] = value

    options["display_options"] = disp_options

    # Viewport Options has a mixture of Viewport2 Options and Viewport Options
    # to pass along to capture. So we'll need to differentiate between the two
    VIEWPORT2_OPTIONS = {
        "textureMaxResolution",
        "renderDepthOfField",
        "ssaoEnable",
        "ssaoSamples",
        "ssaoAmount",
        "ssaoRadius",
        "ssaoFilterRadius",
        "hwFogStart",
        "hwFogEnd",
        "hwFogAlpha",
        "hwFogFalloff",
        "hwFogColorR",
        "hwFogColorG",
        "hwFogColorB",
        "hwFogDensity",
        "motionBlurEnable",
        "motionBlurSampleCount",
        "motionBlurShutterOpenFraction",
        "lineAAEnable"
    }
    for key, value in data["ViewportOptions"].items():

        # There are some keys we want to ignore
        if key in {"override_viewport_options", "high_quality"}:
            continue

        # First handle special cases where we do value conversion to
        # separate option values
        if key == 'textureMaxResolution':
            viewport2_options['textureMaxResolution'] = value
            if value > 0:
                viewport2_options['enableTextureMaxRes'] = True
                viewport2_options['textureMaxResMode'] = 1
            else:
                viewport2_options['enableTextureMaxRes'] = False
                viewport2_options['textureMaxResMode'] = 0

        elif key == 'multiSample':
            viewport2_options['multiSampleEnable'] = value > 0
            viewport2_options['multiSampleCount'] = value

        elif key == 'alphaCut':
            viewport2_options['transparencyAlgorithm'] = 5
            viewport2_options['transparencyQuality'] = 1

        elif key == 'hwFogFalloff':
            # Settings enum value string to integer
            viewport2_options['hwFogFalloff'] = int(value)

        # Then handle Viewport 2.0 Options
        elif key in VIEWPORT2_OPTIONS:
            viewport2_options[key] = value

        # Then assume remainder is Viewport Options
        else:
            viewport_options[key] = value

    options['viewport_options'] = viewport_options
    options['viewport2_options'] = viewport2_options
    options['camera_options'] = camera_options

    # use active sound track
    scene = capture.parse_active_scene()
    options['sound'] = scene['sound']

    return options

lsattr(attr, value=None)

Return nodes matching key and value

Parameters:

Name Type Description Default
attr str

Name of Maya attribute

required
value object

Value of attribute. If none is provided, return all nodes with this attribute.

None
Example

lsattr("id", "myId") ["myNode"] lsattr("id") ["myNode", "myOtherNode"]

Source code in client/ayon_maya/api/lib.py
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
def lsattr(attr, value=None):
    """Return nodes matching `key` and `value`

    Arguments:
        attr (str): Name of Maya attribute
        value (object, optional): Value of attribute. If none
            is provided, return all nodes with this attribute.

    Example:
        >> lsattr("id", "myId")
        ["myNode"]
        >> lsattr("id")
        ["myNode", "myOtherNode"]

    """

    if value is None:
        return cmds.ls("*.%s" % attr,
                       recursive=True,
                       objectsOnly=True,
                       long=True)
    return lsattrs({attr: value})

lsattrs(attrs)

Return nodes with the given attribute(s).

Parameters:

Name Type Description Default
attrs dict

Name and value pairs of expected matches

required
Example

Return nodes with an age of five.

lsattrs({"age": "five"})

Return nodes with both age and color of five and blue.

lsattrs({"age": "five", "color": "blue"})

Return

list: matching nodes.

Source code in client/ayon_maya/api/lib.py
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
def lsattrs(attrs):
    """Return nodes with the given attribute(s).

    Arguments:
        attrs (dict): Name and value pairs of expected matches

    Example:
        >>> # Return nodes with an `age` of five.
        >>> lsattrs({"age": "five"})
        >>> # Return nodes with both `age` and `color` of five and blue.
        >>> lsattrs({"age": "five", "color": "blue"})

    Return:
         list: matching nodes.

    """

    dep_fn = OpenMaya.MFnDependencyNode()
    dag_fn = OpenMaya.MFnDagNode()
    selection_list = OpenMaya.MSelectionList()

    first_attr = next(iter(attrs))

    try:
        selection_list.add("*.{0}".format(first_attr),
                           searchChildNamespaces=True)
    except RuntimeError as exc:
        if str(exc).endswith("Object does not exist"):
            return []

    matches = set()
    for i in range(selection_list.length()):
        node = selection_list.getDependNode(i)
        if node.hasFn(OpenMaya.MFn.kDagNode):
            fn_node = dag_fn.setObject(node)
            full_path_names = [path.fullPathName()
                               for path in fn_node.getAllPaths()]
        else:
            fn_node = dep_fn.setObject(node)
            full_path_names = [fn_node.name()]

        for attr in attrs:
            try:
                plug = fn_node.findPlug(attr, True)
                if plug.asString() != attrs[attr]:
                    break
            except RuntimeError:
                break
        else:
            matches.update(full_path_names)

    return list(matches)

maintained_selection()

Maintain selection during context

Example

scene = cmds.file(new=True, force=True) node = cmds.createNode("transform", name="Test") cmds.select("persp") with maintained_selection(): ... cmds.select("Test", replace=True) "Test" in cmds.ls(selection=True) False

Source code in client/ayon_maya/api/lib.py
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
@contextlib.contextmanager
def maintained_selection():
    """Maintain selection during context

    Example:
        >>> scene = cmds.file(new=True, force=True)
        >>> node = cmds.createNode("transform", name="Test")
        >>> cmds.select("persp")
        >>> with maintained_selection():
        ...     cmds.select("Test", replace=True)
        >>> "Test" in cmds.ls(selection=True)
        False

    """

    previous_selection = cmds.ls(selection=True)
    try:
        yield
    finally:
        if previous_selection:
            cmds.select(previous_selection,
                        replace=True,
                        noExpand=True)
        else:
            cmds.select(clear=True)

maintained_selection_api()

Maintain selection using the Maya Python API.

Warning: This is not added to the undo stack.

Source code in client/ayon_maya/api/lib.py
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
@contextlib.contextmanager
def maintained_selection_api():
    """Maintain selection using the Maya Python API.

    Warning: This is *not* added to the undo stack.

    """
    original = OpenMaya.MGlobal.getActiveSelectionList()
    try:
        yield
    finally:
        OpenMaya.MGlobal.setActiveSelectionList(original)

material_loading_mode(mode='immediate')

Set material loading mode during context

Source code in client/ayon_maya/api/lib.py
356
357
358
359
360
361
362
363
364
@contextlib.contextmanager
def material_loading_mode(mode="immediate"):
    """Set material loading mode during context"""
    original = cmds.displayPref(query=True, materialLoadingMode=True)
    cmds.displayPref(materialLoadingMode=mode)
    try:
        yield
    finally:
        cmds.displayPref(materialLoadingMode=original)

matrix_equals(a, b, tolerance=1e-10)

Compares two matrices with an imperfection tolerance

Parameters:

Name Type Description Default
a (list, tuple)

the matrix to check

required
b (list, tuple)

the matrix to check against

required
tolerance float

the precision of the differences

1e-10

Returns:

Name Type Description
bool

True or False

Source code in client/ayon_maya/api/lib.py
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
def matrix_equals(a, b, tolerance=1e-10):
    """
    Compares two matrices with an imperfection tolerance

    Args:
        a (list, tuple): the matrix to check
        b (list, tuple): the matrix to check against
        tolerance (float): the precision of the differences

    Returns:
        bool : True or False

    """
    if not all(abs(x - y) < tolerance for x, y in zip(a, b)):
        return False
    return True

namespaced(namespace, new=True, relative_names=None)

Work inside namespace during context

Parameters:

Name Type Description Default
new bool

When enabled this will rename the namespace to a unique namespace if the input namespace already exists.

True

Yields:

Name Type Description
str

The namespace that is used during the context

Source code in client/ayon_maya/api/lib.py
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
@contextlib.contextmanager
def namespaced(namespace, new=True, relative_names=None):
    """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, absoluteName=True)
    original_relative_names = cmds.namespace(query=True, relativeNames=True)
    if new:
        namespace = unique_namespace(namespace)
        cmds.namespace(add=namespace)
    if relative_names is not None:
        cmds.namespace(relativeNames=relative_names)
    try:
        cmds.namespace(set=namespace)
        yield namespace
    finally:
        cmds.namespace(set=original)
        if relative_names is not None:
            cmds.namespace(relativeNames=original_relative_names)

no_display_layers(nodes)

Ensure nodes are not in a displayLayer during context.

Parameters:

Name Type Description Default
nodes list

The nodes to remove from any display layer.

required
Source code in client/ayon_maya/api/lib.py
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
@contextlib.contextmanager
def no_display_layers(nodes):
    """Ensure nodes are not in a displayLayer during context.

    Arguments:
        nodes (list): The nodes to remove from any display layer.

    """

    # Ensure long names
    nodes = cmds.ls(nodes, long=True)

    # Get the original state
    lookup = set(nodes)
    original = {}
    for layer in cmds.ls(type='displayLayer'):

        # Skip default layer
        if layer == "defaultLayer":
            continue

        members = cmds.editDisplayLayerMembers(layer,
                                               query=True,
                                               fullNames=True)
        if not members:
            continue
        members = set(members)

        included = lookup.intersection(members)
        if included:
            original[layer] = list(included)

    try:
        # Add all nodes to default layer
        cmds.editDisplayLayerMembers("defaultLayer", nodes, noRecurse=True)
        yield
    finally:
        # Restore original members
        _iteritems = getattr(original, "iteritems", original.items)
        for layer, members in _iteritems():
            cmds.editDisplayLayerMembers(layer, members, noRecurse=True)

no_undo(flush=False)

Disable the undo queue during the context

Parameters:

Name Type Description Default
flush bool

When True the undo queue will be emptied when returning from the context losing all undo history. Defaults to False.

False
Source code in client/ayon_maya/api/lib.py
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
@contextlib.contextmanager
def no_undo(flush=False):
    """Disable the undo queue during the context

    Arguments:
        flush (bool): When True the undo queue will be emptied when returning
            from the context losing all undo history. Defaults to False.

    """
    original = cmds.undoInfo(query=True, state=True)
    keyword = 'state' if flush else 'stateWithoutFlush'

    try:
        cmds.undoInfo(**{keyword: False})
        yield
    finally:
        cmds.undoInfo(**{keyword: original})

pairwise(iterable)

s -> (s0,s1), (s2,s3), (s4, s5), ...

Source code in client/ayon_maya/api/lib.py
571
572
573
574
def pairwise(iterable):
    """s -> (s0,s1), (s2,s3), (s4, s5), ..."""
    a = iter(iterable)
    return zip(a, a)

panel_camera(panel, camera)

Set modelPanel's camera during the context.

Parameters:

Name Type Description Default
panel str

modelPanel name.

required
camera str

camera name.

required
Source code in client/ayon_maya/api/lib.py
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
@contextlib.contextmanager
def panel_camera(panel, camera):
    """Set modelPanel's camera during the context.

    Arguments:
        panel (str): modelPanel name.
        camera (str): camera name.

    """
    original_camera = cmds.modelPanel(panel, query=True, camera=True)
    try:
        cmds.modelPanel(panel, edit=True, camera=camera)
        yield
    finally:
        cmds.modelPanel(panel, edit=True, camera=original_camera)

parent_nodes(nodes, parent=None)

Context manager to un-parent provided nodes and return them back.

Source code in client/ayon_maya/api/lib.py
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
@contextlib.contextmanager
def parent_nodes(nodes, parent=None):
    # type: (list, str) -> list
    """Context manager to un-parent provided nodes and return them back."""

    def _as_mdagpath(node):
        """Return MDagPath for node path."""
        if not node:
            return
        sel = OpenMaya.MSelectionList()
        sel.add(node)
        return sel.getDagPath(0)

    # We can only parent dag nodes so we ensure input contains only dag nodes
    nodes = cmds.ls(nodes, type="dagNode", long=True)
    if not nodes:
        # opt-out early
        yield
        return

    parent_node_path = None
    delete_parent = False
    if parent:
        if not cmds.objExists(parent):
            parent_node = cmds.createNode("transform",
                                          name=parent,
                                          skipSelect=False)
            delete_parent = True
        else:
            parent_node = parent
        parent_node_path = cmds.ls(parent_node, long=True)[0]

    # Store original parents
    node_parents = []
    for node in nodes:
        node_parent = get_node_parent(node)
        node_parents.append((_as_mdagpath(node), _as_mdagpath(node_parent)))

    try:
        for node, node_parent in node_parents:
            node_parent_path = node_parent.fullPathName() if node_parent else None  # noqa
            if node_parent_path == parent_node_path:
                # Already a child
                continue

            if parent_node_path:
                cmds.parent(node.fullPathName(), parent_node_path)
            else:
                cmds.parent(node.fullPathName(), world=True)

        yield
    finally:
        # Reparent to original parents
        for node, original_parent in node_parents:
            node_path = node.fullPathName()
            if not node_path:
                # Node must have been deleted
                continue

            node_parent_path = get_node_parent(node_path)

            original_parent_path = None
            if original_parent:
                original_parent_path = original_parent.fullPathName()
                if not original_parent_path:
                    # Original parent node must have been deleted
                    continue

            if node_parent_path != original_parent_path:
                if not original_parent_path:
                    cmds.parent(node_path, world=True)
                else:
                    cmds.parent(node_path, original_parent_path)

        if delete_parent:
            cmds.delete(parent_node_path)

polyConstraint(components, *args, **kwargs)

Return the list of components with the constraints applied.

A wrapper around Maya's polySelectConstraint to retrieve its results as a list without altering selections. For a list of possible constraints see maya.cmds.polySelectConstraint documentation.

Parameters:

Name Type Description Default
components list

List of components of polygon meshes

required

Returns:

Name Type Description
list

The list of components filtered by the given constraints.

Source code in client/ayon_maya/api/lib.py
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
def polyConstraint(components, *args, **kwargs):
    """Return the list of *components* with the constraints applied.

    A wrapper around Maya's `polySelectConstraint` to retrieve its results as
    a list without altering selections. For a list of possible constraints
    see `maya.cmds.polySelectConstraint` documentation.

    Arguments:
        components (list): List of components of polygon meshes

    Returns:
        list: The list of components filtered by the given constraints.

    """

    kwargs.pop('mode', None)

    with no_undo(flush=False):
        # Reverting selection to the original selection using
        # `maya.cmds.select` can be slow in rare cases where previously
        # `maya.cmds.polySelectConstraint` had set constrain to "All and Next"
        # and the "Random" setting was activated. To work around this we
        # revert to the original selection using the Maya API. This is safe
        # since we're not generating any undo change anyway.
        with tool("selectSuperContext"):
            # Selection can be very slow when in a manipulator mode.
            # So we force the selection context which is fast.
            with maintained_selection_api():
                # Apply constraint using mode=2 (current and next) so
                # it applies to the selection made before it; because just
                # a `maya.cmds.select()` call will not trigger the constraint.
                with reset_polySelectConstraint():
                    cmds.select(components, r=1, noExpand=True)
                    cmds.polySelectConstraint(*args, mode=2, **kwargs)
                    result = cmds.ls(selection=True)
                    cmds.select(clear=True)
                    return result

prompt_reset_context()

Prompt the user what context settings to reset. This prompt is used on saving to a different task to allow the scene to get matched to the new context.

Source code in client/ayon_maya/api/lib.py
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
def prompt_reset_context():
    """Prompt the user what context settings to reset.
    This prompt is used on saving to a different task to allow the scene to
    get matched to the new context.
    """
    # TODO: Cleanup this prototyped mess of imports and odd dialog
    from ayon_core.tools.attribute_defs.dialog import (
        AttributeDefinitionsDialog
    )
    from ayon_core.style import load_stylesheet
    from ayon_core.lib import BoolDef, UILabelDef

    definitions = [
        UILabelDef(
            label=(
                "You are saving your workfile into a different folder or task."
                "\n\n"
                "Would you like to update some settings to the new context?\n"
            )
        ),
        BoolDef(
            "fps",
            label="FPS",
            tooltip="Reset workfile FPS",
            default=True
        ),
        BoolDef(
            "frame_range",
            label="Frame Range",
            tooltip="Reset workfile start and end frame ranges",
            default=True
        ),
        BoolDef(
            "resolution",
            label="Resolution",
            tooltip="Reset workfile resolution",
            default=True
        ),
        BoolDef(
            "colorspace",
            label="Colorspace",
            tooltip="Reset workfile resolution",
            default=True
        ),
        BoolDef(
            "instances",
            label="Publish instances",
            tooltip="Update all publish instance's folder and task to match "
                    "the new folder and task",
            default=True
        ),
    ]

    dialog = AttributeDefinitionsDialog(definitions)
    dialog.setWindowTitle("Saving to different context.")
    dialog.setStyleSheet(load_stylesheet())
    if not dialog.exec_():
        return None

    options = dialog.get_values()
    with suspended_refresh():
        set_context_settings(
            fps=options["fps"],
            resolution=options["resolution"],
            frame_range=options["frame_range"],
            colorspace=options["colorspace"]
        )
        if options["instances"]:
            update_content_on_context_change()

    dialog.deleteLater()

read(node)

Return user-defined attributes from node

Source code in client/ayon_maya/api/lib.py
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
def read(node):
    """Return user-defined attributes from `node`"""

    data = dict()

    for attr in cmds.listAttr(node, userDefined=True) or list():
        try:
            value = cmds.getAttr(node + "." + attr, asString=True)

        except RuntimeError:
            # For Message type attribute or others that have connections,
            # take source node name as value.
            source = cmds.listConnections(node + "." + attr,
                                          source=True,
                                          destination=False)
            source = cmds.ls(source, long=True) or [None]
            value = source[0]

        except ValueError:
            # Some attributes cannot be read directly,
            # such as mesh and color attributes. These
            # are considered non-essential to this
            # particular publishing pipeline.
            value = None

        data[attr] = value

    return data

reload_all_udim_tile_previews()

Regenerate all UDIM tile preview in texture file

Source code in client/ayon_maya/api/lib.py
153
154
155
156
157
def reload_all_udim_tile_previews():
    """Regenerate all UDIM tile preview in texture file"""
    for texture_file in cmds.ls(type="file"):
        if cmds.getAttr("{}.uvTilingMode".format(texture_file)) > 0:
            cmds.ogs(regenerateUVTilePreview=texture_file)

remove_other_uv_sets(mesh)

Remove all other UV sets than the current UV set.

Keep only current UV set and ensure it's the renamed to default 'map1'.

Source code in client/ayon_maya/api/lib.py
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
def remove_other_uv_sets(mesh):
    """Remove all other UV sets than the current UV set.

    Keep only current UV set and ensure it's the renamed to default 'map1'.

    """

    uvSets = cmds.polyUVSet(mesh, query=True, allUVSets=True)
    current = cmds.polyUVSet(mesh, query=True, currentUVSet=True)[0]

    # Copy over to map1
    if current != 'map1':
        cmds.polyUVSet(mesh, uvSet=current, newUVSet='map1', copy=True)
        cmds.polyUVSet(mesh, currentUVSet=True, uvSet='map1')
        current = 'map1'

    # Delete all non-current UV sets
    deleteUVSets = [uvSet for uvSet in uvSets if uvSet != current]
    uvSet = None

    # Maya Bug (tested in 2015/2016):
    # In some cases the API's MFnMesh will report less UV sets than
    # maya.cmds.polyUVSet. This seems to happen when the deletion of UV sets
    # has not triggered a cleanup of the UVSet array attribute on the mesh
    # node. It will still have extra entries in the attribute, though it will
    # not show up in API or UI. Nevertheless it does show up in
    # maya.cmds.polyUVSet. To ensure we clean up the array we'll force delete
    # the extra remaining 'indices' that we don't want.

    # TODO: Implement a better fix
    # The best way to fix would be to get the UVSet indices from api with
    # MFnMesh (to ensure we keep correct ones) and then only force delete the
    # other entries in the array attribute on the node. But for now we're
    # deleting all entries except first one. Note that the first entry could
    # never be removed (the default 'map1' always exists and is supposed to
    # be undeletable.)
    try:
        for uvSet in deleteUVSets:
            cmds.polyUVSet(mesh, delete=True, uvSet=uvSet)
    except RuntimeError as exc:
        log.warning('Error uvSet: %s - %s', uvSet, exc)
        indices = cmds.getAttr('{0}.uvSet'.format(mesh),
                               multiIndices=True)
        if not indices:
            log.warning("No uv set found indices for: %s", mesh)
            return

        # Delete from end to avoid shifting indices
        # and remove the indices in the attribute
        indices = reversed(indices[1:])
        for i in indices:
            attr = '{0}.uvSet[{1}]'.format(mesh, i)
            cmds.removeMultiInstance(attr, b=True)

render_capture_preset(preset)

Capture playblast with a preset.

To generate the preset use generate_capture_preset.

Parameters:

Name Type Description Default
preset dict

preset options

required

Returns:

Name Type Description
str

Output path of capture.capture

Source code in client/ayon_maya/api/lib.py
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
def render_capture_preset(preset):
    """Capture playblast with a preset.

    To generate the preset use `generate_capture_preset`.

    Args:
        preset (dict): preset options

    Returns:
        str: Output path of `capture.capture`
    """

    # Force a refresh at the start of the timeline
    # TODO (Question): Why do we need to do this? What bug does it solve?
    #   Is this for simulations?
    cmds.refresh(force=True)
    refresh_frame_int = int(cmds.playbackOptions(query=True, minTime=True))
    cmds.currentTime(refresh_frame_int - 1, edit=True)
    cmds.currentTime(refresh_frame_int, edit=True)
    log.debug(
        "Using preset: {}".format(
            json.dumps(preset, indent=4, sort_keys=True)
        )
    )
    preset = copy.deepcopy(preset)
    # not supported by `capture` so we pop it off of the preset
    reload_textures = preset["viewport_options"].pop("loadTextures", False)
    panel = preset.pop("panel")
    with contextlib.ExitStack() as stack:
        stack.enter_context(maintained_time())
        stack.enter_context(panel_camera(panel, preset["camera"]))
        stack.enter_context(viewport_default_options(panel, preset))
        if reload_textures:
            # Force immediate texture loading when to ensure
            # all textures have loaded before the playblast starts
            stack.enter_context(material_loading_mode(mode="immediate"))
            # Regenerate all UDIM tiles previews
            reload_all_udim_tile_previews()
        path = capture.capture(log=self.log, **preset)

    return path

renderlayer(layer)

Set the renderlayer during the context

Parameters:

Name Type Description Default
layer str

Name of layer to switch to.

required
Source code in client/ayon_maya/api/lib.py
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
@contextlib.contextmanager
def renderlayer(layer):
    """Set the renderlayer during the context

    Arguments:
        layer (str): Name of layer to switch to.

    """

    original = cmds.editRenderLayerGlobals(query=True,
                                           currentRenderLayer=True)

    try:
        cmds.editRenderLayerGlobals(currentRenderLayer=layer)
        yield
    finally:
        cmds.editRenderLayerGlobals(currentRenderLayer=original)

reset_frame_range(playback=True, render=True, fps=True)

Set frame range to current folder.

Parameters:

Name Type Description Default
playback (bool, Optional)

Whether to set the maya timeline playback frame range. Defaults to True.

True
render (bool, Optional)

Whether to set the maya render frame range. Defaults to True.

True
fps (bool, Optional)

Whether to set scene FPS. Defaults to True.

True
Source code in client/ayon_maya/api/lib.py
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
def reset_frame_range(playback=True, render=True, fps=True):
    """Set frame range to current folder.

    Args:
        playback (bool, Optional): Whether to set the maya timeline playback
            frame range. Defaults to True.
        render (bool, Optional): Whether to set the maya render frame range.
            Defaults to True.
        fps (bool, Optional): Whether to set scene FPS. Defaults to True.
    """
    if fps:
        set_scene_fps(get_fps_for_current_context())

    frame_range = get_frame_range(include_animation_range=True)
    if not frame_range:
        # No frame range data found for folder
        return

    frame_start = frame_range["frameStart"]
    frame_end = frame_range["frameEnd"]
    animation_start = frame_range["animationStart"]
    animation_end = frame_range["animationEnd"]

    if playback:
        cmds.playbackOptions(
            minTime=frame_start,
            maxTime=frame_end,
            animationStartTime=animation_start,
            animationEndTime=animation_end
        )
        cmds.currentTime(frame_start)

    if render:
        cmds.setAttr("defaultRenderGlobals.startFrame", animation_start)
        cmds.setAttr("defaultRenderGlobals.endFrame", animation_end)

reset_polySelectConstraint(reset=True)

Context during which the given polyConstraint settings are disabled.

The original settings are restored after the context.

Source code in client/ayon_maya/api/lib.py
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
@contextlib.contextmanager
def reset_polySelectConstraint(reset=True):
    """Context during which the given polyConstraint settings are disabled.

    The original settings are restored after the context.

    """

    original = cmds.polySelectConstraint(query=True, stateString=True)

    try:
        if reset:
            # Ensure command is available in mel
            # This can happen when running standalone
            if not mel.eval("exists resetPolySelectConstraint"):
                mel.eval("source polygonConstraint")

            # Reset all parameters
            mel.eval("resetPolySelectConstraint;")
        cmds.polySelectConstraint(disable=True)
        yield
    finally:
        mel.eval(original)

reset_scene_resolution()

Apply the scene resolution from the project definition

The scene resolution will be retrieved from the current task entity's attributes.

Returns:

Type Description

None

Source code in client/ayon_maya/api/lib.py
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
def reset_scene_resolution():
    """Apply the scene resolution  from the project definition

    The scene resolution will be retrieved from the current task entity's
    attributes.

    Returns:
        None
    """

    task_attributes = get_current_task_entity(fields={"attrib"})["attrib"]

    # Set resolution
    width = task_attributes.get("resolutionWidth", 1920)
    height = task_attributes.get("resolutionHeight", 1080)
    pixel_aspect = task_attributes.get("pixelAspect", 1)

    set_scene_resolution(width, height, pixel_aspect)

search_textures(filepath)

Search all texture files on disk.

This also parses to full sequences for those with dynamic patterns like and %04d in the filename.

Parameters:

Name Type Description Default
filepath str

The full path to the file, including any dynamic patterns like or %04d

required

Returns:

Name Type Description
list

The files found on disk

Source code in client/ayon_maya/api/lib.py
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
def search_textures(filepath):
    """Search all texture files on disk.

    This also parses to full sequences for those with dynamic patterns
    like <UDIM> and %04d in the filename.

    Args:
        filepath (str): The full path to the file, including any
            dynamic patterns like <UDIM> or %04d

    Returns:
        list: The files found on disk

    """
    filename = os.path.basename(filepath)

    # Collect full sequence if it matches a sequence pattern
    # For UDIM based textures (tiles)
    if "<UDIM>" in filename:
        sequences = get_sequence(filepath,
                                 pattern="<UDIM>")
        if sequences:
            return sequences

    # Frame/time - Based textures (animated masks f.e)
    elif "%04d" in filename:
        sequences = get_sequence(filepath,
                                 pattern="%04d")
        if sequences:
            return sequences

    # Assuming it is a fixed name (single file)
    if os.path.exists(filepath):
        return [filepath]

    return []

set_attribute(attribute, value, node)

Adjust attributes based on the value from the attribute data

If an attribute does not exists on the target it will be added with the dataType being controlled by the value type.

Parameters:

Name Type Description Default
attribute str

name of the attribute to change

required
value

the value to change to attribute to

required
node str

name of the node

required

Returns:

Type Description

None

Source code in client/ayon_maya/api/lib.py
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
def set_attribute(attribute, value, node):
    """Adjust attributes based on the value from the attribute data

    If an attribute does not exists on the target it will be added with
    the dataType being controlled by the value type.

    Args:
        attribute (str): name of the attribute to change
        value: the value to change to attribute to
        node (str): name of the node

    Returns:
        None
    """

    value_type = type(value).__name__
    kwargs = ATTRIBUTE_DICT[value_type]
    if not cmds.attributeQuery(attribute, node=node, exists=True):
        log.debug("Creating attribute '{}' on "
                  "'{}'".format(attribute, node))
        cmds.addAttr(node, longName=attribute, **kwargs)

    node_attr = "{}.{}".format(node, attribute)
    enum_type = cmds.attributeQuery(attribute, node=node, enum=True)
    if enum_type and value_type == "str":
        enum_string_values = cmds.attributeQuery(
            attribute, node=node, listEnum=True
        )[0].split(":")
        cmds.setAttr(
            "{}.{}".format(node, attribute), enum_string_values.index(value)
        )
    elif "dataType" in kwargs:
        attr_type = kwargs["dataType"]
        cmds.setAttr(node_attr, value, type=attr_type)
    else:
        cmds.setAttr(node_attr, value)

set_colorspace()

Set Colorspace from project configuration

Source code in client/ayon_maya/api/lib.py
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
def set_colorspace():
    """Set Colorspace from project configuration"""

    project_name = get_current_project_name()
    imageio = get_project_settings(project_name)["maya"]["imageio"]

    if not imageio["workfile"]["enabled"]:
        log.info(
            "AYON Maya Color Management settings for workfile are disabled."
        )
        return

    # set color spaces for rendering space and view transforms
    def _colormanage(**kwargs):
        """Wrapper around `cmds.colorManagementPrefs`.

        This logs errors instead of raising an error so color management
        settings get applied as much as possible.

        """
        assert len(kwargs) == 1, "Must receive one keyword argument"
        try:
            cmds.colorManagementPrefs(edit=True, **kwargs)
            log.debug("Setting Color Management Preference: {}".format(kwargs))
        except RuntimeError as exc:
            log.error(exc)

    log.info("Setting Maya colorspace..")

    # enable color management
    cmds.colorManagementPrefs(edit=True, cmEnabled=True)
    cmds.colorManagementPrefs(edit=True, ocioRulesEnabled=True)

    is_ocio_set = bool(os.environ.get("OCIO"))
    if not is_ocio_set:
        # Set the Maya 2022+ default OCIO v2 config file path
        log.info("Setting default Maya OCIO v2 config")
        # Note: Setting "" as value also sets this default however
        # introduces a bug where launching a file on startup will prompt
        # to save the empty scene before it, so we set using the path.
        # This value has been the same for 2022, 2023 and 2024.
        path = "<MAYA_RESOURCES>/OCIO-configs/Maya2022-default/config.ocio"
        cmds.colorManagementPrefs(edit=True, configFilePath=path)

    # set rendering space and view transform
    _colormanage(renderingSpaceName=imageio["workfile"]["renderSpace"])
    _colormanage(viewName=imageio["workfile"]["viewName"])
    _colormanage(displayName=imageio["workfile"]["displayName"])

set_context_settings(fps=True, resolution=True, frame_range=True, colorspace=True)

Apply the project settings from the project definition

Settings can be overwritten by an asset if the asset.data contains any information regarding those settings.

Parameters:

Name Type Description Default
fps bool

Whether to set the scene FPS.

True
resolution bool

Whether to set the render resolution.

True
frame_range bool

Whether to reset the time slide frame ranges.

True
colorspace bool

Whether to reset the colorspace.

True

Returns:

Type Description

None

Source code in client/ayon_maya/api/lib.py
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
def set_context_settings(
        fps=True,
        resolution=True,
        frame_range=True,
        colorspace=True
):
    """Apply the project settings from the project definition

    Settings can be overwritten by an asset if the asset.data contains
    any information regarding those settings.

    Args:
        fps (bool): Whether to set the scene FPS.
        resolution (bool): Whether to set the render resolution.
        frame_range (bool): Whether to reset the time slide frame ranges.
        colorspace (bool): Whether to reset the colorspace.

    Returns:
        None

    """
    if fps:
        # Set project fps
        set_scene_fps(get_fps_for_current_context())

    if resolution:
        reset_scene_resolution()

    # Set frame range.
    if frame_range:
        reset_frame_range(fps=False)

    # Set colorspace
    if colorspace:
        set_colorspace()

set_id(node, unique_id, overwrite=False)

Add cbId to node unless one already exists.

Parameters:

Name Type Description Default
node str

the node to add the "cbId" on

required
unique_id str

The unique node id to assign. This should be generated by generate_ids.

required
overwrite bool

When True overrides the current value even if node already has an id. Defaults to False.

False

Returns:

Type Description

None

Source code in client/ayon_maya/api/lib.py
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
def set_id(node, unique_id, overwrite=False):
    """Add cbId to `node` unless one already exists.

    Args:
        node (str): the node to add the "cbId" on
        unique_id (str): The unique node id to assign.
            This should be generated by `generate_ids`.
        overwrite (bool, optional): When True overrides the current value even
            if `node` already has an id. Defaults to False.

    Returns:
        None

    """

    exists = cmds.attributeQuery("cbId", node=node, exists=True)

    # Add the attribute if it does not exist yet
    if not exists:
        cmds.addAttr(node, longName="cbId", dataType="string")

    # Set the value
    if not exists or overwrite:
        attr = "{0}.cbId".format(node)
        cmds.setAttr(attr, unique_id, type="string")

set_scene_fps(fps, update=True)

Set FPS from project configuration

Parameters:

Name Type Description Default
fps (int, float)

desired FPS

required
update(bool)

toggle update animation, default is True

required

Returns:

Type Description

None

Source code in client/ayon_maya/api/lib.py
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
def set_scene_fps(fps, update=True):
    """Set FPS from project configuration

    Args:
        fps (int, float): desired FPS
        update(bool): toggle update animation, default is True

    Returns:
        None

    """

    fps_mapping = {
        '2': '2fps',
        '3': '3fps',
        '4': '4fps',
        '5': '5fps',
        '6': '6fps',
        '8': '8fps',
        '10': '10fps',
        '12': '12fps',
        '15': 'game',
        '16': '16fps',
        '24': 'film',
        '25': 'pal',
        '30': 'ntsc',
        '48': 'show',
        '50': 'palf',
        '60': 'ntscf',
        '23.976023976023978': '23.976fps',
        '29.97002997002997': '29.97fps',
        '47.952047952047955': '47.952fps',
        '59.94005994005994': '59.94fps',
        '44100': '44100fps',
        '48000': '48000fps'
    }

    unit = fps_mapping.get(str(convert_to_maya_fps(fps)), None)
    if unit is None:
        raise ValueError("Unsupported FPS value: `%s`" % fps)

    # Get time slider current state
    start_frame = cmds.playbackOptions(query=True, minTime=True)
    end_frame = cmds.playbackOptions(query=True, maxTime=True)

    # Get animation data
    animation_start = cmds.playbackOptions(query=True, animationStartTime=True)
    animation_end = cmds.playbackOptions(query=True, animationEndTime=True)

    current_frame = cmds.currentTime(query=True)

    log.info("Setting scene FPS to: '{}'".format(unit))
    cmds.currentUnit(time=unit, updateAnimation=update)

    # Set time slider data back to previous state
    cmds.playbackOptions(minTime=start_frame,
                         maxTime=end_frame,
                         animationStartTime=animation_start,
                         animationEndTime=animation_end)

    cmds.currentTime(current_frame, edit=True, update=True)

    # Force file stated to 'modified'
    cmds.file(modified=True)

set_scene_resolution(width, height, pixelAspect)

Set the render resolution

Parameters:

Name Type Description Default
width(int)

value of the width

required
height(int)

value of the height

required

Returns:

Type Description

None

Source code in client/ayon_maya/api/lib.py
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
def set_scene_resolution(width, height, pixelAspect):
    """Set the render resolution

    Args:
        width(int): value of the width
        height(int): value of the height

    Returns:
        None

    """

    control_node = "defaultResolution"
    current_renderer = cmds.getAttr("defaultRenderGlobals.currentRenderer")
    aspect_ratio_attr = "deviceAspectRatio"

    # Give VRay a helping hand as it is slightly different from the rest
    if current_renderer == "vray":
        aspect_ratio_attr = "aspectRatio"
        vray_node = "vraySettings"
        if cmds.objExists(vray_node):
            control_node = vray_node
        else:
            log.error("Can't set VRay resolution because there is no node "
                      "named: `%s`" % vray_node)

    log.info("Setting scene resolution to: %s x %s" % (width, height))
    cmds.setAttr("%s.width" % control_node, width)
    cmds.setAttr("%s.height" % control_node, height)

    deviceAspectRatio = ((float(width) / float(height)) * float(pixelAspect))
    cmds.setAttr(
        "{}.{}".format(control_node, aspect_ratio_attr), deviceAspectRatio)
    cmds.setAttr("%s.pixelAspect" % control_node, pixelAspect)

shader(nodes, shadingEngine='initialShadingGroup')

Assign a shader to nodes during the context

Source code in client/ayon_maya/api/lib.py
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
@contextlib.contextmanager
def shader(nodes, shadingEngine="initialShadingGroup"):
    """Assign a shader to nodes during the context"""

    shapes = cmds.ls(nodes, dag=1, objectsOnly=1, shapes=1, long=1)
    original = get_shader_assignments_from_shapes(shapes)

    try:
        # Assign override shader
        if shapes:
            cmds.sets(shapes, edit=True, forceElement=shadingEngine)
        yield
    finally:

        # Assign original shaders
        for sg, members in original.items():
            if members:
                cmds.sets(members, edit=True, forceElement=sg)

strip_namespace(node, namespace)

Strip given namespace from node path.

The namespace will only be stripped from names if it starts with that namespace. If the namespace occurs within another namespace it's not removed.

Examples:

>>> strip_namespace("namespace:node", namespace="namespace:")
"node"
>>> strip_namespace("hello:world:node", namespace="hello:world")
"node"
>>> strip_namespace("hello:world:node", namespace="hello")
"world:node"
>>> strip_namespace("hello:world:node", namespace="world")
"hello:world:node"
>>> strip_namespace("ns:group|ns:node", namespace="ns")
"group|node"

Returns:

Name Type Description
str

Node name without given starting namespace.

Source code in client/ayon_maya/api/lib.py
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
def strip_namespace(node, namespace):
    """Strip given namespace from node path.

    The namespace will only be stripped from names
    if it starts with that namespace. If the namespace
    occurs within another namespace it's not removed.

    Examples:
        >>> strip_namespace("namespace:node", namespace="namespace:")
        "node"
        >>> strip_namespace("hello:world:node", namespace="hello:world")
        "node"
        >>> strip_namespace("hello:world:node", namespace="hello")
        "world:node"
        >>> strip_namespace("hello:world:node", namespace="world")
        "hello:world:node"
        >>> strip_namespace("ns:group|ns:node", namespace="ns")
        "group|node"

    Returns:
        str: Node name without given starting namespace.

    """

    # Ensure namespace ends with `:`
    if not namespace.endswith(":"):
        namespace = "{}:".format(namespace)

    # The long path for a node can also have the namespace
    # in its parents so we need to remove it from each
    return "|".join(
        name[len(namespace):] if name.startswith(namespace) else name
        for name in node.split("|")
    )

suspended_refresh(suspend=True)

Suspend viewport refreshes

cmds.ogs(pause=True) is a toggle so we can't pass False.

Source code in client/ayon_maya/api/lib.py
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
@contextlib.contextmanager
def suspended_refresh(suspend=True):
    """Suspend viewport refreshes

    cmds.ogs(pause=True) is a toggle so we can't pass False.
    """
    if IS_HEADLESS:
        yield
        return

    original_state = cmds.ogs(query=True, pause=True)
    try:
        if suspend and not original_state:
            cmds.ogs(pause=True)
        yield
    finally:
        if suspend and not original_state:
            cmds.ogs(pause=True)

tool(context)

Set a tool context during the context manager.

Source code in client/ayon_maya/api/lib.py
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
@contextlib.contextmanager
def tool(context):
    """Set a tool context during the context manager.

    """
    original = cmds.currentCtx()
    try:
        cmds.setToolTo(context)
        yield
    finally:
        cmds.setToolTo(original)

undo_chunk()

Open a undo chunk during context.

Source code in client/ayon_maya/api/lib.py
833
834
835
836
837
838
839
840
841
@contextlib.contextmanager
def undo_chunk():
    """Open a undo chunk during context."""

    try:
        cmds.undoInfo(openChunk=True)
        yield
    finally:
        cmds.undoInfo(closeChunk=True)

unique_namespace(namespace, format='%02d', prefix='', suffix='')

Return unique namespace

Parameters:

Name Type Description Default
namespace str

Name of namespace to consider

required
format str

Formatting of the given iteration number

'%02d'
suffix str

Only consider namespaces with this suffix.

''

unique_namespace("bar")

bar01

unique_namespace(":hello")

:hello01

unique_namespace("bar:", suffix="_NS")

bar01_NS:

Source code in client/ayon_maya/api/lib.py
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
def unique_namespace(namespace, format="%02d", prefix="", suffix=""):
    """Return unique namespace

    Arguments:
        namespace (str): Name of namespace to consider
        format (str, optional): Formatting of the given iteration number
        suffix (str, optional): Only consider namespaces with this suffix.

    >>> unique_namespace("bar")
    # bar01
    >>> unique_namespace(":hello")
    # :hello01
    >>> unique_namespace("bar:", suffix="_NS")
    # bar01_NS:

    """

    def current_namespace():
        current = cmds.namespaceInfo(currentNamespace=True,
                                     absoluteName=True)
        # When inside a namespace Maya adds no trailing :
        if not current.endswith(":"):
            current += ":"
        return current

    # Always check against the absolute namespace root
    # There's no clash with :x if we're defining namespace :a:x
    ROOT = ":" if namespace.startswith(":") else current_namespace()

    # Strip trailing `:` tokens since we might want to add a suffix
    start = ":" if namespace.startswith(":") else ""
    end = ":" if namespace.endswith(":") else ""
    namespace = namespace.strip(":")
    if ":" in namespace:
        # Split off any nesting that we don't uniqify anyway.
        parents, namespace = namespace.rsplit(":", 1)
        start += parents + ":"
        ROOT += start

    def exists(n):
        # Check for clash with nodes and namespaces
        fullpath = ROOT + n
        return cmds.objExists(fullpath) or cmds.namespace(exists=fullpath)

    iteration = 1
    while True:
        nr_namespace = namespace + format % iteration
        unique = prefix + nr_namespace + suffix

        if not exists(unique):
            return start + unique + end

        iteration += 1

update_content_on_context_change()

This will update scene content to match new folder on context change

Source code in client/ayon_maya/api/lib.py
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
def update_content_on_context_change():
    """
    This will update scene content to match new folder on context change
    """

    host = registered_host()
    create_context = CreateContext(host)
    task_entity = get_current_task_entity(fields={"attrib"})

    instance_values = {
        "folderPath": create_context.get_current_folder_path(),
        "task": create_context.get_current_task_name(),
    }
    creator_attribute_values = {
        "frameStart": float(task_entity["attrib"]["frameStart"]),
        "frameEnd": float(task_entity["attrib"]["frameEnd"]),
        "handleStart": float(task_entity["attrib"]["handleStart"]),
        "handleEnd": float(task_entity["attrib"]["handleEnd"]),
    }

    has_changes = False
    for instance in create_context.instances:
        for key, value in instance_values.items():
            if key not in instance or instance[key] == value:
                continue

            # Update instance value
            print(f"Updating {instance.product_name} {key} to: {value}")
            instance[key] = value
            has_changes = True

        creator_attributes = instance.creator_attributes
        for key, value in creator_attribute_values.items():
            if (
                    key not in creator_attributes
                    or creator_attributes[key] == value
            ):
                continue

            # Update instance creator attribute value
            print(f"Updating {instance.product_name} {key} to: {value}")
            creator_attributes[key] = value
            has_changes = True

    if has_changes:
        create_context.save_changes()

validate_fps()

Validate current scene FPS and show pop-up when it is incorrect

Returns:

Type Description

bool

Source code in client/ayon_maya/api/lib.py
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
def validate_fps():
    """Validate current scene FPS and show pop-up when it is incorrect

    Returns:
        bool

    """

    expected_fps = get_fps_for_current_context()
    current_fps = mel.eval("currentTimeUnitToFPS()")

    fps_match = current_fps == expected_fps
    if not fps_match and not IS_HEADLESS:
        from ayon_core.tools.utils import PopupUpdateKeys

        parent = get_main_window()

        dialog = PopupUpdateKeys(parent=parent)
        dialog.setModal(True)
        dialog.setWindowTitle("Maya scene does not match project FPS")
        dialog.set_message(
            "Scene {} FPS does not match project {} FPS".format(
                current_fps, expected_fps
            )
        )
        dialog.set_button_text("Fix")

        # Set new text for button (add optional argument for the popup?)
        def on_click(update):
            set_scene_fps(expected_fps, update)

        dialog.on_clicked_state.connect(on_click)
        dialog.show()

        return False

    return fps_match

viewport_default_options(panel, preset)

Context manager used by render_capture_preset.

We need to explicitly enable some viewport changes so the viewport is refreshed ahead of playblasting.

Source code in client/ayon_maya/api/lib.py
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
@contextlib.contextmanager
def viewport_default_options(panel, preset):
    """Context manager used by `render_capture_preset`.

    We need to explicitly enable some viewport changes so the viewport is
    refreshed ahead of playblasting.

    """
    # TODO: Clarify in the docstring WHY we need to set it ahead of
    #  playblasting. What issues does it solve?
    viewport_defaults = {}
    try:
        keys = [
            "useDefaultMaterial",
            "wireframeOnShaded",
            "xray",
            "jointXray",
            "backfaceCulling",
            "textures"
        ]
        for key in keys:
            viewport_defaults[key] = cmds.modelEditor(
                panel, query=True, **{key: True}
            )
            if preset["viewport_options"].get(key):
                cmds.modelEditor(
                    panel, edit=True, **{key: True}
                )
        yield
    finally:
        # Restoring viewport options.
        if viewport_defaults:
            cmds.modelEditor(
                panel, edit=True, **viewport_defaults
            )

write_xgen_file(data, filepath)

Overwrites data in .xgen files.

Quite naive approach to mainly overwrite "xgDataPath" and "xgProjectPath".

Parameters:

Name Type Description Default
data dict

Dictionary of key, value. Key matches with xgen file.

required
For example

{"xgDataPath": "some/path"}

required
filepath string

Absolute path of .xgen file.

required
Source code in client/ayon_maya/api/lib.py
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
def write_xgen_file(data, filepath):
    """Overwrites data in .xgen files.

    Quite naive approach to mainly overwrite "xgDataPath" and "xgProjectPath".

    Args:
        data (dict): Dictionary of key, value. Key matches with xgen file.
        For example:
            {"xgDataPath": "some/path"}
        filepath (string): Absolute path of .xgen file.
    """
    # Generate regex lookup for line to key basically
    # match any of the keys in `\t{key}\t\t`
    keys = "|".join(re.escape(key) for key in data.keys())
    re_keys = re.compile("^\t({})\t\t".format(keys))

    lines = []
    with open(filepath, "r") as f:
        for line in f:
            match = re_keys.match(line)
            if match:
                key = match.group(1)
                value = data[key]
                line = "\t{}\t\t{}\n".format(key, value)

            lines.append(line)

    with open(filepath, "w") as f:
        f.writelines(lines)