Skip to content

G

Source code in core/nodeclass.py
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
class G:

    def __init__(self, prefix: str = ""):
        """ Group functional call

        This class is provided to expose ***Group*** nodes as functions with keyword arguments.
        When a Group named "Do Something" is created, it can be called with two syntaxes:
        - Using `Group` node: `node = Group("Do Something", ...)`
        - Using `G` function with the snake case name : `node = G().do_someting(...)`

        This facility can be particularilty usedful for projects with a lot of groups. The groups
        can be grouped by prefixes. The prefixes are hidden in the code.


        ``` python

        from geonodes import GeoNodes, Geometry, Float, Mesh, G

        with GeoNodes("Do Something", is_group=True, prefix="Utils"):

            g = Geometry()
            a = Float(3.14, "Pi")
            b = Float(6.28, "Tau")
            g += Mesh.Cube()

            g = Mesh(g)
            g.points.Pi = a + b

            g.out()

            a.out("Pi")

        with GeoNodes("Do Something Else", is_group=True, prefix="Utils"):

            g = Geometry()
            a = Float(3.14, "Pi")
            b = Float(6.28, "Tau")
            g += Mesh.Cube()

            g = Mesh(g)
            g.points.Pi = a + b

            g.out()

        with GeoNodes("Calling Groups"):

            utils = G("Utils")

            g = utils.do_something(Geometry(), pi=6.28)
            g = utils.do_something_else(g, g.pi, tau=7)
            g.out()   
        ```

        Parameters
        ----------
        prefix
            prefix to use when searching a tree

        """
        if prefix is None:
            self.prefix = ""
        else:
            self.prefix = str(prefix)
            if len(self.prefix):
                self.prefix += " "
        self.functions = {}

    # ====================================================================================================
    # Str returns a string to be compatible with prefix argument in Tree initialization

    def __str__(self):
        if self.prefix == "":
            return ""
        else:
            return self.prefix[:-1]

    # ====================================================================================================
    # Build a function from a node
    # ====================================================================================================

    @staticmethod
    def _call_group(group_name, *args, **kwargs):
        """Shared group invocation for G and decorated Python builders."""
        node = Group(group_name)
        return node.method_call(*args, **kwargs)

    def build_function(self, btree):
        """ Dynamically create a function to call the tree as Group

        The name of the function is the snake case version of the tree name.

        Parameters
        ----------
        btree : Blender GeometryNodeTree | ShaderNodeTree
            the tree

        Returns
        -------
        None
        """

        func_name = utils.snake_case(btree.name)
        if func_name in self.functions:
            return self.functions[func_name]['f']

        # ---------------------------------------------------------------------------
        # Calling the node
        # ---------------------------------------------------------------------------

        def f(*args, **kwargs):
            return self._call_group(btree.name, *args, **kwargs)

        # ---------------------------------------------------------------------------
        # Adding the function
        # ---------------------------------------------------------------------------

        self.functions[func_name] = {'f': f, 'source': ""}

        return f

    # ====================================================================================================
    # Source code
    # ====================================================================================================

    def error(self, f, exception=None):
        """ Raise an error when function call fails.

        Raises
        ------
        - NodeError

        Parameters
        ----------
        f : function
            the function in error

        exception : Exception
            the exception that was raised

        """

        spec = self.functions.get(f.__name__)
        if spec is None:
            source = f"No source code found for function: {f.__name__}. Existing functions are {list(self.functions.keys())}."
        else:
            source = spec['source']

        se = "No exception " if exception is None else str(exception)

        raise NodeError(f"Error when calling function '{f.__name__}' of group {self}.\n\n"
                        f"Signature is:\n\n{source}\n",
                        error_message = se)

    # ====================================================================================================
    # Get a tree by its name
    # ====================================================================================================

    @classmethod
    def get_tree(cls, name, tree_type = 'GeometryNodeTree'):

        for ng in bpy.data.node_groups:
            if ng.bl_idname != tree_type:
                continue
            if ng.name == name:
                return ng

        return None

    # ====================================================================================================
    # Get a tree by its snake case name
    # ====================================================================================================

    def __getattr__(self, name):

        if name in {"__dict__", "__weakref__"}:
            raise AttributeError(name)

        tree_type = Tree.current_tree()._btree.bl_idname
        groups = utils.get_available_groups(tree_type)

        target = utils.snake_case(self.prefix + name)
        group_name = utils.find_snake_case_name(target, list(groups.keys()))
        if group_name is None:
            raise AttributeError(f"Group '{self.prefix + name}' not found")

        group = blender.load_node_group(groups[group_name])

        return self.build_function(group)


    @staticmethod
    def _class_test():

        from geonodes import GeoNodes, Geometry, Float, Mesh, G

        with GeoNodes("Do Something", is_group=True, prefix="Utils"):

            g = Geometry()
            a = Float(3.14, "Pi")
            b = Float(6.28, "Tau")
            g += Mesh.Cube()

            g = Mesh(g)
            g.points.Pi = a + b

            g.out()

            a.out("Pi")

        with GeoNodes("Do Something Else", is_group=True, prefix="Utils"):

            g = Geometry()
            a = Float(3.14, "Pi")
            b = Float(6.28, "Tau")
            g += Mesh.Cube()

            g = Mesh(g)
            g.points.Pi = a + b

            g.out()

        with GeoNodes("Calling Groups"):

            utils = G("Utils")

            g = utils.do_something(Geometry(), pi=6.28)
            g = utils.do_something_else(g, g.pi, tau=7)
            g.out()  

