"""Blender Operators for importing robot models.
This module implements the user-facing operators that handle the import of
robot descriptions into the Blender environment.
"""
from __future__ import annotations
import os
import typing
from contextlib import suppress
from pathlib import Path
import bpy
from bpy.types import Context, Operator
from bpy_extras.io_utils import ImportHelper
from .. import core
from ..adapters.context import BlenderContext
from ..constants import (
EXT_SRDF,
EXT_URDF,
EXT_URDF_XACRO,
EXT_XACRO,
FORMAT_URDF,
FORMAT_XACRO,
)
from ..core import get_logger
from ..core.validation import find_sandbox_root
from ..logic import asynchronous_builder
from ..preferences import get_addon_prefs
from ..utils.decorators import OperatorReturn, safe_execute
from ..utils.scene_utils import clear_stats_cache
logger = get_logger(__name__)
[docs]
class LINKFORGE_OT_import_robot_model(Operator, ImportHelper): # type: ignore[misc]
"""Import robot from URDF or XACRO file.
This operator opens a file browser to select a robot description file,
auto-detects the format (URDF or XACRO), validates the model structure,
and initiates an asynchronous import process into the Blender scene.
"""
bl_idname = "linkforge.import_robot_model"
bl_label = "Import Robot Model"
bl_description = "Import robot from supported formats (URDF, XACRO, etc.)"
# Operator properties for ExportHelper/ImportHelper
filepath: bpy.props.StringProperty(subtype="FILE_PATH") # type: ignore
filter_glob: bpy.props.StringProperty( # type: ignore
default="*.urdf;*.xacro;*.xml",
options={"HIDDEN"},
maxlen=255,
)
import_companion_srdf: bpy.props.BoolProperty( # type: ignore
name="Import Companion SRDF",
description="Automatically detect and load companion .srdf planning configuration if found",
default=True,
)
[docs]
def draw(self, _context: Context) -> None:
"""Draw operator options in the file browser sidebar."""
layout = self.layout
if not layout:
return
box = layout.box()
box.label(text="Planning Semantics", icon="ARMATURE_DATA")
box.prop(self, "import_companion_srdf")
# Type ignore to resolve 'misc' definition collision with Operator.check
[docs]
def check(self, _context: Context) -> typing.Any:
"""Check if the operator can update its properties.
Args:
_context: The current Blender context (unused, required by API).
Returns:
True to indicate the properties have changed and the UI needs update.
"""
return True
[docs]
@safe_execute
def execute(self, context: Context) -> OperatorReturn:
"""Execute the robot import process.
Args:
context: The execution context.
Returns:
Set containing the execution state (e.g., {'FINISHED'} or {'CANCELLED'}).
"""
# Clear XACRO cache to ensure changes on disk are picked up
core.clear_xacro_cache()
# Parse URDF/XACRO file
source_path = Path(self.filepath)
# Smart Directory Handling
# If user selects a folder, try to find the main robot file automatically.
if source_path.is_dir():
candidates = [
source_path / f"{source_path.name}{EXT_URDF}",
source_path / f"{source_path.name}{EXT_XACRO}",
source_path / f"{source_path.name}{EXT_URDF_XACRO}",
source_path / f"robot{EXT_URDF}",
source_path / f"robot{EXT_XACRO}",
source_path / f"robot{EXT_URDF_XACRO}",
]
found = [f for f in candidates if f.is_file()]
valid_files = list(source_path.glob(f"*{EXT_URDF}")) + list(
source_path.glob(f"*{EXT_XACRO}")
)
if found:
# Pick the first "best guess" match
source_path = found[0]
self.report({"INFO"}, f"Auto-detected robot description: {source_path.name}")
elif len(valid_files) == 1:
# If there's only one valid file in the folder, use it
source_path = valid_files[0]
self.report({"INFO"}, f"Auto-detected single robot file: {source_path.name}")
else:
self.report(
{"ERROR"},
f"Directory selected but no obvious robot file found. Please select a {EXT_URDF} or {EXT_XACRO} file directly.",
)
return {"CANCELLED"}
# Validate that the path is now a file
if not source_path.is_file():
self.report({"ERROR"}, f"File not found: {source_path}")
return {"CANCELLED"}
is_xacro = source_path.suffix.lower() == EXT_XACRO or source_path.name.lower().endswith(
EXT_URDF_XACRO
)
# Detect Sandbox Root for security (allows sibling folders like meshes/)
sandbox_root = find_sandbox_root(source_path)
logger.info(f"Importing robot from: {source_path}")
logger.debug(f"Detected sandbox root: {sandbox_root}")
# Smart Import Logic: Try URDF first, fall back to Xacro if Xacro tags are detected.
# Read additional package paths from preferences
prefs = get_addon_prefs(context)
additional_paths = []
if prefs and hasattr(prefs, "additional_search_paths") and prefs.additional_search_paths:
# Split by comma or os.pathsep (collapsing spaces)
raw_paths = prefs.additional_search_paths.replace(",", os.pathsep).split(os.pathsep)
additional_paths = [Path(p.strip()) for p in raw_paths if p.strip()]
resolver = core.FileSystemResolver(additional_search_paths=additional_paths)
try:
if not is_xacro:
try:
# Attempt standard URDF import
robot = core.URDFParser(
sandbox_root=sandbox_root, resource_resolver=resolver
).parse(source_path)
except core.XacroDetectedError:
# Explicitly detected Xacro, enable fallback
self.report(
{"WARNING"},
"Detected XACRO content in robot model file. Switching to XACRO parser...",
)
is_xacro = True
except core.RobotParserError as e:
# Real validation error
self.report({"ERROR"}, f"URDF Parsing failed: {e}")
return {"CANCELLED"}
# XACRO PROCESSING (Triggered by extension OR fallback detection)
if is_xacro:
# Convert XACRO to URDF using native XacroResolver
self.report({"INFO"}, f"Processing XACRO file: {source_path.name}")
# Pass the additional paths so XACRO includes can find package:// references
xacro_resolver = core.XacroResolver(search_paths=additional_paths)
urdf_string = xacro_resolver.resolve_file(source_path)
# Parse URDF string with directory for mesh path validation
self.report({"INFO"}, "Parsing URDF...")
robot = core.URDFParser(
sandbox_root=sandbox_root, resource_resolver=resolver
).parse_string(
urdf_string,
source_directory=source_path.parent,
default_name=source_path.stem,
)
except core.RobotParserError as e:
self.report({"ERROR"}, f"Import failed: {e}")
return {"CANCELLED"}
except Exception as e:
self.report({"ERROR"}, f"Unexpected internal error: {e}")
logger.exception("Import process crashed")
return {"CANCELLED"}
if not robot.links and not robot.joints:
self.report(
{"ERROR"},
f"The file '{source_path.name}' contains no links or joints. "
"It may be a macro-only XACRO file. Please import the top-level robot description instead.",
)
return {"CANCELLED"}
# Auto-detect and parse companion SRDF file if enabled
loaded_srdf_name: str | None = None
if getattr(self, "import_companion_srdf", True):
base_stem = (
source_path.name.removesuffix(EXT_URDF_XACRO)
if source_path.name.endswith(EXT_URDF_XACRO)
else source_path.stem
)
srdf_candidates = [
source_path.parent / f"{base_stem}{EXT_SRDF}",
source_path.parent / f"{robot.name}{EXT_SRDF}",
source_path.parent.parent / "config" / f"{base_stem}{EXT_SRDF}",
source_path.parent.parent / "config" / f"{robot.name}{EXT_SRDF}",
source_path.parent.parent / "srdf" / f"{base_stem}{EXT_SRDF}",
source_path.parent.parent / "srdf" / f"{robot.name}{EXT_SRDF}",
]
for srdf_candidate in srdf_candidates:
if srdf_candidate.is_file():
try:
robot.semantic = core.SRDFParser(
sandbox_root=sandbox_root, resource_resolver=resolver
).parse(srdf_candidate, robot=robot, validate=False)
loaded_srdf_name = srdf_candidate.name
logger.info(f"Auto-loaded companion SRDF: {srdf_candidate.name}")
except Exception as srdf_err:
logger.warning(
f"Failed to parse companion SRDF '{srdf_candidate.name}': {srdf_err}"
)
break
# Validate robot structure
validator = core.RobotValidator()
result = validator.validate(robot)
srdf_info = f" + companion SRDF ({loaded_srdf_name})" if loaded_srdf_name else ""
if not result.is_valid:
# Report the most critical errors via popups/info bar
for issue in result.errors[:2]:
self.report({"WARNING"}, f"Validation Error: {issue.message}")
self.report(
{"WARNING"},
f"Imported robot '{robot.name}'{srdf_info} has {result.error_count} structural errors. "
"Check the Validation panel for details.",
)
elif result.has_warnings:
self.report(
{"INFO"},
f"Imported robot '{robot.name}'{srdf_info} with {result.warning_count} warnings.",
)
else:
self.report(
{"INFO"},
f"Imported robot '{robot.name}'{srdf_info} successfully.",
)
# Import to scene (Asynchronous)
builder = asynchronous_builder.AsynchronousRobotBuilder(
robot, source_path, BlenderContext(context)
)
builder.start()
# We return FINISHED here, but the builder continues in the background via timers.
# This is standard for long-running non-blocking tasks in Blender.
file_type = FORMAT_XACRO if is_xacro else FORMAT_URDF
self.report(
{"INFO"},
f"Started background import of {file_type}: '{robot.name}'...",
)
clear_stats_cache()
return {"FINISHED"}
# Registration
classes = [
LINKFORGE_OT_import_robot_model,
]
[docs]
def register() -> None:
"""Register operators."""
for cls in classes:
try:
bpy.utils.register_class(cls)
except ValueError:
bpy.utils.unregister_class(cls)
bpy.utils.register_class(cls)
[docs]
def unregister() -> None:
"""Unregister operators."""
for cls in reversed(classes):
with suppress(RuntimeError):
bpy.utils.unregister_class(cls)
if __name__ == "__main__":
register()