Skip to content

lib

DirmapCache

Caching class to get settings and sitesync easily and only once.

Source code in client/ayon_nuke/api/lib.py
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
class DirmapCache:
    """Caching class to get settings and sitesync easily and only once."""
    _project_name = None
    _project_settings = None
    _sitesync_addon_discovered = False
    _sitesync_addon = None
    _mapping = None

    @classmethod
    def project_name(cls):
        if cls._project_name is None:
            cls._project_name = os.getenv("AYON_PROJECT_NAME")
        return cls._project_name

    @classmethod
    def project_settings(cls):
        if cls._project_settings is None:
            cls._project_settings = get_project_settings(cls.project_name())
        return cls._project_settings

    @classmethod
    def sitesync_addon(cls):
        if not cls._sitesync_addon_discovered:
            cls._sitesync_addon_discovered = True
            cls._sitesync_addon = AddonsManager().get("sitesync")
        return cls._sitesync_addon

    @classmethod
    def mapping(cls):
        return cls._mapping

    @classmethod
    def set_mapping(cls, mapping):
        cls._mapping = mapping

Knobby

Bases: object

[DEPRECATED] For creating knob which it's type isn't mapped in create_knobs

Parameters:

Name Type Description Default
type string

Nuke knob type name

required
value

Value to be set with Knob.setValue, put None if not required

required
flags list

Knob flags to be set with Knob.setFlag

None
*args

Args other than knob name for initializing knob class

()
Source code in client/ayon_nuke/api/lib.py
219
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
class Knobby(object):
    """[DEPRECATED] For creating knob which it's type isn't
                    mapped in `create_knobs`

    Args:
        type (string): Nuke knob type name
        value: Value to be set with `Knob.setValue`, put `None` if not required
        flags (list, optional): Knob flags to be set with `Knob.setFlag`
        *args: Args other than knob name for initializing knob class

    """

    def __init__(self, type, value, flags=None, *args):
        self.type = type
        self.value = value
        self.flags = flags or []
        self.args = args

    def create(self, name, nice=None):
        knob_cls = getattr(nuke, self.type)
        knob = knob_cls(name, nice, *self.args)
        if self.value is not None:
            knob.setValue(self.value)
        for flag in self.flags:
            knob.setFlag(flag)
        return knob

    @staticmethod
    def nice_naming(key):
        """Convert camelCase name into UI Display Name"""
        words = re.findall('[A-Z][^A-Z]*', key[0].upper() + key[1:])
        return " ".join(words)

nice_naming(key) staticmethod

Convert camelCase name into UI Display Name

Source code in client/ayon_nuke/api/lib.py
246
247
248
249
250
@staticmethod
def nice_naming(key):
    """Convert camelCase name into UI Display Name"""
    words = re.findall('[A-Z][^A-Z]*', key[0].upper() + key[1:])
    return " ".join(words)

NukeDirmap

Bases: HostDirmap

Source code in client/ayon_nuke/api/lib.py
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
class NukeDirmap(HostDirmap):
    def __init__(self, file_name, *args, **kwargs):
        """
        Args:
            file_name (str): full path of referenced file from workfiles
            *args (tuple): Positional arguments for 'HostDirmap' class
            **kwargs (dict): Keyword arguments for 'HostDirmap' class
        """

        self.file_name = file_name
        super(NukeDirmap, self).__init__(*args, **kwargs)

    def on_enable_dirmap(self):
        pass

    def dirmap_routine(self, source_path, destination_path):
        source_path = source_path.lower().replace(os.sep, '/')
        destination_path = destination_path.lower().replace(os.sep, '/')
        if platform.system().lower() == "windows":
            self.file_name = self.file_name.lower().replace(
                source_path, destination_path)
        else:
            self.file_name = self.file_name.replace(
                source_path, destination_path)

__init__(file_name, *args, **kwargs)

Parameters:

Name Type Description Default
file_name str

full path of referenced file from workfiles

required
*args tuple

Positional arguments for 'HostDirmap' class

()
**kwargs dict

Keyword arguments for 'HostDirmap' class

{}
Source code in client/ayon_nuke/api/lib.py
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
def __init__(self, file_name, *args, **kwargs):
    """
    Args:
        file_name (str): full path of referenced file from workfiles
        *args (tuple): Positional arguments for 'HostDirmap' class
        **kwargs (dict): Keyword arguments for 'HostDirmap' class
    """

    self.file_name = file_name
    super(NukeDirmap, self).__init__(*args, **kwargs)

WorkfileSettings

Bases: object

All settings for workfile will be set

This object is setting all possible root settings to the workfile. Including Colorspace, Frame ranges, Resolution format. It can set it to Root node or to any given node.

Parameters:

Name Type Description Default
root node

nuke's root node

required
nodes list

list of nuke's nodes

None
nodes_filter list

filtering classes for nodes

