diff --git a/molecularnodes/blender/nodes.py b/molecularnodes/blender/nodes.py index 8f30696e..95b6058c 100644 --- a/molecularnodes/blender/nodes.py +++ b/molecularnodes/blender/nodes.py @@ -328,6 +328,13 @@ def create_starting_nodes_density(object, threshold=0.8, style="density_surface" mod = get_mod(object) node_name = f"MN_density_{object.name}" + try: + tree = bpy.data.node_groups[node_name] + mod.node_group = tree + return + except KeyError: + pass + # create a new GN node group, specific to this particular molecule group = new_tree(node_name, fallback=False) link = group.links.new @@ -380,8 +387,14 @@ def create_starting_node_tree( if not name: name = f"MN_{object.name}" - # create a new GN node group, specific to this particular molecule - mod = get_mod(object) + # check if the node tree already exists and use that instead + try: + tree = bpy.data.node_groups[name] + mod.node_group = tree + return + except KeyError: + pass + tree = new_tree(name) tree.is_modifier = is_modifier link = tree.links.new diff --git a/tests/test_nodes.py b/tests/test_nodes.py index a3b256fb..5b97ac6f 100644 --- a/tests/test_nodes.py +++ b/tests/test_nodes.py @@ -283,3 +283,16 @@ def test_is_modifier(): assert not tree.is_modifier mol = mn.entities.fetch("4ozs") assert mol.tree.is_modifier + + +def test_reuse_node_group(): + mol = mn.entities.fetch("4ozs") + tree = bpy.data.node_groups["MN_4ozs"] + n_nodes = len(tree.nodes) + bpy.data.objects.remove(mol.object) + del mol + + assert n_nodes == len(tree.nodes) + + mol = mn.fetch("4ozs") + assert n_nodes == len(tree.nodes)