__init__(prefix='')

Group functional call

This class is provided to expose Group nodes as functions with keyword arguments. When a Group named "Do Something" is created, it can be called with two syntaxes: - Using Group node: node = Group("Do Something", ...) - Using G function with the snake case name : node = G().do_someting(...)

This facility can be particularilty usedful for projects with a lot of groups. The groups can be grouped by prefixes. The prefixes are hidden in the code.

from geonodes import GeoNodes, Geometry, Float, Mesh, G

with GeoNodes("Do Something", is_group=True, prefix="Utils"):

    g = Geometry()
    a = Float(3.14, "Pi")
    b = Float(6.28, "Tau")
    g += Mesh.Cube()

    g = Mesh(g)
    g.points.Pi = a + b

    g.out()

    a.out("Pi")

with GeoNodes("Do Something Else", is_group=True, prefix="Utils"):

    g = Geometry()
    a = Float(3.14, "Pi")
    b = Float(6.28, "Tau")
    g += Mesh.Cube()

    g = Mesh(g)
    g.points.Pi = a + b

    g.out()

with GeoNodes("Calling Groups"):

    utils = G("Utils")

    g = utils.do_something(Geometry(), pi=6.28)
    g = utils.do_something_else(g, g.pi, tau=7)
    g.out()   

Parameters:

Name Type Description Default
prefix str

prefix to use when searching a tree

''
Source code in core/nodeclass.py
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
def __init__(self, prefix: str = ""):
    """ Group functional call

    This class is provided to expose ***Group*** nodes as functions with keyword arguments.
    When a Group named "Do Something" is created, it can be called with two syntaxes:
    - Using `Group` node: `node = Group("Do Something", ...)`
    - Using `G` function with the snake case name : `node = G().do_someting(...)`

    This facility can be particularilty usedful for projects with a lot of groups. The groups
    can be grouped by prefixes. The prefixes are hidden in the code.


    ``` python

    from geonodes import GeoNodes, Geometry, Float, Mesh, G

    with GeoNodes("Do Something", is_group=True, prefix="Utils"):

        g = Geometry()
        a = Float(3.14, "Pi")
        b = Float(6.28, "Tau")
        g += Mesh.Cube()

        g = Mesh(g)
        g.points.Pi = a + b

        g.out()

        a.out("Pi")

    with GeoNodes("Do Something Else", is_group=True, prefix="Utils"):

        g = Geometry()
        a = Float(3.14, "Pi")
        b = Float(6.28, "Tau")
        g += Mesh.Cube()

        g = Mesh(g)
        g.points.Pi = a + b

        g.out()

    with GeoNodes("Calling Groups"):

        utils = G("Utils")

        g = utils.do_something(Geometry(), pi=6.28)
        g = utils.do_something_else(g, g.pi, tau=7)
        g.out()   
    ```

    Parameters
    ----------
    prefix
        prefix to use when searching a tree

    """
    if prefix is None:
        self.prefix = ""
    else:
        self.prefix = str(prefix)
        if len(self.prefix):
            self.prefix += " "
    self.functions = {}

_call_group(group_name, *args, **kwargs) staticmethod

Shared group invocation for G and decorated Python builders.

Source code in core/nodeclass.py
2950
2951
2952
2953
2954
@staticmethod
def _call_group(group_name, *args, **kwargs):
    """Shared group invocation for G and decorated Python builders."""
    node = Group(group_name)
    return node.method_call(*args, **kwargs)

build_function(btree)

Dynamically create a function to call the tree as Group

The name of the function is the snake case version of the tree name.

Parameters:

Name Type Description Default
btree Blender GeometryNodeTree | ShaderNodeTree

the tree

required

Returns:

Type Description
None
Source code in core/nodeclass.py
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
def build_function(self, btree):
    """ Dynamically create a function to call the tree as Group

    The name of the function is the snake case version of the tree name.

    Parameters
    ----------
    btree : Blender GeometryNodeTree | ShaderNodeTree
        the tree

    Returns
    -------
    None
    """

    func_name = utils.snake_case(btree.name)
    if func_name in self.functions:
        return self.functions[func_name]['f']

    # ---------------------------------------------------------------------------
    # Calling the node
    # ---------------------------------------------------------------------------

    def f(*args, **kwargs):
        return self._call_group(btree.name, *args, **kwargs)

    # ---------------------------------------------------------------------------
    # Adding the function
    # ---------------------------------------------------------------------------

    self.functions[func_name] = {'f': f, 'source': ""}

    return f

error(f, exception=None)

Raise an error when function call fails.

Raises:

Type Description
-NodeError

Parameters:

Name Type Description Default
f function

the function in error

required
exception Exception

the exception that was raised

None
Source code in core/nodeclass.py
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
def error(self, f, exception=None):
    """ Raise an error when function call fails.

    Raises
    ------
    - NodeError

    Parameters
    ----------
    f : function
        the function in error

    exception : Exception
        the exception that was raised

    """

    spec = self.functions.get(f.__name__)
    if spec is None:
        source = f"No source code found for function: {f.__name__}. Existing functions are {list(self.functions.keys())}."
    else:
        source = spec['source']

    se = "No exception " if exception is None else str(exception)

    raise NodeError(f"Error when calling function '{f.__name__}' of group {self}.\n\n"
                    f"Signature is:\n\n{source}\n",
                    error_message = se)