required
Source code in client/ayon_nuke/api/lib.py
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
1536
1537
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
1564
1565
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
1613
1614
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
1640
1641
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
1705
1706
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
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
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
1801
1802
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
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
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
1920
1921
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
1988
1989
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
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
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
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
class WorkfileSettings(object):
    """
    All settings for workfile will be set

    This object is setting all possible root settings to the workfile.
    Including Colorspace, Frame ranges, Resolution format. It can set it
    to Root node or to any given node.

    Arguments:
        root (node): nuke's root node
        nodes (list): list of nuke's nodes
        nodes_filter (list): filtering classes for nodes

    """

    def __init__(self, root_node=None, nodes=None, **kwargs):
        project_entity = kwargs.get("project")
        if project_entity is None:
            project_name = get_current_project_name()
            project_entity = ayon_api.get_project(project_name)
        else:
            project_name = project_entity["name"]

        Context._project_entity = project_entity
        self._project_name = project_name
        self._folder_path = get_current_folder_path()
        self._folder_entity = ayon_api.get_folder_by_path(
            project_name, self._folder_path
        )
        self._task_name = get_current_task_name()
        self._context_label = "{} > {}".format(self._folder_path,
                                               self._task_name)
        self._task_entity = ayon_api.get_task_by_name(
            project_name,
            self._folder_entity["id"],
            self._task_name
        )
        self._root_node = root_node or nuke.root()
        self._nodes = self.get_nodes(nodes=nodes)

        context_data = get_template_data_with_names(
            project_name, self._folder_path, self._task_name, "nuke"
        )
        self.formatting_data = context_data

    def get_nodes(self, nodes=None, nodes_filter=None):

        if not isinstance(nodes, list) and not isinstance(nodes_filter, list):
            return [n for n in nuke.allNodes()]
        elif not isinstance(nodes, list) and isinstance(nodes_filter, list):
            nodes = list()
            for filter in nodes_filter:
                [nodes.append(n) for n in nuke.allNodes(filter=filter)]
            return nodes
        elif isinstance(nodes, list) and not isinstance(nodes_filter, list):
            return [n for n in self._nodes]
        elif isinstance(nodes, list) and isinstance(nodes_filter, list):
            for filter in nodes_filter:
                return [n for n in self._nodes if filter in n.Class()]

    # TODO: move into ./colorspace.py
    def set_viewers_colorspace(self, imageio_nuke):
        ''' Adds correct colorspace to viewer

        Arguments:
            imageio_nuke (dict): nuke colorspace configurations

        '''
        filter_knobs = [
            "viewerProcess",
            "wipe_position",
            "monitorOutOutputTransform"
        ]
        viewer_process = get_formatted_display_and_view(
            imageio_nuke["viewer"], self.formatting_data, self._root_node
        )
        output_transform = get_formatted_display_and_view(
            imageio_nuke["monitor"], self.formatting_data, self._root_node
        )
        erased_viewers = []
        for v in nuke.allNodes(filter="Viewer"):
            # set viewProcess to preset from settings
            v["viewerProcess"].setValue(viewer_process)

            if viewer_process not in v["viewerProcess"].value():
                copy_inputs = v.dependencies()
                copy_knobs = {
                    k: v[k].value() for k in v.knobs()
                    if k not in filter_knobs
                }

                # delete viewer with wrong settings
                erased_viewers.append(v["name"].value())
                nuke.delete(v)

                # create new viewer
                nv = nuke.createNode("Viewer")

                # connect to original inputs
                for i, n in enumerate(copy_inputs):
                    nv.setInput(i, n)

                # set copied knobs
                for knob_name, knob_value in copy_knobs.items():
                    nv[knob_name].setValue(knob_value)

                # set viewerProcess
                nv["viewerProcess"].setValue(viewer_process)
                nv["monitorOutOutputTransform"].setValue(output_transform)

        if erased_viewers:
            log.warning(
                "Attention! Viewer nodes {} were erased."
                "It had wrong color profile".format(erased_viewers))

    # TODO: move into ./colorspace.py
    def set_root_colorspace(self, imageio_host):
        ''' Adds correct colorspace to root

        Arguments:
            imageio_host (dict): host colorspace configurations

        '''
        config_data = get_current_context_imageio_config_preset()

        workfile_settings = imageio_host["workfile"]
        color_management = workfile_settings["color_management"]
        native_ocio_config = workfile_settings["native_ocio_config"]

        if not config_data:
            # no ocio config found and no custom path used
            if self._root_node["colorManagement"].value() \
                        not in color_management:
                self._root_node["colorManagement"].setValue(color_management)

            # second set ocio version
            if self._root_node["OCIO_config"].value() \
                        not in native_ocio_config:
                self._root_node["OCIO_config"].setValue(native_ocio_config)

        else:
            # OCIO config path is defined from prelaunch hook
            self._root_node["colorManagement"].setValue("OCIO")

            # print previous settings in case some were found in workfile
            residual_path = self._root_node["customOCIOConfigPath"].value()
            if residual_path:
                log.info("Residual OCIO config path found: `{}`".format(
                    residual_path
                ))

        # set ocio config path
        if config_data:
            config_path = config_data["path"].replace("\\", "/")
            log.info("OCIO config path found: `{}`".format(
                config_path))

            # check if there's a mismatch between environment and settings
            correct_settings = self._is_settings_matching_environment(
                config_data)

            # if there's no mismatch between environment and settings
            if correct_settings:
                self._set_ocio_config_path_to_workfile(config_data)

        workfile_settings_output = {}
        # get monitor lut from settings respecting Nuke version differences
        monitor_lut_data = self._get_monitor_settings(
            workfile_settings["monitor_out_lut"],
            workfile_settings["monitor_lut"]
        )
        workfile_settings_output.update(monitor_lut_data)
        workfile_settings_output.update(
            {
                "workingSpaceLUT": workfile_settings["working_space"],
                "int8Lut": workfile_settings["int_8_lut"],
                "int16Lut": workfile_settings["int_16_lut"],
                "logLut": workfile_settings["log_lut"],
                "floatLut": workfile_settings["float_lut"],
            }
        )

        # then set the rest
        for knob, value_ in workfile_settings_output.items():
            # skip unfilled ocio config path
            # it will be dict in value
            if isinstance(value_, dict):
                continue
            # skip empty values
            if not value_:
                continue
            self._root_node[knob].setValue(str(value_))

    def _get_monitor_settings(self, viewer_lut, monitor_lut):
        """ Get monitor settings from viewer and monitor lut

        Args:
            viewer_lut (str): viewer lut string
            monitor_lut (str): monitor lut string

        Returns:
            dict: monitor settings
        """
        output_data = {}
        m_display, m_viewer = get_viewer_config_from_string(monitor_lut)
        v_display, v_viewer = get_viewer_config_from_string(viewer_lut)

        # set monitor lut differently for nuke version 14
        if nuke.NUKE_VERSION_MAJOR >= 14:
            output_data["monitorOutLUT"] = create_viewer_profile_string(
                m_viewer, m_display, path_like=False)
            # monitorLut=thumbnails - viewerProcess makes more sense
            output_data["monitorLut"] = create_viewer_profile_string(
                v_viewer, v_display, path_like=False)

        if nuke.NUKE_VERSION_MAJOR == 13:
            output_data["monitorOutLUT"] = create_viewer_profile_string(
                m_viewer, m_display, path_like=False)
            # monitorLut=thumbnails - viewerProcess makes more sense
            output_data["monitorLut"] = create_viewer_profile_string(
                v_viewer, v_display, path_like=True)
        if nuke.NUKE_VERSION_MAJOR <= 12:
            output_data["monitorLut"] = create_viewer_profile_string(
                m_viewer, m_display, path_like=True)

        return output_data

    def _is_settings_matching_environment(self, config_data):
        """ Check if OCIO config path is different from environment

        Args:
            config_data (dict): OCIO config data from settings

        Returns:
            bool: True if settings are matching environment, False otherwise
        """
        current_ocio_path = os.environ["OCIO"]
        settings_ocio_path = config_data["path"]

        # normalize all paths to forward slashes
        current_ocio_path = current_ocio_path.replace("\\", "/")
        settings_ocio_path = settings_ocio_path.replace("\\", "/")

        if current_ocio_path != settings_ocio_path:
            message = """
It seems like there's a mismatch between the OCIO config path set in your Nuke
settings and the actual path set in your OCIO environment.

To resolve this, please follow these steps:
1. Close Nuke if it's currently open.
2. Reopen Nuke.

Please note the paths for your reference:

- The OCIO environment path currently set:
  `{env_path}`

- The path in your current Nuke settings:
  `{settings_path}`

Reopening Nuke should synchronize these paths and resolve any discrepancies.
"""
            nuke.message(
                message.format(
                    env_path=current_ocio_path,
                    settings_path=settings_ocio_path
                )
            )
            return False

        return True

    def _set_ocio_config_path_to_workfile(self, config_data):
        """ Set OCIO config path to workfile

        Path set into nuke workfile. It is trying to replace path with
        environment variable if possible. If not, it will set it as it is.
        It also saves the script to apply the change, but only if it's not
        empty Untitled script.

        Args:
            config_data (dict): OCIO config data from settings

        """
        # replace path with env var if possible
        ocio_path = self._replace_ocio_path_with_env_var(config_data)

        log.info("Setting OCIO config path to: `{}`".format(
            ocio_path))

        self._root_node["customOCIOConfigPath"].setValue(
            ocio_path
        )
        self._root_node["OCIO_config"].setValue("custom")

        # only save script if it's not empty
        if self._root_node["name"].value() != "":
            log.info("Saving script to apply OCIO config path change.")
            nuke.scriptSave()

    def _get_included_vars(self, config_template):
        """ Get all environment variables included in template

        Args:
            config_template (str): OCIO config template from settings

        Returns:
            list: list of environment variables included in template
        """
        # resolve all environments for whitelist variables
        included_vars = [
            "BUILTIN_OCIO_ROOT",
        ]

        # include all project root related env vars
        for env_var in os.environ:
            if env_var.startswith("AYON_PROJECT_ROOT_"):
                included_vars.append(env_var)

        # use regex to find env var in template with format {ENV_VAR}
        # this way we make sure only template used env vars are included
        env_var_regex = r"\{([A-Z0-9_]+)\}"
        env_var = re.findall(env_var_regex, config_template)
        if env_var:
            included_vars.append(env_var[0])

        return included_vars

    def _replace_ocio_path_with_env_var(self, config_data):
        """ Replace OCIO config path with environment variable

        Environment variable is added as TCL expression to path. TCL expression
        is also replacing backward slashes found in path for windows
        formatted values.

        Args:
            config_data (str): OCIO config dict from settings

        Returns:
            str: OCIO config path with environment variable TCL expression
        """
        config_path = config_data["path"].replace("\\", "/")
        config_template = config_data["template"]

        included_vars = self._get_included_vars(config_template)

        # make sure we return original path if no env var is included
        new_path = config_path

        for env_var in included_vars:
            env_path = os.getenv(env_var)
            if not env_path:
                continue

            # it has to be directory current process can see
            if not os.path.isdir(env_path):
                continue

            # make sure paths are in same format
            env_path = env_path.replace("\\", "/")
            path = config_path.replace("\\", "/")

            # check if env_path is in path and replace to first found positive
            if env_path in path:
                # with regsub we make sure path format of slashes is correct
                resub_expr = (
                    "[regsub -all {{\\\\}} [getenv {}] \"/\"]").format(env_var)

                new_path = path.replace(
                    env_path, resub_expr
                )
                break

        return new_path

    # TODO: move into ./colorspace.py
    def set_writes_colorspace(self):
        ''' Adds correct colorspace to write node dict

        '''
        for node in nuke.allNodes(filter="Group", group=self._root_node):
            log.info("Setting colorspace to `{}`".format(node.name()))

            # get data from avalon knob
            avalon_knob_data = read_avalon_data(node)
            node_data = get_node_data(node, INSTANCE_DATA_KNOB)

            if (
                # backward compatibility
                # TODO: remove this once old avalon data api will be removed
                avalon_knob_data
                and avalon_knob_data.get("id") not in {
                    AYON_INSTANCE_ID, AVALON_INSTANCE_ID
                }
            ):
                continue
            elif (
                node_data
                and node_data.get("id") not in {
                    AYON_INSTANCE_ID, AVALON_INSTANCE_ID
                }
            ):
                continue

            if (
                # backward compatibility
                # TODO: remove this once old avalon data api will be removed
                avalon_knob_data
                and "creator" not in avalon_knob_data
            ):
                continue
            elif (
                node_data
                and "creator_identifier" not in node_data
            ):
                continue

            nuke_imageio_writes = None
            if avalon_knob_data:
                # establish families
                product_type = avalon_knob_data.get("productType")
                if product_type is None:
                    product_type = avalon_knob_data["family"]
                families = [product_type]
                if avalon_knob_data.get("families"):
                    families.append(avalon_knob_data.get("families"))

                nuke_imageio_writes = get_imageio_node_setting(
                    node_class=avalon_knob_data["families"],
                    plugin_name=avalon_knob_data["creator"],
                    product_name=avalon_knob_data["productName"]
                )
            elif node_data:
                nuke_imageio_writes = get_write_node_template_attr(node)

            if not nuke_imageio_writes:
                return

            write_node = None

            # get into the group node
            node.begin()
            for x in nuke.allNodes():
                if x.Class() == "Write":
                    write_node = x
            node.end()

            if not write_node:
                return

            set_node_knobs_from_settings(
                write_node, nuke_imageio_writes["knobs"])

    # TODO: move into ./colorspace.py
    def set_reads_colorspace(self, read_clrs_inputs):
        """ Setting colorspace to Read nodes

        Looping through all read nodes and tries to set colorspace based
        on regex rules in presets
        """
        changes = {}
        for n in nuke.allNodes():
            file = nuke.filename(n)
            if n.Class() != "Read":
                continue

            # check if any colorspace presets for read is matching
            preset_clrsp = None

            for input in read_clrs_inputs:
                if not bool(re.search(input["regex"], file)):
                    continue
                preset_clrsp = input["colorspace"]

            if preset_clrsp is not None:
                current = n["colorspace"].value()
                future = str(preset_clrsp)
                if current != future:
                    changes[n.name()] = {
                        "from": current,
                        "to": future
                    }

        if changes:
            msg = "Read nodes are not set to correct colorspace:\n\n"
            for nname, knobs in changes.items():
                msg += (
                    " - node: '{0}' is now '{1}' but should be '{2}'\n"
                ).format(nname, knobs["from"], knobs["to"])

            msg += "\nWould you like to change it?"

            if nuke.ask(msg):
                for nname, knobs in changes.items():
                    n = nuke.toNode(nname)
                    n["colorspace"].setValue(knobs["to"])
                    log.info(
                        "Setting `{0}` to `{1}`".format(
                            nname,
                            knobs["to"]))

    # TODO: move into ./colorspace.py
    def set_colorspace(self):
        ''' Setting colorspace following presets
        '''
        # get imageio
        nuke_colorspace = get_nuke_imageio_settings()

        log.info("Setting colorspace to workfile...")
        try:
            self.set_root_colorspace(nuke_colorspace)
        except AttributeError as _error:
            msg = "Set Colorspace to workfile error: {}".format(_error)
            nuke.message(msg)

        log.info("Setting colorspace to viewers...")
        try:
            self.set_viewers_colorspace(nuke_colorspace)
        except AttributeError as _error:
            msg = "Set Colorspace to viewer error: {}".format(_error)
            nuke.message(msg)

        log.info("Setting colorspace to write nodes...")
        try:
            self.set_writes_colorspace()
        except AttributeError as _error:
            nuke.message(_error)
            log.error(_error)

        log.info("Setting colorspace to read nodes...")
        read_clrs_inputs = nuke_colorspace["regex_inputs"].get("inputs", [])
        if read_clrs_inputs:
            self.set_reads_colorspace(read_clrs_inputs)

    def reset_frame_range_handles(self):
        """Set frame range to current folder."""

        if "attrib" not in self._task_entity:
            msg = "Task {} doesn't have set any 'attrib'".format(
                self._context_label
            )
            log.warning(msg)
            nuke.message(msg)
            return

        task_attributes = self._task_entity["attrib"]

        missing_cols = []
        check_cols = ["fps", "frameStart", "frameEnd",
                      "handleStart", "handleEnd"]

        for col in check_cols:
            if col not in task_attributes:
                missing_cols.append(col)

        if len(missing_cols) > 0:
            missing = ", ".join(missing_cols)
            msg = "'{}' are not set for task '{}'!".format(
                missing, self._context_label)
            log.warning(msg)
            nuke.message(msg)
            return

        # get handles values
        handle_start = task_attributes["handleStart"]
        handle_end = task_attributes["handleEnd"]
        frame_start = task_attributes["frameStart"]
        frame_end = task_attributes["frameEnd"]

        fps = float(task_attributes["fps"])
        frame_start_handle = frame_start - handle_start
        frame_end_handle = frame_end + handle_end

        self._root_node["lock_range"].setValue(False)
        self._root_node["fps"].setValue(fps)
        self._root_node["first_frame"].setValue(frame_start_handle)
        self._root_node["last_frame"].setValue(frame_end_handle)
        self._root_node["lock_range"].setValue(True)

        # update node graph so knobs are updated
        update_node_graph()

        frame_range = '{0}-{1}'.format(frame_start, frame_end)

        for node in nuke.allNodes(filter="Viewer"):
            node['frame_range'].setValue(frame_range)
            node['frame_range_lock'].setValue(True)
            node['frame_range'].setValue(frame_range)
            node['frame_range_lock'].setValue(True)

        if not ASSIST:
            set_node_data(
                self._root_node,
                INSTANCE_DATA_KNOB,
                {
                    "handleStart": int(handle_start),
                    "handleEnd": int(handle_end)
                }
            )
        else:
            log.warning(
                "NukeAssist mode is not allowing "
                "updating custom knobs..."
            )

    def reset_resolution(self):
        """Set resolution to project resolution."""
        log.info("Resetting resolution")
        project_name = get_current_project_name()
        task_attributes = self._task_entity["attrib"]

        format_data = {
            "width": task_attributes["resolutionWidth"],
            "height": task_attributes["resolutionHeight"],
            "pixel_aspect": task_attributes["pixelAspect"],
            "name": project_name
        }

        if any(x_ for x_ in format_data.values() if x_ is None):
            msg = ("Missing set shot attributes in DB."
                   "\nContact your supervisor!."
                   "\n\nWidth: `{width}`"
                   "\nHeight: `{height}`"
                   "\nPixel Aspect: `{pixel_aspect}`").format(**format_data)
            log.error(msg)
            nuke.message(msg)

        existing_format = None
        for format in nuke.formats():
            if format_data["name"] == format.name():
                existing_format = format
                break

        if existing_format:
            # Enforce existing format to be correct.
            existing_format.setWidth(format_data["width"])
            existing_format.setHeight(format_data["height"])
            existing_format.setPixelAspect(format_data["pixel_aspect"])
        else:
            format_string = self.make_format_string(**format_data)
            log.info("Creating new format: {}".format(format_string))
            nuke.addFormat(format_string)

        nuke.root()["format"].setValue(format_data["name"])
        log.info("Format is set.")

        # update node graph so knobs are updated
        update_node_graph()

    def make_format_string(self, **kwargs):
        if kwargs.get("r"):
            return (
                "{width} "
                "{height} "
                "{x} "
                "{y} "
                "{r} "
                "{t} "
                "{pixel_aspect:.2f} "
                "{name}".format(**kwargs)
            )
        else:
            return (
                "{width} "
                "{height} "
                "{pixel_aspect:.2f} "
                "{name}".format(**kwargs)
            )

    def set_context_settings(self):
        # replace reset resolution from avalon core to pype's
        self.reset_resolution()
        # replace reset resolution from avalon core to pype's
        self.reset_frame_range_handles()
        # add colorspace menu item
        self.set_colorspace()

    def set_favorites(self):
        from .utils import set_context_favorites

        work_dir = os.getenv("AYON_WORKDIR")
        # TODO validate functionality
        # - does expect the structure is '{root}/{project}/{folder}'
        # - this used asset name expecting it is unique in project
        folder_path = get_current_folder_path()
        folder_name = folder_path.split("/")[-1]
        favorite_items = OrderedDict()

        # project
        # get project's root and split to parts
        projects_root = os.path.normpath(work_dir.split(
            Context.project_name)[0])
        # add project name
        project_dir = os.path.join(projects_root, Context.project_name) + "/"
        # add to favorites
        favorite_items.update({"Project dir": project_dir.replace("\\", "/")})

        # folder
        folder_root = os.path.normpath(work_dir.split(
            folder_name)[0])
        # add folder name
        folder_dir = os.path.join(folder_root, folder_name) + "/"
        # add to favorites
        favorite_items.update({"Shot dir": folder_dir.replace("\\", "/")})

        # workdir
        favorite_items.update({"Work dir": work_dir.replace("\\", "/")})

        set_context_favorites(favorite_items)

