Skip to content

Tree

Root class for GeoNodes and ShaderNodes trees.

The system manages a stack of Trees. When a Tree is created, it is placed at the top of the stack and becomes the current tree. The Tree is poped from the stack with the method pop.

Better use the context management syntax:

with GeoNodes("My Tree") as tree:
    pass

Important

Trees scripted with geonodes are kept distinct from manually created trees by putting the marker string 'GEONODES' in the description attribute. If you initialize a Tree with the name of an existing tree:

  • it will be replaced if it is a tree scripted with geonodes
  • it will be renamed if it is not the case

This avoids to accidentally delete a manually created tree.

Warning

This doesn't work with shaders embedded in a Material. It is why the argument replace_material is set to False by default when creating a Shader. Hence, an existing material is not replaced by a geonodes scripts except if you change the default value of replace_material argument to True.

# Create the material if it doesn't exist
# Do nothing if it already exists
with ShaderNodes("My Material"):
    pass

# Replace the existing material
with ShaderNodes("My Material", replace_material=True):
    pass

Note

prefix argument is added at the begining of the name.

# The two following modifiers have the same name

with GeoNodes("My Modifier", prefix="Utils"):
    pass

with GeoNodes("Utils My Modifier"):
    pass
````

The `prefix` is usefull for big projects with numerous Groups and when you want the Groups to be sorted by their name.
You can then use the special class `G` to call the groups as python functions:

