Class for quick node creation by their type.
Code by Skarn.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
class NodeTreeBuilder: def __init__( self , node_tree : bpy.types.NodeTree , x : float = -200 , y : float = -200 , delimeter : float = 300 ): self._x = x self._y = y self.tree = node_tree self.delimeter = delimeter self.purge_tree() def purge_tree(self): for node in self.tree.nodes: self.tree.nodes.remove(node) def add_node( self , node_type : str , node_name : str , column : int , row : int , node_descr : str = "" ): node = self.tree.nodes.new(node_type) node.name = node_name node.label = node_descr if node_descr else node_name node.location = (self.delimeter * column + self._x, -self.delimeter * row + self._y) return node |
It is convenient to create nodes in a single line by its type with this class. The type of any node is specified in its bl_idname property:
1 2 |
print(bpy.context.active_object.active_material.node_tree.nodes.active.bl_idname) 'ShaderNodeTexImage' |
Creating an instance of the class, we pass a pointer to the current node tree to its input parameters. The new nodes will be created in the specified node tree. Now to create a new node, we just need to call the “add_node” method, specifying the node type, name to set, and location by the columns and rows indexes in the parameters. The method returns a pointer to the created node, which allows to easily change its default parameters if necessary.
Code usage example:
1 2 3 4 5 6 7 8 9 10 |
node_tree = bpy.context.active_object.active_material.node_tree tree_builder = NodeTreeBuilder(node_tree) uvmap = tree_builder.add_node('ShaderNodeUVMap', 'UVMap', 0, 1) uvmap.uv_map = 'UVMap' diffuse_tex = tree_builder.add_node('ShaderNodeTexImage', 'DiffuseTexture1', 1, 1) diffuse_tex.image = bpy.data.images['diffuse.jpg'] node_tree.links.new(uvmap.outputs['UV'], diffuse_tex.inputs['Vector']) |
Here we define an instance of the class to work with the current node tree. Next, we create two nodes “UVMap” and “ImageTexture”, change their parameters, and connect them together by node links.