reset_frame_range_handles()

Set frame range to current folder.

Source code in client/ayon_nuke/api/lib.py
1984
1985
1986
1987
1988
1989
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
def reset_frame_range_handles(self):
    """Set frame range to current folder."""

    if "attrib" not in self._task_entity:
        msg = "Task {} doesn't have set any 'attrib'".format(
            self._context_label
        )
        log.warning(msg)
        nuke.message(msg)
        return

    task_attributes = self._task_entity["attrib"]

    missing_cols = []
    check_cols = ["fps", "frameStart", "frameEnd",
                  "handleStart", "handleEnd"]

    for col in check_cols:
        if col not in task_attributes:
            missing_cols.append(col)

    if len(missing_cols) > 0:
        missing = ", ".join(missing_cols)
        msg = "'{}' are not set for task '{}'!".format(
            missing, self._context_label)
        log.warning(msg)
        nuke.message(msg)
        return

    # get handles values
    handle_start = task_attributes["handleStart"]
    handle_end = task_attributes["handleEnd"]
    frame_start = task_attributes["frameStart"]
    frame_end = task_attributes["frameEnd"]

    fps = float(task_attributes["fps"])
    frame_start_handle = frame_start - handle_start
    frame_end_handle = frame_end + handle_end

    self._root_node["lock_range"].setValue(False)
    self._root_node["fps"].setValue(fps)
    self._root_node["first_frame"].setValue(frame_start_handle)
    self._root_node["last_frame"].setValue(frame_end_handle)
    self._root_node["lock_range"].setValue(True)

    # update node graph so knobs are updated
    update_node_graph()

    frame_range = '{0}-{1}'.format(frame_start, frame_end)

    for node in nuke.allNodes(filter="Viewer"):
        node['frame_range'].setValue(frame_range)
        node['frame_range_lock'].setValue(True)
        node['frame_range'].setValue(frame_range)
        node['frame_range_lock'].setValue(True)

    if not ASSIST:
        set_node_data(
            self._root_node,
            INSTANCE_DATA_KNOB,
            {
                "handleStart": int(handle_start),
                "handleEnd": int(handle_end)
            }
        )
    else:
        log.warning(
            "NukeAssist mode is not allowing "
            "updating custom knobs..."
        )

reset_resolution()

Set resolution to project resolution.

Source code in client/ayon_nuke/api/lib.py
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
def reset_resolution(self):
    """Set resolution to project resolution."""
    log.info("Resetting resolution")
    project_name = get_current_project_name()
    task_attributes = self._task_entity["attrib"]

    format_data = {
        "width": task_attributes["resolutionWidth"],
        "height": task_attributes["resolutionHeight"],
        "pixel_aspect": task_attributes["pixelAspect"],
        "name": project_name
    }

    if any(x_ for x_ in format_data.values() if x_ is None):
        msg = ("Missing set shot attributes in DB."
               "\nContact your supervisor!."
               "\n\nWidth: `{width}`"
               "\nHeight: `{height}`"
               "\nPixel Aspect: `{pixel_aspect}`").format(**format_data)
        log.error(msg)
        nuke.message(msg)

    existing_format = None
    for format in nuke.formats():
        if format_data["name"] == format.name():
            existing_format = format
            break

    if existing_format:
        # Enforce existing format to be correct.
        existing_format.setWidth(format_data["width"])
        existing_format.setHeight(format_data["height"])
        existing_format.setPixelAspect(format_data["pixel_aspect"])
    else:
        format_string = self.make_format_string(**format_data)
        log.info("Creating new format: {}".format(format_string))
        nuke.addFormat(format_string)

    nuke.root()["format"].setValue(format_data["name"])
    log.info("Format is set.")

    # update node graph so knobs are updated
    update_node_graph()

set_colorspace()

Setting colorspace following presets

Source code in client/ayon_nuke/api/lib.py
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
def set_colorspace(self):
    ''' Setting colorspace following presets
    '''
    # get imageio
    nuke_colorspace = get_nuke_imageio_settings()

    log.info("Setting colorspace to workfile...")
    try:
        self.set_root_colorspace(nuke_colorspace)
    except AttributeError as _error:
        msg = "Set Colorspace to workfile error: {}".format(_error)
        nuke.message(msg)

    log.info("Setting colorspace to viewers...")
    try:
        self.set_viewers_colorspace(nuke_colorspace)
    except AttributeError as _error:
        msg = "Set Colorspace to viewer error: {}".format(_error)
        nuke.message(msg)

    log.info("Setting colorspace to write nodes...")
    try:
        self.set_writes_colorspace()
    except AttributeError as _error:
        nuke.message(_error)
        log.error(_error)

    log.info("Setting colorspace to read nodes...")
    read_clrs_inputs = nuke_colorspace["regex_inputs"].get("inputs", [])
    if read_clrs_inputs:
        self.set_reads_colorspace(read_clrs_inputs)

set_reads_colorspace(read_clrs_inputs)

Setting colorspace to Read nodes

Looping through all read nodes and tries to set colorspace based on regex rules in presets

Source code in client/ayon_nuke/api/lib.py
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
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
def set_reads_colorspace(self, read_clrs_inputs):
    """ Setting colorspace to Read nodes

    Looping through all read nodes and tries to set colorspace based
    on regex rules in presets
    """
    changes = {}
    for n in nuke.allNodes():
        file = nuke.filename(n)
        if n.Class() != "Read":
            continue

        # check if any colorspace presets for read is matching
        preset_clrsp = None

        for input in read_clrs_inputs:
            if not bool(re.search(input["regex"], file)):
                continue
            preset_clrsp = input["colorspace"]

        if preset_clrsp is not None:
            current = n["colorspace"].value()
            future = str(preset_clrsp)
            if current != future:
                changes[n.name()] = {
                    "from": current,
                    "to": future
                }

    if changes:
        msg = "Read nodes are not set to correct colorspace:\n\n"
        for nname, knobs in changes.items():
            msg += (
                " - node: '{0}' is now '{1}' but should be '{2}'\n"
            ).format(nname, knobs["from"], knobs["to"])

        msg += "\nWould you like to change it?"

        if nuke.ask(msg):
            for nname, knobs in changes.items():
                n = nuke.toNode(nname)
                n["colorspace"].setValue(knobs["to"])
                log.info(
                    "Setting `{0}` to `{1}`".format(
                        nname,
                        knobs["to"]))

set_root_colorspace(imageio_host)

Adds correct colorspace to root

Parameters:

Name Type Description Default
imageio_host dict

host colorspace configurations

required
Source code in client/ayon_nuke/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
1613
1614
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
1640
1641
def set_root_colorspace(self, imageio_host):
    ''' Adds correct colorspace to root

    Arguments:
        imageio_host (dict): host colorspace configurations

    '''
    config_data = get_current_context_imageio_config_preset()

    workfile_settings = imageio_host["workfile"]
    color_management = workfile_settings["color_management"]
    native_ocio_config = workfile_settings["native_ocio_config"]

    if not config_data:
        # no ocio config found and no custom path used
        if self._root_node["colorManagement"].value() \
                    not in color_management:
            self._root_node["colorManagement"].setValue(color_management)

        # second set ocio version
        if self._root_node["OCIO_config"].value() \
                    not in native_ocio_config:
            self._root_node["OCIO_config"].setValue(native_ocio_config)

    else:
        # OCIO config path is defined from prelaunch hook
        self._root_node["colorManagement"].setValue("OCIO")

        # print previous settings in case some were found in workfile
        residual_path = self._root_node["customOCIOConfigPath"].value()
        if residual_path:
            log.info("Residual OCIO config path found: `{}`".format(
                residual_path
            ))

    # set ocio config path
    if config_data:
        config_path = config_data["path"].replace("\\", "/")
        log.info("OCIO config path found: `{}`".format(
            config_path))

        # check if there's a mismatch between environment and settings
        correct_settings = self._is_settings_matching_environment(
            config_data)

        # if there's no mismatch between environment and settings
        if correct_settings:
            self._set_ocio_config_path_to_workfile(config_data)

    workfile_settings_output = {}
    # get monitor lut from settings respecting Nuke version differences
    monitor_lut_data = self._get_monitor_settings(
        workfile_settings["monitor_out_lut"],
        workfile_settings["monitor_lut"]
    )
    workfile_settings_output.update(monitor_lut_data)
    workfile_settings_output.update(
        {
            "workingSpaceLUT": workfile_settings["working_space"],
            "int8Lut": workfile_settings["int_8_lut"],
            "int16Lut": workfile_settings["int_16_lut"],
            "logLut": workfile_settings["log_lut"],
            "floatLut": workfile_settings["float_lut"],
        }
    )

    # then set the rest
    for knob, value_ in workfile_settings_output.items():
        # skip unfilled ocio config path
        # it will be dict in value
        if isinstance(value_, dict):
            continue
        # skip empty values
        if not value_:
            continue
        self._root_node[knob].setValue(str(value_))

set_viewers_colorspace(imageio_nuke)

Adds correct colorspace to viewer

Parameters:

Name Type Description Default
imageio_nuke dict

nuke colorspace configurations

required
Source code in client/ayon_nuke/api/lib.py
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
1536
1537
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 set_viewers_colorspace(self, imageio_nuke):
    ''' Adds correct colorspace to viewer

    Arguments:
        imageio_nuke (dict): nuke colorspace configurations

    '''
    filter_knobs = [
        "viewerProcess",
        "wipe_position",
        "monitorOutOutputTransform"
    ]
    viewer_process = get_formatted_display_and_view(
        imageio_nuke["viewer"], self.formatting_data, self._root_node
    )
    output_transform = get_formatted_display_and_view(
        imageio_nuke["monitor"], self.formatting_data, self._root_node
    )
    erased_viewers = []
    for v in nuke.allNodes(filter="Viewer"):
        # set viewProcess to preset from settings
        v["viewerProcess"].setValue(viewer_process)

        if viewer_process not in v["viewerProcess"].value():
            copy_inputs = v.dependencies()
            copy_knobs = {
                k: v[k].value() for k in v.knobs()
                if k not in filter_knobs
            }

            # delete viewer with wrong settings
            erased_viewers.append(v["name"].value())
            nuke.delete(v)

            # create new viewer
            nv = nuke.createNode("Viewer")

            # connect to original inputs
            for i, n in enumerate(copy_inputs):
                nv.setInput(i, n)

            # set copied knobs
            for knob_name, knob_value in copy_knobs.items():
                nv[knob_name].setValue(knob_value)

            # set viewerProcess
            nv["viewerProcess"].setValue(viewer_process)
            nv["monitorOutOutputTransform"].setValue(output_transform)

    if erased_viewers:
        log.warning(
            "Attention! Viewer nodes {} were erased."
            "It had wrong color profile".format(erased_viewers))

set_writes_colorspace()

Adds correct colorspace to write node dict