``` python
# Prefix
util = "Util"
math = "Math"

# Util Change Shape
with GeoNodes("Change Shape", prefix=util):
    pass

# Util Rotate
with GeoNodes("Rotate", prefix=util):
    pass

# Math Multiply
with GeoNodes("Multiply", prefix=math)
    pass

# Math Divide
with GeoNodes("Divide", prefix=math)
    pass

# Call the groups
with GeoNodes("My Modifier"):
    # Call a math group with the special class G
    a = G(math).divide(...)
Source code in core/treeclass.py
 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
 345
 346
 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
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 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
 492
 493
 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
 536
 537
 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
 567
 568
 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
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 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
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 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
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 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
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
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
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
class Tree:
    """ Root class for GeoNodes and ShaderNodes trees.

    The system manages a stack of Trees. When a Tree is created, it is placed at the top of the stack
    and becomes the current tree.
    The Tree is poped from the stack with the method pop.

    Better use the context management syntax:

    ``` python
    with GeoNodes("My Tree") as tree:
        pass
    ```

    !!! important

        Trees scripted with **geonodes** are kept distinct from manually created trees by putting the
        marker string _'GEONODES'_ in the description attribute. If you initialize a Tree with the
        name of an existing tree:

        - it will be replaced if it is a tree scripted with **geonodes**
        - it will be renamed if it is not the case

        This avoids to accidentally delete a manually created tree.

    !!! warning
        This doesn't work with shaders embedded in a Material. It is why the argument `replace_material` is set to False
        by default when creating a Shader. Hence, an existing material is not replaced by a geonodes scripts
        except if you change the default value of `replace_material` argument to True.

    ``` python
    # Create the material if it doesn't exist
    # Do nothing if it already exists
    with ShaderNodes("My Material"):
        pass

    # Replace the existing material
    with ShaderNodes("My Material", replace_material=True):
        pass
    ```

    !!! note
        `prefix` argument is added at the begining of the name.

    ``` python
    # The two following modifiers have the same name

    with GeoNodes("My Modifier", prefix="Utils"):
        pass

    with GeoNodes("Utils My Modifier"):
        pass
    ````

    The `prefix` is usefull for big projects with numerous Groups and when you want the Groups to be sorted by their name.
    You can then use the special class `G` to call the groups as python functions:

    ``` python
    # Prefix
    util = "Util"
    math = "Math"

    # Util Change Shape
    with GeoNodes("Change Shape", prefix=util):
        pass

    # Util Rotate
    with GeoNodes("Rotate", prefix=util):
        pass

    # Math Multiply
    with GeoNodes("Multiply", prefix=math)
        pass

    # Math Divide
    with GeoNodes("Divide", prefix=math)
        pass

    # Call the groups
    with GeoNodes("My Modifier"):
        # Call a math group with the special class G
        a = G(math).divide(...)
    ```
    """

    _total_nodes = 0
    _total_links = 0
    _total_built = 0
    _total_existing = 0
    _total_warnings = 0
    _total_time = 0.0
    _total_arrange_time = 0.0
    _counter_started = None

    TREE_STACK = []

    def __init__(self,
            tree_name        : str, 
            tree_type        : str   = 'GeometryNodeTree',
            *,
            fake_user        : bool  = False, 
            is_group         : bool  = False,
            prefix           : str   = "",
            rebuild          : bool  = True,
            color_tag        : str   = 'NONE',
            ):

        """ 

        Parameters
        ----------
        tree_name : str
            tree name

        tree_type : {'GeometryNodeTree', 'ShaderNodeTree'}, default='GeometryNodeTree'
            tree type 

        fake_user : bool, default=False
            fake user flag

        is_group : bool, default=False
            Group or not

        prefix : str, default=""
            prefix to add at the begining of the tree name

        rebuild : bool, default=True
            rebuild an existing tree; new trees are always built

        color_tag : str, default='NONE'
            group or modifier color_tag attribute

        """
        self._build_started = perf_counter()
        self._arrange_time = 0.0
        if Tree._counter_started is None:
            Tree._counter_started = self._build_started
        self._btree = None

        # Wrap an existing NodeTree without clearing or finalizing it
        self._loaded = False

        # Arrange when finished
        self._use_arrange = True

        # In / out nodes cache
        self._input_node  = None
        self._output_node = None

        # ---------------------------------------------------------------------------
        # Stacks
        # ---------------------------------------------------------------------------

        self._panels  = [ItemPath(None)]
        self._layouts = []

        # Input / output socket creation are performed by node with dynamic
        # sockets (either with items or with tree_node)
        # By default, these are input_node and output_node
        # This behavior can be overloaded using input and output stacks

        self._output_stack  = []
        self._input_stack   = []

        # Prefix
        if prefix is None:
            prefix =  ""

        prefix = str(prefix)
        if len(prefix):
            tree_name = f"{prefix} {tree_name}"
        self._prefix = prefix

        # ----------------------------------------------------------------------------------------------------
        # Shader Node tree is a property of Material
        # ----------------------------------------------------------------------------------------------------

        replace_material = rebuild and not is_group and tree_type == 'ShaderNodeTree'

        if tree_type is None:
            btree = tree_name
            if not isinstance(btree, bpy.types.NodeTree):
                raise NodeError(
                    f"Tree inititialization error: when 'tree_type' is None, 'tree_name' must be a tree, not <{tree_name}>."
                    )
            self._btree = btree
            self._loaded = True
            rebuild = True

        elif tree_type == 'ShaderNodeTree':

            self._material = None
            if not is_group:
                self._material = bpy.data.materials.get(tree_name)

                if self._material is None:
                    self._material = bpy.data.materials.new(tree_name)
                    rebuild = True
                else:
                    rebuild = replace_material

                if rebuild:
                    self._material.use_nodes = True
                self._btree = self._material.node_tree
                if rebuild:
                    self._material.use_fake_user = fake_user

        # ----------------------------------------------------------------------------------------------------
        # Get the tree nodes from node_groups
        # ----------------------------------------------------------------------------------------------------

        if self._btree is None and not (tree_type == 'ShaderNodeTree' and not is_group):

            btree = utils.get_tree(tree_name, tree_type=tree_type, create=False)
            if btree is None:
                self._btree = utils.get_tree(tree_name, tree_type=tree_type, create=True)
                rebuild = True
            else:
                self._btree = btree
            if rebuild:
                self._btree.use_fake_user = fake_user

        self._is_group = is_group

        # Managed lists
        self._kept_nodes = []
        self._nodes      = {} # Registered nodes: bpy.types.Node.name -> Node
        self._mod_vals   = {} # To restore modifiers values when necessary (menus)

        # ---------------------------------------------------------------------------
        # Clear / Keep the tree
        # ---------------------------------------------------------------------------

        # Store the current value of each input socket
        if tree_type == 'GeometryNodeTree' or self._is_group:
            for bnode in self._btree.nodes:
                if bnode.bl_idname != 'NodeGroupInput':
                    continue

                for name, mod in self.get_modifiers().items():
                    values = {}
                    mod_inputs = mod.properties.inputs
                    for bsock in bnode.outputs:
                        if bsock.identifier in mod_inputs:
                            prop = getattr(mod_inputs, bsock.identifier)
                            val = getattr(prop, 'value', None)
                            if val is not None:
                                values[(bsock.name, bsock.bl_idname)] = val
                                values[bsock.identifier] = val

                    self._mod_vals[name] = values

                break

        # Clear tree
        if rebuild and (not self._loaded):
            self.clear(keep_nodes=False)

        # ---------------------------------------------------------------------------
        # Effective build policy (new trees are always built)
        # ---------------------------------------------------------------------------

        self._rebuild = rebuild

        # ---------------------------------------------------------------------------
        # Color tag
        # ---------------------------------------------------------------------------

        if self._rebuild and not self._loaded and hasattr(self._btree, 'color_tag'):
            utils.set_rna_attr(self._btree, 'color_tag', color_tag)

        # ---------------------------------------------------------------------------
        # Interface
        # ---------------------------------------------------------------------------

        self._interface = None
        if self._is_group or tree_type == 'GeometryNodeTree':
            self._interface = TreeInterface(self._btree)
            if self._rebuild and not self._loaded:
                self._interface.clear(use_bin=True)

        # ---------------------------------------------------------------------------
        # Random generator for random colors
        # ---------------------------------------------------------------------------

        self._rng = np.random.default_rng(0)

        # Load the tree
        if self._loaded:
            self.load_btree()

    # ====================================================================================================
    # Stack of trees
    # ====================================================================================================

    @staticmethod
    def current_tree():
        """ > Get the Current Tree.

        Returns None if no tree is currently open

        Returns
        -------
        Tree
            current tree or None

        """
        if len(Tree.TREE_STACK):
            return Tree.TREE_STACK[-1]
        else:
            return None

    # ----------------------------------------------------------------------------------------------------
    # Push the current tree zone
    # ----------------------------------------------------------------------------------------------------

    def push(self):
        """ > Make this tree zone the current one

        !!! important
            This methods shouldn't be called directly, better use a **with** context block.

        ``` python
        with Tree("My Name"):
            pass
        ```
        """
        Tree.TREE_STACK.append(self)
        return self

    # ----------------------------------------------------------------------------------------------------
    # Pop from the stack
    # ----------------------------------------------------------------------------------------------------

    def pop(self, error=False):
        """ > Remove this tree from the stack

        !!! important
            This methods shouldn't be called directly, better use a **with** context block.

        Raises
        ------
        NodeError
            if this tree is not the current one


        ``` python
        with Tree("My Name"):
            pass
        ```
        """
        # ---------------------------------------------------------------------------
        # Ignore changes
        # ---------------------------------------------------------------------------

        if not Tree.TREE_STACK or Tree.TREE_STACK[-1] is not self:
            raise RuntimeError("Error in tree stack management")

        if not self._rebuild or self._loaded:
            Tree.TREE_STACK.pop()
            Tree._total_existing += 1
            return

        # ---------------------------------------------------------------------------
        # Remove kept nodes
        # ---------------------------------------------------------------------------

        for bnode in self._kept_nodes:
            self._btree.nodes.remove(bnode)

        # ---------------------------------------------------------------------------
        # Update modifiers inputs
        # ---------------------------------------------------------------------------

        if self._has_input_node:

            modifiers = self.get_modifiers()

            for bsock in self.input_node._bnode.outputs:

                isock = self._interface.by_identifier(bsock.identifier)
                if not hasattr(isock, 'default_value'):
                    continue

                # ----------------------------------------
                # Menu socket
                # ----------------------------------------

                if bsock.bl_idname == 'NodeSocketMenu':
                    for mod_name, mod in modifiers.items():

                        current = None

                        mod_vals = self._mod_vals.get(mod_name)

                        if mod_vals is not None:
                            current = mod_vals.get(bsock.identifier, None)

                        if current is None:
                            current = isock.default_value

                        mod_input = getattr(mod.properties.inputs, bsock.identifier)

                        try:
                            mod_input.value = current
                        except Exception as e:
                            try:
                                mod_input.value = isock.default_value
                            except:
                                pass

                    continue

                # ----------------------------------------
                # General
                # ----------------------------------------

                for mod_name, mod in modifiers.items():

                    mod_vals = self._mod_vals.get(mod_name)
                    if mod_vals is None:
                        continue

                    # Nothing to do if identifier exists
                    if bsock.identifier in mod_vals:
                        continue

                    # Nen identifier : let's set the default value
                    mod_input = getattr(mod.properties.inputs, bsock.identifier)
                    if not hasattr(mod_input, 'value'):
                        continue

                    try:
                        mod_input.value = isock.default_value
                    except Exception as e:
                        print(f"CAUTION: error when setting default <{isock.default_value}> value to socket '{bsock.name}'.\n -> error is: {str(e)}")

        # ---------------------------------------------------------------------------
        # Finalize
        # ---------------------------------------------------------------------------

        # Check dead ends
        warnings = 0
        if not error:
            utils.check_zones(self._btree)
            # Socket structures, notably inside nested closures, may still be
            # unresolved immediately after a link is created. Validate links
            # only once Blender has inferred the completed tree.
            for link in self._btree.links:
                utils.check_link(link)
            warnings = self.check_warnings()

        # Remove from stack
        tree = Tree.TREE_STACK.pop()
        if tree != self:
            raise RuntimeError(f"Error in tree stack management")

        # Empty the interface bin
        if (not error) and self._interface is not None:
            self._interface.empty_bin()

        # Last node in error
        if error and len(self._nodes):
            for node in reversed(self._nodes.values()):
                if node._bnode.bl_idname in ['NodeGroupOutput', 'NodeGroupInput']:
                    continue
                utils.set_node_error(node._bnode)
                break

        # Arrange the nodes
        self.arrange()

        # Stats
        if self._btree.bl_idname == 'ShaderNodeTree' and self._material is not None:
            name = f"Material '{self._material.name}'"
        else:
            name = f"Tree '{self._btree.name}'"

        elapsed = perf_counter() - self._build_started
        print(f"{name} built: {self._str_stats}, warnings: {warnings}, "
              f"time: {elapsed:.2f} s (arrange: {self._arrange_time:.2f} s)")

        Tree._total_nodes += len(self._btree.nodes)
        Tree._total_links += len(self._btree.links)
        Tree._total_built += int(not error)
        Tree._total_warnings += warnings
        Tree._total_time = perf_counter() - Tree._counter_started

    # ----------------------------------------------------------------------------------------------------
    # Context management
    # ----------------------------------------------------------------------------------------------------

    def __enter__(self):
        self.push()
        return self

    def __exit__(self, type, exc_value, traceback):

        ok = exc_value is None or isinstance(exc_value, Break)

        self.pop(not ok)

        if isinstance(exc_value, Break):
            return True

    # ====================================================================================================
    # Remove node groups
    # ====================================================================================================

    @staticmethod
    def remove_groups(names=None, prefix=None, geonodes=True, shadernodes=True):
        """ > Remove Groups created by GeoNodes.

        !!! important
             This method can only remove groups created by **GeoNodes**.

        Parameters
        ----------
        names : str or list of strs, optional
            name of the node groups to remove (all if None)

        prefix : str, optional
            name prefix for the groups to delete

        geonodes : bool, default=True
            remove geometry nodes groups

        shadernodes : bool, default=True
            remove shader nodes groups


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

        groups = []
        if prefix is None:
            prefix_ = ""
        else:
            prefix_ = prefix + ' '

        tree_types = []
        if geonodes:
            tree_types.append('GeometryNodeTree')
        if shadernodes:
            tree_types.append('ShaderNodeTree')

        for group in bpy.data.node_groups:
            if group.bl_idname not in tree_types:
                continue

            if not group.description.startswith('GEONODES'):
                continue

            if prefix is not None and group.name[:len(prefix_)] != prefix_:
                continue

            if names is None:
                pass
            elif isinstance(names, str):
                if group.name != prefix_ + names:
                    continue
            elif isinstance(names, list):
                ok = False
                for name in names:
                    if group.name == prefix_ + name:
                        ok = True
                        break
                if not ok:
                    continue
            else:
                raise Exception(f"Argument names '{names}' is not valid: None, str or list of strs expected")

            groups.append(group)

        print("Remove node groups")
        for group in groups:
            print(' -', group.name)
            bpy.data.node_groups.remove(group)

        print(f"{len(groups)} node groups removed")

    # ====================================================================================================
    # Check if the blender node is valid in the context
    #
    # Nodes specific to tools can't be inserted in modifiers
    # ====================================================================================================

    def check_node_validity(self, bnode):
        pass

    # ====================================================================================================
    # Counters
    # ====================================================================================================

    def __str__(self):
        return f"<Tree '{self._btree.name}' ({type(self).__name__}): {len(self._btree.nodes)} nodes and {len(self._btree.links)} links>"

    @staticmethod
    def _btree_repr(btree):
        s = ""

        sepa = "\n   - "

        s += "\nInputs:"
        in_node, out_node = None, None
        for node in btree.nodes:
            if node.bl_idname == 'NodeGroupInput':
                in_node = node
            if node.bl_idname == 'NodeGroupOutput':
                out_node = node

        if in_node is not None:
            a = []
            for sock in in_node.outputs:
                name = f"[{sock.name}]"
                if not sock.enabled:
                    name += "( d)"
                if sock.is_linked:
                    name += " -> " + sock.links[0].to_socket.name
                a.append(name)

            s += sepa + sepa.join(a)

        s += "\nOutputs:"
        if out_node is not None:
            a = []
            for sock in out_node.inputs:
                name = f"[{sock.name}]"
                if not sock.enabled:
                    name += "( d)"
                if sock.is_linked:
                    name = sock.links[0].from_socket.name + " -> " + name
                a.append(name)
            s += sepa + sepa.join(a) + "\n"

        return s + "\n"


    def __repr__(self):
        return str(self) + "\n" + Tree._btree_repr(self._btree)

    @classmethod
    def _init_package(cls, title):
        """Print a package heading and start its build statistics session."""
        print()
        print('-' * 80)
        print(title)
        print()
        cls._reset_counters()

    @classmethod
    def _reset_counters(cls):
        """Start a shared statistics session for successive tree builds."""
        Tree._total_nodes = 0
        Tree._total_links = 0
        Tree._total_built = 0
        Tree._total_existing = 0
        Tree._total_warnings = 0
        Tree._total_time = 0.0
        Tree._total_arrange_time = 0.0
        Tree._counter_started = perf_counter()

    @classmethod
    def _display_counter(cls, title):
        """Print cumulative counts and wall time since the last reset."""
        if Tree._counter_started is not None:
            Tree._total_time = perf_counter() - Tree._counter_started
        print(f"{title}: Built: {Tree._total_built}, Existing: {Tree._total_existing}")
        print(f"  {Tree._total_nodes} nodes, {Tree._total_links} links, "
              f"{Tree._total_warnings} warnings in {Tree._total_time:.2f} s "
              f"(arrange: {Tree._total_arrange_time:.2f} s)")
        print()

    @property
    def _str_stats(self):
        return f"{len(self._btree.nodes)} nodes, {len(self._btree.links)} links"

    # ====================================================================================================
    # Types of tree
    # ====================================================================================================

    @classmethod
    def is_geonodes(cls):
        """ > Current Tree is Geometry Nodes.

        Returns
        -------
        True if Tree is GeoNodes, False otherwise
        """
        return cls.current_tree()._btree.bl_idname == 'GeometryNodeTree'

    @classmethod
    def is_shader(cls):
        """ > Current Tree is Shader Nodes.

        Returns
        -------
        True if Tree is ShaderNodes, False otherwise
        """
        return cls.current_tree()._btree.bl_idname == 'ShaderNodeTree'

    @classmethod
    def is_compositor(cls):
        return cls.current_tree()._btree.bl_idname == 'CompositorNodeTree'

    # ====================================================================================================
    # Panel
    # ====================================================================================================

    def get_panel(self, sub_panel: str = ""):
        return self._panels[-1] + ItemPath.to_item_path(sub_panel)

    def push_panel(self, new_panel: str):
        self._panels.append(ItemPath.to_item_path(new_panel))

    def pop_panel(self):
        self._panels.pop()
        assert len(self._panels) >= 1, f"Error in pushing / poping tree panels."

    # ====================================================================================================
    # Nodes
    # ====================================================================================================

    # ----------------------------------------------------------------------------------------------------
    # Clear the Tree
    # ----------------------------------------------------------------------------------------------------

    def clear(self, keep_nodes: bool = True):
        """ Clear the content of the Tree.

        Remove all the nodes in the Tree.
        """
        self._nodes.clear()

        # Keep menu switch nodes to preserver input links
        # They will be deleted at the end

        if keep_nodes:
            del_nodes = []
            self._kept_nodes = []
            for bnode in self._btree.nodes:
                if bnode.bl_idname in ['GeometryNodeMenuSwitch', 'NodeGroupInput']:
                    self._kept_nodes.append(bnode)
                else:
                    del_nodes.append(bnode)

            for bnode in del_nodes:
                self._btree.nodes.remove(bnode)

        else:
            self._btree.links.clear()
            self._btree.nodes.clear()

    # ----------------------------------------------------------------------------------------------------
    # Register a new Node
    # ----------------------------------------------------------------------------------------------------

    def register_node(self, node):
        """ Register a new Node.

        This method is called by the Node class constructor. Never call directly.

        Registered Nodes are stored in the dictionary : _nodes = bpy.types.Node.name -> Node

        Parameters
        ----------
        node : Node
            the newly created Node to register


        Returns
        -------
        Node
            the passed argument

        """

        self._nodes[node._bnode.name] = node
        if len(self._layouts):
            self._layouts[-1].include_node(node)

        node._stack = NodeError.stack_lines()

        if self._input_node is None and node._bnode.bl_idname == 'NodeGroupInput':
            self._input_node = node

        if self._output_node is None and node._bnode.bl_idname == 'NodeGroupOutput':
            self._output_node = node

        return node

    # ----------------------------------------------------------------------------------------------------
    # Load the tree
    # ----------------------------------------------------------------------------------------------------

    def load_btree(self):
        from .nodeclass import Node

        self._use_arrange = False

        self.push()
        for bnode in self._btree.nodes:
            if bnode.bl_idname in []:
                pass
            else:
                Node(bnode)
        self.pop()

    # ====================================================================================================
    # Sockets creation
    # ====================================================================================================

    # ----------------------------------------------------------------------------------------------------
    # Set the default value of an input socket
    # ----------------------------------------------------------------------------------------------------

    def set_input_socket_default(self, socket, value=None):

        if value is None:
            return

        bsocket = utils.get_bsocket(socket)
        if bsocket is None:
            return

        try:
            bsocket.default_value = value
        except Exception:
            pass

        io_socket = self._interface.by_identifier(bsocket.identifier)
        if io_socket is None:
            return

        if not hasattr(io_socket, 'default_value'):
            return

        try:
            io_socket.default_value = value
        except Exception:
            return

    # ----------------------------------------------------------------------------------------------------
    # Create an input socket
    # ----------------------------------------------------------------------------------------------------

    def create_input_socket(self, bl_idname, name, panel="", **props):
        """ Create a new input socket.

        This is an **input socket** of the zone, hence an **output socket** of the input node.

        Parameters
        ----------
        bl_idname : str
            Socket bl_idname

        name : str
            Socket name

        panel : str, optional
            Panel to place the socket in

        **props : dict, optional
            Properties specific to interface socket


        Returns
        -------
        Socket
        """        
        input_node = self.get_input_node()
        socket = input_node.create_socket('OUTPUT', bl_idname, name, panel=panel, **props)
        def_val = props.get('default_value')
        if def_val is not None:
            try:
                bsocket = utils.get_bsocket(socket)
                if bsocket.type == 'VECTOR' and isinstance(def_val, tuple):
                    dimensions = len(bsocket.default_value)
                    def_val = (
                        def_val[:dimensions]
                        + (0,) * max(0, dimensions - len(def_val))
                    )
                bsocket.default_value = def_val
            except Exception as e:
                print(f"WARNING Tree.create_input_socket: {str(e)}")

        return socket

    # ====================================================================================================
    # Get the signature
    # ====================================================================================================

    def get_signature(self, include: list = None, exclude: list = [], enabled_only=True, with_sockets: bool = False):
        """ Build the closure signature of the tree.

        The closure signature is the tuple made of the output signature of the input node
        and the input signature of the output node

        Returns
        -------
        Signature
        """
        return Signature(
            self.input_node.get_signature(
                include         = include,
                exclude         = exclude,
                enabled_only    = enabled_only,
                with_sockets    = with_sockets).outputs,
            self.output_node.get_signature(
                enabled_only    = enabled_only,
                with_sockets    = with_sockets).inputs)

    # ====================================================================================================
    # Arranges nodes
    # ====================================================================================================

    def arrange(self):
        """ > Arrange the nodes in the editor.

        Try to arrange properly the nodes from left to right.

        This method is called when the Tree is poped from the stack.

        Returns
        -------
        None
        """
        if self._use_arrange:
            started = perf_counter()
            try:
                treearrange.arrange(self._btree)
            finally:
                elapsed = perf_counter() - started
                self._arrange_time += elapsed
                Tree._total_arrange_time += elapsed

    # ====================================================================================================
    # Node colors
    # ====================================================================================================

    @staticmethod
    def _get_color(value):

        if isinstance(value, str):
            if value == 'RANDOM':
                rng = Tree.current_tree()._rng
                value = tuple(rng.uniform(0., .7, 3))

            elif value in ['OP', 'OPERATION']:
                value = (.406, .541, .608)
            elif value == 'MACRO':
                value = (.261, .963, .409)
            elif value == 'AUTO_GEN':
                value = (.583, .229, .963)
            elif value == 'WARNING':
                value = (.949, .574, .119)
            else:
                return SysColor(value)

        return SysColor(value)

    # ====================================================================================================
    # Create a link
    # ====================================================================================================

    def link(self, out_socket, in_socket, handle_dynamic_sockets=False):
        """ > Create a link between two sockets.

        Parameters
        ----------
        out_socket : socket
            a node output socket

        in_socket : socket
            input socket from another node


        Returns
        -------
        Link
        """

        #if hasattr(out_socket, '_bsocket'):
        if '_bsocket' in dir(out_socket):
            out_socket = out_socket._bsocket

        #if hasattr(in_socket, '_bsocket'):
        if '_bsocket' in dir(in_socket):
            in_socket = in_socket._bsocket

        for socket in (out_socket, in_socket):
            if socket.id_data != self._btree:
                raise NodeError(
                    f"Socket '{socket.node.name}.{socket.name}' "
                    f"belongs to tree '{socket.id_data.name}', "
                    f"but current tree is '{self._btree.name}'"
                )

        link = self._btree.links.new(out_socket, in_socket, handle_dynamic_sockets=handle_dynamic_sockets)

        return link

    # ====================================================================================================
    # Tree Input / Output
    # ====================================================================================================

    @property
    def _has_tree(self):
        if self.is_geonodes():
            return True
        elif self.is_shader():
            return self._is_group
        return False

    @property
    def _has_input_node(self):
        return self._is_group or self._btree.bl_idname != 'ShaderNodeTree'

    # ----------------------------------------------------------------------------------------------------
    # Default input node
    # ----------------------------------------------------------------------------------------------------

    @property
    def input_node(self):
        """ > Return a Group Input node

        If the node doesn't already exist, it is created.

        Returns
        -------
        Node
        """
        from .nodeclass import Node

        if self._input_node is None:
            return Node('NodeGroupInput')
        else:
            return self._input_node

    # ----------------------------------------------------------------------------------------------------
    # Default output node
    # ----------------------------------------------------------------------------------------------------

    @property
    def output_node(self):
        """ Returns a Group Output node

        If the node doesn't already exist, it is created.

        Returns
        -------
        Node
        """
        from .nodeclass import Node

        if self._output_node is None:
            return Node('NodeGroupOutput')
        else:
            return self._output_node

    # ----------------------------------------------------------------------------------------------------
    # Using stack
    # ----------------------------------------------------------------------------------------------------

    def get_input_node(self):
        if len(self._input_stack):
            return self._input_stack[-1]
        else:
            return self.input_node

    def get_output_node(self):
        if len(self._output_stack):
            return self._output_stack[-1]
        else:
            return self.output_node

    # ====================================================================================================
    # Dict of modifiers using this tree
    # ====================================================================================================

    def get_modifiers(self):
        return blender.get_geonodes_modifiers(self._btree)

    # ====================================================================================================
    # Check warnings
    # ====================================================================================================

    def check_warnings(self):

        from .nodezone import ZoneNode

        tab = "\n   | " 

        count = 0

        dead_ends = []
        unlinkeds = []

        for node in self._nodes.values():

            if node._bnode.bl_idname in (
                'NodeGroupInput', 'GeometryNodeWarning',
                'GeometryNodeGizmoDial', 'GeometryNodeGizmoLinear', 'GeometryNodeGizmoTransform',
                ):
                continue

            # ---------------------------------------------------------------------------
            # Dead ends
            # ---------------------------------------------------------------------------

            is_linked = False
            n = 0
            for bsock in node._bnode.outputs:
                if bsock.is_linked:
                    is_linked = True
                    break
                n += 1

            if not is_linked and n > 0:
                dead_ends.append((node))

            # ---------------------------------------------------------------------------
            # Unlinked zone output nodes
            # ---------------------------------------------------------------------------

            if isinstance(node, ZoneNode):
                unlinked = []
                for bsock in node._bnode.inputs:
                    if bsock.type == 'CUSTOM':
                        continue
                    if bsock.name in ["Skip"]:
                        continue
                    if not bsock.is_linked:
                        unlinked.append(bsock.name)

                if len(unlinked):
                    unlinkeds.append((node, unlinked))

        # ---------------------------------------------------------------------------
        # Display
        # ---------------------------------------------------------------------------

        if len(dead_ends):
            print()
            print("-"*100)
            print(f"The following node{' is' if len(dead_ends) == 1 else 's are'} not connected")

        for i, node in enumerate(dead_ends):
            #node._bnode.label = f"DEAD END {i + 1}"
            utils.set_node_warning(node._bnode)

            print()
            print(node)
            if node._stack is not None:
                print(tab + tab.join(node._stack[1:]))

        if len(unlinkeds):
            print()
            print("-"*100)
            print(f"The output node of the following zone{' is' if len(unlinkeds) == 1 else 's are'} missing input links.")
            print("The variables uses in the loop are not updated.")
            print()

            for i, (node, names) in enumerate(unlinkeds):
                node._bnode.label = f"UPDATE MISSING {i + 1}"
                utils.set_node_warning(node._bnode)

                print()
                print(node)
                #node._bnode.label = f"DEAD END {i + 1}"
                print("Unlinked sockets:", names)
                if node._stack is not None:
                    print(tab + tab.join(node._stack[1:]))

        # Total number of warnings

        return len(dead_ends) + len(unlinkeds)

    # ====================================================================================================
    # Create a method calling this Group
    # ====================================================================================================

    def add_method(self, 
        target_class    : type, 
        func_name       : str = None,
        self_attr       : str = None, 
        ret_class       : type = None, 
        **fixed):
        """ Add a method calling the Group.

        Parameters
        ----------
        target_class : type
            class to add the method to

        func_name : str, optional
            name of the method to create (snae case version of group name if None) default=None.

        self_attr : str, optional
            self name attribute name default=None.

        ret_class : type, optional
            class to use to transtype the output socket default=None.

        fixed : dict
            fixed values for sockets        

        """
        from .nodeclass import Group

        group_name = self._btree.name
        if self._prefix != "":
            group_name = group_name[len(self._prefix) + 1:]

        Group.add_method(group_name, target_class,
            func_name       = func_name,
            self_attr       = self_attr, 
            ret_class       = ret_class, 
            prefix          = self._prefix,
            **fixed)


    # ====================================================================================================
    # Dump content
    # ====================================================================================================

    def dump(self):
        for bnode in self._btree.nodes:
            print(f"Node '{bnode.name}' ({bnode.bl_idname})")
            print("Inputs")
            for bsock in bnode.inputs:
                print(f"   - {bsock.name:20s} : {bsock.bl_idname}")
            print("Outputs")
            for bsock in bnode.outputs:
                print(f"   - {bsock.name:20s} : {bsock.bl_idname}")
            print()

    def gen_node_headers(self, default_values=True):
        for node in self._btree.nodes:
            if default_values:
                print(f"def FUNCTION(self,", ", ".join([utils.snake_case(sock.name) + f"={sock.default_value}" for sock in node.inputs]))
            else:
                print(f"def FUNCTION(self,", ", ".join([utils.snake_case(sock.name) + "=None" for sock in node.inputs]))

            sockets = ", ".join([f"'{sock.name}': {utils.snake_case(sock.name)}" for sock in node.inputs])
            print(f"Node('{node.name}', " + "{" + sockets + "}")
            print()

