Look for Links.
Requested clarification, am making same assumption that you're after adding your group node between BSDF and Material Output.
Similarly to Look for Links method from this answer. The concept is to look for a certain link in all materials and, if it exists poke a group node inbetween.
Edit To reflect your Node Group
- Name of Node Group (
groupname
)
- Name or Index of Input Socket (
in_socket
)
- Name or Index of Output Socket (
out_socket
)
If there is no node group with groupname
as name, do nothing print message.
Look for all node materials links (links
) between BSDF and into Material Outputs "Surface" socket. Looking at the node type avoids error if the node has been renamed.
If there are links then add a new group node and plug the bsdf out into designated in socket and out socket into material output surface socket. (Need a drink)
Shift the material output by 120% of group node width, and put groupnode where output node was.
Test script, as always back up first.
from bpy import data
# details of groupnode.
groupname = "NodeGroup"
# sockets to link by name or by index
in_socket = "Shader"
out_socket = 0
# get the group node
group = data.node_groups.get(groupname)
if group:
# find all the links to poke groupnode into
links = [
(mat.node_tree, link)
for mat in data.materials
if mat.use_nodes and not mat.is_grease_pencil
for link in mat.node_tree.links
if link.to_node.type.startswith('OUTPUT_MATERIAL')
and link.to_socket.name.startswith("Surface")
and link.from_node.type.startswith('BSDF_PRINCIPLED')
]
while links:
nt, link = links.pop()
# make a groupnode assign it group.
gn = nt.nodes.new('ShaderNodeGroup')
gn.node_tree = group
# put group node at location of output node
# and move output to accomodate.
gn.location = link.to_node.location
link.to_node.location.x += 1.2 * gn.width
# the sockets
group_in = gn.inputs[in_socket]
group_out = gn.outputs[out_socket]
# make new links
nt.links.new(link.from_socket, group_in)
nt.links.new(group_out, link.to_socket)
else:
print(f"No groupnode named {groupname}")