Source code in client/ayon_nuke/api/lib.py
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
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
def set_writes_colorspace(self):
    ''' Adds correct colorspace to write node dict

    '''
    for node in nuke.allNodes(filter="Group", group=self._root_node):
        log.info("Setting colorspace to `{}`".format(node.name()))

        # get data from avalon knob
        avalon_knob_data = read_avalon_data(node)
        node_data = get_node_data(node, INSTANCE_DATA_KNOB)

        if (
            # backward compatibility
            # TODO: remove this once old avalon data api will be removed
            avalon_knob_data
            and avalon_knob_data.get("id") not in {
                AYON_INSTANCE_ID, AVALON_INSTANCE_ID
            }
        ):
            continue
        elif (
            node_data
            and node_data.get("id") not in {
                AYON_INSTANCE_ID, AVALON_INSTANCE_ID
            }
        ):
            continue

        if (
            # backward compatibility
            # TODO: remove this once old avalon data api will be removed
            avalon_knob_data
            and "creator" not in avalon_knob_data
        ):
            continue
        elif (
            node_data
            and "creator_identifier" not in node_data
        ):
            continue

        nuke_imageio_writes = None
        if avalon_knob_data:
            # establish families
            product_type = avalon_knob_data.get("productType")
            if product_type is None:
                product_type = avalon_knob_data["family"]
            families = [product_type]
            if avalon_knob_data.get("families"):
                families.append(avalon_knob_data.get("families"))

            nuke_imageio_writes = get_imageio_node_setting(
                node_class=avalon_knob_data["families"],
                plugin_name=avalon_knob_data["creator"],
                product_name=avalon_knob_data["productName"]
            )
        elif node_data:
            nuke_imageio_writes = get_write_node_template_attr(node)

        if not nuke_imageio_writes:
            return

        write_node = None

        # get into the group node
        node.begin()
        for x in nuke.allNodes():
            if x.Class() == "Write":
                write_node = x
        node.end()

        if not write_node:
            return

        set_node_knobs_from_settings(
            write_node, nuke_imageio_writes["knobs"])

add_publish_knob(node)

[DEPRECATED] Add Publish knob to node

Parameters:

Name Type Description Default
node Node

nuke node to be processed

required

Returns:

Name Type Description
node Node

processed nuke node

Source code in client/ayon_nuke/api/lib.py
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
@deprecated
def add_publish_knob(node):
    """[DEPRECATED] Add Publish knob to node

    Arguments:
        node (nuke.Node): nuke node to be processed

    Returns:
        node (nuke.Node): processed nuke node

    """
    if "publish" not in node.knobs():
        body = OrderedDict()
        body[("divd", "Publishing")] = Knobby("Text_Knob", '')
        body["publish"] = True
        imprint(node, body)
    return node

add_write_node(name, file_path, knobs, **kwarg)

Adding nuke write node

Parameters:

Name Type Description Default
name str

nuke node name

required
kwarg attrs

data for nuke knobs

{}

Returns:

Name Type Description
node obj

nuke write node

Source code in client/ayon_nuke/api/lib.py
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
def add_write_node(name, file_path, knobs, **kwarg):
    """Adding nuke write node

    Arguments:
        name (str): nuke node name
        kwarg (attrs): data for nuke knobs

    Returns:
        node (obj): nuke write node
    """
    use_range_limit = kwarg.get("use_range_limit", None)

    w = nuke.createNode(
        "Write",
        "name {}".format(name),
        inpanel=False
    )

    w["file"].setValue(file_path)

    # finally add knob overrides
    set_node_knobs_from_settings(w, knobs, **kwarg)

    if use_range_limit:
        w["use_limit"].setValue(True)
        w["first"].setValue(kwarg["frame_range"][0])
        w["last"].setValue(kwarg["frame_range"][1])

    return w

check_inventory_versions()

Update loaded container nodes' colors based on version state.

This will group containers by their version to outdated, not found, invalid or latest and colorize the nodes based on the category.

Source code in client/ayon_nuke/api/lib.py
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
def check_inventory_versions():
    """Update loaded container nodes' colors based on version state.

    This will group containers by their version to outdated, not found,
    invalid or latest and colorize the nodes based on the category.
    """
    try:
        host = registered_host()
        containers = host.get_containers()
        project_name = get_current_project_name()

        filtered_containers = filter_containers(containers, project_name)
        for category, containers in filtered_containers._asdict().items():
            if category not in LOADER_CATEGORY_COLORS:
                continue
            color = LOADER_CATEGORY_COLORS[category]
            color = int(color, 16)  # convert hex to nuke tile color int
            for container in containers:
                container["node"]["tile_color"].setValue(color)
    except Exception as error:
        log.warning(error)

check_product_name_exists(nodes, product_name)

Checking if node is not already created to secure there is no duplicity

Parameters:

Name Type Description Default
nodes list

list of nuke.Node objects

required
product_name str

name we try to find

required

Returns:

Name Type Description
bool

True of False

Source code in client/ayon_nuke/api/lib.py
931
932
933
934
935
936
937
938
939
940
941
942
943
944
def check_product_name_exists(nodes, product_name):
    """
    Checking if node is not already created to secure there is no duplicity

    Arguments:
        nodes (list): list of nuke.Node objects
        product_name (str): name we try to find

    Returns:
        bool: True of False
    """
    return next((True for n in nodes
                 if product_name in read_avalon_data(n).get("productName", "")),
                False)

create_backdrop(label='', color=None, layer=0, nodes=None)

Create Backdrop node

Parameters:

Name Type Description Default
color str

nuke compatible string with color code

None
layer int

layer of node usually used (self.pos_layer - 1)

0
label str

the message

''
nodes list

list of nodes to be wrapped into backdrop

None
Source code in client/ayon_nuke/api/lib.py
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
def create_backdrop(label="", color=None, layer=0,
                    nodes=None):
    """
    Create Backdrop node

    Arguments:
        color (str): nuke compatible string with color code
        layer (int): layer of node usually used (self.pos_layer - 1)
        label (str): the message
        nodes (list): list of nodes to be wrapped into backdrop

    """
    assert isinstance(nodes, list), "`nodes` should be a list of nodes"

    # Calculate bounds for the backdrop node.
    bdX = min([node.xpos() for node in nodes])
    bdY = min([node.ypos() for node in nodes])
    bdW = max([node.xpos() + node.screenWidth() for node in nodes]) - bdX
    bdH = max([node.ypos() + node.screenHeight() for node in nodes]) - bdY

    # Expand the bounds to leave a little border. Elements are offsets
    # for left, top, right and bottom edges respectively
    left, top, right, bottom = (-20, -65, 20, 60)
    bdX += left
    bdY += top
    bdW += (right - left)
    bdH += (bottom - top)

    bdn = nuke.createNode("BackdropNode")
    bdn["z_order"].setValue(layer)

    if color:
        bdn["tile_color"].setValue(int(color, 16))

    bdn["xpos"].setValue(bdX)
    bdn["ypos"].setValue(bdY)
    bdn["bdwidth"].setValue(bdW)
    bdn["bdheight"].setValue(bdH)

    if label:
        bdn["label"].setValue(label)

    bdn["note_font_size"].setValue(20)
    return bdn

create_camera_node_by_version()

Function to create the camera with the latest node class For Nuke version 14.0 or later, the Camera4 camera node class would be used For the version before, the Camera2 camera node class would be used Returns: Node: camera node

Source code in client/ayon_nuke/api/lib.py
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
def create_camera_node_by_version():
    """Function to create the camera with the latest node class
    For Nuke version 14.0 or later, the Camera4 camera node class
        would be used
    For the version before, the Camera2 camera node class
        would be used
    Returns:
        Node: camera node
    """
    nuke_number_version = nuke.NUKE_VERSION_MAJOR
    if nuke_number_version >= 14:
        return nuke.createNode("Camera4")
    else:
        return nuke.createNode("Camera2")

create_knobs(data, tab=None)

Create knobs by data

Depending on the type of each dict value and creates the correct Knob.

Mapped types

bool: nuke.Boolean_Knob int: nuke.Int_Knob float: nuke.Double_Knob list: nuke.Enumeration_Knob str: nuke.String_Knob

dict: If it's a nested dict (all values are dict), will turn into A tabs group. Or just a knobs group.

Parameters:

Name Type Description Default
data dict

collection of attributes and their value

required
tab string

Knobs' tab name

None

Returns:

Name Type Description
list

A list of nuke.Knob objects

Source code in client/ayon_nuke/api/lib.py
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
317
318
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
def create_knobs(data, tab=None):
    """Create knobs by data

    Depending on the type of each dict value and creates the correct Knob.

    Mapped types:
        bool: nuke.Boolean_Knob
        int: nuke.Int_Knob
        float: nuke.Double_Knob
        list: nuke.Enumeration_Knob
        str: nuke.String_Knob

        dict: If it's a nested dict (all values are dict), will turn into
            A tabs group. Or just a knobs group.

    Args:
        data (dict): collection of attributes and their value
        tab (string, optional): Knobs' tab name

    Returns:
        list: A list of `nuke.Knob` objects

    """
    def nice_naming(key):
        """Convert camelCase name into UI Display Name"""
        words = re.findall('[A-Z][^A-Z]*', key[0].upper() + key[1:])
        return " ".join(words)

    # Turn key-value pairs into knobs
    knobs = list()

    if tab:
        knobs.append(nuke.Tab_Knob(tab))

    for key, value in data.items():
        # Knob name
        if isinstance(key, tuple):
            name, nice = key
        else:
            name, nice = key, nice_naming(key)

        # Create knob by value type
        if isinstance(value, Knobby):
            knobby = value
            knob = knobby.create(name, nice)

        elif isinstance(value, float):
            knob = nuke.Double_Knob(name, nice)
            knob.setValue(value)

        elif isinstance(value, bool):
            knob = nuke.Boolean_Knob(name, nice)
            knob.setValue(value)
            knob.setFlag(nuke.STARTLINE)

        elif isinstance(value, int):
            knob = nuke.Int_Knob(name, nice)
            knob.setValue(value)

        elif isinstance(value, str):
            knob = nuke.String_Knob(name, nice)
            knob.setValue(value)

        elif isinstance(value, list):
            knob = nuke.Enumeration_Knob(name, nice, value)

        elif isinstance(value, dict):
            if all(isinstance(v, dict) for v in value.values()):
                # Create a group of tabs
                begain = nuke.BeginTabGroup_Knob()
                end = nuke.EndTabGroup_Knob()
                begain.setName(name)
                end.setName(name + "_End")
                knobs.append(begain)
                for k, v in value.items():
                    knobs += create_knobs(v, tab=k)
                knobs.append(end)
            else:
                # Create a group of knobs
                knobs.append(nuke.Tab_Knob(
                    name, nice, nuke.TABBEGINCLOSEDGROUP))
                knobs += create_knobs(value)
                knobs.append(
                    nuke.Tab_Knob(name + "_End", nice, nuke.TABENDGROUP))
            continue

        else:
            raise TypeError("Unsupported type: %r" % type(value))

        knobs.append(knob)

    return knobs

create_viewer_profile_string(viewer, display=None, path_like=False)

Convert viewer and display to string

Parameters:

Name Type Description Default
viewer str

viewer name

required
display Optional[str]

display name

None
path_like Optional[bool]

if True, return path like string

False

Returns:

Name Type Description
str

viewer config string

Source code in client/ayon_nuke/api/lib.py
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
def create_viewer_profile_string(viewer, display=None, path_like=False):
    """Convert viewer and display to string

    Args:
        viewer (str): viewer name
        display (Optional[str]): display name
        path_like (Optional[bool]): if True, return path like string

    Returns:
        str: viewer config string
    """
    if not display:
        return viewer

    if path_like:
        return "{}/{}".format(display, viewer)
    return "{} ({})".format(viewer, display)

create_write_node(name, data, input=None, prenodes=None, linked_knobs=None, **kwargs)

Creating write node which is group node

Parameters:

Name Type Description Default
name str

name of node

required
data dict

creator write instance data

required
input node)[optional]

selected node to connect to

None
prenodes Optional[list[dict]]

nodes to be created before write with dependency

None
review bool)[optional]

adding review knob

required
farm bool)[optional]

rendering workflow target

required
kwargs dict)[optional]

additional key arguments for formatting

{}
Example

prenodes = { "nodeName": { "nodeclass": "Reformat", "dependent": [ following_node_01, ... ], "knobs": [ { "type": "text", "name": "knobname", "value": "knob value" }, ... ] }, ... }

Return

node (obj): group node with avalon data as Knobs