input_node property

Return a Group Input node

If the node doesn't already exist, it is created.

Returns:

Type Description
Node

output_node property

Returns a Group Output node

If the node doesn't already exist, it is created.

Returns:

Type Description
Node

__init__(tree_name, tree_type='GeometryNodeTree', *, fake_user=False, is_group=False, prefix='', rebuild=True, color_tag='NONE')

Parameters:

Name Type Description Default
tree_name str

tree name

required
tree_type (GeometryNodeTree, ShaderNodeTree)

tree type

'GeometryNodeTree'
fake_user bool

fake user flag

False
is_group bool

Group or not

False
prefix str

prefix to add at the begining of the tree name

""
rebuild bool

rebuild an existing tree; new trees are always built

True
color_tag str

group or modifier color_tag attribute

'NONE'
Source code in core/treeclass.py
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
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
492
493
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
536
537
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
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
def __init__(self,
        tree_name        : str, 
        tree_type        : str   = 'GeometryNodeTree',
        *,
        fake_user        : bool  = False, 
        is_group         : bool  = False,
        prefix           : str   = "",
        rebuild          : bool  = True,
        color_tag        : str   = 'NONE',
        ):

    """ 

    Parameters
    ----------
    tree_name : str
        tree name

    tree_type : {'GeometryNodeTree', 'ShaderNodeTree'}, default='GeometryNodeTree'
        tree type 

    fake_user : bool, default=False
        fake user flag

    is_group : bool, default=False
        Group or not

    prefix : str, default=""
        prefix to add at the begining of the tree name

    rebuild : bool, default=True
        rebuild an existing tree; new trees are always built

    color_tag : str, default='NONE'
        group or modifier color_tag attribute

    """
    self._build_started = perf_counter()
    self._arrange_time = 0.0
    if Tree._counter_started is None:
        Tree._counter_started = self._build_started
    self._btree = None

    # Wrap an existing NodeTree without clearing or finalizing it
    self._loaded = False

    # Arrange when finished
    self._use_arrange = True

    # In / out nodes cache
    self._input_node  = None
    self._output_node = None

    # ---------------------------------------------------------------------------
    # Stacks
    # ---------------------------------------------------------------------------

    self._panels  = [ItemPath(None)]
    self._layouts = []

    # Input / output socket creation are performed by node with dynamic
    # sockets (either with items or with tree_node)
    # By default, these are input_node and output_node
    # This behavior can be overloaded using input and output stacks

    self._output_stack  = []
    self._input_stack   = []

    # Prefix
    if prefix is None:
        prefix =  ""

    prefix = str(prefix)
    if len(prefix):
        tree_name = f"{prefix} {tree_name}"
    self._prefix = prefix

    # ----------------------------------------------------------------------------------------------------
    # Shader Node tree is a property of Material
    # ----------------------------------------------------------------------------------------------------

    replace_material = rebuild and not is_group and tree_type == 'ShaderNodeTree'

    if tree_type is None:
        btree = tree_name
        if not isinstance(btree, bpy.types.NodeTree):
            raise NodeError(
                f"Tree inititialization error: when 'tree_type' is None, 'tree_name' must be a tree, not <{tree_name}>."
                )
        self._btree = btree
        self._loaded = True
        rebuild = True

    elif tree_type == 'ShaderNodeTree':

        self._material = None
        if not is_group:
            self._material = bpy.data.materials.get(tree_name)

            if self._material is None:
                self._material = bpy.data.materials.new(tree_name)
                rebuild = True
            else:
                rebuild = replace_material

            if rebuild:
                self._material.use_nodes = True
            self._btree = self._material.node_tree
            if rebuild:
                self._material.use_fake_user = fake_user

    # ----------------------------------------------------------------------------------------------------
    # Get the tree nodes from node_groups
    # ----------------------------------------------------------------------------------------------------

    if self._btree is None and not (tree_type == 'ShaderNodeTree' and not is_group):

        btree = utils.get_tree(tree_name, tree_type=tree_type, create=False)
        if btree is None:
            self._btree = utils.get_tree(tree_name, tree_type=tree_type, create=True)
            rebuild = True
        else:
            self._btree = btree
        if rebuild:
            self._btree.use_fake_user = fake_user

    self._is_group = is_group

    # Managed lists
    self._kept_nodes = []
    self._nodes      = {} # Registered nodes: bpy.types.Node.name -> Node
    self._mod_vals   = {} # To restore modifiers values when necessary (menus)

    # ---------------------------------------------------------------------------
    # Clear / Keep the tree
    # ---------------------------------------------------------------------------

    # Store the current value of each input socket
    if tree_type == 'GeometryNodeTree' or self._is_group:
        for bnode in self._btree.nodes:
            if bnode.bl_idname != 'NodeGroupInput':
                continue

            for name, mod in self.get_modifiers().items():
                values = {}
                mod_inputs = mod.properties.inputs
                for bsock in bnode.outputs:
                    if bsock.identifier in mod_inputs:
                        prop = getattr(mod_inputs, bsock.identifier)
                        val = getattr(prop, 'value', None)
                        if val is not None:
                            values[(bsock.name, bsock.bl_idname)] = val
                            values[bsock.identifier] = val

                self._mod_vals[name] = values

            break

    # Clear tree
    if rebuild and (not self._loaded):
        self.clear(keep_nodes=False)

    # ---------------------------------------------------------------------------
    # Effective build policy (new trees are always built)
    # ---------------------------------------------------------------------------

    self._rebuild = rebuild

    # ---------------------------------------------------------------------------
    # Color tag
    # ---------------------------------------------------------------------------

    if self._rebuild and not self._loaded and hasattr(self._btree, 'color_tag'):
        utils.set_rna_attr(self._btree, 'color_tag', color_tag)

    # ---------------------------------------------------------------------------
    # Interface
    # ---------------------------------------------------------------------------

    self._interface = None
    if self._is_group or tree_type == 'GeometryNodeTree':
        self._interface = TreeInterface(self._btree)
        if self._rebuild and not self._loaded:
            self._interface.clear(use_bin=True)

    # ---------------------------------------------------------------------------
    # Random generator for random colors
    # ---------------------------------------------------------------------------

    self._rng = np.random.default_rng(0)

    # Load the tree
    if self._loaded:
        self.load_btree()

