Added function to get collections

Also added a flag in old function to get selection to include collections.
This commit is contained in:
Simone Barbieri 2023-11-09 10:42:38 +00:00
parent 7b9c6c3b99
commit 0d6e728552
2 changed files with 58 additions and 26 deletions

View file

@ -266,9 +266,57 @@ def read(node: bpy.types.bpy_struct_meta_idprop):
return data
def get_selection() -> List[bpy.types.Object]:
"""Return the selected objects from the current scene."""
return [obj for obj in bpy.context.scene.objects if obj.select_get()]
def get_selected_collections():
"""
Returns a list of the currently selected collections in the outliner.
Raises:
RuntimeError: If the outliner cannot be found in the main Blender
window.
Returns:
list: A list of `bpy.types.Collection` objects that are currently
selected in the outliner.
"""
try:
area = next(
area for area in bpy.context.window.screen.areas
if area.type == 'OUTLINER')
region = next(
region for region in area.regions
if region.type == 'WINDOW')
except StopIteration as e:
raise RuntimeError("Could not find outliner. An outliner space "
"must be in the main Blender window.") from e
with bpy.context.temp_override(
window=bpy.context.window,
area=area,
region=region,
screen=bpy.context.window.screen
):
ids = bpy.context.selected_ids
return [id for id in ids if isinstance(id, bpy.types.Collection)]
def get_selection(include_collections: bool = False) -> List[bpy.types.Object]:
"""
Returns a list of selected objects in the current Blender scene.
Args:
include_collections (bool, optional): Whether to include selected
collections in the result. Defaults to False.
Returns:
List[bpy.types.Object]: A list of selected objects.
"""
selection = [obj for obj in bpy.context.scene.objects if obj.select_get()]
if include_collections:
selection.extend(get_selected_collections())
return selection
@contextlib.contextmanager

View file

@ -40,29 +40,13 @@ class CreateBlendScene(plugin.Creator):
self.data['task'] = get_current_task_name()
lib.imprint(asset_group, self.data)
try:
area = next(
area for area in bpy.context.window.screen.areas
if area.type == 'OUTLINER')
region = next(
region for region in area.regions
if region.type == 'WINDOW')
except StopIteration as e:
raise RuntimeError("Could not find outliner. An outliner space "
"must be in the main Blender window.") from e
if (self.options or {}).get("useSelection"):
selection = lib.get_selection(include_collections=True)
with bpy.context.temp_override(
window=bpy.context.window,
area=area,
region=region,
screen=bpy.context.window.screen
):
ids = bpy.context.selected_ids
for id in ids:
if isinstance(id, bpy.types.Collection):
asset_group.children.link(id)
elif isinstance(id, bpy.types.Object):
asset_group.objects.link(id)
for data in selection:
if isinstance(data, bpy.types.Collection):
asset_group.children.link(data)
elif isinstance(data, bpy.types.Object):
asset_group.objects.link(data)
return asset_group