Source code in client/ayon_nuke/api/lib.py
1086
1087
1088
1089
1090
1091
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
1138
1139
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
1181
1182
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
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
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
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
def create_write_node(
    name,
    data,
    input=None,
    prenodes=None,
    linked_knobs=None,
    **kwargs
):
    ''' Creating write node which is group node

    Arguments:
        name (str): name of node
        data (dict): creator write instance data
        input (node)[optional]: selected node to connect to
        prenodes (Optional[list[dict]]): nodes to be created before write
            with dependency
        review (bool)[optional]: adding review knob
        farm (bool)[optional]: rendering workflow target
        kwargs (dict)[optional]: additional key arguments for formatting

    Example:
        prenodes = {
            "nodeName": {
                "nodeclass": "Reformat",
                "dependent": [
                    following_node_01,
                    ...
                ],
                "knobs": [
                    {
                        "type": "text",
                        "name": "knobname",
                        "value": "knob value"
                    },
                    ...
                ]
            },
            ...
        }


    Return:
        node (obj): group node with avalon data as Knobs
    '''
    # Ensure name does not contain any invalid characters.
    special_chars = re.escape("!@#$%^&*()=[]{}|\\;',.<>/?~+-")
    special_chars_regex = re.compile(f"[{special_chars}]")
    found_special_characters = list(special_chars_regex.findall(name))

    msg = (
        f"Special characters found in name \"{name}\": "
        f"{' '.join(found_special_characters)}"
    )
    assert not found_special_characters, msg

    prenodes = prenodes or []

    # filtering variables
    plugin_name = data["creator"]
    product_name = data["productName"]

    # get knob settings for write node
    imageio_writes = get_imageio_node_setting(
        node_class="Write",
        plugin_name=plugin_name,
        product_name=product_name
    )

    ext = None
    knobs = imageio_writes["knobs"]
    knob_names = {knob["name"]: knob for knob in knobs}

    if "ext" in knob_names:
        knob_type = knob_names["ext"]["type"]
        ext = knob_names["ext"][knob_type]

    # For most extensions, setting the "file_type"
    # is enough, however sometimes they differ, e.g.:
    # ext = sxr / file_type = exr
    # ext = jpg / file_type = jpeg
    elif "file_type" in knob_names:
        knob_type = knob_names["file_type"]["type"]
        ext = knob_names["file_type"][knob_type]

    if not ext:
        raise RuntimeError(
            "Could not determine extension from settings for "
            f"plugin_name={plugin_name} product_name={product_name}"
        )

    data.update({
        "imageio_writes": imageio_writes,
        "ext": ext
    })

    # build file path to workfiles
    data["work"] = get_work_default_directory(data)
    fpath = StringTemplate(data["fpath_template"]).format_strict(data)

    # Override output directory is provided staging directory.
    if data.get("staging_dir"):
        basename = os.path.basename(fpath)
        staging_path = pathlib.Path(data["staging_dir"]) / basename
        fpath = staging_path.as_posix()

    # create directory
    if not os.path.isdir(os.path.dirname(fpath)):
        log.warning("Path does not exist! I am creating it.")
        os.makedirs(os.path.dirname(fpath))

    GN = nuke.createNode("Group", "name {}".format(name))

    prev_node = None
    with GN:
        if input:
            input_name = str(input.name()).replace(" ", "")
            # if connected input node was defined
            prev_node = nuke.createNode(
                "Input",
                "name {}".format(input_name),
                inpanel=False
            )
        else:
            # generic input node connected to nothing
            prev_node = nuke.createNode(
                "Input",
                "name {}".format("rgba"),
                inpanel=False
            )

        # creating pre-write nodes `prenodes`
        last_prenode = create_prenodes(
            prev_node,
            prenodes,
            plugin_name,
            product_name,
            **kwargs
        )
        if last_prenode:
            prev_node = last_prenode

        # creating write node
        write_node = now_node = add_write_node(
            "inside_{}".format(name),
            fpath,
            imageio_writes["knobs"],
            **data
        )
        # connect to previous node
        now_node.setInput(0, prev_node)

        # switch actual node to previous
        prev_node = now_node

        now_node = nuke.createNode("Output", "name Output1", inpanel=False)

        # connect to previous node
        now_node.setInput(0, prev_node)

    # add divider
    GN.addKnob(nuke.Text_Knob('', 'Rendering'))

    # Add linked knobs.
    linked_knob_names = []

    # add input linked knobs and create group only if any input
    if linked_knobs:
        linked_knob_names.append("_grp-start_")
        linked_knob_names.extend(linked_knobs)
        linked_knob_names.append("_grp-end_")

    linked_knob_names.append("Render")

    for _k_name in linked_knob_names:
        if "_grp-start_" in _k_name:
            knob = nuke.Tab_Knob(
                "rnd_attr", "Rendering attributes", nuke.TABBEGINCLOSEDGROUP)
            GN.addKnob(knob)
        elif "_grp-end_" in _k_name:
            knob = nuke.Tab_Knob(
                "rnd_attr_end", "Rendering attributes", nuke.TABENDGROUP)
            GN.addKnob(knob)
        else:
            if "___" in _k_name:
                # add divider
                GN.addKnob(nuke.Text_Knob(""))
            else:
                # add linked knob by _k_name
                link = nuke.Link_Knob("")
                link.makeLink(write_node.name(), _k_name)
                link.setName(_k_name)

                # make render
                if "Render" in _k_name:
                    link.setLabel("Render Local")
                link.setFlag(0x1000)
                GN.addKnob(link)

    # Adding render farm submission button.
    if data.get("render_on_farm", False):
        add_button_render_on_farm(GN)

    # adding write to read button
    add_button_write_to_read(GN)

    # adding write to read button
    add_button_clear_rendered(GN, os.path.dirname(fpath))

    # set tile color
    tile_color = next(
        iter(
            k[k["type"]] for k in imageio_writes["knobs"]
            if "tile_color" in k["name"]
        ), [255, 0, 0, 255]
    )
    new_tile_color = []
    for c in tile_color:
        if isinstance(c, float):
            c = int(c * 255)
        new_tile_color.append(c)
    GN["tile_color"].setValue(
        color_gui_to_int(new_tile_color))

    return GN

deprecated(new_destination)

Mark functions as deprecated.

It will result in a warning being emitted when the function is used.

Source code in client/ayon_nuke/api/lib.py
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
def deprecated(new_destination):
    """Mark functions as deprecated.

    It will result in a warning being emitted when the function is used.
    """

    func = None
    if callable(new_destination):
        func = new_destination
        new_destination = None

    def _decorator(decorated_func):
        if new_destination is None:
            warning_message = (
                " Please check content of deprecated function to figure out"
                " possible replacement."
            )
        else:
            warning_message = " Please replace your usage with '{}'.".format(
                new_destination
            )

        @functools.wraps(decorated_func)
        def wrapper(*args, **kwargs):
            warnings.simplefilter("always", DeprecatedWarning)
            warnings.warn(
                (
                    "Call to deprecated function '{}'"
                    "\nFunction was moved or removed.{}"
                ).format(decorated_func.__name__, warning_message),
                category=DeprecatedWarning,
                stacklevel=4
            )
            return decorated_func(*args, **kwargs)
        return wrapper

    if func is None:
        return _decorator
    return _decorator(func)

dirmap_file_name_filter(file_name)

Nuke callback function with single full path argument.

Checks project settings for potential mapping from source to dest.

Source code in client/ayon_nuke/api/lib.py
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
def dirmap_file_name_filter(file_name):
    """Nuke callback function with single full path argument.

        Checks project settings for potential mapping from source to dest.
    """

    dirmap_processor = NukeDirmap(
        file_name,
        "nuke",
        DirmapCache.project_name(),
        DirmapCache.project_settings(),
        DirmapCache.sitesync_addon(),
    )
    if not DirmapCache.mapping():
        DirmapCache.set_mapping(dirmap_processor.get_mappings())

    dirmap_processor.process_dirmap(DirmapCache.mapping())
    if os.path.exists(dirmap_processor.file_name):
        return dirmap_processor.file_name
    return file_name

find_free_space_to_paste_nodes(nodes, group=nuke.root(), direction='right', offset=300)

For getting coordinates in DAG (node graph) for placing new nodes

Parameters:

Name Type Description Default
nodes list

list of nuke.Node objects

required
group nuke.Node) [optional]

object in which context it is

root()
direction str) [optional]

where we want it to be placed [left, right, top, bottom]

'right'
offset int) [optional]

what offset it is from rest of nodes

300

Returns:

Name Type Description
xpos int

x coordinace in DAG

ypos int

y coordinace in DAG

Source code in client/ayon_nuke/api/lib.py
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
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
def find_free_space_to_paste_nodes(
    nodes,
    group=nuke.root(),
    direction="right",
    offset=300
):
    """
    For getting coordinates in DAG (node graph) for placing new nodes

    Arguments:
        nodes (list): list of nuke.Node objects
        group (nuke.Node) [optional]: object in which context it is
        direction (str) [optional]: where we want it to be placed
                                    [left, right, top, bottom]
        offset (int) [optional]: what offset it is from rest of nodes

    Returns:
        xpos (int): x coordinace in DAG
        ypos (int): y coordinace in DAG
    """
    if len(nodes) == 0:
        return 0, 0

    group_xpos = list()
    group_ypos = list()

    # get local coordinates of all nodes
    nodes_xpos = [n.xpos() for n in nodes] + \
                 [n.xpos() + n.screenWidth() for n in nodes]

    nodes_ypos = [n.ypos() for n in nodes] + \
                 [n.ypos() + n.screenHeight() for n in nodes]

    # get complete screen size of all nodes to be placed in
    nodes_screen_width = max(nodes_xpos) - min(nodes_xpos)
    nodes_screen_heigth = max(nodes_ypos) - min(nodes_ypos)

    # get screen size (r,l,t,b) of all nodes in `group`
    with group:
        group_xpos = [n.xpos() for n in nuke.allNodes() if n not in nodes] + \
                     [n.xpos() + n.screenWidth() for n in nuke.allNodes()
                      if n not in nodes]
        group_ypos = [n.ypos() for n in nuke.allNodes() if n not in nodes] + \
                     [n.ypos() + n.screenHeight() for n in nuke.allNodes()
                      if n not in nodes]

        if len(group_xpos) == 0:
            group_xpos = [0]
        if len(group_ypos) == 0:
            group_ypos = [0]

        # calc output left
        if direction in "left":
            xpos = min(group_xpos) - abs(nodes_screen_width) - abs(offset)
            ypos = min(group_ypos)
            return xpos, ypos
        # calc output right
        if direction in "right":
            xpos = max(group_xpos) + abs(offset)
            ypos = min(group_ypos)
            return xpos, ypos
        # calc output top
        if direction in "top":
            xpos = min(group_xpos)
            ypos = min(group_ypos) - abs(nodes_screen_heigth) - abs(offset)
            return xpos, ypos
        # calc output bottom
        if direction in "bottom":
            xpos = min(group_xpos)
            ypos = max(group_ypos) + abs(offset)
            return xpos, ypos

get_avalon_knob_data(node, prefix='avalon:', create=True)

[DEPRECATED] Gets a data from nodes's avalon knob

This function is still used but soon will be deprecated. Use get_node_data instead.

Parameters:

Name Type Description Default
node obj

Nuke node to search for data,

required
prefix str

filtering prefix

'avalon:'

Returns:

Type Description

data (dict)

Source code in client/ayon_nuke/api/lib.py
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
@deprecated("ayon_nuke.api.lib.get_node_data")
def get_avalon_knob_data(node, prefix="avalon:", create=True):
    """[DEPRECATED]  Gets a data from nodes's avalon knob

    This function is still used but soon will be deprecated.
    Use `get_node_data` instead.

    Arguments:
        node (obj): Nuke node to search for data,
        prefix (str, optional): filtering prefix

    Returns:
        data (dict)
    """

    data = {}
    if NODE_TAB_NAME not in node.knobs():
        return data

    # check if lists
    if not isinstance(prefix, list):
        prefix = [prefix]

    # loop prefix
    for p in prefix:
        # check if the node is avalon tracked
        try:
            # check if data available on the node
            _ = node[DATA_GROUP_KEY].value()
        except NameError:
            # if it doesn't then create it
            if create:
                node = set_avalon_knob_data(node)
                return get_avalon_knob_data(node)
            return {}

        # get data from filtered knobs
        data.update({k.replace(p, ''): node[k].value()
                    for k in node.knobs().keys()
                    if p in k})

    return data

get_current_context_template_data_and_environ()

Return current context template data and os environ.

Output contains
  • Regular template data from get_template_data
  • Anatomy Roots
  • os.environ keys

Returns:

Type Description

dict[str, Any]: Template data to fill templates.

Source code in client/ayon_nuke/api/lib.py
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
def get_current_context_template_data_and_environ():
    """Return current context template data and os environ.

    Output contains:
      - Regular template data from `get_template_data`
      - Anatomy Roots
      - os.environ keys

    Returns:
         dict[str, Any]: Template data to fill templates.

    """
    context = get_current_context()
    project_name = context["project_name"]
    folder_path = context["folder_path"]
    task_name = context["task_name"]
    host_name = get_current_host_name()

    project_entity = ayon_api.get_project(project_name)
    anatomy = Anatomy(project_name, project_entity=project_entity)
    folder_entity = ayon_api.get_folder_by_path(project_name, folder_path)
    task_entity = ayon_api.get_task_by_name(
        project_name, folder_entity["id"], task_name
    )

    template_data = get_template_data(
        project_entity, folder_entity, task_entity, host_name
    )
    template_data["root"] = anatomy.roots

    template_data.update(os.environ)

    return template_data