_display_counter(title) classmethod

Print cumulative counts and wall time since the last reset.

Source code in core/treeclass.py
966
967
968
969
970
971
972
973
974
975
@classmethod
def _display_counter(cls, title):
    """Print cumulative counts and wall time since the last reset."""
    if Tree._counter_started is not None:
        Tree._total_time = perf_counter() - Tree._counter_started
    print(f"{title}: Built: {Tree._total_built}, Existing: {Tree._total_existing}")
    print(f"  {Tree._total_nodes} nodes, {Tree._total_links} links, "
          f"{Tree._total_warnings} warnings in {Tree._total_time:.2f} s "
          f"(arrange: {Tree._total_arrange_time:.2f} s)")
    print()

_init_package(title) classmethod

Print a package heading and start its build statistics session.

Source code in core/treeclass.py
945
946
947
948
949
950
951
952
@classmethod
def _init_package(cls, title):
    """Print a package heading and start its build statistics session."""
    print()
    print('-' * 80)
    print(title)
    print()
    cls._reset_counters()

_reset_counters() classmethod

Start a shared statistics session for successive tree builds.

Source code in core/treeclass.py
954
955
956
957
958
959
960
961
962
963
964
@classmethod
def _reset_counters(cls):
    """Start a shared statistics session for successive tree builds."""
    Tree._total_nodes = 0
    Tree._total_links = 0
    Tree._total_built = 0
    Tree._total_existing = 0
    Tree._total_warnings = 0
    Tree._total_time = 0.0
    Tree._total_arrange_time = 0.0
    Tree._counter_started = perf_counter()

