Python API - copying nodes from one shader graph to another
Currently in Python API there is no option to just copy some nodes from one shader graph to another. The only way to do that I've found is by doing some tomfoolery with context overriding and basically emulating user using
bpy.ops.node.clipboard_copy
and
bpy.ops.node.clipboard_paste
. Which seems a bit unreliable and might break at some point, not to mention polluting clipboard.
It would be nice to have a simple way to copy some parts of graph with links or the entire graph from python API.
Current workaround from here - blender.stackexchange.com/questions/123887/how-to-copy-nodes-and-their-links-from-one-node-tree-material-to-another-in-py/294548 :
def get_shader_editor_context():
for screen in bpy.data.screens:
for area in screen.areas:
if area.type == "NODE_EDITOR":
for space in area.spaces:
if space.tree_type == "ShaderNodeTree":
context_override = {"area": area, "space": space, "screen": screen}
return context_override
def copy_node_graph_to_active_object(material):
temp_override = get_shader_editor_context()
old_material = bpy.context.object.active_material
new_material = material
# remove all nodes from the current material
for n in old_material.node_tree.nodes[:]:
old_material.node_tree.nodes.remove(n)
# change current material and make other window's shader editor is updated
bpy.context.object.active_material = new_material
temp_override['space'].node_tree = new_material.node_tree
# select all nodes and copy them to clipboard
for node in new_material.node_tree.nodes:
node.select = True
bpy.ops.node.clipboard_copy(temp_override)
# back to original material
bpy.context.object.active_material = old_material
temp_override['space'].node_tree = old_material.node_tree
bpy.ops.node.clipboard_paste(temp_override, offset=(0,0))
0 Comments