| |
| """ |
| Simple VLN Environment for SAGE-3D Benchmark. |
| |
| Provides Isaac Sim based VLN environment with RGB-D rendering, |
| physics simulation, and collision detection. |
| """ |
|
|
| import os |
| import math |
| import json |
| from pathlib import Path |
| from typing import Tuple, List, Dict, Any, Optional |
| import numpy as np |
| from PIL import Image |
| import imageio |
|
|
|
|
| def _should_print_debug() -> bool: |
| """Check if debug messages should be printed.""" |
| return not os.environ.get('SILENT_LOGGING_MODE', False) |
|
|
|
|
| def _debug_print(msg: str) -> None: |
| """Conditionally print debug messages.""" |
| if _should_print_debug(): |
| print(msg) |
| try: |
| from isaacsim.simulation_app import SimulationApp |
| except Exception: |
| from omni.isaac.kit import SimulationApp |
|
|
| |
| try: |
| from .collision_detector import SemanticMap2DCollisionDetector |
| except ImportError: |
| try: |
| from collision_detector import SemanticMap2DCollisionDetector |
| except ImportError: |
| print("[WARNING] Cannot import SemanticMap2DCollisionDetector, 2D semantic map collision detection will be disabled") |
| SemanticMap2DCollisionDetector = None |
|
|
| class SimpleVLNEnv: |
| """Simple VLN Environment based on Isaac Sim for SAGE-3D Benchmark.""" |
| |
| def __init__( |
| self, |
| scene_usd_path: str, |
| headless: bool = True, |
| hz: int = 30, |
| agent_prim_path: str = "/World/AgentCamera", |
| resolution: Tuple[int, int] = (640, 480), |
| map_json_path: str = None |
| ) -> None: |
| """Initialize SimpleVLNEnv. |
| |
| Args: |
| scene_usd_path: Path to scene USD/USDA file |
| headless: Whether to run in headless mode (no GUI) |
| hz: Simulation frequency in Hz |
| agent_prim_path: USD path for agent prim |
| resolution: Camera resolution (width, height) |
| map_json_path: Path to 2D semantic map JSON for collision detection |
| """ |
| print("[ENV_INIT] ===== SimpleVLNEnv Initialization Start =====") |
| print(f"[ENV_INIT] scene_usd_path: {scene_usd_path}") |
| print(f"[ENV_INIT] headless: {headless}") |
| print(f"[ENV_INIT] hz: {hz}") |
| print(f"[ENV_INIT] agent_prim_path: {agent_prim_path}") |
| print(f"[ENV_INIT] resolution: {resolution}") |
| self.scene_usd_path = str(Path(scene_usd_path).resolve()) |
| self.hz = hz |
| self.agent_prim_path = agent_prim_path |
| self.resolution = resolution |
| self.headless = headless |
| self.is_stop_called = False |
| self.consecutive_collisions = 0 |
| self._total_collision_count = 0 |
| self._debug_disable_collision = False |
| |
| |
| import time |
| self._episode_start_time = time.time() |
| self._current_time = time.time() |
| self._collision_detected = False |
| |
| |
| self._log_function = None |
| self._map_json_path = map_json_path |
| |
| self.semantic_map_path = map_json_path |
| self.collision_detector = None |
| |
| |
| self._init_isaac_sim() |
|
|
| def _log(self, msg: str) -> None: |
| """Log message to console and file.""" |
| print(msg, flush=True) |
| if self._log_function: |
| try: |
| self._log_function(msg) |
| except: |
| pass |
| |
| def update_time_and_reset_collision(self) -> None: |
| """Update current time and reset collision state (called each step).""" |
| import time |
| self._current_time = time.time() |
| self._collision_detected = False |
| |
| def reset_episode_time(self) -> None: |
| """Reset episode start time (called when new episode starts).""" |
| import time |
| self._episode_start_time = time.time() |
| self._current_time = time.time() |
| self._collision_detected = False |
|
|
| def set_log_function(self, log_func) -> None: |
| """Set log function.""" |
| self._log_function = log_func |
| |
| self._init_collision_detector(self._map_json_path) |
|
|
| def _init_collision_detector(self, map_json_path: str) -> None: |
| """Initialize 2D semantic map collision detector.""" |
| self._log(f"[COLLISION_2D] ===== Starting 2D Collision Detector Initialization =====") |
| self._log(f"[COLLISION_2D] map_json_path: {map_json_path}") |
| self._log(f"[COLLISION_2D] SemanticMap2DCollisionDetector available: {SemanticMap2DCollisionDetector is not None}") |
| if map_json_path: |
| self._log(f"[COLLISION_2D] Map file exists: {os.path.exists(map_json_path)}") |
| |
| if SemanticMap2DCollisionDetector is not None and map_json_path and os.path.exists(map_json_path): |
| try: |
| self._log(f"[COLLISION_2D] Initializing 2D semantic map collision detector...") |
| self.collision_detector = SemanticMap2DCollisionDetector( |
| map_json_path, |
| robot_radius_m=0.08, |
| scale=0.05 |
| ) |
| self._log(f"[COLLISION_2D] ✓ Successfully loaded 2D semantic map collision detector: {map_json_path}") |
| collision_info = self.collision_detector.get_collision_info() |
| self._log(f"[COLLISION_2D] ✓ Map info: obstacle pixels {collision_info['obstacle_pixels']}/{collision_info['total_pixels']} ({collision_info['obstacle_ratio']:.1%})") |
| except Exception as e: |
| self._log(f"[COLLISION_2D] ✗ Warning: Cannot load 2D semantic map collision detector: {e}") |
| import traceback |
| traceback.print_exc() |
| self.collision_detector = None |
| else: |
| if SemanticMap2DCollisionDetector is None: |
| self._log(f"[COLLISION_2D] ✗ Warning: SemanticMap2DCollisionDetector class not available, using original collision detection") |
| elif not map_json_path: |
| self._log(f"[COLLISION_2D] ℹ Info: No 2D semantic map path provided, using original collision detection") |
| elif not os.path.exists(map_json_path): |
| self._log(f"[COLLISION_2D] ✗ Warning: 2D semantic map file does not exist: {map_json_path}") |
| |
| self._log(f"[COLLISION_2D] Final state: collision_detector = {self.collision_detector is not None}") |
| self._log(f"[COLLISION_2D] ===== 2D Collision Detector Initialization Complete =====") |
|
|
| def _init_isaac_sim(self): |
| """Initialize Isaac Sim environment.""" |
| |
| self.sim = SimulationApp({"headless": self.headless}) |
| |
| import omni.usd |
| from pxr import UsdGeom, UsdPhysics |
| |
| try: |
| from isaacsim.sensors.camera import Camera |
| print("[CAMERA] Using isaacsim.sensors.camera") |
| except ImportError: |
| try: |
| from omni.isaac.sensor import Camera |
| print("[CAMERA] Using omni.isaac.sensor") |
| except ImportError: |
| print("[ERROR] Cannot import Camera class") |
| raise |
| from omni.isaac.core import World |
| from omni.isaac.core.utils.stage import open_stage |
| |
| |
| try: |
| import omni.isaac.core.utils.extensions as extensions |
| extensions.enable_extension("omni.isaac.core") |
| print(f"[EXTENSIONS] Enabled omni.isaac.core") |
| except: |
| try: |
| import isaacsim.core.utils.extensions as extensions |
| extensions.enable_extension("isaacsim.core") |
| print(f"[EXTENSIONS] Enabled isaacsim.core") |
| except Exception as e: |
| print(f"[EXTENSIONS] WARN: Failed to enable core extension: {e}") |
| |
| |
| try: |
| import omni.kit.commands |
| omni.kit.commands.execute('EnableExtension', id="omni.isaac.physics") |
| print(f"[EXTENSIONS] Forced enable omni.isaac.physics") |
| except Exception as e: |
| print(f"[EXTENSIONS] Failed to force enable physics: {e}") |
| try: |
| extensions.enable_extension("isaacsim.physics") |
| print(f"[EXTENSIONS] Enabled isaacsim.physics") |
| except Exception as e2: |
| print(f"[EXTENSIONS] WARN: Failed to enable physics extensions: {e2}") |
| |
| try: |
| extensions.enable_extension("omni.isaac.dynamic_control") |
| print(f"[EXTENSIONS] Enabled omni.isaac.dynamic_control") |
| except Exception as e: |
| print(f"[EXTENSIONS] WARN: Failed to enable dynamic control: {e}") |
| self._UsdGeom = UsdGeom |
| self._UsdPhysics = UsdPhysics |
| self._Camera = Camera |
| self._World = World |
| self._open_stage = open_stage |
| self._omni_usd = omni.usd |
| self._omni_usd.get_context().close_stage() |
| assert self._open_stage(usd_path=self.scene_usd_path), f"Failed to open stage: {self.scene_usd_path}" |
| self.stage = self._omni_usd.get_context().get_stage() |
| |
| |
| try: |
| print(f"[ISAAC_SIM] Initializing Isaac Sim World...") |
| self.world = self._World() |
| print(f"[ISAAC_SIM] Resetting World...") |
| self.world.reset() |
| print(f"[ISAAC_SIM] Running initialization steps...") |
| for i in range(5): |
| self.world.step(render=True) |
| print(f"[ISAAC_SIM] Isaac Sim World initialization complete") |
| except Exception as e: |
| print(f"[ISAAC_SIM] ERROR: Isaac Sim World initialization failed: {e}") |
| import traceback |
| traceback.print_exc() |
| raise |
| |
| self._pos = np.array([0.0, 0.0, 0.85], dtype=np.float32) |
| self._yaw = 0.0 |
| self.agent_radius = 0.01 |
| |
| |
| self._cleanup_existing_camera() |
| self._create_simple_camera() |
| |
| |
| self._verify_physics_system() |
| |
| |
| self._get_scene_bounds() |
| |
| def _cleanup_existing_camera(self) -> None: |
| """Cleanup any existing camera to ensure fresh creation.""" |
| try: |
| if hasattr(self, 'cam'): |
| try: |
| self.cam = None |
| except Exception as e: |
| self.cam = None |
| |
| |
| if hasattr(self, 'stage') and self.stage: |
| camera_paths = [ |
| self.agent_prim_path + "/Camera", |
| self.agent_prim_path, |
| "/World/Camera" |
| ] |
| |
| for cam_path in camera_paths: |
| try: |
| cam_prim = self.stage.GetPrimAtPath(cam_path) |
| if cam_prim and cam_prim.IsValid(): |
| self.stage.RemovePrim(cam_prim.GetPath()) |
| except Exception as e: |
| pass |
| |
| except Exception as e: |
| pass |
| |
| def _ensure_depth_annotator_runtime(self) -> None: |
| """Ensure depth annotator exists at runtime.""" |
| try: |
| self._log("[RUNTIME_DEPTH_FIX] Checking depth annotator...") |
| |
| |
| frame = self.cam.get_current_frame() |
| available_keys = list(frame.keys()) if frame else [] |
| self._log(f"[RUNTIME_DEPTH_FIX] Current frame keys: {available_keys}") |
| |
| if 'distance_to_image_plane' not in available_keys: |
| self._log(f"[RUNTIME_DEPTH_FIX] No depth data, attempting fix...") |
| |
| |
| success = False |
| |
| |
| if hasattr(self.cam, 'add_distance_to_image_plane_to_frame'): |
| try: |
| self._log("[RUNTIME_DEPTH_FIX] Trying to add distance_to_image_plane annotator...") |
| self.cam.add_distance_to_image_plane_to_frame() |
| |
| |
| self._configure_isaac_sim_depth_rendering() |
| |
| |
| self.world.step(render=True) |
| new_frame = self.cam.get_current_frame() |
| new_keys = list(new_frame.keys()) if new_frame else [] |
| |
| if 'distance_to_image_plane' in new_keys: |
| |
| test_depth = new_frame['distance_to_image_plane'] |
| if test_depth is not None and hasattr(test_depth, 'std'): |
| depth_std = test_depth.std() if hasattr(test_depth, 'std') else 0 |
| if depth_std > 0.01: |
| self._log("[RUNTIME_DEPTH_FIX] Successfully added valid depth annotator") |
| success = True |
| else: |
| self._log(f"[RUNTIME_DEPTH_FIX] Depth annotator added but no data change, std={depth_std}") |
| else: |
| self._log("[RUNTIME_DEPTH_FIX] Depth annotator added but data invalid") |
| else: |
| self._log(f"[RUNTIME_DEPTH_FIX] Still no depth data after adding, new keys: {new_keys}") |
| |
| except Exception as e: |
| self._log(f"[RUNTIME_DEPTH_FIX] Failed to add annotator: {e}") |
| |
| |
| if not success: |
| annotator_methods = [ |
| 'add_distance_to_camera_to_frame', |
| 'add_linear_depth_to_frame', |
| 'add_depth_to_frame' |
| ] |
| |
| for method_name in annotator_methods: |
| if hasattr(self.cam, method_name): |
| try: |
| self._log(f"[RUNTIME_DEPTH_FIX] Trying {method_name}...") |
| method = getattr(self.cam, method_name) |
| method() |
| |
| |
| self.world.step(render=True) |
| test_frame = self.cam.get_current_frame() |
| if test_frame and any('distance' in k or 'depth' in k for k in test_frame.keys()): |
| self._log(f"[RUNTIME_DEPTH_FIX] Success") |
| success = True |
| break |
| |
| except Exception as e: |
| self._log(f"[RUNTIME_DEPTH_FIX] Failed: {e}") |
| |
| |
| if not success: |
| self._log("[RUNTIME_DEPTH_FIX] Analyzing camera object...") |
| depth_methods = [attr for attr in dir(self.cam) if 'depth' in attr.lower() or 'distance' in attr.lower()] |
| self._log(f"[RUNTIME_DEPTH_FIX] Available depth methods: {depth_methods}") |
| |
| annotator_methods = [attr for attr in dir(self.cam) if 'add' in attr.lower() and ('annotator' in attr.lower() or 'frame' in attr.lower())] |
| self._log(f"[RUNTIME_DEPTH_FIX] Available annotator methods: {annotator_methods}") |
| |
| if not success: |
| self._log("[RUNTIME_DEPTH_FIX] All depth annotator methods failed") |
| |
| else: |
| self._log("[RUNTIME_DEPTH_FIX] Depth annotator exists, verifying data...") |
| |
| depth_data = frame.get('distance_to_image_plane') |
| if depth_data is not None: |
| self._log(f"[RUNTIME_DEPTH_FIX] Depth data type: {type(depth_data)}, valid: {hasattr(depth_data, 'shape')}") |
| else: |
| self._log("[RUNTIME_DEPTH_FIX] Depth annotator exists but data is None") |
| |
| except Exception as e: |
| self._log(f"[RUNTIME_DEPTH_FIX] Runtime depth fix failed: {e}") |
| import traceback |
| self._log(f"[RUNTIME_DEPTH_FIX] Error details: {traceback.format_exc()}") |
| |
| def _force_refresh_depth_pipeline(self) -> None: |
| """Force refresh depth rendering pipeline.""" |
| try: |
| self._log("[DEPTH_PIPELINE] Force refreshing depth pipeline...") |
| |
| |
| if hasattr(self, 'cam') and self.cam: |
| try: |
| |
| cam_pos, cam_rot = self.cam.get_world_pose() |
| self._log(f"[DEPTH_PIPELINE] Current camera position: {cam_pos}") |
| |
| |
| try: |
| |
| frame = self.cam.get_current_frame() |
| if frame: |
| depth_keys = [k for k in frame.keys() if 'depth' in k.lower() or 'distance' in k.lower()] |
| self._log(f"[DEPTH_PIPELINE] Found existing depth keys: {depth_keys}") |
| |
| |
| self.cam.add_distance_to_image_plane_to_frame() |
| self._log("[DEPTH_PIPELINE] Re-added distance_to_image_plane annotator") |
| |
| except Exception as e: |
| self._log(f"[DEPTH_PIPELINE] Failed to re-add annotator: {e}") |
| |
| except Exception as e: |
| self._log(f"[DEPTH_PIPELINE] Camera depth config failed: {e}") |
| |
| |
| try: |
| self._log("[DEPTH_PIPELINE] Force resetting collision mesh...") |
| self.set_collision_mesh_visibility(False) |
| for i in range(2): |
| self.world.step(render=True) |
| self.set_collision_mesh_visibility(True) |
| for i in range(2): |
| self.world.step(render=True) |
| self._log("[DEPTH_PIPELINE] Collision mesh reset complete") |
| |
| except Exception as e: |
| self._log(f"[DEPTH_PIPELINE] Collision mesh reset failed: {e}") |
| |
| |
| try: |
| self._log("[DEPTH_PIPELINE] Reconfiguring Isaac Sim renderer...") |
| |
| |
| self._configure_isaac_sim_depth_rendering() |
| |
| |
| for i in range(3): |
| self.world.step(render=True) |
| |
| self._log("[DEPTH_PIPELINE] Renderer reconfiguration complete") |
| |
| except Exception as e: |
| self._log(f"[DEPTH_PIPELINE] Renderer reconfiguration failed: {e}") |
| |
| self._log("[DEPTH_PIPELINE] Depth pipeline refresh complete") |
| |
| except Exception as e: |
| self._log(f"[DEPTH_PIPELINE] Depth pipeline refresh failed: {e}") |
| import traceback |
| self._log(f"[DEPTH_PIPELINE] Error details: {traceback.format_exc()}") |
| |
| def _configure_isaac_sim_depth_rendering(self) -> None: |
| """Configure Isaac Sim depth rendering for 3DGS+collision mesh scenes.""" |
| try: |
| self._log("[DEPTH_CONFIG] Configuring 3DGS scene depth rendering...") |
| |
| |
| self._make_collision_mesh_visible_for_depth() |
| |
| |
| try: |
| import carb.settings |
| settings = carb.settings.get_settings() |
| |
| |
| settings.set("/renderer/enabled", True) |
| settings.set("/renderer/asyncRenderEnabled", False) |
| settings.set("/rtx/rendermode", "RayTracedLighting") |
| settings.set("/rtx/pathtracing/enabled", False) |
| |
| |
| settings.set("/renderer/depth/enabled", True) |
| settings.set("/renderer/depth/format", "float32") |
| |
| self._log("[DEPTH_CONFIG] carb settings configured") |
| |
| except Exception as e: |
| self._log(f"[DEPTH_CONFIG] carb settings failed: {e}") |
| |
| |
| try: |
| if hasattr(self, 'usd_cam') and self.usd_cam: |
| |
| self.usd_cam.GetClippingRangeAttr().Set((0.01, 50.0)) |
| self._log("[DEPTH_CONFIG] Camera clipping range set to(0.01, 50.0)") |
| elif hasattr(self, 'cam') and self.cam: |
| |
| if hasattr(self.cam, 'set_clipping_range'): |
| self.cam.set_clipping_range(0.01, 50.0) |
| self._log("[DEPTH_CONFIG] Isaac Sim camera clipping range set") |
| |
| except Exception as e: |
| self._log(f"[DEPTH_CONFIG] Camera clipping range setting failed: {e}") |
| |
| |
| try: |
| if hasattr(self, 'world') and self.world: |
| |
| for i in range(3): |
| self.world.step(render=True) |
| self._log("[DEPTH_CONFIG] Renderer refresh complete") |
| |
| except Exception as e: |
| self._log(f"[DEPTH_CONFIG] Renderer refresh failed: {e}") |
| |
| except Exception as e: |
| self._log(f"[DEPTH_CONFIG] Depth rendering config failed: {e}") |
| |
| def _make_collision_mesh_visible_for_depth(self) -> None: |
| """Make collision mesh visible for depth rendering.""" |
| try: |
| self._log("[COLLISION_DEPTH] Finding and configuring collision mesh for depth...") |
| |
| |
| collision_paths = [ |
| "/World/scene_collision", |
| "/World/collision", |
| "/collision", |
| "/World/Collision", |
| "/Collision", |
| "/World/collision_mesh", |
| "/collision_mesh" |
| ] |
| |
| found_collision = False |
| |
| for collision_path in collision_paths: |
| try: |
| collision_prim = self.stage.GetPrimAtPath(collision_path) |
| if collision_prim and collision_prim.IsValid(): |
| self._log(f"[COLLISION_DEPTH] Found collision mesh: {collision_path}") |
| |
| |
| from pxr import UsdGeom |
| |
| |
| try: |
| imageable = UsdGeom.Imageable(collision_prim) |
| current_visibility = imageable.GetVisibilityAttr().Get() |
| self._log(f"[COLLISION_DEPTH] Current collision visibility: {current_visibility}") |
| |
| |
| imageable.GetVisibilityAttr().Set(UsdGeom.Tokens.visible) |
| self._log(f"[COLLISION_DEPTH] Set collision root prim visible") |
| |
| except Exception as e: |
| self._log(f"[COLLISION_DEPTH] Failed to set root prim visibility: {e}") |
| |
| |
| def make_mesh_visible_for_depth(prim): |
| try: |
| |
| if hasattr(prim, 'GetTypeName'): |
| prim_type = prim.GetTypeName() |
| prim_path = str(prim.GetPath()) |
| |
| if prim_type in ['Mesh', 'Xform', 'Scope']: |
| imageable = UsdGeom.Imageable(prim) |
| if imageable: |
| imageable.GetVisibilityAttr().Set(UsdGeom.Tokens.visible) |
| self._log(f"[COLLISION_DEPTH] Set visible: {prim_path} ({prim_type})") |
| |
| |
| for child in prim.GetChildren(): |
| make_mesh_visible_for_depth(child) |
| |
| except Exception as e: |
| self._log(f"[COLLISION_DEPTH] Failed to configure child prim {prim.GetPath()}: {e}") |
| |
| |
| make_mesh_visible_for_depth(collision_prim) |
| found_collision = True |
| self._log(f"[COLLISION_DEPTH] Successfully configured collision and child meshes for depth") |
| break |
| |
| except Exception as e: |
| self._log(f"[COLLISION_DEPTH] Failed to check path: {e}") |
| |
| if not found_collision: |
| self._log("[COLLISION_DEPTH] Collision mesh not found, searching all meshes...") |
| |
| self._find_and_configure_all_meshes() |
| |
| except Exception as e: |
| self._log(f"[COLLISION_DEPTH] Collision mesh config failed: {e}") |
| |
| def _find_and_configure_all_meshes(self) -> None: |
| """Find and configure all meshes in scene for depth rendering.""" |
| try: |
| from pxr import UsdGeom, Usd |
| |
| self._log("[MESH_SEARCH] Searching all meshes in scene...") |
| |
| |
| def traverse_and_configure(prim): |
| try: |
| if prim.GetTypeName() == 'Mesh': |
| mesh_path = str(prim.GetPath()) |
| self._log(f"[MESH_SEARCH] Found mesh: {mesh_path}") |
| |
| |
| imageable = UsdGeom.Imageable(prim) |
| imageable.GetVisibilityAttr().Set(UsdGeom.Tokens.visible) |
| |
| |
| if any(word in mesh_path.lower() for word in ['collision', 'physics', 'collider']): |
| self._log(f"[MESH_SEARCH] Configured collision mesh for depth: {mesh_path}") |
| else: |
| self._log(f"[MESH_SEARCH] Configured regular mesh for depth: {mesh_path}") |
| |
| |
| for child in prim.GetChildren(): |
| traverse_and_configure(child) |
| |
| except Exception as e: |
| self._log(f"[MESH_SEARCH] Failed to process prim {prim.GetPath()}: {e}") |
| |
| |
| root_prim = self.stage.GetDefaultPrim() |
| if root_prim: |
| traverse_and_configure(root_prim) |
| else: |
| |
| world_prim = self.stage.GetPrimAtPath("/World") |
| if world_prim: |
| traverse_and_configure(world_prim) |
| |
| self._log("[MESH_SEARCH] Mesh search and config complete") |
| |
| except Exception as e: |
| self._log(f"[MESH_SEARCH] Mesh search failed: {e}") |
| |
| def set_collision_mesh_visibility(self, visible: bool) -> None: |
| """Force set collision mesh visibility. |
| |
| Args: |
| visible (bool): True for visible (depth), False for invisible (RGB) |
| """ |
| try: |
| action = "enable" if visible else "disable" |
| self._log(f"[COLLISION_VIS] Force setting collision mesh visibility...") |
| |
| |
| collision_paths = [ |
| "/World/scene_collision", |
| "/World/collision", |
| "/collision", |
| "/World/Collision", |
| "/Collision", |
| "/World/collision_mesh", |
| "/collision_mesh", |
| "/scene_collision" |
| ] |
| |
| from pxr import UsdGeom |
| collision_prims_found = [] |
| |
| |
| for coll_path in collision_paths: |
| try: |
| collision_prim = self.stage.GetPrimAtPath(coll_path) |
| if collision_prim and collision_prim.IsValid(): |
| collision_prims_found.append((coll_path, collision_prim)) |
| self._log(f"[COLLISION_VIS] Found collision: {coll_path}") |
| except Exception as e: |
| continue |
| |
| if not collision_prims_found: |
| self._log("[COLLISION_VIS] No collision mesh found, searching all collision paths...") |
| |
| from pxr import Usd |
| def search_collision_recursive(prim, path=""): |
| current_path = str(prim.GetPath()) |
| if "collision" in current_path.lower(): |
| self._log(f"[COLLISION_SEARCH] Found possible collision path: {current_path}") |
| return [current_path] |
| |
| found_paths = [] |
| for child in prim.GetChildren(): |
| found_paths.extend(search_collision_recursive(child, current_path)) |
| return found_paths |
| |
| all_collision_paths = search_collision_recursive(self.stage.GetPseudoRoot()) |
| if all_collision_paths: |
| self._log(f"[COLLISION_SEARCH] Found collision-related paths: {all_collision_paths}") |
| |
| for found_path in all_collision_paths[:3]: |
| try: |
| collision_prim = self.stage.GetPrimAtPath(found_path) |
| if collision_prim and collision_prim.IsValid(): |
| collision_prims_found.append((found_path, collision_prim)) |
| self._log(f"[COLLISION_VIS] Dynamically found collision: {found_path}") |
| except Exception as e: |
| continue |
| |
| if not collision_prims_found: |
| self._log("[COLLISION_VIS] No collision mesh found, depth may be invalid") |
| return |
| |
| |
| for coll_path, collision_prim in collision_prims_found: |
| try: |
| |
| imageable = UsdGeom.Imageable(collision_prim) |
| |
| if visible: |
| imageable.GetVisibilityAttr().Set(UsdGeom.Tokens.visible) |
| self._log(f"[COLLISION_VIS] Set visible") |
| else: |
| imageable.GetVisibilityAttr().Set(UsdGeom.Tokens.invisible) |
| self._log(f"[COLLISION_VIS] Set invisible") |
| |
| |
| def force_set_visibility(prim, vis_state): |
| try: |
| |
| child_imageable = UsdGeom.Imageable(prim) |
| if child_imageable: |
| if vis_state: |
| child_imageable.GetVisibilityAttr().Set(UsdGeom.Tokens.visible) |
| else: |
| child_imageable.GetVisibilityAttr().Set(UsdGeom.Tokens.invisible) |
| |
| |
| for child in prim.GetChildren(): |
| force_set_visibility(child, vis_state) |
| except Exception: |
| pass |
| |
| |
| force_set_visibility(collision_prim, visible) |
| |
| except Exception as e: |
| self._log(f"[COLLISION_VIS] Failed to set: {e}") |
| |
| |
| if hasattr(self, 'world') and self.world: |
| for i in range(3): |
| self.world.step(render=True) |
| |
| self._log(f"[COLLISION_VIS] Collision mesh visibility set") |
| |
| except Exception as e: |
| self._log(f"[COLLISION_VIS] Failed to set collision mesh visibility: {e}") |
| |
| def _create_simple_camera(self) -> None: |
| """Create agent with physics body and camera.""" |
| print("[CAMERA_CREATE] Creating camera...") |
| print(f"[CAMERA_CREATE] agent_prim_path: {self.agent_prim_path}") |
| print(f"[CAMERA_CREATE] resolution: {self.resolution}") |
| print(f"[CAMERA_CREATE] hz: {self.hz}") |
| try: |
| |
| agent_xform = self._UsdGeom.Xform.Define(self.stage, self.agent_prim_path) |
| |
| |
| collision_cylinder_path = self.agent_prim_path + "/CollisionCylinder" |
| collision_cylinder = self._UsdGeom.Cylinder.Define(self.stage, collision_cylinder_path) |
| collision_cylinder.CreateRadiusAttr(0.1) |
| collision_cylinder.CreateHeightAttr(0.5) |
| collision_cylinder.CreateAxisAttr("Z") |
| |
| |
| |
| collision_cylinder.AddTranslateOp().Set((0.0, 0.0, 0.0)) |
| |
| |
| collision_cylinder.CreateVisibilityAttr("invisible") |
| |
| _debug_print(f"[PHYSICS] Created collision cylinder: radius=0.1m, height=0.5m, bottom_clearance=0.5m") |
| |
| |
| agent_rigid_body = self._UsdPhysics.RigidBodyAPI.Apply(agent_xform.GetPrim()) |
| |
| |
| agent_rigid_body.CreateKinematicEnabledAttr(True) |
| |
| _debug_print(f"[PHYSICS] Using kinematic rigid body with physics-based collision response") |
| |
| |
| try: |
| agent_rigid_body.CreateMassAttr(1.0) |
| _debug_print(f"[PHYSICS] Set mass to 1.0") |
| except: |
| try: |
| |
| if hasattr(agent_rigid_body, 'CreateMassAttr'): |
| agent_rigid_body.CreateMassAttr(1.0) |
| else: |
| _debug_print(f"[PHYSICS] WARN: CreateMassAttr not available") |
| except Exception as e: |
| _debug_print(f"[PHYSICS] WARN: Failed to set mass: {e}") |
| |
| try: |
| agent_rigid_body.CreateRigidBodyEnabledAttr(True) |
| _debug_print(f"[PHYSICS] Enabled rigid body") |
| except: |
| try: |
| |
| if hasattr(agent_rigid_body, 'CreateRigidBodyEnabledAttr'): |
| agent_rigid_body.CreateRigidBodyEnabledAttr(True) |
| else: |
| _debug_print(f"[PHYSICS] WARN: CreateRigidBodyEnabledAttr not available") |
| except Exception as e: |
| _debug_print(f"[PHYSICS] WARN: Failed to enable rigid body: {e}") |
| |
| |
| collision_api = self._UsdPhysics.CollisionAPI.Apply(collision_cylinder.GetPrim()) |
| |
| |
| try: |
| |
| collision_shape = collision_cylinder |
| _debug_print(f"[PHYSICS] Using geometric cylinder as collision shape") |
| |
| |
| collision_api.CreateCollisionEnabledAttr(True) |
| _debug_print(f"[PHYSICS] Enabled collision detection") |
| |
| |
| self.collision_shape_prim = collision_cylinder |
| self.collision_cylinder_prim = collision_cylinder |
| |
| except Exception as e: |
| _debug_print(f"[PHYSICS] WARN: Failed to setup collision: {e}") |
| self.collision_shape_prim = None |
| self.collision_cylinder_prim = None |
| |
| |
| try: |
| collision_api.CreateCollisionEnabledAttr(True) |
| _debug_print(f"[PHYSICS] Enabled collision detection") |
| except Exception as e: |
| _debug_print(f"[PHYSICS] WARN: Failed to enable collision: {e}") |
| |
| |
| try: |
| |
| camera_path = self.agent_prim_path + "/Camera" |
| |
| |
| camera_prim = self._UsdGeom.Camera.Define(self.stage, camera_path) |
| |
| |
| self.cam = self._Camera( |
| prim_path=camera_path, |
| frequency=self.hz, |
| resolution=self.resolution |
| ) |
| |
| |
| try: |
| |
| if hasattr(self.cam, 'add_distance_to_image_plane_to_frame'): |
| self.cam.add_distance_to_image_plane_to_frame() |
| print("[CAMERA] Added distance_to_image_plane annotator") |
| |
| |
| elif hasattr(self.cam, 'add_distance_to_camera_to_frame'): |
| self.cam.add_distance_to_camera_to_frame() |
| print("[CAMERA] Added distance_to_camera annotator") |
| |
| |
| elif hasattr(self.cam, 'add_annotator'): |
| self.cam.add_annotator("distance_to_image_plane") |
| print("[CAMERA] Added depth annotator via generic method") |
| |
| else: |
| print("[CAMERA] Camera does not support depth annotator methods") |
| |
| annotator_methods = [m for m in dir(self.cam) if 'add' in m.lower() and ('distance' in m.lower() or 'depth' in m.lower() or 'annotator' in m.lower())] |
| print(f"[CAMERA] Available annotator methods: {annotator_methods}") |
| |
| except Exception as e: |
| print(f"[CAMERA] Failed to add depth annotator: {e}") |
| |
| self.cam.initialize() |
| |
| |
| try: |
| |
| if hasattr(self, 'world') and self.world: |
| self.world.step(render=True) |
| |
| frame = self.cam.get_current_frame() |
| available_keys = list(frame.keys()) if frame else [] |
| print(f"[CAMERA] Camera frame available data: {available_keys}") |
| |
| if 'distance_to_image_plane' in available_keys: |
| print("[CAMERA] Depth annotator verified") |
| else: |
| print("[CAMERA] Depth annotator verification failed") |
| |
| except Exception as e: |
| print(f"[CAMERA] Annotator verification failed: {e}") |
| |
| |
| self.cam_prim = self.stage.GetPrimAtPath(camera_path) |
| self.usd_cam = self._UsdGeom.Camera(self.cam_prim) |
| |
| |
| try: |
| |
| self.usd_cam.GetClippingRangeAttr().Set((0.1, 50.0)) |
| print("[CAMERA] Set camera clipping range (0.1, 50.0)") |
| except Exception as e: |
| print(f"[CAMERA] Failed to set clipping range: {e}") |
| |
| |
| self.usd_cam.GetFocalLengthAttr().Set(8.0) |
| |
| print(f"[INFO] Created Isaac Sim camera at: {camera_path}") |
| |
| except Exception as e: |
| print(f"[ERROR] Failed to create camera: {e}") |
| import traceback |
| traceback.print_exc() |
| self.cam = None |
| self.cam_prim = None |
| self.usd_cam = None |
| |
| |
| self.agent_prim = agent_xform.GetPrim() |
| self.collision_cylinder_prim = collision_cylinder.GetPrim() |
| self.collision_shape_prim = collision_cylinder.GetPrim() |
| |
| print(f"[INFO] Created agent with physics: cylinder radius=0.01m, height=0.7m, camera at z=1.2m, focal_length=8.0") |
| print(f"[INFO] Physics enabled: RigidBody={agent_rigid_body.GetRigidBodyEnabledAttr().Get()}, Collision={collision_api.GetCollisionEnabledAttr().Get()}") |
| |
| |
| self._setup_physics_scene() |
| |
| |
| self._verify_agent_physics() |
| |
| |
| self._verify_collision_system() |
| |
| except Exception as e: |
| print(f"[ERROR] Failed to create agent with physics: {e}") |
| |
| try: |
| |
| if hasattr(self, 'agent_prim') and self.agent_prim: |
| try: |
| import omni.usd |
| omni.usd.delete_prim(self.stage, self.agent_prim.GetPath()) |
| print(f"[CLEANUP] Removed failed agent prim") |
| except: |
| pass |
| |
| |
| camera_prim = self._UsdGeom.Camera.Define(self.stage, self.agent_prim_path) |
| |
| |
| self.cam = self._Camera(prim_path=self.agent_prim_path, frequency=self.hz, resolution=self.resolution) |
| self.cam.initialize() |
| |
| |
| self.cam_prim = self.stage.GetPrimAtPath(self.agent_prim_path) |
| self.usd_cam = self._UsdGeom.Camera(self.cam_prim) |
| self.usd_cam.GetFocalLengthAttr().Set(8.0) |
| |
| |
| self.agent_prim = camera_prim.GetPrim() |
| self.collision_cylinder_prim = None |
| self.collision_shape_prim = None |
| |
| print(f"[WARN] Fallback to simple camera without physics") |
| except Exception as e2: |
| print(f"[ERROR] Failed to create fallback camera: {e2}") |
| raise e2 |
| def _verify_physics_system(self) -> None: |
| """Verify physics system initialization.""" |
| try: |
| print(f"[PHYSICS_VERIFY] Checking physics system status...") |
| |
| |
| if hasattr(self, 'world') and self.world: |
| print(f"[PHYSICS_VERIFY] World object: {type(self.world)}") |
| else: |
| print(f"[PHYSICS_VERIFY] WARN: No world object") |
| |
| |
| if hasattr(self, 'agent_prim') and self.agent_prim: |
| print(f"[PHYSICS_VERIFY] Agent prim: {self.agent_prim.GetPath()}") |
| |
| |
| rigid_body = self._UsdPhysics.RigidBodyAPI(self.agent_prim) |
| if rigid_body: |
| try: |
| enabled = rigid_body.GetRigidBodyEnabledAttr().Get() |
| kinematic = rigid_body.GetKinematicEnabledAttr().Get() |
| print(f"[PHYSICS_VERIFY] RigidBody: enabled={enabled}, kinematic={kinematic}") |
| except Exception as e: |
| print(f"[PHYSICS_VERIFY] RigidBody: API available but failed to get attributes: {e}") |
| else: |
| print(f"[PHYSICS_VERIFY] WARN: No RigidBody API") |
| else: |
| print(f"[PHYSICS_VERIFY] WARN: No agent prim") |
| |
| |
| if hasattr(self, 'collision_shape_prim') and self.collision_shape_prim: |
| print(f"[PHYSICS_VERIFY] Collision shape: {self.collision_shape_prim.GetPath()}") |
| |
| |
| try: |
| collision_api = self._UsdPhysics.CollisionAPI(self.collision_shape_prim) |
| if collision_api: |
| try: |
| enabled = collision_api.GetCollisionEnabledAttr().Get() |
| print(f"[PHYSICS_VERIFY] Collision: enabled={enabled}") |
| except Exception as e: |
| print(f"[PHYSICS_VERIFY] Collision: API available but failed to get enabled attribute: {e}") |
| else: |
| print(f"[PHYSICS_VERIFY] WARN: No Collision API") |
| except Exception as e: |
| print(f"[PHYSICS_VERIFY] WARN: Failed to create Collision API: {e}") |
| else: |
| print(f"[PHYSICS_VERIFY] WARN: No collision shape prim") |
| |
| print(f"[PHYSICS_VERIFY] Physics system verification complete") |
| |
| except Exception as e: |
| print(f"[PHYSICS_VERIFY] ERROR: Failed to verify physics system: {e}") |
| def _get_scene_bounds(self) -> None: |
| """Get scene bounds information.""" |
| try: |
| print(f"[SCENE_BOUNDS] Analyzing scene boundaries...") |
| |
| |
| stage = self.stage |
| if stage: |
| |
| root_path = stage.GetPseudoRoot().GetPath() |
| |
| |
| all_prims = [] |
| def collect_prims(prim): |
| all_prims.append(prim) |
| for child in prim.GetChildren(): |
| collect_prims(child) |
| |
| collect_prims(stage.GetPseudoRoot()) |
| |
| |
| geom_prims = [p for p in all_prims if p.IsA(self._UsdGeom.Gprim)] |
| |
| if geom_prims: |
| |
| min_x, min_y, min_z = float('inf'), float('inf'), float('inf') |
| max_x, max_y, max_z = float('-inf'), float('-inf'), float('-inf') |
| |
| for prim in geom_prims: |
| try: |
| |
| bbox = self._UsdGeom.ComputeBoundingBox(prim, 0) |
| if bbox: |
| min_x = min(min_x, bbox.GetMin()[0]) |
| min_y = min(min_y, bbox.GetMin()[1]) |
| min_z = min(min_z, bbox.GetMin()[2]) |
| max_x = max(max_x, bbox.GetMax()[0]) |
| max_y = max(max_y, bbox.GetMax()[1]) |
| max_z = max(max_z, bbox.GetMax()[2]) |
| except: |
| continue |
| |
| if min_x != float('inf'): |
| self.scene_bounds = { |
| 'x': (min_x, max_x), |
| 'y': (min_y, max_y), |
| 'z': (min_z, max_z) |
| } |
| print(f"[SCENE_BOUNDS] Scene bounds: x=[{min_x:.2f}, {max_x:.2f}], y=[{min_y:.2f}, {max_y:.2f}], z=[{min_z:.2f}, {max_z:.2f}]") |
| else: |
| print(f"[SCENE_BOUNDS] WARN: Could not determine scene bounds") |
| self.scene_bounds = {'x': (-5, 5), 'y': (-12, 3), 'z': (0, 3)} |
| else: |
| print(f"[SCENE_BOUNDS] WARN: No geometric prims found in scene") |
| self.scene_bounds = {'x': (-5, 5), 'y': (-12, 3), 'z': (0, 3)} |
| else: |
| print(f"[SCENE_BOUNDS] WARN: No stage available") |
| self.scene_bounds = {'x': (-5, 5), 'y': (-12, 3), 'z': (0, 3)} |
| |
| except Exception as e: |
| print(f"[SCENE_BOUNDS] ERROR: Failed to get scene bounds: {e}") |
| self.scene_bounds = {'x': (-5, 5), 'y': (-12, 3), 'z': (0, 3)} |
| |
| |
| def load_scene(self, new_scene_usd_path: str) -> bool: |
| """ |
| Switch to new scene. |
| |
| Args: |
| new_scene_usd_path: Path to new scene USD file |
| |
| Returns: |
| bool: Whether scene was loaded successfully |
| """ |
| try: |
| print(f"[SCENE_SWITCH] Switching scene...") |
| print(f"[SCENE_SWITCH] Current scene: {self.scene_usd_path}") |
| print(f"[SCENE_SWITCH] New scene: {new_scene_usd_path}") |
| |
| |
| self.scene_usd_path = str(Path(new_scene_usd_path).resolve()) |
| |
| |
| if hasattr(self.sim, 'load_scene'): |
| return self.sim.load_scene(new_scene_usd_path) |
| else: |
| print(f"[SCENE_SWITCH] sim object does not support scene switching") |
| return False |
| |
| except Exception as e: |
| print(f"[SCENE_SWITCH] Scene switch failed: {e}") |
| import traceback |
| traceback.print_exc() |
| return False |
|
|
| def update_map(self, new_map_path: str) -> bool: |
| """ |
| Dynamically update 2D semantic map. |
| |
| Args: |
| new_map_path: Path to new 2D semantic map file |
| |
| Returns: |
| bool: Whether update was successful |
| """ |
| try: |
| print(f"[MAP_SWITCH] Switching map...") |
| print(f"[MAP_SWITCH] Current map: {self._map_json_path}") |
| print(f"[MAP_SWITCH] New map: {new_map_path}") |
| |
| |
| self._map_json_path = new_map_path |
| self.semantic_map_path = new_map_path |
| |
| |
| self._init_collision_detector(new_map_path) |
| |
| print(f"[MAP_SWITCH] Map switch successful") |
| return True |
| |
| except Exception as e: |
| print(f"[MAP_SWITCH] Map switch failed: {e}") |
| import traceback |
| traceback.print_exc() |
| return False |
|
|
| def close(self) -> None: |
| self.sim.close() |
| def set_start_pose(self, position: List[float], rotation_xyzw: List[float]) -> None: |
| |
| self.is_stop_called = False |
| self.consecutive_collisions = 0 |
| self._total_collision_count = 0 |
| self._log(f"[EPISODE_RESET] Reset episode state") |
| |
| self._pos = np.array(position, dtype=np.float32) |
| |
| x, y, z, w = rotation_xyzw |
| |
| |
| self._original_quaternion = rotation_xyzw.copy() |
| |
| |
| |
| |
| |
| |
| |
| qz_original = -x |
| qw_original = w |
| |
| yaw_new = 2 * math.atan2(qz_original, qw_original) |
| self._yaw = yaw_new - math.pi |
| |
| |
| if self._yaw < -math.pi: |
| self._yaw += 2 * math.pi |
| elif self._yaw > math.pi: |
| self._yaw -= 2 * math.pi |
| |
| |
| self._initial_yaw = self._yaw |
| |
| |
| self._log(f"[DEBUG] Setting start pose:") |
| self._log(f"[DEBUG] Input position: {position}") |
| self._log(f"[DEBUG] Input rotation: {rotation_xyzw}") |
| self._log(f"[DEBUG] qz_original: {qz_original:.3f}, qw_original: {qw_original:.3f}") |
| |
| self._log(f"[DEBUG] Final position: {self._pos}") |
| |
| |
| self._apply_pose() |
| for _ in range(5): |
| self.world.step(render=True) |
| def _update_camera_position(self) -> None: |
| """Update camera position to follow agent.""" |
| try: |
| |
| |
| |
| if hasattr(self, 'cam') and self.cam: |
| camera_pos = self._pos.copy() |
| camera_pos[2] = 1.2 |
| |
| |
| if hasattr(self, '_original_quaternion') and hasattr(self, '_initial_yaw'): |
| |
| |
| yaw_delta = self._yaw - self._initial_yaw |
| |
| |
| qx_orig, qy_orig, qz_orig, qw_orig = self._original_quaternion |
| angle_correction = math.radians(-45) |
| qx_correction = math.sin(angle_correction/2) |
| |
| |
| base_qx = qx_orig + qx_correction |
| base_qy = qy_orig |
| base_qz = qz_orig |
| base_qw = qw_orig |
| |
| |
| if abs(yaw_delta) > 0.01: |
| |
| qz_delta_tmp = math.sin(yaw_delta/2.0) |
| qw_delta_tmp = math.cos(yaw_delta/2.0) |
| |
| |
| qx = base_qx * qw_delta_tmp + base_qw * (-qz_delta_tmp) |
| qy = base_qy * qw_delta_tmp |
| qz = base_qz * qw_delta_tmp |
| qw = base_qw * qw_delta_tmp - base_qx * (-qz_delta_tmp) |
| else: |
| |
| qx, qy, qz, qw = base_qx, base_qy, base_qz, base_qw |
| |
| orientation = np.array([qx, qy, qz, qw], dtype=np.float32) |
| |
| |
| |
| |
| |
| elif hasattr(self, '_original_quaternion'): |
| |
| qx_orig, qy_orig, qz_orig, qw_orig = self._original_quaternion |
| |
| angle_correction = math.radians(-45) |
| qx_correction = math.sin(angle_correction/2) |
| |
| qx = qx_orig + qx_correction |
| qy = qy_orig |
| qz = qz_orig |
| qw = qw_orig |
| |
| orientation = np.array([qx, qy, qz, qw], dtype=np.float32) |
| |
| else: |
| |
| qz_tmp = math.sin(self._yaw/2.0) |
| qw_tmp = math.cos(self._yaw/2.0) |
| |
| qx = -qz_tmp |
| qy = 0.0 |
| qz = 0.0 |
| qw = qw_tmp |
| orientation = np.array([qx, qy, qz, qw], dtype=np.float32) |
| |
| |
| if not hasattr(self, '_last_yaw') or abs(self._last_yaw - self._yaw) > 0.01: |
| if hasattr(self, '_initial_yaw'): |
| yaw_delta = self._yaw - self._initial_yaw |
| else: |
| pass |
| |
| if hasattr(self, '_original_quaternion'): |
| pass |
| |
| self._last_yaw = self._yaw |
| |
| |
| |
| try: |
| self.cam.set_world_pose(position=camera_pos.astype(np.float32), orientation=orientation) |
| except Exception as e: |
| pass |
| |
| |
| if hasattr(self, 'agent_prim') and self.agent_prim: |
| try: |
| xform = self._UsdGeom.Xform(self.agent_prim) |
| xform.ClearXformOpOrder() |
| |
| translate_op = xform.AddTranslateOp() |
| translate_op.Set(tuple(self._pos)) |
| |
| rotate_op = xform.AddRotateZOp() |
| rotate_op.Set(math.degrees(self._yaw)) |
| except Exception as e: |
| pass |
| |
| if not hasattr(self, '_camera_log_count'): |
| self._camera_log_count = 0 |
| self._last_logged_pos = self._pos[:2].copy() |
| |
| self._camera_log_count += 1 |
| distance_moved = np.linalg.norm(self._pos[:2] - self._last_logged_pos) |
| |
| |
| if distance_moved > 0.1 or self._camera_log_count >= 50: |
| _debug_print(f"[CAMERA_UPDATE] Step #{self._camera_log_count}: Camera at {camera_pos[:2]} (moved: {distance_moved:.3f}m)") |
| |
| self._last_logged_pos = self._pos[:2].copy() |
| self._camera_log_count = 0 |
| |
| except Exception as e: |
| print(f"[CAMERA_UPDATE_ERROR] Failed to update camera: {e}") |
| |
| |
| |
|
|
| def _apply_pose(self) -> None: |
| """Apply position and orientation to physics system.""" |
| |
| qx = -math.sin(self._yaw/2.0) |
| qy = 0.0 |
| qz = 0.0 |
| qw = math.cos(self._yaw/2.0) |
| orientation = np.array([qx,qy,qz,qw], dtype=np.float32) |
| |
| |
| if hasattr(self, 'agent_prim') and self.agent_prim: |
| try: |
| |
| xform = self._UsdGeom.Xform(self.agent_prim) |
| xform.ClearXformOpOrder() |
| |
| translate_op = xform.AddTranslateOp() |
| translate_op.Set(tuple(self._pos)) |
| |
| rotate_op = xform.AddRotateZOp() |
| rotate_op.Set(math.degrees(self._yaw)) |
| |
| |
| except Exception as e: |
| print(f"[WARN] Failed to apply pose: {e}") |
| |
| |
| self._update_camera_position() |
| |
| |
| if hasattr(self, 'world'): |
| self.world.step(render=True) |
| def get_agent_pos(self) -> np.ndarray: |
| return self._pos.copy() |
| def get_rgb(self) -> np.ndarray: |
| if hasattr(self, 'cam') and self.cam: |
| try: |
| |
| |
| |
| |
| self.set_collision_mesh_visibility(False) |
| |
| |
| |
| self._update_camera_position() |
| for i in range(2): |
| self.world.step(render=True) |
| |
| |
| cam_pos, cam_orientation = self.cam.get_world_pose() |
| |
| |
| |
| |
| |
| |
| |
| img = self.cam.get_rgba() |
| |
| |
| if img is None or img.size == 0: |
| |
| return None |
| |
| |
| rgb_img = img[:, :, :3].astype(np.uint8) |
| |
| return rgb_img |
| |
| except Exception as e: |
| return None |
| else: |
| return np.zeros((480, 640, 3), dtype=np.uint8) |
|
|
| def get_depth(self) -> np.ndarray: |
| """Get depth image.""" |
| if hasattr(self, 'cam') and self.cam: |
| try: |
| |
| |
| |
| |
| self.set_collision_mesh_visibility(True) |
| |
| |
| |
| self._update_camera_position() |
| for i in range(2): |
| self.world.step(render=True) |
| |
| |
| |
| |
| |
| self._force_refresh_depth_pipeline() |
| |
| |
| depth_img = None |
| |
| |
| |
| |
| if depth_img is None: |
| try: |
| frame = self.cam.get_current_frame() |
| if frame and 'distance_to_image_plane' in frame: |
| depth_img = frame['distance_to_image_plane'] |
| |
| |
| if hasattr(depth_img, 'cpu'): |
| depth_img = depth_img.cpu().numpy() |
| depth_img = np.array(depth_img, dtype=np.float32) |
| else: |
| available_keys = list(frame.keys()) if frame else [] |
| |
| except Exception as e: |
| pass |
| |
| if depth_img is None: |
| try: |
| |
| import omni.replicator.core as rep |
| |
| |
| with rep.new_layer(): |
| rep_camera = rep.create.camera( |
| position=(0, 0, 0), |
| look_at=(0, 0, -1) |
| ) |
| |
| render_products = rep.create.render_product(rep_camera, self.resolution) |
| depth_annotator = rep.AnnotatorRegistry.get_annotator("distance_to_image_plane") |
| depth_annotator.attach([render_products]) |
| |
| |
| rep.orchestrator.step() |
| depth_data = depth_annotator.get_data() |
| if depth_data is not None and len(depth_data) > 0: |
| depth_img = np.array(depth_data, dtype=np.float32) |
| |
| else: |
| pass |
| |
| |
| except Exception as e: |
| pass |
| |
| if depth_img is None: |
| try: |
| import omni.syntheticdata._syntheticdata as sd |
| |
| |
| depth_img = sd.get_depth_linear(viewport_name="Viewport") |
| if depth_img is not None and depth_img.size > 0: |
| depth_img = np.array(depth_img, dtype=np.float32) |
| |
| else: |
| pass |
| |
| except Exception as e: |
| pass |
| |
| if depth_img is None: |
| try: |
| |
| from pxr import UsdRender |
| import omni.usd |
| |
| stage = omni.usd.get_context().get_stage() |
| |
| render_settings = UsdRender.Settings.GetStage(stage) |
| if render_settings: |
| |
| render_settings.CreateEnabledAttr().Set(True) |
| |
| |
| cam_prim = stage.GetPrimAtPath(self.cam.prim_path) |
| if cam_prim: |
| |
| if cam_prim.HasAttribute("depth"): |
| depth_attr = cam_prim.GetAttribute("depth") |
| depth_img = depth_attr.Get() |
| if depth_img is not None: |
| depth_img = np.array(depth_img, dtype=np.float32) |
| |
| |
| except Exception as e: |
| pass |
| |
| if depth_img is None: |
| depth_methods = ['get_distance_to_image_plane', 'get_depth_data', 'get_depth', 'get_linear_depth'] |
| |
| for method_name in depth_methods: |
| if hasattr(self.cam, method_name): |
| try: |
| method = getattr(self.cam, method_name) |
| depth_img = method() |
| if depth_img is not None and hasattr(depth_img, 'size') and depth_img.size > 0: |
| |
| if hasattr(depth_img, 'cpu'): |
| depth_img = depth_img.cpu().numpy() |
| depth_img = np.array(depth_img, dtype=np.float32) |
| break |
| else: |
| pass |
| |
| except Exception as e: |
| pass |
| continue |
| |
| |
| if depth_img is None: |
| try: |
| |
| |
| |
| |
| height, width = self.resolution[1], self.resolution[0] |
| |
| |
| y, x = np.ogrid[:height, :width] |
| center_y, center_x = height // 2, width // 2 |
| |
| |
| dist_from_center = np.sqrt((x - center_x)**2 + (y - center_y)**2) |
| max_dist = np.sqrt(center_x**2 + center_y**2) |
| |
| |
| depth_img = 1.0 + 5.0 * (dist_from_center / max_dist) |
| depth_img = depth_img.astype(np.float32) |
| |
| |
| |
| except Exception as e: |
| pass |
| depth_img = None |
| |
| |
| if depth_img is None: |
| |
| |
| if hasattr(self.cam, 'data'): |
| data_attrs = [attr for attr in dir(self.cam.data) if not attr.startswith('_')] |
| |
| |
| available_methods = [attr for attr in dir(self.cam) if 'depth' in attr.lower() or 'distance' in attr.lower()] |
| |
| return None |
| if depth_img is None or depth_img.size == 0: |
| self._log(f"[WARN] Camera returned None/empty depth image") |
| return None |
| |
| |
| |
| depth_img = depth_img.astype(np.float32) |
| |
| |
| depth_img = np.clip(depth_img, 0.1, 6.5) |
| |
| |
| return depth_img |
| except Exception as e: |
| self._log(f"[WARN] Failed to get depth from Isaac Sim camera: {e}") |
| return None |
| else: |
| |
| self._log(f"[WARN] No Isaac Sim camera available, returning default depth image") |
| |
| return np.full((480, 640), 5.0, dtype=np.float32) |
|
|
| def get_rgbd(self) -> tuple: |
| """Get RGB and depth images.""" |
| if hasattr(self, 'cam') and self.cam: |
| try: |
| |
| |
| |
| |
| self.set_collision_mesh_visibility(False) |
| |
| |
| self._update_camera_position() |
| self.world.step(render=True) |
| |
| |
| rgba_img = self.cam.get_rgba() |
| rgb_img = None |
| if rgba_img is not None and rgba_img.size > 0: |
| rgb_img = rgba_img[:, :, :3].astype(np.uint8) |
| |
| else: |
| pass |
| |
| |
| |
| |
| |
| |
| |
| self.set_collision_mesh_visibility(True) |
| |
| |
| |
| self._update_camera_position() |
| for i in range(3): |
| self.world.step(render=True) |
| |
| |
| |
| self.set_collision_mesh_visibility(True) |
| |
| |
| |
| self._ensure_depth_annotator_runtime() |
| |
| |
| |
| self._force_refresh_depth_pipeline() |
| |
| |
| for i in range(5): |
| self.world.step(render=True) |
| |
| |
| |
| depth_img = None |
| |
| |
| |
| |
| if depth_img is None: |
| try: |
| |
| |
| self.set_collision_mesh_visibility(True) |
| |
| |
| self.world.step(render=True) |
| frame = self.cam.get_current_frame() |
| |
| if frame: |
| available_keys = list(frame.keys()) |
| |
| |
| |
| depth_keys = ['distance_to_image_plane', 'depth', 'distance_to_camera', 'linear_depth'] |
| depth_data = None |
| used_key = None |
| |
| for key in depth_keys: |
| if key in frame: |
| depth_data = frame[key] |
| used_key = key |
| |
| break |
| |
| if depth_data is not None: |
| |
| |
| |
| |
| if hasattr(depth_data, 'shape'): |
| |
| |
| |
| if depth_data.size > 0: |
| if hasattr(depth_data, 'cpu'): |
| depth_img = depth_data.cpu().numpy() |
| elif hasattr(depth_data, 'numpy'): |
| depth_img = depth_data.numpy() |
| else: |
| depth_img = np.array(depth_data, dtype=np.float32) |
| |
| |
| |
| |
| |
| if depth_img.ndim == 3 and depth_img.shape[-1] == 1: |
| depth_img = depth_img.squeeze(-1) |
| |
| elif depth_img.ndim == 1: |
| |
| expected_size = self.resolution[0] * self.resolution[1] |
| if depth_img.size == expected_size: |
| depth_img = depth_img.reshape(self.resolution[1], self.resolution[0]) |
| |
| |
| |
| if depth_img.ndim == 2: |
| depth_std = depth_img.std() |
| depth_range = depth_img.max() - depth_img.min() |
| |
| if depth_std < 0.001 and depth_range < 0.001: |
| pass |
| |
| if depth_img.shape == (self.resolution[1], self.resolution[0]): |
| pass |
| else: |
| depth_img = None |
| else: |
| depth_img = None |
| else: |
| depth_img = None |
| else: |
| depth_img = None |
| else: |
| pass |
| |
| else: |
| pass |
| |
| |
| except Exception as e: |
| pass |
| import traceback |
| |
| |
| |
| if depth_img is None: |
| try: |
| |
| |
| self.set_collision_mesh_visibility(True) |
| self.world.step(render=True) |
| import omni.kit.viewport.utility as vp_utils |
| import omni.syntheticdata as sd |
| |
| viewport_api = vp_utils.get_viewport_from_window_name("Viewport") |
| if viewport_api: |
| sd_interface = sd.acquire_syntheticdata_interface() |
| depth_img = sd_interface.get_viewport_data(viewport_api, "distance_to_image_plane") |
| if depth_img is not None and len(depth_img) > 0: |
| depth_img = np.array(depth_img, dtype=np.float32).reshape(self.resolution[1], self.resolution[0]) |
| |
| except Exception as e: |
| pass |
| |
| if depth_img is None: |
| |
| |
| self.set_collision_mesh_visibility(True) |
| self.world.step(render=True) |
| |
| depth_methods = ['get_distance_to_image_plane', 'get_depth_data', 'get_depth', 'get_linear_depth'] |
| |
| for method_name in depth_methods: |
| if hasattr(self.cam, method_name): |
| try: |
| method = getattr(self.cam, method_name) |
| depth_img = method() |
| if depth_img is not None and hasattr(depth_img, 'size') and depth_img.size > 0: |
| |
| if hasattr(depth_img, 'cpu'): |
| depth_img = depth_img.cpu().numpy() |
| depth_img = np.array(depth_img, dtype=np.float32) |
| break |
| except Exception as e: |
| pass |
| continue |
| |
| |
| if depth_img is None or (hasattr(depth_img, 'size') and depth_img.size == 0): |
| |
| |
| try: |
| height, width = self.resolution[1], self.resolution[0] |
| |
| |
| |
| y, x = np.ogrid[:height, :width] |
| center_y, center_x = height // 2, width // 2 |
| |
| |
| dist_from_center = np.sqrt((x - center_x)**2 + (y - center_y)**2) |
| max_dist = np.sqrt(center_x**2 + center_y**2) |
| |
| |
| depth_img = 1.5 + 4.5 * (dist_from_center / max_dist) |
| |
| |
| noise = np.random.normal(0, 0.1, depth_img.shape) |
| depth_img = depth_img + noise |
| depth_img = np.clip(depth_img, 0.5, 6.0).astype(np.float32) |
| |
| |
| |
| except Exception as e: |
| pass |
| |
| try: |
| height, width = self.resolution[1], self.resolution[0] |
| depth_img = np.full((height, width), 3.0, dtype=np.float32) |
| |
| except Exception as e2: |
| pass |
| depth_img = np.full((480, 640), 3.0, dtype=np.float32) |
| |
| |
| if rgb_img is None: |
| self._log(f"[WARN] Failed to get RGB image") |
| rgb_img = np.zeros((480, 640, 3), dtype=np.uint8) |
| |
| if depth_img is None: |
| self._log(f"[WARN] Failed to get depth image") |
| depth_img = np.full((480, 640), 3.0, dtype=np.float32) |
| |
| |
| depth_img = depth_img.astype(np.float32) |
| depth_img = np.clip(depth_img, 0.1, 6.5) |
| |
| |
| |
| return rgb_img, depth_img |
| |
| except Exception as e: |
| self._log(f"[WARN] Failed to get RGB-D from Isaac Sim camera: {e}") |
| return None, None |
| else: |
| self._log(f"[WARN] No Isaac Sim camera available, returning default RGB-D") |
| rgb = np.zeros((480, 640, 3), dtype=np.uint8) |
| depth = np.full((480, 640), 5.0, dtype=np.float32) |
| return rgb, depth |
| |
| def _check_collision(self, new_pos) -> bool: |
| """ |
| Collision detection: prefer 2D semantic map, fallback to Isaac Sim physics |
| """ |
| try: |
| |
| if hasattr(self, '_debug_disable_collision') and self._debug_disable_collision: |
| |
| return False |
| |
| |
| if self.collision_detector is not None: |
| |
| is_collision = self.collision_detector.check_collision_3d(new_pos) |
| if is_collision: |
| self._collision_detected = True |
| self._total_collision_count += 1 |
| return True |
| else: |
| |
| return False |
| else: |
| pass |
| |
| |
| |
| |
| return self._check_collision_isaac_sim(new_pos) |
| |
| except Exception as e: |
| pass |
| |
| return self._check_collision_isaac_sim(new_pos) |
| |
| def _check_collision_isaac_sim(self, new_pos) -> bool: |
| """ |
| Original Isaac Sim physics collision detection (as fallback) |
| """ |
| try: |
| |
| current_pos = self._pos.copy() |
| |
| |
| self._pos = new_pos |
| self._apply_pose() |
| |
| |
| self.world.step(render=False) |
| |
| |
| |
| actual_pos = self._get_agent_physics_position() |
| if actual_pos is not None: |
| position_diff = np.linalg.norm(new_pos - actual_pos) |
| |
| |
| if position_diff > 0.02: |
| |
| |
| |
| self._pos = current_pos |
| self._apply_pose() |
| return True |
| elif position_diff > 0.01: |
| pass |
| |
| |
| expected_movement = np.linalg.norm(new_pos[:2] - current_pos[:2]) |
| actual_movement = np.linalg.norm(actual_pos[:2] - current_pos[:2]) if actual_pos is not None else 0 |
| movement_ratio = actual_movement / expected_movement if expected_movement > 0.001 else 1.0 |
| |
| if movement_ratio < 0.5: |
| if expected_movement > 0.05: |
| print(f"[ISAAC_COLLISION_BLOCKED] Movement severely restricted by physics") |
| |
| self._pos = current_pos |
| self._apply_pose() |
| return True |
| |
| |
| return False |
| |
| except Exception as e: |
| pass |
| |
| self._pos = current_pos if 'current_pos' in locals() else self._pos |
| self._apply_pose() |
| return False |
| |
| def _check_path_collision(self, start_pos: np.ndarray, end_pos: np.ndarray) -> bool: |
| """Check if there are collision bodies on path.""" |
| try: |
| |
| num_samples = 5 |
| for i in range(1, num_samples + 1): |
| t = i / (num_samples + 1) |
| sample_pos = start_pos * (1 - t) + end_pos * t |
| |
| |
| if self._check_point_collision(sample_pos): |
| print(f"[PATH_COLLISION] Sample point {i} at {sample_pos[:2]} is in collision") |
| return True |
| |
| return False |
| except Exception as e: |
| print(f"[WARN] Path collision check failed: {e}") |
| return False |
| |
| def _check_point_collision(self, pos: np.ndarray) -> bool: |
| """Check if specific point is in collision body.""" |
| try: |
| |
| if hasattr(self, 'world') and self.world: |
| |
| ray_start = pos + np.array([0, 0, 0.5]) |
| ray_end = pos + np.array([0, 0, -0.5]) |
| |
| |
| |
| return False |
| |
| return False |
| except Exception as e: |
| print(f"[WARN] Point collision check failed: {e}") |
| return False |
| |
| def _get_agent_physics_position(self) -> Optional[np.ndarray]: |
| """Get agent actual position in physics system.""" |
| try: |
| if hasattr(self, 'agent_prim') and self.agent_prim: |
| |
| xformable = self._UsdGeom.Xformable(self.agent_prim) |
| if xformable: |
| |
| world_transform = xformable.ComputeLocalToWorldTransform(0) |
| if world_transform: |
| |
| translation = world_transform.ExtractTranslation() |
| return np.array([translation[0], translation[1], translation[2]], dtype=np.float32) |
| return None |
| except Exception as e: |
| print(f"[WARN] Failed to get agent physics position: {e}") |
| return None |
| def apply_cmd_for(self, vx: float, vy: float, yaw_rate: float, duration_s: float) -> None: |
| """ |
| Improved motion control with smart sliding algorithm |
| """ |
| _debug_print(f"[DEBUG] apply_cmd_for start: vx={vx:.3f}, vy={vy:.3f}, yaw_rate={yaw_rate:.3f}, current_yaw={math.degrees(self._yaw):.1f}°") |
| self._log(f"[DEBUG] apply_cmd_for start: vx={vx:.3f}, vy={vy:.3f}, yaw_rate={yaw_rate:.3f}, current_yaw={math.degrees(self._yaw):.1f}°") |
| |
| |
| |
| |
| cos_yaw = math.cos(self._yaw) |
| sin_yaw = math.sin(self._yaw) |
| |
| |
| |
| world_vx = vx * cos_yaw - vy * sin_yaw |
| world_vy = vx * sin_yaw + vy * cos_yaw |
| |
| total_dx = world_vx * duration_s |
| total_dy = world_vy * duration_s |
| total_dyaw = yaw_rate * duration_s |
| |
| |
| |
| |
| |
| _debug_print(f"[DEBUG] Total movement: dx={total_dx:.3f}, dy={total_dy:.3f}, dyaw={math.degrees(total_dyaw):.1f}°") |
| |
| |
| old_pos = self._pos.copy() |
| intended_movement = np.linalg.norm([total_dx, total_dy]) |
| |
| if intended_movement > 0.001: |
| |
| target_pos = old_pos.copy() |
| target_pos[0] += total_dx |
| target_pos[1] += total_dy |
| |
| |
| |
| |
| actual_movement = self._safe_gradual_movement(old_pos, target_pos, intended_movement) |
| |
| |
| |
| |
| |
| |
| movement_efficiency = actual_movement / intended_movement if intended_movement > 0 else 1.0 |
| |
| if movement_efficiency < 0.3 and intended_movement > 0.05: |
| self.consecutive_collisions += 1 |
| |
| if self.consecutive_collisions >= 3: |
| pass |
| else: |
| |
| if movement_efficiency > 0.6: |
| if self.consecutive_collisions > 0: |
| pass |
| self.consecutive_collisions = 0 |
| else: |
| |
| pass |
| |
| |
| old_yaw = self._yaw |
| self._yaw += total_dyaw |
| self._yaw = ((self._yaw + math.pi) % (2 * math.pi)) - math.pi |
| |
| |
| |
| |
| |
| self._update_camera_position() |
| |
| _debug_print(f"[DEBUG] Finished env.apply_cmd_for") |
| self._log(f"[DEBUG] Finished env.apply_cmd_for") |
|
|
| def _safe_gradual_movement(self, start_pos: np.ndarray, target_pos: np.ndarray, target_distance: float) -> float: |
| """ |
| Absolutely safe movement: strictly prevent clipping, use lateral exploration to avoid stuck. |
| |
| Args: |
| start_pos: Start position |
| target_pos: Target position |
| target_distance: Target distance |
| |
| Returns: |
| Actual distance moved |
| """ |
| |
| |
| |
| current_pos = self._pos.copy() |
| |
| |
| direction = target_pos - current_pos |
| direction_norm = np.linalg.norm(direction[:2]) |
| |
| |
| if direction_norm < 0.001: |
| return 0.0 |
| |
| |
| unit_direction = direction / direction_norm |
| |
| |
| max_distance = min(0.20, target_distance) |
| |
| |
| direct_movement = self._try_direct_movement(current_pos, unit_direction, max_distance) |
| |
| if direct_movement > 0.01: |
| |
| return direct_movement |
| |
| |
| |
| exploration_movement = self._try_exploration_movement(current_pos, unit_direction) |
| |
| if exploration_movement > 0.005: |
| |
| return exploration_movement |
| |
| |
| |
| return 0.0 |
|
|
| def _try_direct_movement(self, start_pos: np.ndarray, direction: np.ndarray, max_distance: float) -> float: |
| """Try direct movement towards target.""" |
| total_moved = 0.0 |
| current_pos = start_pos.copy() |
| step_size = 0.01 |
| |
| while total_moved < max_distance: |
| step_distance = min(step_size, max_distance - total_moved) |
| next_pos = current_pos + direction * step_distance |
| |
| |
| if self._is_position_safe(next_pos): |
| |
| old_pos = self._pos.copy() |
| self._pos = next_pos |
| self._apply_pose() |
| self.world.step(render=False) |
| |
| |
| actual_pos = self._get_agent_physics_position() |
| if actual_pos is None: |
| actual_pos = self._pos |
| |
| |
| position_diff = np.linalg.norm(actual_pos[:2] - next_pos[:2]) |
| |
| if position_diff < 0.002: |
| current_pos = actual_pos |
| self._pos = actual_pos |
| total_moved += step_distance |
| |
| else: |
| |
| |
| self._pos = old_pos |
| self._apply_pose() |
| break |
| else: |
| |
| |
| break |
| |
| actual_movement = np.linalg.norm(current_pos[:2] - start_pos[:2]) |
| return actual_movement |
|
|
| def _try_exploration_movement(self, start_pos: np.ndarray, blocked_direction: np.ndarray) -> float: |
| """Try lateral exploration when direct movement blocked.""" |
| |
| |
| |
| perpendicular = np.array([-blocked_direction[1], blocked_direction[0], 0]) |
| exploration_directions = [ |
| perpendicular, |
| -perpendicular, |
| perpendicular * 0.707 + blocked_direction * 0.707, |
| -perpendicular * 0.707 + blocked_direction * 0.707, |
| ] |
| |
| best_movement = 0.0 |
| best_pos = start_pos.copy() |
| |
| for i, direction in enumerate(exploration_directions): |
| direction_norm = np.linalg.norm(direction[:2]) |
| if direction_norm > 0.001: |
| direction = direction / direction_norm |
| |
| |
| |
| |
| movement = self._try_short_movement(start_pos, direction, 0.05) |
| |
| if movement > best_movement: |
| best_movement = movement |
| best_pos = self._pos.copy() |
| |
| |
| |
| if best_movement > 0.005: |
| self._pos = best_pos |
| self._apply_pose() |
| |
| |
| return best_movement |
|
|
| def _try_short_movement(self, start_pos: np.ndarray, direction: np.ndarray, max_distance: float) -> float: |
| """Try short distance movement.""" |
| step_size = 0.005 |
| total_moved = 0.0 |
| current_pos = start_pos.copy() |
| |
| while total_moved < max_distance: |
| step_distance = min(step_size, max_distance - total_moved) |
| next_pos = current_pos + direction * step_distance |
| |
| if self._is_position_safe(next_pos): |
| |
| old_pos = self._pos.copy() |
| self._pos = next_pos |
| self._apply_pose() |
| self.world.step(render=False) |
| |
| actual_pos = self._get_agent_physics_position() |
| if actual_pos is None: |
| actual_pos = self._pos |
| |
| position_diff = np.linalg.norm(actual_pos[:2] - next_pos[:2]) |
| |
| if position_diff < 0.002: |
| current_pos = actual_pos |
| total_moved += step_distance |
| else: |
| |
| self._pos = old_pos |
| self._apply_pose() |
| break |
| else: |
| break |
| |
| return total_moved |
|
|
| def _is_position_safe(self, pos: np.ndarray) -> bool: |
| """Strictly check if position is safe (no collision).""" |
| try: |
| |
| if self.collision_detector is not None: |
| if self.collision_detector.check_collision_3d(pos): |
| return False |
| |
| |
| |
| |
| return True |
| except Exception as e: |
| pass |
| return False |
|
|
| def _smart_slide_movement_deprecated(self, start_pos: np.ndarray, dx: float, dy: float) -> Tuple[np.ndarray, float]: |
| """ |
| Smart sliding algorithm: try to move to closest collision-free position. |
| |
| Args: |
| start_pos: Start position |
| dx, dy: Expected movement vector |
| |
| Returns: |
| Tuple[final_position, actual_distance] |
| """ |
| intended_distance = np.linalg.norm([dx, dy]) |
| if intended_distance < 0.001: |
| return start_pos.copy(), 0.0 |
| |
| |
| move_direction = np.array([dx, dy]) / intended_distance |
| |
| print(f"[SMART_SLIDE] Starting smart slide: intended={intended_distance:.3f}m, direction={move_direction}") |
| |
| |
| print(f"[SMART_SLIDE] Trying binary search for direct movement...") |
| max_distance = self._binary_search_max_distance(start_pos, move_direction, intended_distance) |
| |
| if max_distance > 0.01: |
| final_pos = start_pos.copy() |
| final_pos[0] += move_direction[0] * max_distance |
| final_pos[1] += move_direction[1] * max_distance |
| print(f"[SMART_SLIDE] Binary search success: max_distance={max_distance:.3f}m") |
| return final_pos, max_distance |
| |
| |
| print(f"[SMART_SLIDE] Direct movement blocked, trying sliding along obstacles") |
| slide_pos, slide_distance = self._try_obstacle_sliding(start_pos, move_direction, intended_distance) |
| |
| if slide_distance > 0.005: |
| print(f"[SMART_SLIDE] Obstacle sliding success: distance={slide_distance:.3f}m") |
| return slide_pos, slide_distance |
| |
| |
| print(f"[SMART_SLIDE] Trying multi-directional micro-movements") |
| explore_pos, explore_distance = self._try_micro_exploration(start_pos, move_direction, min(intended_distance, 0.05)) |
| |
| if explore_distance > 0.002: |
| print(f"[SMART_SLIDE] Micro-exploration success: distance={explore_distance:.3f}m") |
| return explore_pos, explore_distance |
| |
| |
| print(f"[SMART_SLIDE] All strategies failed, trying ultra-micro movements...") |
| ultra_micro_pos, ultra_micro_distance = self._try_ultra_micro_escape(start_pos, move_direction) |
| |
| print(f"[SMART_SLIDE_DEBUG] ultra_micro_distance={ultra_micro_distance:.10f}, checking >= 0.001") |
| if ultra_micro_distance >= 0.0009: |
| print(f"[SMART_SLIDE] Ultra-micro escape success: distance={ultra_micro_distance:.4f}m") |
| return ultra_micro_pos, ultra_micro_distance |
| |
| |
| print(f"[SMART_SLIDE] EMERGENCY: All strategies failed, ultra_micro_distance={ultra_micro_distance:.6f}m") |
| print(f"[SMART_SLIDE] EMERGENCY: Forcing 1mm movement in ANY direction!") |
| |
| |
| emergency_pos = start_pos.copy() |
| emergency_pos[0] += 0.001 |
| return emergency_pos, 0.001 |
|
|
| def _binary_search_max_distance(self, start_pos: np.ndarray, direction: np.ndarray, max_distance: float) -> float: |
| """ |
| Use binary search to find max movable distance in given direction |
| """ |
| min_dist = 0.0 |
| max_dist = min(0.1, max_distance) |
| best_dist = 0.0 |
| |
| |
| for _ in range(20): |
| test_dist = (min_dist + max_dist) / 2.0 |
| |
| if test_dist < 0.001: |
| break |
| |
| test_pos = start_pos.copy() |
| test_pos[0] += direction[0] * test_dist |
| test_pos[1] += direction[1] * test_dist |
| |
| if self._test_position_safety(start_pos, test_pos): |
| best_dist = test_dist |
| min_dist = test_dist |
| else: |
| max_dist = test_dist |
| |
| return best_dist |
|
|
| def _try_obstacle_sliding(self, start_pos: np.ndarray, primary_direction: np.ndarray, intended_distance: float) -> Tuple[np.ndarray, float]: |
| """ |
| Try sliding along obstacle edge |
| """ |
| |
| perp_left = np.array([-primary_direction[1], primary_direction[0]]) |
| perp_right = np.array([primary_direction[1], -primary_direction[0]]) |
| |
| best_pos = start_pos.copy() |
| best_distance = 0.0 |
| |
| |
| slide_distances = [0.02, 0.05, 0.1, 0.15] |
| |
| for slide_dist in slide_distances: |
| if slide_dist > intended_distance: |
| slide_dist = intended_distance |
| |
| |
| for perp_ratio in [0.3, 0.5, 0.7, 1.0]: |
| slide_direction = primary_direction * (1 - perp_ratio) + perp_left * perp_ratio |
| slide_direction = slide_direction / np.linalg.norm(slide_direction) |
| |
| test_pos = start_pos.copy() |
| test_pos[0] += slide_direction[0] * slide_dist |
| test_pos[1] += slide_direction[1] * slide_dist |
| |
| if self._test_position_safety(start_pos, test_pos): |
| actual_distance = np.linalg.norm(test_pos[:2] - start_pos[:2]) |
| if actual_distance > best_distance: |
| best_pos = test_pos |
| best_distance = actual_distance |
| |
| |
| for perp_ratio in [0.3, 0.5, 0.7, 1.0]: |
| slide_direction = primary_direction * (1 - perp_ratio) + perp_right * perp_ratio |
| slide_direction = slide_direction / np.linalg.norm(slide_direction) |
| |
| test_pos = start_pos.copy() |
| test_pos[0] += slide_direction[0] * slide_dist |
| test_pos[1] += slide_direction[1] * slide_dist |
| |
| if self._test_position_safety(start_pos, test_pos): |
| actual_distance = np.linalg.norm(test_pos[:2] - start_pos[:2]) |
| if actual_distance > best_distance: |
| best_pos = test_pos |
| best_distance = actual_distance |
| |
| return best_pos, best_distance |
|
|
| def _try_micro_exploration(self, start_pos: np.ndarray, primary_direction: np.ndarray, max_distance: float) -> Tuple[np.ndarray, float]: |
| """ |
| Try small multi-direction exploration |
| """ |
| best_pos = start_pos.copy() |
| best_distance = 0.0 |
| |
| |
| angle_offsets = [-45, -30, -15, 0, 15, 30, 45] |
| distances = [max_distance * 0.2, max_distance * 0.5, max_distance * 0.8, max_distance] |
| |
| for angle_deg in angle_offsets: |
| angle_rad = math.radians(angle_deg) |
| |
| cos_a, sin_a = math.cos(angle_rad), math.sin(angle_rad) |
| rotated_direction = np.array([ |
| primary_direction[0] * cos_a - primary_direction[1] * sin_a, |
| primary_direction[0] * sin_a + primary_direction[1] * cos_a |
| ]) |
| |
| for test_distance in distances: |
| test_pos = start_pos.copy() |
| test_pos[0] += rotated_direction[0] * test_distance |
| test_pos[1] += rotated_direction[1] * test_distance |
| |
| if self._test_position_safety(start_pos, test_pos): |
| actual_distance = np.linalg.norm(test_pos[:2] - start_pos[:2]) |
| if actual_distance > best_distance: |
| best_pos = test_pos |
| best_distance = actual_distance |
| |
| return best_pos, best_distance |
|
|
| def _try_ultra_micro_escape(self, start_pos: np.ndarray, primary_direction: np.ndarray) -> Tuple[np.ndarray, float]: |
| """ |
| Ultimate escape: try minimal forced movement, bypass safety check |
| """ |
| best_pos = start_pos.copy() |
| best_distance = 0.0 |
| |
| print(f"[ULTRA_MICRO] Attempting ultra-micro escape from complete blockage") |
| |
| |
| directions = [ |
| np.array([1.0, 0.0]), |
| np.array([-1.0, 0.0]), |
| np.array([0.0, 1.0]), |
| np.array([0.0, -1.0]), |
| np.array([0.707, 0.707]), |
| np.array([-0.707, 0.707]), |
| np.array([0.707, -0.707]), |
| np.array([-0.707, -0.707]), |
| primary_direction, |
| ] |
| |
| |
| micro_distances = [0.001, 0.002, 0.003, 0.005] |
| |
| for direction in directions: |
| direction = direction / np.linalg.norm(direction) |
| |
| for micro_dist in micro_distances: |
| test_pos = start_pos.copy() |
| test_pos[0] += direction[0] * micro_dist |
| test_pos[1] += direction[1] * micro_dist |
| |
| |
| safety_result = self._ultra_permissive_safety_check(start_pos, test_pos) |
| if safety_result: |
| actual_distance = np.linalg.norm(test_pos[:2] - start_pos[:2]) |
| if actual_distance > best_distance: |
| best_pos = test_pos |
| best_distance = actual_distance |
| movement_mm = direction[:2] * micro_dist * 1000 |
| print(f"[ULTRA_MICRO] Found viable micro-movement: [{movement_mm[0]:.1f}, {movement_mm[1]:.1f}]mm, distance={actual_distance:.4f}m") |
| print(f"[ULTRA_MICRO] Immediately returning: pos={best_pos[:2]}, distance={best_distance:.6f}m") |
| |
| |
| return best_pos, best_distance |
| else: |
| print(f"[ULTRA_MICRO_DEBUG] Safety check failed for {micro_dist*1000:.1f}mm movement") |
| |
| |
| if best_distance == 0.0: |
| print(f"[ULTRA_MICRO] Forcing minimal movement in primary direction") |
| forced_pos = start_pos.copy() |
| forced_pos[0] += primary_direction[0] * 0.001 |
| forced_pos[1] += primary_direction[1] * 0.001 |
| print(f"[ULTRA_MICRO] Forced movement: distance=0.001m") |
| return forced_pos, 0.001 |
| |
| print(f"[ULTRA_MICRO] Returning best movement: distance={best_distance:.4f}m") |
| return best_pos, best_distance |
|
|
| def _ultra_permissive_safety_check(self, start_pos: np.ndarray, test_pos: np.ndarray) -> bool: |
| """ |
| Ultra relaxed safety check for extreme stuck situations |
| """ |
| try: |
| |
| movement_distance = np.linalg.norm(test_pos[:2] - start_pos[:2]) |
| |
| |
| if movement_distance < 0.003: |
| return True |
| |
| |
| if movement_distance < 0.006: |
| return True |
| |
| return False |
| |
| except Exception as e: |
| print(f"[ULTRA_PERMISSIVE_ERROR] {e}") |
| |
| movement_distance = np.linalg.norm(test_pos[:2] - start_pos[:2]) |
| return movement_distance < 0.002 |
|
|
| def _test_position_safety(self, start_pos: np.ndarray, test_pos: np.ndarray) -> bool: |
| """ |
| Test if position is safe (no collision). |
| Uses lightweight collision detection to avoid performance impact. |
| """ |
| try: |
| |
| if hasattr(self, '_debug_disable_collision') and self._debug_disable_collision: |
| return True |
| |
| |
| if abs(test_pos[0]) > 20 or abs(test_pos[1]) > 20 or test_pos[2] < 0 or test_pos[2] > 5: |
| return False |
| |
| original_pos = self._pos.copy() |
| |
| |
| self._pos = test_pos |
| self._apply_pose() |
| |
| |
| self.world.step(render=False) |
| |
| |
| actual_pos = self._get_agent_physics_position() |
| if actual_pos is None: |
| |
| self._pos = original_pos |
| self._apply_pose() |
| return False |
| |
| |
| position_diff = np.linalg.norm(test_pos - actual_pos) |
| |
| |
| self._pos = original_pos |
| self._apply_pose() |
| |
| |
| is_safe = position_diff < 0.03 |
| |
| if not is_safe and position_diff > 0.05: |
| pass |
| |
| return is_safe |
| |
| except Exception as e: |
| print(f"[SAFETY_TEST_ERROR] {e}") |
| |
| self._pos = start_pos |
| self._apply_pose() |
| return False |
|
|
| def _apply_gradual_movement(self, start_pos: np.ndarray, target_pos: np.ndarray, target_distance: float) -> float: |
| """ |
| Force movement: try to move to target while respecting collision. |
| |
| Args: |
| start_pos: Start position |
| target_pos: Target position |
| target_distance: Target distance |
| |
| Returns: |
| Actual distance moved |
| """ |
| |
| |
| |
| current_pos = self._pos.copy() |
| |
| |
| direction = target_pos - current_pos |
| direction_norm = np.linalg.norm(direction[:2]) |
| |
| |
| if direction_norm < 0.001: |
| return 0.0 |
| |
| |
| unit_direction = direction / direction_norm |
| |
| |
| max_distance = min(0.25, target_distance) |
| |
| |
| total_moved = 0.0 |
| step_size = 0.05 |
| collision_detected = False |
| |
| while total_moved < max_distance: |
| |
| step_distance = min(step_size, max_distance - total_moved) |
| next_pos = current_pos + unit_direction * step_distance |
| |
| |
| temp_pos = self._pos.copy() |
| |
| |
| if self.collision_detector is not None: |
| is_2d_collision = self.collision_detector.check_collision_3d(next_pos) |
| if is_2d_collision: |
| |
| collision_detected = True |
| break |
| else: |
| pass |
| |
| |
| |
| self._pos = next_pos |
| |
| |
| self._apply_pose() |
| |
| |
| self.world.step(render=False) |
| |
| |
| actual_pos = self._get_agent_physics_position() |
| if actual_pos is None: |
| actual_pos = self._pos |
| |
| |
| actual_movement = np.linalg.norm(actual_pos[:2] - current_pos[:2]) |
| |
| |
| position_diff = np.linalg.norm(actual_pos[:2] - next_pos[:2]) |
| |
| if position_diff > 0.02: |
| |
| |
| self._pos = temp_pos |
| self._apply_pose() |
| collision_detected = True |
| break |
| |
| |
| current_pos = actual_pos |
| total_moved += step_distance |
| |
| |
| actual_movement = np.linalg.norm(current_pos[:2] - start_pos[:2]) |
| |
| |
| expected_movement = target_distance |
| movement_efficiency = actual_movement / expected_movement if expected_movement > 0 else 1.0 |
| |
| if movement_efficiency < 0.3 and expected_movement > 0.05: |
| self.consecutive_collisions += 1 |
| |
| if self.consecutive_collisions >= 3: |
| pass |
| else: |
| |
| if movement_efficiency > 0.6: |
| if self.consecutive_collisions > 0: |
| pass |
| self.consecutive_collisions = 0 |
| |
| |
| |
| return actual_movement |
|
|
| def get_yaw(self) -> float: |
| return float(self._yaw) |
| |
| def get_collision_count(self) -> int: |
| """Get total collision count for current episode (CR metric).""" |
| return getattr(self, '_total_collision_count', 0) |
| |
| def set_collision_detection(self, enabled: bool) -> None: |
| """Enable or disable collision detection.""" |
| old_value = getattr(self, '_debug_disable_collision', False) |
| self._debug_disable_collision = not enabled |
| |
| |
| def debug_pose(self) -> Dict[str, Any]: |
| """Debug current pose information""" |
| return { |
| "position": self._pos.tolist(), |
| "yaw_rad": self._yaw, |
| "yaw_deg": math.degrees(self._yaw), |
| "quaternion": [-math.sin(self._yaw/2.0), 0.0, 0.0, math.cos(self._yaw/2.0)] |
| } |
| |
| def transform_coordinates(self, position: List[float], rotation_xyzw: List[float]) -> Tuple[np.ndarray, float]: |
| """ |
| Transform coordinates from your trajectory system to Isaac Sim system. |
| This method helps debug coordinate system mismatches. |
| """ |
| |
| |
| |
| |
| x, y, z, w = rotation_xyzw |
| yaw = math.atan2(2*(w*z + x*y), 1 - 2*(y*y + z*z)) |
| |
| |
| |
| transformed_pos = np.array(position, dtype=np.float32) |
| transformed_yaw = yaw |
| |
| return transformed_pos, transformed_yaw |
| @staticmethod |
| def write_video(frames: List[np.ndarray], out_path: str, fps: int = 10) -> None: |
| Path(out_path).parent.mkdir(parents=True, exist_ok=True) |
| seq_dir = Path(out_path).with_suffix("") |
| seq_dir.mkdir(parents=True, exist_ok=True) |
| |
| norm_frames: List[np.ndarray] = [] |
| for f in frames: |
| arr = f.astype(np.uint8) |
| if arr.ndim == 3 and arr.shape[2] == 4: |
| arr = arr[:, :, :3] |
| norm_frames.append(arr) |
| |
| mp4_ok = False |
| try: |
| writer = imageio.get_writer( |
| str(out_path), fps=fps, format="FFMPEG", codec="libx264", |
| quality=8, bitrate="8M", |
| macro_block_size=None, |
| output_params=["-pix_fmt", "yuv420p"] |
| ) |
| for fr in norm_frames: |
| writer.append_data(fr) |
| writer.close() |
| mp4_ok = os.path.exists(out_path) and os.path.getsize(out_path) > 0 |
| except Exception: |
| mp4_ok = False |
| |
| if not mp4_ok: |
| try: |
| import cv2 |
| if len(norm_frames) > 0: |
| h, w = norm_frames[0].shape[:2] |
| fourcc = cv2.VideoWriter_fourcc(*'mp4v') |
| vw = cv2.VideoWriter(str(out_path), fourcc, float(fps), (w, h)) |
| for fr in norm_frames: |
| if fr.shape[0] != h or fr.shape[1] != w: |
| fr = cv2.resize(fr, (w, h)) |
| bgr = cv2.cvtColor(fr, cv2.COLOR_RGB2BGR) |
| vw.write(bgr) |
| vw.release() |
| mp4_ok = os.path.exists(out_path) and os.path.getsize(out_path) > 0 |
| except Exception: |
| mp4_ok = False |
| |
| for i, fr in enumerate(norm_frames): |
| imageio.imwrite(str(seq_dir / f"frame_{i:05d}.png"), fr) |
|
|
| def _verify_agent_physics(self) -> None: |
| """Verify agent physics configuration.""" |
| print(f"[PHYSICS_VERIFY] Checking agent physics configuration...") |
| |
| try: |
| |
| agent_prim = self.stage.GetPrimAtPath(self.agent_prim_path) |
| if not agent_prim.IsValid(): |
| print(f"[PHYSICS_ERROR] Agent prim not found at {self.agent_prim_path}") |
| return |
| |
| print(f"[PHYSICS_VERIFY] Agent prim found: {self.agent_prim_path}") |
| |
| |
| collision_path = self.agent_prim_path + "/CollisionCylinder" |
| collision_prim = self.stage.GetPrimAtPath(collision_path) |
| if not collision_prim.IsValid(): |
| print(f"[PHYSICS_ERROR] Collision cylinder not found at {collision_path}") |
| return |
| |
| print(f"[PHYSICS_VERIFY] Collision cylinder found: {collision_path}") |
| |
| |
| if agent_prim.HasAPI(self._UsdPhysics.RigidBodyAPI): |
| rigid_body = self._UsdPhysics.RigidBodyAPI(agent_prim) |
| kinematic = rigid_body.GetKinematicEnabledAttr().Get() |
| enabled = rigid_body.GetRigidBodyEnabledAttr().Get() |
| print(f"[PHYSICS_VERIFY] RigidBody: enabled={enabled}, kinematic={kinematic}") |
| else: |
| print(f"[PHYSICS_ERROR] RigidBodyAPI not applied to agent") |
| |
| |
| if collision_prim.HasAPI(self._UsdPhysics.CollisionAPI): |
| collision_api = self._UsdPhysics.CollisionAPI(collision_prim) |
| collision_enabled = collision_api.GetCollisionEnabledAttr().Get() |
| print(f"[PHYSICS_VERIFY] Collision: enabled={collision_enabled}") |
| else: |
| print(f"[PHYSICS_ERROR] CollisionAPI not applied to collision cylinder") |
| |
| |
| cylinder = self._UsdGeom.Cylinder(collision_prim) |
| radius = cylinder.GetRadiusAttr().Get() |
| height = cylinder.GetHeightAttr().Get() |
| print(f"[PHYSICS_VERIFY] Cylinder: radius={radius}m, height={height}m") |
| |
| |
| pos = self._get_agent_physics_position() |
| if pos is not None: |
| print(f"[PHYSICS_VERIFY] Agent position: {pos}") |
| print(f"[PHYSICS_VERIFY] Agent height (z): {pos[2]}m") |
| if pos[2] < 0.7 or pos[2] > 0.9: |
| print(f"[PHYSICS_WARN] Agent center height {pos[2]}m may not be correct (expected ~0.8m for 1.6m tall agent)") |
| else: |
| print(f"[PHYSICS_ERROR] Could not get agent position") |
| |
| print(f"[PHYSICS_VERIFY] Physics verification complete") |
| |
| except Exception as e: |
| print(f"[PHYSICS_ERROR] Failed to verify physics: {e}") |
| import traceback |
| traceback.print_exc() |
|
|
| def _setup_physics_scene(self) -> None: |
| """Setup physics scene for collision detection.""" |
| try: |
| print(f"[PHYSICS_SETUP] Setting up physics scene...") |
| |
| |
| from pxr import UsdPhysics |
| scene = UsdPhysics.Scene.Define(self.stage, "/physicsScene") |
| scene.CreateGravityDirectionAttr().Set((0.0, 0.0, -1.0)) |
| scene.CreateGravityMagnitudeAttr().Set(981.0) |
| print(f"[PHYSICS_SETUP] Created physics scene with gravity") |
| |
| |
| material_path = "/physicsMaterial" |
| if not self.stage.GetPrimAtPath(material_path): |
| material = UsdPhysics.MaterialAPI.Apply( |
| self.stage.DefinePrim(material_path, "Material") |
| ) |
| material.CreateStaticFrictionAttr().Set(0.5) |
| material.CreateDynamicFrictionAttr().Set(0.5) |
| material.CreateRestitutionAttr().Set(0.0) |
| print(f"[PHYSICS_SETUP] Created default physics material") |
| |
| print(f"[PHYSICS_SETUP] Physics scene setup complete") |
| |
| except Exception as e: |
| print(f"[PHYSICS_SETUP_ERROR] Failed to setup physics scene: {e}") |
| import traceback |
| traceback.print_exc() |
| |
| def _verify_collision_system(self) -> None: |
| """Verify entire collision system works correctly.""" |
| print(f"[COLLISION_VERIFY] Verifying collision system...") |
| |
| try: |
| |
| scene_prim = self.stage.GetPrimAtPath("/physicsScene") |
| if scene_prim.IsValid(): |
| print(f"[COLLISION_VERIFY] Physics scene found: /physicsScene") |
| else: |
| print(f"[COLLISION_ERROR] Physics scene not found!") |
| |
| |
| collision_path = self.agent_prim_path + "/CollisionCylinder" |
| collision_prim = self.stage.GetPrimAtPath(collision_path) |
| if collision_prim.IsValid(): |
| print(f"[COLLISION_VERIFY] Agent collision body found: {collision_path}") |
| |
| |
| collision_xform = self._UsdGeom.Xformable(collision_prim) |
| local_transform = collision_xform.GetLocalTransformation() |
| print(f"[COLLISION_VERIFY] Collision body transform: {local_transform}") |
| |
| else: |
| print(f"[COLLISION_ERROR] Agent collision body not found!") |
| |
| |
| collision_count = 0 |
| for prim in self.stage.Traverse(): |
| if prim.HasAPI(self._UsdPhysics.CollisionAPI): |
| collision_count += 1 |
| if collision_count <= 5: |
| print(f"[COLLISION_VERIFY] Found collision object: {prim.GetPath()}") |
| |
| print(f"[COLLISION_VERIFY] Total collision objects in scene: {collision_count}") |
| |
| if collision_count < 2: |
| print(f"[COLLISION_WARN] Very few collision objects found. Scene may not have proper collision setup.") |
| |
| print(f"[COLLISION_VERIFY] Collision system verification complete") |
| |
| except Exception as e: |
| print(f"[COLLISION_VERIFY_ERROR] Failed to verify collision system: {e}") |
| import traceback |
| traceback.print_exc() |
|
|
| def _enhanced_collision_check(self, old_pos: np.ndarray, new_pos: np.ndarray) -> bool: |
| """ |
| Enhanced collision detection using multiple methods |
| """ |
| try: |
| |
| temp_pos = self._pos.copy() |
| self._pos = new_pos |
| self._apply_pose() |
| |
| |
| self.world.step(render=False) |
| |
| |
| actual_pos = self._get_agent_physics_position() |
| if actual_pos is not None: |
| |
| position_diff = np.linalg.norm(new_pos - actual_pos) |
| if position_diff > 0.001: |
| print(f"[COLLISION_CHECK] Expected: {new_pos[:2]}, Actual: {actual_pos[:2]}, Diff: {position_diff:.4f}") |
| |
| |
| if position_diff > 0.03: |
| |
| self._pos = temp_pos |
| self._apply_pose() |
| return True |
| |
| |
| if actual_pos is not None: |
| height_diff = abs(actual_pos[2] - new_pos[2]) |
| if height_diff > 0.5: |
| print(f"[COLLISION_HEIGHT] Unexpected height change: {height_diff:.4f}m") |
| self._pos = temp_pos |
| self._apply_pose() |
| return True |
| |
| |
| movement_intended = np.linalg.norm(new_pos[:2] - old_pos[:2]) |
| movement_actual = np.linalg.norm(actual_pos[:2] - old_pos[:2]) if actual_pos is not None else movement_intended |
| |
| if movement_intended > 0.05: |
| movement_ratio = movement_actual / movement_intended |
| if movement_ratio < 0.05: |
| print(f"[COLLISION_MOVEMENT] Movement severely restricted: ratio={movement_ratio:.2f}") |
| self._pos = temp_pos |
| self._apply_pose() |
| return True |
| |
| |
| return False |
| |
| except Exception as e: |
| print(f"[COLLISION_CHECK_ERROR] {e}") |
| |
| self._pos = old_pos |
| self._apply_pose() |
| return True |
| |
| def _verify_collision_system(self) -> None: |
| """Verify entire collision system works correctly.""" |
| print(f"[COLLISION_VERIFY] Verifying collision system...") |
| |
| try: |
| |
| scene_prim = self.stage.GetPrimAtPath("/physicsScene") |
| if scene_prim.IsValid(): |
| print(f"[COLLISION_VERIFY] Physics scene found: /physicsScene") |
| else: |
| print(f"[COLLISION_ERROR] Physics scene not found!") |
| |
| |
| collision_path = self.agent_prim_path + "/CollisionCylinder" |
| collision_prim = self.stage.GetPrimAtPath(collision_path) |
| if collision_prim.IsValid(): |
| print(f"[COLLISION_VERIFY] Agent collision body found: {collision_path}") |
| |
| |
| collision_xform = self._UsdGeom.Xformable(collision_prim) |
| local_transform = collision_xform.GetLocalTransformation() |
| print(f"[COLLISION_VERIFY] Collision body transform: {local_transform}") |
| |
| else: |
| print(f"[COLLISION_ERROR] Agent collision body not found!") |
| |
| |
| collision_count = 0 |
| for prim in self.stage.Traverse(): |
| if prim.HasAPI(self._UsdPhysics.CollisionAPI): |
| collision_count += 1 |
| if collision_count <= 5: |
| print(f"[COLLISION_VERIFY] Found collision object: {prim.GetPath()}") |
| |
| print(f"[COLLISION_VERIFY] Total collision objects in scene: {collision_count}") |
| |
| if collision_count < 2: |
| print(f"[COLLISION_WARN] Very few collision objects found. Scene may not have proper collision setup.") |
| |
| print(f"[COLLISION_VERIFY] Collision system verification complete") |
| |
| except Exception as e: |
| print(f"[COLLISION_VERIFY_ERROR] Failed to verify collision system: {e}") |
| import traceback |
| traceback.print_exc() |
|
|
| def _enhanced_collision_check(self, old_pos: np.ndarray, new_pos: np.ndarray) -> bool: |
| """ |
| Enhanced collision detection using multiple methods |
| """ |
| try: |
| |
| temp_pos = self._pos.copy() |
| self._pos = new_pos |
| self._apply_pose() |
| |
| |
| self.world.step(render=False) |
| |
| |
| actual_pos = self._get_agent_physics_position() |
| if actual_pos is not None: |
| |
| position_diff = np.linalg.norm(new_pos - actual_pos) |
| if position_diff > 0.001: |
| print(f"[COLLISION_CHECK] Expected: {new_pos[:2]}, Actual: {actual_pos[:2]}, Diff: {position_diff:.4f}") |
| |
| |
| if position_diff > 0.03: |
| |
| self._pos = temp_pos |
| self._apply_pose() |
| return True |
| |
| |
| if actual_pos is not None: |
| height_diff = abs(actual_pos[2] - new_pos[2]) |
| if height_diff > 0.5: |
| print(f"[COLLISION_HEIGHT] Unexpected height change: {height_diff:.4f}m") |
| self._pos = temp_pos |
| self._apply_pose() |
| return True |
| |
| |
| movement_intended = np.linalg.norm(new_pos[:2] - old_pos[:2]) |
| movement_actual = np.linalg.norm(actual_pos[:2] - old_pos[:2]) if actual_pos is not None else movement_intended |
| |
| if movement_intended > 0.05: |
| movement_ratio = movement_actual / movement_intended |
| if movement_ratio < 0.05: |
| print(f"[COLLISION_MOVEMENT] Movement severely restricted: ratio={movement_ratio:.2f}") |
| self._pos = temp_pos |
| self._apply_pose() |
| return True |
| |
| |
| return False |
| |
| except Exception as e: |
| print(f"[COLLISION_CHECK_ERROR] {e}") |
| |
| self._pos = old_pos |
| self._apply_pose() |
| return True |