add_method(target_class, func_name=None, self_attr=None, ret_class=None, **fixed)

Add a method calling the Group.

Parameters:

Name Type Description Default
target_class type

class to add the method to

required
func_name str

name of the method to create (snae case version of group name if None) default=None.

None
self_attr str

self name attribute name default=None.

None
ret_class type

class to use to transtype the output socket default=None.

None
fixed dict

fixed values for sockets

{}
Source code in core/treeclass.py
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
def add_method(self, 
    target_class    : type, 
    func_name       : str = None,
    self_attr       : str = None, 
    ret_class       : type = None, 
    **fixed):
    """ Add a method calling the Group.

    Parameters
    ----------
    target_class : type
        class to add the method to

    func_name : str, optional
        name of the method to create (snae case version of group name if None) default=None.

    self_attr : str, optional
        self name attribute name default=None.

    ret_class : type, optional
        class to use to transtype the output socket default=None.

    fixed : dict
        fixed values for sockets        

    """
    from .nodeclass import Group

    group_name = self._btree.name
    if self._prefix != "":
        group_name = group_name[len(self._prefix) + 1:]

    Group.add_method(group_name, target_class,
        func_name       = func_name,
        self_attr       = self_attr, 
        ret_class       = ret_class, 
        prefix          = self._prefix,
        **fixed)