get_dependent_nodes(nodes)

Get all dependent nodes connected to the list of nodes.

Looking for connections outside of the nodes in incoming argument.

Parameters:

Name Type Description Default
nodes list

list of nuke.Node objects

required

Returns:

Name Type Description
connections_in

dictionary of nodes and its dependencies

connections_out

dictionary of nodes and its dependency

Source code in client/ayon_nuke/api/lib.py
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
def get_dependent_nodes(nodes):
    """Get all dependent nodes connected to the list of nodes.

    Looking for connections outside of the nodes in incoming argument.

    Arguments:
        nodes (list): list of nuke.Node objects

    Returns:
        connections_in: dictionary of nodes and its dependencies
        connections_out: dictionary of nodes and its dependency
    """

    connections_in = dict()
    connections_out = dict()
    node_names = [n.name() for n in nodes]
    for node in nodes:
        inputs = node.dependencies()
        outputs = node.dependent()
        # collect all inputs outside
        test_in = [(i, n) for i, n in enumerate(inputs)
                   if n.name() not in node_names]
        if test_in:
            connections_in.update({
                node: test_in
            })
        # collect all outputs outside
        test_out = [i for i in outputs if i.name() not in node_names]
        if test_out:
            # only one dependent node is allowed
            connections_out.update({
                node: test_out[-1]
            })

    return connections_in, connections_out

get_extreme_positions(nodes)

Get the 4 numbers that represent the box of a group of nodes.

Source code in client/ayon_nuke/api/lib.py
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
def get_extreme_positions(nodes):
    """Get the 4 numbers that represent the box of a group of nodes."""

    if not nodes:
        raise ValueError("there is no nodes in the list")

    nodes_xpos = [n.xpos() for n in nodes] + \
        [n.xpos() + n.screenWidth() for n in nodes]

    nodes_ypos = [n.ypos() for n in nodes] + \
        [n.ypos() + n.screenHeight() for n in nodes]

    min_x, min_y = (min(nodes_xpos), min(nodes_ypos))
    max_x, max_y = (max(nodes_xpos), max(nodes_ypos))
    return min_x, min_y, max_x, max_y

get_filenames_without_hash(filename, frame_start, frame_end)

Get filenames without frame hash i.e. "renderCompositingMain.baking.0001.exr"

Parameters:

Name Type Description Default
filename str

filename with frame hash

required
frame_start str

start of the frame

required
frame_end str

end of the frame

required

Returns:

Name Type Description
list

filename per frame of the sequence

Source code in client/ayon_nuke/api/lib.py
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
def get_filenames_without_hash(filename, frame_start, frame_end):
    """Get filenames without frame hash
        i.e. "renderCompositingMain.baking.0001.exr"

    Args:
        filename (str): filename with frame hash
        frame_start (str): start of the frame
        frame_end (str): end of the frame

    Returns:
        list: filename per frame of the sequence
    """
    filenames = []
    for frame in range(int(frame_start), (int(frame_end) + 1)):
        if "#" in filename:
            # use regex to convert #### to {:0>4}
            def replace(match):
                return "{{:0>{}}}".format(len(match.group()))
            filename_without_hashes = re.sub("#+", replace, filename)
            new_filename = filename_without_hashes.format(frame)
            filenames.append(new_filename)
    return filenames

get_group_io_nodes(nodes)

Get the input and the output of a group of nodes.

Source code in client/ayon_nuke/api/lib.py
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
def get_group_io_nodes(nodes):
    """Get the input and the output of a group of nodes."""

    if not nodes:
        raise ValueError("there is no nodes in the list")

    input_node = None
    output_node = None

    if len(nodes) == 1:
        input_node = output_node = nodes[0]

    else:
        for node in nodes:
            if "Input" in node.name():
                input_node = node

            if "Output" in node.name():
                output_node = node

            if input_node is not None and output_node is not None:
                break

        if input_node is None:
            log.warning("No Input found")

        if output_node is None:
            log.warning("No Output found")

    return input_node, output_node

get_imageio_input_colorspace(filename)

Get input file colorspace based on regex in settings.

Source code in client/ayon_nuke/api/lib.py
772
773
774
775
776
777
778
779
780
781
782
783
def get_imageio_input_colorspace(filename):
    ''' Get input file colorspace based on regex in settings.
    '''
    imageio_regex_inputs = (
        get_nuke_imageio_settings()["regex_inputs"]["inputs"])

    preset_clrsp = None
    for regexInput in imageio_regex_inputs:
        if bool(re.search(regexInput["regex"], filename)):
            preset_clrsp = str(regexInput["colorspace"])

    return preset_clrsp

get_imageio_node_override_setting(node_class, plugin_name, product_name, knobs_settings)

Get imageio node overrides from settings

Source code in client/ayon_nuke/api/lib.py
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
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
def get_imageio_node_override_setting(
    node_class, plugin_name, product_name, knobs_settings
):
    ''' Get imageio node overrides from settings
    '''
    imageio_nodes = get_nuke_imageio_settings()["nodes"]
    override_nodes = imageio_nodes["override_nodes"]

    # find matching override node
    override_imageio_node = None
    for onode in override_nodes:

        node_class_preset = onode["nuke_node_class"]

        if onode.get("custom_class"):
            node_class_preset = onode["custom_class"]

        if node_class not in node_class_preset:
            continue

        if plugin_name not in onode["plugins"]:
            continue

        product_names = onode["product_names"]

        if (
            product_names
            and not any(
                re.search(s.lower(), product_name.lower())
                for s in product_names
            )
        ):
            continue

        override_imageio_node = onode
        break

    # add overrides to imageio_node
    if override_imageio_node:
        # get all knob names in imageio_node
        knob_names = [k["name"] for k in knobs_settings]

        for oknob in override_imageio_node["knobs"]:
            oknob_name = oknob["name"]
            oknob_type = oknob["type"]
            oknob_value = oknob[oknob_type]
            for knob in knobs_settings:
                # add missing knobs into imageio_node
                if oknob_name not in knob_names:
                    knobs_settings.append(oknob)
                    knob_names.append(oknob_name)
                    continue

                if oknob_name != knob["name"]:
                    continue

                knob_type = knob["type"]
                # override matching knob name
                if not oknob_value:
                    # remove original knob if no value found in oknob
                    knobs_settings.remove(knob)
                else:
                    # override knob value with oknob's
                    knob[knob_type] = oknob_value

    return knobs_settings

get_imageio_node_setting(node_class, plugin_name, product_name)

Get preset data for dataflow (fileType, compression, bitDepth)

Source code in client/ayon_nuke/api/lib.py
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
def get_imageio_node_setting(node_class, plugin_name, product_name):
    ''' Get preset data for dataflow (fileType, compression, bitDepth)
    '''
    imageio_nodes = get_nuke_imageio_settings()["nodes"]
    required_nodes = imageio_nodes["required_nodes"]

    imageio_node = None
    for node in required_nodes:
        node_class_preset = node["nuke_node_class"]
        if node.get("custom_class"):
            node_class_preset = node["custom_class"]
        if (
            node_class in node_class_preset
            and plugin_name in node["plugins"]
        ):
            imageio_node = node
            break

    if not imageio_node:
        return

    # find overrides and update knobs with them
    get_imageio_node_override_setting(
        node_class,
        plugin_name,
        product_name,
        imageio_node["knobs"]
    )
    return imageio_node

get_main_window()

Acquire Nuke's main window

Source code in client/ayon_nuke/api/lib.py
140
141
142
143
144
145
146
147
148
149
150
151
152
153
def get_main_window():
    """Acquire Nuke's main window"""
    if Context.main_window is None:

        top_widgets = QtWidgets.QApplication.topLevelWidgets()
        name = "Foundry::UI::DockMainWindow"
        for widget in top_widgets:
            if (
                widget.inherits("QMainWindow")
                and widget.metaObject().className() == name
            ):
                Context.main_window = widget
                break
    return Context.main_window

get_names_from_nodes(nodes)

Get list of nodes names.

Parameters:

Name Type Description Default
nodes(List[nuke.Node])

List of nodes to convert into names.

required

Returns:

Type Description

List[str]: Name of passed nodes.

Source code in client/ayon_nuke/api/lib.py
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
def get_names_from_nodes(nodes):
    """Get list of nodes names.

    Args:
        nodes(List[nuke.Node]): List of nodes to convert into names.

    Returns:
        List[str]: Name of passed nodes.
    """

    return [
        node.name()
        for node in nodes
    ]

get_node_data(node, knobname)

Read data from node.

Parameters:

Name Type Description Default
node Node

node object

required
knobname str

knob name

required

Returns:

Name Type Description
dict

data stored in knob

Source code in client/ayon_nuke/api/lib.py
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
def get_node_data(node, knobname):
    """Read data from node.

    Args:
        node (nuke.Node): node object
        knobname (str): knob name

    Returns:
        dict: data stored in knob
    """
    if knobname not in node.knobs():
        return

    rawdata = node[knobname].getValue()
    if (
        isinstance(rawdata, str)
        and rawdata.startswith(JSON_PREFIX)
    ):
        try:
            return json.loads(rawdata[len(JSON_PREFIX):])
        except json.JSONDecodeError:
            return

get_node_path(path, padding=4)

Get filename for the Nuke write with padded number as '#'

Parameters:

Name Type Description Default
path str

The path to render to.

required

Returns:

Name Type Description
tuple

head, padding, tail (extension)

Examples:

>>> get_frame_path("test.exr")
('test', 4, '.exr')
>>> get_frame_path("filename.#####.tif")
('filename.', 5, '.tif')
>>> get_frame_path("foobar##.tif")
('foobar', 2, '.tif')
>>> get_frame_path("foobar_%08d.tif")
('foobar_', 8, '.tif')
Source code in client/ayon_nuke/api/lib.py
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
654
655
656
657
658
659
660
661
662
663
664
665
def get_node_path(path, padding=4):
    """Get filename for the Nuke write with padded number as '#'

    Arguments:
        path (str): The path to render to.

    Returns:
        tuple: head, padding, tail (extension)

    Examples:
        >>> get_frame_path("test.exr")
        ('test', 4, '.exr')

        >>> get_frame_path("filename.#####.tif")
        ('filename.', 5, '.tif')

        >>> get_frame_path("foobar##.tif")
        ('foobar', 2, '.tif')

        >>> get_frame_path("foobar_%08d.tif")
        ('foobar_', 8, '.tif')
    """
    filename, ext = os.path.splitext(path)

    # Find a final number group
    if '%' in filename:
        match = re.match('.*?(%[0-9]+d)$', filename)
        if match:
            padding = int(match.group(1).replace('%', '').replace('d', ''))
            # remove number from end since fusion
            # will swap it with the frame number
            filename = filename.replace(match.group(1), '')
    elif '#' in filename:
        match = re.match('.*?(#+)$', filename)

        if match:
            padding = len(match.group(1))
            # remove number from end since fusion
            # will swap it with the frame number
            filename = filename.replace(match.group(1), '')

    return filename, padding, ext

get_nodes_by_names(names)

Get list of nuke nodes based on their names.

Parameters:

Name Type Description Default
names List[str]

List of node names to be found.

required

Returns:

Type Description

List[nuke.Node]: List of nodes found by name.

Source code in client/ayon_nuke/api/lib.py
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
def get_nodes_by_names(names):
    """Get list of nuke nodes based on their names.

    Args:
        names (List[str]): List of node names to be found.

    Returns:
        List[nuke.Node]: List of nodes found by name.
    """

    return [
        nuke.toNode(name)
        for name in names
    ]

get_version_from_path(file)

Find version number in file path string.

Looks for formats: - _v0001 - .v001 - /v001/ - difference from ayon-core.path_tools.get_version_from_path

Parameters:

Name Type Description Default
file str

file path

required

Returns:

Name Type Description
str

version number in string ('001')

Source code in client/ayon_nuke/api/lib.py
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
def get_version_from_path(file):
    """Find version number in file path string.

    Looks for formats:
    - `_v0001`
    - `.v001`
    - `/v001/` - difference from ayon-core.path_tools.get_version_from_path

    Args:
        file (str): file path

    Returns:
        str: version number in string ('001')
    """

    pattern = re.compile(r"[\._/]v([0-9]+)", re.IGNORECASE)
    try:
        return pattern.findall(file)[-1]
    except IndexError:
        log.error(
            "templates:get_version_from_workfile:"
            "`{}` missing version string."
            "Example `v004`".format(file)
        )

