From 94b35bf75a43d2cfeb7bec8bb9756ae8a11fc1a3 Mon Sep 17 00:00:00 2001 From: Dominik Winkelbauer Date: Fri, 27 Sep 2024 17:23:28 +0200 Subject: [PATCH] fix(loader): Preserves collection hierarchies when importing them from blend file --- blenderproc/python/loader/BlendLoader.py | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/blenderproc/python/loader/BlendLoader.py b/blenderproc/python/loader/BlendLoader.py index b7cd371a0..3937afbf2 100644 --- a/blenderproc/python/loader/BlendLoader.py +++ b/blenderproc/python/loader/BlendLoader.py @@ -65,8 +65,10 @@ def load_blend(path: str, obj_types: Optional[Union[List[str], str]] = None, nam for obj in getattr(data_to, data_block): # Check that the object type is desired if obj.type.lower() in obj_types: - # Link objects to the scene - bpy.context.collection.objects.link(obj) + # If object does not yet belong to a imported collection + if len(obj.users_collection) == 0: + # Link objects to the scene collection + bpy.context.collection.objects.link(obj) loaded_objects.append(convert_to_entity_subclass(obj)) # If a camera was imported @@ -89,6 +91,17 @@ def load_blend(path: str, obj_types: Optional[Union[List[str], str]] = None, nam # Remove object again if its type is not desired bpy.data.objects.remove(obj, do_unlink=True) print("Selected " + str(len(loaded_objects)) + " of the loaded objects by type") + elif data_block == "collections": + # Build up mapping of possible parent-child collection relationships + collection_parents = {} + for collection in getattr(data_to, data_block): + for child in collection.children: + collection_parents[child.name] = collection + + # Add all collections to scene collection which do not yet belong to any other collection + for collection in getattr(data_to, data_block): + if collection.name not in collection_parents: + bpy.context.collection.children.link(collection) else: loaded_objects.extend(getattr(data_to, data_block))