arrange()

Arrange the nodes in the editor.

Try to arrange properly the nodes from left to right.

This method is called when the Tree is poped from the stack.

Returns:

Type Description
None
Source code in core/treeclass.py
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
def arrange(self):
    """ > Arrange the nodes in the editor.

    Try to arrange properly the nodes from left to right.

    This method is called when the Tree is poped from the stack.

    Returns
    -------
    None
    """
    if self._use_arrange:
        started = perf_counter()
        try:
            treearrange.arrange(self._btree)
        finally:
            elapsed = perf_counter() - started
            self._arrange_time += elapsed
            Tree._total_arrange_time += elapsed

clear(keep_nodes=True)

Clear the content of the Tree.

Remove all the nodes in the Tree.

Source code in core/treeclass.py
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
def clear(self, keep_nodes: bool = True):
    """ Clear the content of the Tree.

    Remove all the nodes in the Tree.
    """
    self._nodes.clear()

    # Keep menu switch nodes to preserver input links
    # They will be deleted at the end

    if keep_nodes:
        del_nodes = []
        self._kept_nodes = []
        for bnode in self._btree.nodes:
            if bnode.bl_idname in ['GeometryNodeMenuSwitch', 'NodeGroupInput']:
                self._kept_nodes.append(bnode)
            else:
                del_nodes.append(bnode)

        for bnode in del_nodes:
            self._btree.nodes.remove(bnode)

    else:
        self._btree.links.clear()
        self._btree.nodes.clear()