get_viewer_config_from_string(input_string)

Convert string to display and viewer string

Parameters:

Name Type Description Default
input_string str

string with viewer

required

Raises:

Type Description
IndexError

if more then one slash in input string

IndexError

if missing closing bracket

Returns:

Type Description

tuple[str]: display, viewer

Source code in client/ayon_nuke/api/lib.py
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
def get_viewer_config_from_string(input_string):
    """Convert string to display and viewer string

    Args:
        input_string (str): string with viewer

    Raises:
        IndexError: if more then one slash in input string
        IndexError: if missing closing bracket

    Returns:
        tuple[str]: display, viewer
    """
    display = None
    viewer = input_string
    # check if () or / or \ in name
    if "/" in viewer:
        split = viewer.split("/")

        # rise if more then one column
        if len(split) > 2:
            raise IndexError((
                "Viewer Input string is not correct. "
                "more then two `/` slashes! {}"
            ).format(input_string))

        viewer = split[1]
        display = split[0]
    elif "(" in viewer:
        pattern = r"([\w\d\s\.\-]+).*[(](.*)[)]"
        result_ = re.findall(pattern, viewer)
        try:
            result_ = result_.pop()
            display = str(result_[1]).rstrip()
            viewer = str(result_[0]).rstrip()
        except IndexError:
            raise IndexError((
                "Viewer Input string is not correct. "
                "Missing bracket! {}"
            ).format(input_string))

    return (display, viewer)

get_work_default_directory(data)

Helping function for formatting of anatomy paths

Parameters:

Name Type Description Default
data dict

dictionary with attributes used for formatting

required
Return

path (str)

Source code in client/ayon_nuke/api/lib.py
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
def get_work_default_directory(data):
    ''' Helping function for formatting of anatomy paths

    Arguments:
        data (dict): dictionary with attributes used for formatting

    Return:
        path (str)
    '''

    project_name = get_current_project_name()
    anatomy = Anatomy(project_name)

    frame_padding = anatomy.templates_obj.frame_padding

    version = data.get("version")
    if version is None:
        file = script_name()
        data["version"] = get_version_from_path(file)

    folder_path = data["folderPath"]
    task_name = data["task"]
    host_name = get_current_host_name()

    context_data = get_template_data_with_names(
        project_name, folder_path, task_name, host_name
    )
    data.update(context_data)
    data.update({
        "subset": data["productName"],
        "family": data["productType"],
        "product": {
            "name": data["productName"],
            "type": data["productType"],
        },
        "frame": "#" * frame_padding,
    })

    work_default_dir_template = anatomy.get_template_item("work", "default", "directory")
    normalized_dir = work_default_dir_template.format_strict(data).normalized()
    return str(normalized_dir).replace("\\", "/")

get_write_node_template_attr(node)

Gets all defined data from presets

Source code in client/ayon_nuke/api/lib.py
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
def get_write_node_template_attr(node):
    ''' Gets all defined data from presets

    '''

    # TODO: add identifiers to settings and rename settings key
    plugin_names_mapping = {
        "create_write_image": "CreateWriteImage",
        "create_write_prerender": "CreateWritePrerender",
        "create_write_render": "CreateWriteRender"
    }
    # get avalon data from node
    node_data = get_node_data(node, INSTANCE_DATA_KNOB)
    identifier = node_data["creator_identifier"]

    # return template data
    product_name = node_data.get("productName")
    if product_name is None:
        product_name = node_data["subset"]
    return get_imageio_node_setting(
        node_class="Write",
        plugin_name=plugin_names_mapping[identifier],
        product_name=product_name
    )

imprint(node, data, tab=None)

Store attributes with value on node

Parse user data into Node knobs. Use collections.OrderedDict to ensure knob order.

Parameters:

Name Type Description Default
node(nuke.Node)

node object from Nuke

required
data(dict)

collection of attributes and their value

required

Returns:

Type Description

None

Examples:

import nuke
from ayon_nuke.api import lib

node = nuke.createNode("NoOp")
data = {
    # Regular type of attributes
    "myList": ["x", "y", "z"],
    "myBool": True,
    "myFloat": 0.1,
    "myInt": 5,

    # Creating non-default imprint type of knob
    "MyFilePath": lib.Knobby("File_Knob", "/file/path"),
    "divider": lib.Knobby("Text_Knob", ""),

    # Manual nice knob naming
    ("my_knob", "Nice Knob Name"): "some text",

    # dict type will be created as knob group
    "KnobGroup": {
        "knob1": 5,
        "knob2": "hello",
        "knob3": ["a", "b"],
    },

    # Nested dict will be created as tab group
    "TabGroup": {
        "tab1": {"count": 5},
        "tab2": {"isGood": True},
        "tab3": {"direction": ["Left", "Right"]},
    },
}
lib.imprint(node, data, tab="Demo")

Source code in client/ayon_nuke/api/lib.py
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
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
def imprint(node, data, tab=None):
    """Store attributes with value on node

    Parse user data into Node knobs.
    Use `collections.OrderedDict` to ensure knob order.

    Args:
        node(nuke.Node): node object from Nuke
        data(dict): collection of attributes and their value

    Returns:
        None

    Examples:
        ```
        import nuke
        from ayon_nuke.api import lib

        node = nuke.createNode("NoOp")
        data = {
            # Regular type of attributes
            "myList": ["x", "y", "z"],
            "myBool": True,
            "myFloat": 0.1,
            "myInt": 5,

            # Creating non-default imprint type of knob
            "MyFilePath": lib.Knobby("File_Knob", "/file/path"),
            "divider": lib.Knobby("Text_Knob", ""),

            # Manual nice knob naming
            ("my_knob", "Nice Knob Name"): "some text",

            # dict type will be created as knob group
            "KnobGroup": {
                "knob1": 5,
                "knob2": "hello",
                "knob3": ["a", "b"],
            },

            # Nested dict will be created as tab group
            "TabGroup": {
                "tab1": {"count": 5},
                "tab2": {"isGood": True},
                "tab3": {"direction": ["Left", "Right"]},
            },
        }
        lib.imprint(node, data, tab="Demo")

        ```

    """
    for knob in create_knobs(data, tab):
        # If knob name exists we set the value. Technically there could be
        # multiple knobs with the same name, but the intent is not to have
        # duplicated knobs so we do not account for that.
        if knob.name() in node.knobs().keys():
            node[knob.name()].setValue(knob.value())
        else:
            node.addKnob(knob)

launch_workfiles_app()

Show workfiles tool on nuke launch.

Trigger to show workfiles tool on application launch. Can be executed only once all other calls are ignored.

Workfiles tool show is deferred after application initialization using QTimer.

Source code in client/ayon_nuke/api/lib.py
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
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
def launch_workfiles_app():
    """Show workfiles tool on nuke launch.

    Trigger to show workfiles tool on application launch. Can be executed only
    once all other calls are ignored.

    Workfiles tool show is deferred after application initialization using
    QTimer.
    """

    if Context.workfiles_launched:
        return

    Context.workfiles_launched = True

    # get all important settings
    open_at_start = env_value_to_bool(
        env_key="AYON_WORKFILE_TOOL_ON_START",
        default=None)

    # return if none is defined
    if not open_at_start:
        return

    # Show workfiles tool using timer
    # - this will be probably triggered during initialization in that case
    #   the application is not be able to show uis so it must be
    #   deferred using timer
    # - timer should be processed when initialization ends
    #       When applications starts to process events.
    timer = QtCore.QTimer()
    timer.timeout.connect(_launch_workfile_app)
    timer.setInterval(100)
    Context.workfiles_tool_timer = timer
    timer.start()

Link knobs from inside group_node

Source code in client/ayon_nuke/api/lib.py
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
def link_knobs(knobs, node, group_node):
    """Link knobs from inside `group_node`"""

    missing_knobs = []
    for knob in knobs:
        if knob in group_node.knobs():
            continue

        if knob not in node.knobs().keys():
            missing_knobs.append(knob)

        link = nuke.Link_Knob("")
        link.makeLink(node.name(), knob)
        link.setName(knob)
        link.setFlag(0x1000)
        group_node.addKnob(link)

    if missing_knobs:
        raise ValueError(
            "Write node exposed knobs missing:\n\n{}\n\nPlease review"
            " project settings.".format("\n".join(missing_knobs))
        )

maintained_selection(exclude_nodes=None)

Maintain selection during context

Maintain selection during context and unselect all nodes after context is done.

Parameters:

Name Type Description Default
exclude_nodes list[Node]

list of nodes to be unselected before context is done

None
Example

with maintained_selection(): ... node["selected"].setValue(True) print(node["selected"].value()) False

Source code in client/ayon_nuke/api/lib.py
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
@contextlib.contextmanager
def maintained_selection(exclude_nodes=None):
    """Maintain selection during context

    Maintain selection during context and unselect
    all nodes after context is done.

    Arguments:
        exclude_nodes (list[nuke.Node]): list of nodes to be unselected
                                         before context is done

    Example:
        >>> with maintained_selection():
        ...     node["selected"].setValue(True)
        >>> print(node["selected"].value())
        False
    """
    if exclude_nodes:
        for node in exclude_nodes:
            node["selected"].setValue(False)

    previous_selection = nuke.selectedNodes()

    try:
        yield
    finally:
        # unselect all selection in case there is some
        reset_selection()

        # and select all previously selected nodes
        if previous_selection:
            select_nodes(previous_selection)

node_tempfile()

Create a temp file where node is pasted during duplication.

This is to avoid using clipboard for node duplication.

Source code in client/ayon_nuke/api/lib.py
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
@contextlib.contextmanager
def node_tempfile():
    """Create a temp file where node is pasted during duplication.

    This is to avoid using clipboard for node duplication.
    """

    tmp_file = tempfile.NamedTemporaryFile(
        mode="w", prefix="openpype_nuke_temp_", suffix=".nk", delete=False
    )
    tmp_file.close()
    node_tempfile_path = tmp_file.name

    try:
        # Yield the path where node can be copied
        yield node_tempfile_path

    finally:
        # Remove the file at the end
        os.remove(node_tempfile_path)

on_script_load()

Callback for ffmpeg support

Source code in client/ayon_nuke/api/lib.py
818
819
820
821
822
823
824
825
826
def on_script_load():
    ''' Callback for ffmpeg support
    '''
    if nuke.env["LINUX"]:
        nuke.tcl('load ffmpegReader')
        nuke.tcl('load ffmpegWriter')
    else:
        nuke.tcl('load movReader')
        nuke.tcl('load movWriter')

process_workfile_builder()

[DEPRECATED] Process workfile builder on nuke start

This function is deprecated and will be removed in future versions. Use settings for project_settings/nuke/templated_workfile_build which are supported by api start_workfile_template_builder().

Source code in client/ayon_nuke/api/lib.py
2469
2470
2471
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
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
@deprecated("ayon_nuke.api.lib.start_workfile_template_builder")
def process_workfile_builder():
    """ [DEPRECATED] Process workfile builder on nuke start

    This function is deprecated and will be removed in future versions.
    Use settings for `project_settings/nuke/templated_workfile_build` which are
    supported by api `start_workfile_template_builder()`.
    """

    # to avoid looping of the callback, remove it!
    nuke.removeOnCreate(process_workfile_builder, nodeClass="Root")

    # get state from settings
    project_settings = get_current_project_settings()
    workfile_builder = project_settings["nuke"].get(
        "workfile_builder", {})

    # get settings
    create_fv_on = workfile_builder.get("create_first_version") or None
    builder_on = workfile_builder.get("builder_on_start") or None

    last_workfile_path = os.environ.get("AYON_LAST_WORKFILE")

    # generate first version in file not existing and feature is enabled
    if create_fv_on and not os.path.exists(last_workfile_path):
        # get custom template path if any
        custom_template_path = get_current_context_custom_workfile_template(
            project_settings=project_settings
        )

        # if custom template is defined
        if custom_template_path:
            log.info("Adding nodes from `{}`...".format(
                custom_template_path
            ))
            try:
                # import nodes into current script
                nuke.nodePaste(custom_template_path)
            except RuntimeError:
                raise RuntimeError((
                    "Template defined for project: {} is not working. "
                    "Talk to your manager for an advise").format(
                        custom_template_path))

        # if builder at start is defined
        if builder_on:
            log.info("Building nodes from presets...")
            # build nodes by defined presets
            BuildWorkfile().process()

        log.info("Saving script as version `{}`...".format(
            last_workfile_path
        ))
        # safe file as version
        save_file(last_workfile_path)
        return

read_avalon_data(node)

