A few basic Python operators for adding nodes in the node editor tree. These operators basically have the same functionality as the 'Add' menu (which currently does not even use operators itself). They can be used in customized tools.

The node_add_move operator is an extended variant which starts the (modal) transform operator right after adding a node, as a quicker way of inserting nodes in a tree.
This commit is contained in:
Lukas Toenne 2012-12-12 12:50:43 +00:00
parent 7ab67541d3
commit 6a6bede3f6

@ -20,7 +20,81 @@
import bpy
from bpy.types import Operator
from bpy.props import EnumProperty
from bpy.props import EnumProperty, StringProperty
# Base class for node 'Add' operators
class NodeAddOperator():
@staticmethod
def store_mouse_cursor(context, event):
space = context.space_data
v2d = context.region.view2d
# convert mouse position to the View2D for later node placement
space.cursor_location = v2d.region_to_view(event.mouse_region_x,
event.mouse_region_y)
def create_node(self, context, node_type):
space = context.space_data
tree = space.edit_tree
node = tree.nodes.new(type=node_type)
# select only the new node
for n in tree.nodes:
n.select = (n == node)
tree.nodes.active = node
node.location = space.cursor_location
return node
@classmethod
def poll(cls, context):
space = context.space_data
# needs active node editor and a tree to add nodes to
return (space.type == 'NODE_EDITOR' and space.edit_tree)
# Default invoke stores the mouse position to place the node correctly
def invoke(self, context, event):
self.store_mouse_cursor(context, event)
return self.execute(context)
# Simple basic operator for adding a node
class NODE_OT_add_node(NodeAddOperator, Operator):
'''Add a node to the active tree'''
bl_idname = "node.add_node"
bl_label = "Add Node"
type = StringProperty(name="Node Type", description="Node type")
# optional group tree parameter for group nodes
group_tree = StringProperty(name="Group tree", description="Group node tree name")
def execute(self, context):
node = self.create_node(context, self.type)
# set the node group tree of a group node
if self.properties.is_property_set('group_tree'):
node.node_tree = bpy.data.node_groups[self.group_tree]
return {'FINISHED'}
# Adds a node and immediately starts the transform operator for inserting in a tree
class NODE_OT_add_node_move(NODE_OT_add_node):
'''Add a node to the active tree and start transform'''
bl_idname = "node.add_node_move"
bl_label = "Add Node and Move"
type = StringProperty(name="Node Type", description="Node type")
# optional group tree parameter for group nodes
group_tree = StringProperty(name="Group tree", description="Group node tree name")
def invoke(self, context, event):
self.store_mouse_cursor(context, event)
self.execute(context)
return bpy.ops.transform.translate('INVOKE_DEFAULT')
# XXX These node item lists should actually be generated by a callback at
# operator execution time (see node_type_items below),