create_input_socket(bl_idname, name, panel='', **props)

Create a new input socket.

This is an input socket of the zone, hence an output socket of the input node.

Parameters:

Name Type Description Default
bl_idname str

Socket bl_idname

required
name str

Socket name

required
panel str

Panel to place the socket in

''
**props dict

Properties specific to interface socket

{}

Returns:

Type Description
Socket
Source code in core/treeclass.py
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
def create_input_socket(self, bl_idname, name, panel="", **props):
    """ Create a new input socket.

    This is an **input socket** of the zone, hence an **output socket** of the input node.

    Parameters
    ----------
    bl_idname : str
        Socket bl_idname

    name : str
        Socket name

    panel : str, optional
        Panel to place the socket in

    **props : dict, optional
        Properties specific to interface socket


    Returns
    -------
    Socket
    """        
    input_node = self.get_input_node()
    socket = input_node.create_socket('OUTPUT', bl_idname, name, panel=panel, **props)
    def_val = props.get('default_value')
    if def_val is not None:
        try:
            bsocket = utils.get_bsocket(socket)
            if bsocket.type == 'VECTOR' and isinstance(def_val, tuple):
                dimensions = len(bsocket.default_value)
                def_val = (
                    def_val[:dimensions]
                    + (0,) * max(0, dimensions - len(def_val))
                )
            bsocket.default_value = def_val
        except Exception as e:
            print(f"WARNING Tree.create_input_socket: {str(e)}")

    return socket

current_tree() staticmethod

Get the Current Tree.

Returns None if no tree is currently open

Returns:

Type Description
Tree

current tree or None

Source code in core/treeclass.py
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
@staticmethod
def current_tree():
    """ > Get the Current Tree.

    Returns None if no tree is currently open

    Returns
    -------
    Tree
        current tree or None

    """
    if len(Tree.TREE_STACK):
        return Tree.TREE_STACK[-1]
    else:
        return None

get_signature(include=None, exclude=[], enabled_only=True, with_sockets=False)

Build the closure signature of the tree.

The closure signature is the tuple made of the output signature of the input node and the input signature of the output node

Returns:

Type Description
Signature
Source code in core/treeclass.py
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
def get_signature(self, include: list = None, exclude: list = [], enabled_only=True, with_sockets: bool = False):
    """ Build the closure signature of the tree.

    The closure signature is the tuple made of the output signature of the input node
    and the input signature of the output node

    Returns
    -------
    Signature
    """
    return Signature(
        self.input_node.get_signature(
            include         = include,
            exclude         = exclude,
            enabled_only    = enabled_only,
            with_sockets    = with_sockets).outputs,
        self.output_node.get_signature(
            enabled_only    = enabled_only,
            with_sockets    = with_sockets).inputs)

is_geonodes() classmethod

Current Tree is Geometry Nodes.

Returns:

Type Description
True if Tree is GeoNodes, False otherwise
Source code in core/treeclass.py
985
986
987
988
989
990
991
992
993
@classmethod
def is_geonodes(cls):
    """ > Current Tree is Geometry Nodes.

    Returns
    -------
    True if Tree is GeoNodes, False otherwise
    """
    return cls.current_tree()._btree.bl_idname == 'GeometryNodeTree'

is_shader() classmethod

Current Tree is Shader Nodes.

Returns:

Type Description
True if Tree is ShaderNodes, False otherwise
Source code in core/treeclass.py
 995
 996
 997
 998
 999
1000
1001
1002
1003
@classmethod
def is_shader(cls):
    """ > Current Tree is Shader Nodes.

    Returns
    -------
    True if Tree is ShaderNodes, False otherwise
    """
    return cls.current_tree()._btree.bl_idname == 'ShaderNodeTree'

Create a link between two sockets.

Parameters:

Name Type Description Default
out_socket socket

a node output socket

required
in_socket socket

input socket from another node

required

Returns:

Type Description
Link
Source code in core/treeclass.py
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
def link(self, out_socket, in_socket, handle_dynamic_sockets=False):
    """ > Create a link between two sockets.

    Parameters
    ----------
    out_socket : socket
        a node output socket

    in_socket : socket
        input socket from another node


    Returns
    -------
    Link
    """

    #if hasattr(out_socket, '_bsocket'):
    if '_bsocket' in dir(out_socket):
        out_socket = out_socket._bsocket

    #if hasattr(in_socket, '_bsocket'):
    if '_bsocket' in dir(in_socket):
        in_socket = in_socket._bsocket

    for socket in (out_socket, in_socket):
        if socket.id_data != self._btree:
            raise NodeError(
                f"Socket '{socket.node.name}.{socket.name}' "
                f"belongs to tree '{socket.id_data.name}', "
                f"but current tree is '{self._btree.name}'"
            )

    link = self._btree.links.new(out_socket, in_socket, handle_dynamic_sockets=handle_dynamic_sockets)

    return link

pop(error=False)

Remove this tree from the stack

Important

This methods shouldn't be called directly, better use a with context block.

Raises:

Type Description
NodeError

if this tree is not the current one