Return user-defined knobs from given node

Parameters:

Name Type Description Default
node Node

Nuke node object

required

Returns:

Name Type Description
list

A list of nuke.Knob object

Source code in client/ayon_nuke/api/lib.py
569
570
571
572
573
574
575
576
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
def read_avalon_data(node):
    """Return user-defined knobs from given `node`

    Args:
        node (nuke.Node): Nuke node object

    Returns:
        list: A list of nuke.Knob object

    """
    def compat_prefixed(knob_name):
        if knob_name.startswith("avalon:"):
            return knob_name[len("avalon:"):]
        elif knob_name.startswith("ak:"):
            return knob_name[len("ak:"):]

    data = dict()

    pattern = ("(?<=addUserKnob {)"
               "([0-9]*) (\\S*)"  # Matching knob type and knob name
               "(?=[ |}])")
    tcl_script = node.writeKnobs(nuke.WRITE_USER_KNOB_DEFS)
    result = re.search(pattern, tcl_script)

    if result:
        first_user_knob = result.group(2)
        # Collect user knobs from the end of the knob list
        for knob in reversed(node.allKnobs()):
            knob_name = knob.name()
            if not knob_name:
                # Ignore unnamed knob
                continue
            try:
                knob_type = nuke.knob(knob.fullyQualifiedName(), type=True)
                value = knob.value()
            except Exception:
                log.debug(
                    f"Error in knob {knob_name}, node {node['name'].value()}")
                continue
            if (
                knob_type not in EXCLUDED_KNOB_TYPE_ON_READ or
                # For compating read-only string data that imprinted
                # by `nuke.Text_Knob`.
                (knob_type == 26 and value)
            ):
                key = compat_prefixed(knob_name)
                if key is not None:
                    data[key] = value

            if knob_name == first_user_knob:
                break

    return data

refresh_node(node)

Correct a bug caused by the multi-threading of nuke.

Refresh the node to make sure that it takes the desired attributes.

Source code in client/ayon_nuke/api/lib.py
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
def refresh_node(node):
    """Correct a bug caused by the multi-threading of nuke.

    Refresh the node to make sure that it takes the desired attributes.
    """

    x = node.xpos()
    y = node.ypos()
    nuke.autoplaceSnap(node)
    node.setXYpos(x, y)

reset_selection()

Deselect all selected nodes

Source code in client/ayon_nuke/api/lib.py
2390
2391
2392
2393
def reset_selection():
    """Deselect all selected nodes"""
    for node in nuke.selectedNodes():
        node["selected"].setValue(False)

script_name()

Returns nuke script path

Source code in client/ayon_nuke/api/lib.py
990
991
992
993
def script_name():
    ''' Returns nuke script path
    '''
    return nuke.root().knob("name").value()

select_nodes(nodes)

Selects all inputted nodes

Parameters:

Name Type Description Default
nodes Union[list, tuple, set]

nuke nodes to be selected

required
Source code in client/ayon_nuke/api/lib.py
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
def select_nodes(nodes):
    """Selects all inputted nodes

    Arguments:
        nodes (Union[list, tuple, set]): nuke nodes to be selected
    """
    assert isinstance(nodes, (list, tuple, set)), \
        "nodes has to be list, tuple or set"

    for node in nodes:
        node["selected"].setValue(True)

set_avalon_knob_data(node, data=None, prefix='avalon:')

[DEPRECATED] Sets data into nodes's avalon knob

This function is still used but soon will be deprecated. Use set_node_data instead.

Parameters:

Name Type Description Default
node Node

Nuke node to imprint with data,

required
data dict

Data to be imprinted into AvalonTab

None
prefix str

filtering prefix

'avalon:'

Returns:

Type Description

node (nuke.Node)

Examples:

data = { 'folderPath': 'sq020sh0280', 'productType': 'render', 'productName': 'productMain' }

Source code in client/ayon_nuke/api/lib.py
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
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
@deprecated("ayon_nuke.api.lib.set_node_data")
def set_avalon_knob_data(node, data=None, prefix="avalon:"):
    """[DEPRECATED] Sets data into nodes's avalon knob

    This function is still used but soon will be deprecated.
    Use `set_node_data` instead.

    Arguments:
        node (nuke.Node): Nuke node to imprint with data,
        data (dict, optional): Data to be imprinted into AvalonTab
        prefix (str, optional): filtering prefix

    Returns:
        node (nuke.Node)

    Examples:
        data = {
            'folderPath': 'sq020sh0280',
            'productType': 'render',
            'productName': 'productMain'
        }
    """
    data = data or dict()
    create = OrderedDict()

    tab_name = NODE_TAB_NAME
    editable = ["folderPath", "productName", "name", "namespace"]

    existed_knobs = node.knobs()

    for key, value in data.items():
        knob_name = prefix + key
        gui_name = key

        if knob_name in existed_knobs:
            # Set value
            try:
                node[knob_name].setValue(value)
            except TypeError:
                node[knob_name].setValue(str(value))
        else:
            # New knob
            name = (knob_name, gui_name)  # Hide prefix on GUI
            if key in editable:
                create[name] = value
            else:
                create[name] = Knobby("String_Knob",
                                      str(value),
                                      flags=[nuke.READ_ONLY])
    if tab_name in existed_knobs:
        tab_name = None
    else:
        tab = OrderedDict()
        warn = Knobby("Text_Knob", "Warning! Do not change following data!")
        divd = Knobby("Text_Knob", "")
        head = [
            (("warn", ""), warn),
            (("divd", ""), divd),
        ]
        tab[DATA_GROUP_KEY] = OrderedDict(head + list(create.items()))
        create = tab

    imprint(node, create, tab=tab_name)
    return node

set_node_data(node, knobname, data)

Write data to node invisible knob

Will create new in case it doesn't exists or update the one already created.

Parameters:

Name Type Description Default
node Node

node object

required
knobname str

knob name

required
data dict

data to be stored in knob

required
Source code in client/ayon_nuke/api/lib.py
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
def set_node_data(node, knobname, data):
    """Write data to node invisible knob

    Will create new in case it doesn't exists
    or update the one already created.

    Args:
        node (nuke.Node): node object
        knobname (str): knob name
        data (dict): data to be stored in knob
    """
    # if exists then update data
    if knobname in node.knobs():
        update_node_data(node, knobname, data)
        return

    # else create new
    knob_value = JSON_PREFIX + json.dumps(data)
    knob = nuke.String_Knob(knobname)
    knob.setValue(knob_value)
    knob.setFlag(nuke.INVISIBLE)
    node.addKnob(knob)

set_node_knobs_from_settings(node, knob_settings, **kwargs)

Overriding knob values from settings

Using schema_nuke_knob_inputs for knob type definitions.

Parameters:

Name Type Description Default
node Node

nuke node

required
knob_settings list

list of dict. Keys are type, name, value

required
kwargs dict)[optional]

keys for formattable knob settings

{}
Source code in client/ayon_nuke/api/lib.py
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
def set_node_knobs_from_settings(node, knob_settings, **kwargs):
    """ Overriding knob values from settings

    Using `schema_nuke_knob_inputs` for knob type definitions.

    Args:
        node (nuke.Node): nuke node
        knob_settings (list): list of dict. Keys are `type`, `name`, `value`
        kwargs (dict)[optional]: keys for formattable knob settings
    """
    for knob in knob_settings:
        knob_name = knob["name"]
        if knob_name not in node.knobs():
            continue

        knob_type = knob["type"]
        knob_value = knob[knob_type]
        if knob_type == "expression":
            node[knob_name].setExpression(knob_value)
            continue

        # first deal with formattable knob settings
        if knob_type == "formatable":
            template = knob_value["template"]
            to_type = knob_value["to_type"]
            try:
                knob_value = template.format(**kwargs)
            except KeyError as msg:
                raise KeyError(
                    "Not able to format expression: {}".format(msg))

            # convert value to correct type
            if to_type == "2d_vector":
                knob_value = knob_value.split(";").split(",")

            knob_type = to_type

        if not knob_value:
            continue

        knob_value = convert_knob_value_to_correct_type(
            knob_type, knob_value)

        node[knob_name].setValue(knob_value)

swap_node_with_dependency(old_node, new_node)

Swap node with dependency

Swap node with dependency and reconnect all inputs and outputs. It removes old node.

Parameters:

Name Type Description Default
old_node Node

node to be replaced

required
new_node Node

node to replace with

required
Example

old_node_name = old_node["name"].value() print(old_node_name) old_node_name_01 with swap_node_with_dependency(old_node, new_node) as node_name: ... new_node["name"].setValue(node_name) print(new_node["name"].value()) old_node_name_01

Source code in client/ayon_nuke/api/lib.py
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
@contextlib.contextmanager
def swap_node_with_dependency(old_node, new_node):
    """ Swap node with dependency

    Swap node with dependency and reconnect all inputs and outputs.
    It removes old node.

    Arguments:
        old_node (nuke.Node): node to be replaced
        new_node (nuke.Node): node to replace with

    Example:
        >>> old_node_name = old_node["name"].value()
        >>> print(old_node_name)
        old_node_name_01
        >>> with swap_node_with_dependency(old_node, new_node) as node_name:
        ...     new_node["name"].setValue(node_name)
        >>> print(new_node["name"].value())
        old_node_name_01
    """
    # preserve position
    xpos, ypos = old_node.xpos(), old_node.ypos()
    # preserve selection after all is done
    outputs = get_node_outputs(old_node)
    inputs = old_node.dependencies()
    node_name = old_node["name"].value()

    try:
        nuke.delete(old_node)

        yield node_name
    finally:

        # Reconnect inputs
        for i, node in enumerate(inputs):
            new_node.setInput(i, node)
        # Reconnect outputs
        if outputs:
            for n, pipes in outputs.items():
                for i in pipes:
                    n.setInput(i, new_node)
        # return to original position
        new_node.setXYpos(xpos, ypos)

update_node_data(node, knobname, data)

Update already present data.

Parameters:

Name Type Description Default
node Node

node object

required
knobname str

knob name

required
data dict

data to update knob value

required
Source code in client/ayon_nuke/api/lib.py
204
205
206
207
208
209
210
211
212
213
214
215
216
def update_node_data(node, knobname, data):
    """Update already present data.

    Args:
        node (nuke.Node): node object
        knobname (str): knob name
        data (dict): data to update knob value
    """
    knob = node[knobname]
    node_data = get_node_data(node, knobname) or {}
    node_data.update(data)
    knob_value = JSON_PREFIX + json.dumps(node_data)
    knob.setValue(knob_value)

version_up_script()

Raising working script's version

Source code in client/ayon_nuke/api/lib.py
924
925
926
927
928
def version_up_script():
    ''' Raising working script's version
    '''
    import nukescripts
    nukescripts.script_and_write_nodes_version_up()

writes_version_sync(write_node, log)

Callback synchronizing version of publishable write nodes

Tries to find version string in render path of write node and bump it to workfile version.

Source code in client/ayon_nuke/api/lib.py
852
853
854
855
856
857
858
859
860
861
862
863
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
def writes_version_sync(write_node, log):
    """ Callback synchronizing version of publishable write nodes

    Tries to find version string in render path of write node and bump it to
    workfile version.

    Args:
        write_node (nuke.Node)
        log (logging.Logger) - logger to output messages into Publisher

    """
    try:
        rootVersion = get_version_from_path(nuke.root().name())
        padding = len(rootVersion)
        new_version = "v" + str("{" + ":0>{}".format(padding) + "}").format(
            int(rootVersion)
        )
    except Exception:
        log.warning("Scene name doesn't have version part.", exc_info=True)
        return

    try:
        write_path = write_node["file"].value()
        node_version = "v" + get_version_from_path(write_path)
        node_new_file = write_path.replace(node_version, new_version)

        def replace_match(match):
            x_value = int(match.group(1))  # Extract the number X
            return '#' * x_value  # Return '#' repeated X times

        # Use regex to find all occurrences of '%0Xd' with `#`s
        node_new_file = re.sub(r'%0*(\d+)d', replace_match, node_new_file)

        log.debug(f"Overwriting Write path to '{node_new_file}'")
        write_node["file"].setValue(node_new_file)
        render_dir = os.path.dirname(node_new_file)
        if not os.path.isdir(render_dir):
            log.warning(f"Path '{render_dir}' does not exist! Creating it.")
            os.makedirs(render_dir)
    except Exception:
        log.warning(
            f"Write node: `{write_node.name()}` has no version "
            f"in path: '{write_path}'. Expected format as `.vXXX` or `_vXXX`.",
            exc_info=True
        )