``` python
with Tree("My Name"):

pass

```
Source code in core/treeclass.py
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
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
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
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
def pop(self, error=False):
    """ > Remove this tree from the stack

    !!! important
        This methods shouldn't be called directly, better use a **with** context block.

    Raises
    ------
    NodeError
        if this tree is not the current one


    ``` python
    with Tree("My Name"):
        pass
    ```
    """
    # ---------------------------------------------------------------------------
    # Ignore changes
    # ---------------------------------------------------------------------------

    if not Tree.TREE_STACK or Tree.TREE_STACK[-1] is not self:
        raise RuntimeError("Error in tree stack management")

    if not self._rebuild or self._loaded:
        Tree.TREE_STACK.pop()
        Tree._total_existing += 1
        return

    # ---------------------------------------------------------------------------
    # Remove kept nodes
    # ---------------------------------------------------------------------------

    for bnode in self._kept_nodes:
        self._btree.nodes.remove(bnode)

    # ---------------------------------------------------------------------------
    # Update modifiers inputs
    # ---------------------------------------------------------------------------

    if self._has_input_node:

        modifiers = self.get_modifiers()

        for bsock in self.input_node._bnode.outputs:

            isock = self._interface.by_identifier(bsock.identifier)
            if not hasattr(isock, 'default_value'):
                continue

            # ----------------------------------------
            # Menu socket
            # ----------------------------------------

            if bsock.bl_idname == 'NodeSocketMenu':
                for mod_name, mod in modifiers.items():

                    current = None

                    mod_vals = self._mod_vals.get(mod_name)

                    if mod_vals is not None:
                        current = mod_vals.get(bsock.identifier, None)

                    if current is None:
                        current = isock.default_value

                    mod_input = getattr(mod.properties.inputs, bsock.identifier)

                    try:
                        mod_input.value = current
                    except Exception as e:
                        try:
                            mod_input.value = isock.default_value
                        except:
                            pass

                continue

            # ----------------------------------------
            # General
            # ----------------------------------------

            for mod_name, mod in modifiers.items():

                mod_vals = self._mod_vals.get(mod_name)
                if mod_vals is None:
                    continue

                # Nothing to do if identifier exists
                if bsock.identifier in mod_vals:
                    continue

                # Nen identifier : let's set the default value
                mod_input = getattr(mod.properties.inputs, bsock.identifier)
                if not hasattr(mod_input, 'value'):
                    continue

                try:
                    mod_input.value = isock.default_value
                except Exception as e:
                    print(f"CAUTION: error when setting default <{isock.default_value}> value to socket '{bsock.name}'.\n -> error is: {str(e)}")

    # ---------------------------------------------------------------------------
    # Finalize
    # ---------------------------------------------------------------------------

    # Check dead ends
    warnings = 0
    if not error:
        utils.check_zones(self._btree)
        # Socket structures, notably inside nested closures, may still be
        # unresolved immediately after a link is created. Validate links
        # only once Blender has inferred the completed tree.
        for link in self._btree.links:
            utils.check_link(link)
        warnings = self.check_warnings()

    # Remove from stack
    tree = Tree.TREE_STACK.pop()
    if tree != self:
        raise RuntimeError(f"Error in tree stack management")

    # Empty the interface bin
    if (not error) and self._interface is not None:
        self._interface.empty_bin()

    # Last node in error
    if error and len(self._nodes):
        for node in reversed(self._nodes.values()):
            if node._bnode.bl_idname in ['NodeGroupOutput', 'NodeGroupInput']:
                continue
            utils.set_node_error(node._bnode)
            break

    # Arrange the nodes
    self.arrange()

    # Stats
    if self._btree.bl_idname == 'ShaderNodeTree' and self._material is not None:
        name = f"Material '{self._material.name}'"
    else:
        name = f"Tree '{self._btree.name}'"

    elapsed = perf_counter() - self._build_started
    print(f"{name} built: {self._str_stats}, warnings: {warnings}, "
          f"time: {elapsed:.2f} s (arrange: {self._arrange_time:.2f} s)")

    Tree._total_nodes += len(self._btree.nodes)
    Tree._total_links += len(self._btree.links)
    Tree._total_built += int(not error)
    Tree._total_warnings += warnings
    Tree._total_time = perf_counter() - Tree._counter_started

push()

Make this tree zone the current one

Important

This methods shouldn't be called directly, better use a with context block.

with Tree("My Name"):
    pass
Source code in core/treeclass.py
618
619
620
621
622
623
624
625
626
627
628
629
630
def push(self):
    """ > Make this tree zone the current one

    !!! important
        This methods shouldn't be called directly, better use a **with** context block.

    ``` python
    with Tree("My Name"):
        pass
    ```
    """
    Tree.TREE_STACK.append(self)
    return self

register_node(node)

Register a new Node.

This method is called by the Node class constructor. Never call directly.

Registered Nodes are stored in the dictionary : _nodes = bpy.types.Node.name -> Node

Parameters:

Name Type Description Default
node Node

the newly created Node to register

required

Returns:

Type Description
Node

the passed argument

Source code in core/treeclass.py
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
def register_node(self, node):
    """ Register a new Node.

    This method is called by the Node class constructor. Never call directly.

    Registered Nodes are stored in the dictionary : _nodes = bpy.types.Node.name -> Node

    Parameters
    ----------
    node : Node
        the newly created Node to register


    Returns
    -------
    Node
        the passed argument

    """

    self._nodes[node._bnode.name] = node
    if len(self._layouts):
        self._layouts[-1].include_node(node)

    node._stack = NodeError.stack_lines()

    if self._input_node is None and node._bnode.bl_idname == 'NodeGroupInput':
        self._input_node = node

    if self._output_node is None and node._bnode.bl_idname == 'NodeGroupOutput':
        self._output_node = node

    return node

remove_groups(names=None, prefix=None, geonodes=True, shadernodes=True) staticmethod

Remove Groups created by GeoNodes.

Important

This method can only remove groups created by GeoNodes.

Parameters:

Name Type Description Default
names str or list of strs

name of the node groups to remove (all if None)

None
prefix str

name prefix for the groups to delete

None
geonodes bool

remove geometry nodes groups

True
shadernodes bool

remove shader nodes groups

True

Returns:

Type Description
None
Source code in core/treeclass.py
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
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
@staticmethod
def remove_groups(names=None, prefix=None, geonodes=True, shadernodes=True):
    """ > Remove Groups created by GeoNodes.

    !!! important
         This method can only remove groups created by **GeoNodes**.

    Parameters
    ----------
    names : str or list of strs, optional
        name of the node groups to remove (all if None)

    prefix : str, optional
        name prefix for the groups to delete

    geonodes : bool, default=True
        remove geometry nodes groups

    shadernodes : bool, default=True
        remove shader nodes groups


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

    groups = []
    if prefix is None:
        prefix_ = ""
    else:
        prefix_ = prefix + ' '

    tree_types = []
    if geonodes:
        tree_types.append('GeometryNodeTree')
    if shadernodes:
        tree_types.append('ShaderNodeTree')

    for group in bpy.data.node_groups:
        if group.bl_idname not in tree_types:
            continue

        if not group.description.startswith('GEONODES'):
            continue

        if prefix is not None and group.name[:len(prefix_)] != prefix_:
            continue

        if names is None:
            pass
        elif isinstance(names, str):
            if group.name != prefix_ + names:
                continue
        elif isinstance(names, list):
            ok = False
            for name in names:
                if group.name == prefix_ + name:
                    ok = True
                    break
            if not ok:
                continue
        else:
            raise Exception(f"Argument names '{names}' is not valid: None, str or list of strs expected")

        groups.append(group)

    print("Remove node groups")
    for group in groups:
        print(' -', group.name)
        bpy.data.node_groups.remove(group)

    print(f"{len(groups)} node groups removed")