Spaces:
Running
Running
File size: 31,996 Bytes
9ee6f68 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 | import sapien as sapien
from sapien.utils import Viewer
import numpy as np
import json
import transforms3d
import os
from pathlib import Path
import os.path as osp
import argparse
import shutil
import tempfile
import xml.etree.ElementTree as ET
from typing import Dict, Any, List, Set, Optional
import sys
sys.path.append(str(Path(__file__).parent.parent.parent))
from src.utils.config_manager import get_sapien_config, get_config
from pathlib import Path
import numpy as np
import glog
class URDFProcessor:
"""Utilities for URDF processing"""
@classmethod
def get_config(cls):
return get_sapien_config()
@staticmethod
def urdf_to_dict(urdf_path: str) -> Dict[str, Any]:
"""Convert URDF file to dictionary structure"""
tree = ET.parse(urdf_path)
root = tree.getroot()
def parse_element(element):
parsed = {}
for child in element:
if len(child) > 0:
name = f"_{child.attrib['name']}" if "name" in child.attrib else ""
parsed[f"{child.tag}{name}"] = parse_element(child)
else:
parsed[child.tag] = child.attrib
return parsed
urdf_dict = {root.tag: parse_element(root)}
return urdf_dict
class SapienSceneManager:
"""Manager for Sapien scene creation and manipulation"""
def __init__(self):
self.fixed_objects: Set[str] = set()
self.config = get_sapien_config()
self.global_config = get_config()
@classmethod
def get_config(cls):
return get_sapien_config()
def create_scene(self) -> sapien.Scene:
"""Create and configure a new Sapien scene"""
scene = sapien.Scene()
scene.set_timestep(self.config.time_step)
scene.add_ground(altitude=self.config.ground_altitude)
directional_light = self.config.directional_light
point_lights = self.config.point_lights
camera_shader = self.config.camera_shader
ray_tracing_denoiser = self.config.ray_tracing_denoiser
# for dir_light in directional_light:
# scene.add_directional_light(dir_light["direction"], dir_light["color"])
# for point_light in point_lights:
# scene.add_point_light(point_light["position"], point_light["color"])
sapien.render.set_camera_shader_dir(camera_shader)
sapien.render.set_ray_tracing_denoiser(ray_tracing_denoiser)
self.setup_lighting(scene)
# scene.set_timestep(time_step)
return scene
def setup_lighting(self, scene: sapien.Scene):
"""Setup lighting for the scene"""
# Ambient light
scene.set_ambient_light(self.config.ambient_light)
# Directional light
for dir_light in self.config.directional_light:
scene.add_directional_light(dir_light["direction"], dir_light["color"])
# Point lights
for light in self.config.point_lights:
scene.add_point_light(light["position"], light["color"])
def setup_camera(self, viewer):
"""Setup camera for the viewer"""
viewer.set_camera_xyz(**self.config.camera_position)
viewer.set_camera_rpy(**self.config.camera_rotation)
viewer.window.set_camera_parameters(**self.config.camera_parameters)
def get_glb_path(self, template_name: str) -> str:
"""Get GLB file path for a template"""
obj_config_path = (
Path(self.global_config.dataset_root_path)
/ "configs/objects"
/ f"{osp.basename(template_name)}.object_config.json"
)
with open(obj_config_path, "r") as f:
obj_config = json.load(f)
relative_glb_path = obj_config["render_asset"]
glb_file_path = os.path.normpath(obj_config_path.parent / relative_glb_path)
return glb_file_path
def _create_object_material(
self, use_default: bool = False
) -> sapien.render.RenderMaterial:
"""Create material for objects"""
material = sapien.render.RenderMaterial()
if use_default:
material.set_base_color(self.config.default_material["base_color"])
material.set_metallic(self.config.default_material["metallic"])
material.set_roughness(self.config.default_material["roughness"])
material.set_specular(self.config.default_material["specular"])
material.set_transmission(self.config.default_material["transmission"])
else:
material.transmission = 1e9
material.base_color = [1.0, 1.0, 1.0, 1.0]
return material
def _apply_rotation_correction(self, quaternion: List[float]) -> List[float]:
"""Apply rotation correction to quaternion"""
rpy = transforms3d.euler.quat2euler(quaternion, axes="sxyz")
corrected_quaternion = transforms3d.euler.euler2quat(
rpy[0] + np.deg2rad(self.config.rotation_offset_x),
rpy[1],
rpy[2],
axes="sxyz",
)
return corrected_quaternion
def add_object_to_scene(self, scene: sapien.Scene, obj: Dict[str, Any]):
"""Add a single object to the scene"""
object_file_path = obj["visual_path"]
collision_path = obj.get("collision_path", None)
position = [
obj["centroid_translation"]["x"],
obj["centroid_translation"]["y"],
obj["centroid_translation"]["z"],
]
quaternion = [
obj["quaternion"]["w"],
obj["quaternion"]["x"],
obj["quaternion"]["y"],
obj["quaternion"]["z"],
]
# Special case adjustments
if "cushion_03" in object_file_path:
position[2] += self.config.cushion_z_offset
# Rotation correction
quaternion = self._apply_rotation_correction(quaternion)
# Create actor
builder = scene.create_actor_builder()
# material = self._create_object_material(use_default=False)
builder.add_visual_from_file(filename=object_file_path)
# Add collision. If the physics-side GLTF parser rejects the visual
# mesh (happens for some HSSD/AI2THOR assets with malformed
# TEXCOORD attributes), fall back to a visual-only actor instead of
# failing the whole scene load. STATIC objects render fine without
# collision; DYNAMIC ones would fall through, so keep a warning.
if collision_path is not None:
builder.add_multiple_convex_collisions_from_file(filename=collision_path)
else:
try:
builder.add_convex_collision_from_file(filename=object_file_path)
except Exception as e:
glog.warning(
f"collision build failed for {object_file_path} "
f"({str(e)[:120]}); loading as visual-only"
)
if obj.get("motion_type") not in ["STATIC", "KEEP_FIXED"]:
glog.warning(
f"{obj.get('name')} is DYNAMIC without collision, "
"it will not interact physically"
)
if obj.get("motion_type") in ["STATIC", "KEEP_FIXED"]:
mesh = builder.build_static(name=obj["name"])
else:
mesh = builder.build(name=obj["name"])
mesh.set_pose(sapien.Pose(p=position, q=quaternion))
def create_body_only_urdf_in_memory(
self, urdf_path: str, template_name: str
) -> str:
"""Process URDF in memory, keeping only root and body links, using a temporary file with automatic cleanup."""
# Read the original URDF
tree = ET.parse(urdf_path)
root = tree.getroot()
# Define the names of links to keep
allowed_links = {"root", "body"}
# Collect links and joints to remove
links_to_remove = []
joints_to_remove = []
# glog.info(f"Processing URDF: {template_name}")
# glog.info("Original links found:")
# Find all links
all_links = [link.get("name") for link in root.findall("link")]
for link_name in all_links:
glog.info(f" - {link_name}")
if link_name not in allowed_links:
links_to_remove.append(link_name)
# glog.info(f"Links to keep: {[l for l in all_links if l in allowed_links]}")
# glog.info(f"Links to remove: {links_to_remove}")
# Find all related joints
for joint in root.findall("joint"):
joint_name = joint.get("name")
parent_elem = joint.find("parent")
child_elem = joint.find("child")
if parent_elem is not None and child_elem is not None:
parent_link = parent_elem.get("link")
child_link = child_elem.get("link")
# Remove the joint if it connects to a link to be removed
if parent_link in links_to_remove or child_link in links_to_remove:
joints_to_remove.append(joint_name)
# glog.info(f"Removing joint: {joint_name} (connects {parent_link} -> {child_link})")
# Remove these elements from the XML
for link_name in links_to_remove:
for link in root.findall(f"link[@name='{link_name}']"):
root.remove(link)
# glog.info(f"Removed link: {link_name}")
for joint_name in joints_to_remove:
for joint in root.findall(f"joint[@name='{joint_name}']"):
root.remove(joint)
# glog.info(f"Removed joint: {joint_name}")
urdf_dir = os.path.dirname(urdf_path)
temp_filename = f"{template_name}_body_only_temp.urdf"
temp_path = os.path.join(urdf_dir, temp_filename)
try:
# Write the processed URDF to a temporary file
with open(temp_path, "w") as temp_file:
# Format the XML output
ET.indent(tree, space=" ")
tree.write(temp_file, encoding="unicode", xml_declaration=True)
# glog.info(f"Created temporary URDF: {temp_path}")
return temp_path
except Exception as e:
# Ensure cleanup of the temporary file in case of error
if os.path.exists(temp_path):
os.unlink(temp_path)
raise e
@staticmethod
def scale_urdf_in_place(urdf_path: str, scale: float):
"""Uniformly scale a URDF file in place.
Scales joint/visual/collision/inertial origins, mesh scales and
primitive sizes (box/sphere/cylinder) by `scale`. Needed because
SAPIEN's URDF/ArticulationBuilder has no scale API, while the
ReplicaCAD scene configs specify uniform_scale < 1.0 for some
articulated objects (e.g. kitchenCupboard_01: 0.38).
"""
if abs(scale - 1.0) < 1e-6:
return
def _fmt(values):
return " ".join(f"{v:.8g}" for v in values)
tree = ET.parse(urdf_path)
root = tree.getroot()
for elem in root.iter():
if elem.tag == "origin" and elem.get("xyz"):
xyz = [float(v) * scale for v in elem.get("xyz").split()]
elem.set("xyz", _fmt(xyz))
elif elem.tag == "mesh":
if elem.get("scale"):
sc = [float(v) * scale for v in elem.get("scale").split()]
else:
sc = [scale] * 3
elem.set("scale", _fmt(sc))
elif elem.tag == "box" and elem.get("size"):
size = [float(v) * scale for v in elem.get("size").split()]
elem.set("size", _fmt(size))
elif elem.tag == "sphere" and elem.get("radius"):
elem.set("radius", f"{float(elem.get('radius')) * scale:.8g}")
elif elem.tag == "cylinder":
if elem.get("radius"):
elem.set("radius", f"{float(elem.get('radius')) * scale:.8g}")
if elem.get("length"):
elem.set("length", f"{float(elem.get('length')) * scale:.8g}")
ET.indent(tree, space=" ")
tree.write(urdf_path, encoding="unicode", xml_declaration=True)
@staticmethod
def freeze_urdf_joints_in_place(urdf_path: str):
"""Turn all movable joints (revolute/prismatic/...) into fixed joints.
Keeps every link in place (qpos = 0) so drawers/doors do not slide or
swing during physics warm-up steps. Useful for photo shooting.
"""
tree = ET.parse(urdf_path)
root = tree.getroot()
n = 0
for joint in root.findall("joint"):
if joint.get("type") not in ("fixed",):
joint.set("type", "fixed")
n += 1
ET.indent(tree, space=" ")
tree.write(urdf_path, encoding="unicode", xml_declaration=True)
glog.info(f"Froze {n} joint(s) in {os.path.basename(urdf_path)}")
def add_articulation_to_scene(
self,
scene: sapien.Scene,
articulated_meta: Dict[str, Any],
body_only: bool = True,
freeze_joints: bool = True,
):
"""Add an articulated object to the scene.
body_only=True keeps only the root/body links (original behaviour);
body_only=False loads every link (drawers, doors, ...) from the URDF.
"""
template_name = articulated_meta["name"]
pos = articulated_meta["translation"]
pos = [pos["x"], pos["y"], pos["z"]]
rot = articulated_meta["rotation"]
rot = [rot["w"], rot["x"], rot["y"], rot["z"]]
# Apply rotation correction
quaternion = self._apply_rotation_correction(rot)
# Create the URDF to load: either body-only (original behaviour) or
# the full file with every link. Never write back to the dataset.
original_urdf_path = articulated_meta["urdf_path"]
if body_only:
processed_urdf_path = self.create_body_only_urdf_in_memory(
original_urdf_path, template_name
)
else:
glog.info(
f"Loading FULL articulation (all links) for {template_name}"
+ (" with joints frozen" if freeze_joints else "")
)
urdf_dir = os.path.dirname(original_urdf_path)
processed_urdf_path = os.path.join(
urdf_dir, f"{template_name}_full_temp.urdf"
)
shutil.copyfile(original_urdf_path, processed_urdf_path)
if freeze_joints:
self.freeze_urdf_joints_in_place(processed_urdf_path)
try:
# Apply the uniform_scale from the scene config (default 1.0)
uniform_scale = articulated_meta.get("uniform_scale") or 1.0
self.scale_urdf_in_place(processed_urdf_path, uniform_scale)
# URDF loading with the processed file
urdf_loader = scene.create_urdf_loader()
urdf_loader.name = f"{template_name}"
urdf_loader.fix_root_link = articulated_meta["fixed_base"]
urdf_loader.disable_self_collisions = True
# Position adjustment based on URDF
base_name = template_name[: template_name.rfind("_")]
urdf_adjustment = {
"fridge": 0.022461603782394812,
"kitchen_counter": 0.02441653738006261,
"kitchenCupboard_01": 0,
"chestOfDrawers_01": -0.003584124570854732,
"cabinet": 0.019934424604485024,
}
if base_name in urdf_adjustment:
pos[2] -= (
urdf_adjustment[base_name] - self.config.urdf_z_adjustment_offset
)
# Build articulation with the processed URDF
builder = urdf_loader.parse(processed_urdf_path)[0][0]
pose = sapien.Pose(pos, quaternion)
builder.initial_pose = pose
articulation = builder.build()
# Verify the loading result
glog.info(f"Successfully loaded {template_name} with links:")
for link in articulation.get_links():
glog.info(f" - {link.get_name()}")
return articulation
finally:
# Automatically clean up the temporary file
try:
if os.path.exists(processed_urdf_path):
os.unlink(processed_urdf_path)
glog.info(f"Cleaned up temporary file: {processed_urdf_path}")
except Exception as e:
glog.info(
f"Warning: Could not clean up temporary file {processed_urdf_path}: {e}"
)
# def add_articulation_to_scene(
# self, scene: sapien.Scene, articulated_meta: Dict[str, Any]
# ):
# """Add an articulated object to the scene"""
# template_name = articulated_meta["name"]
# pos = articulated_meta["translation"]
# pos = [pos["x"], pos["y"], pos["z"]]
# rot = articulated_meta["rotation"]
# rot = [rot["w"], rot["x"], rot["y"], rot["z"]]
# # Rotation correction
# quaternion = self._apply_rotation_correction(rot)
# # URDF loading
# urdf_path = articulated_meta["urdf_path"]
# urdf_loader = scene.create_urdf_loader()
# urdf_loader.name = f"{template_name}"
# urdf_loader.fix_root_link = articulated_meta["fixed_base"]
# urdf_loader.disable_self_collisions = True
# import ipdb; ipdb.set_trace()
# # Position adjustment based on URDF
# base_name = template_name[: template_name.rfind("_")]
# urdf_adjustment = {
# "fridge": 0.022461603782394812,
# "kitchen_counter": 0.02441653738006261,
# "kitchenCupboard_01": 0,
# "chestOfDrawers_01": -0.003584124570854732,
# "cabinet": 0.019934424604485024,
# }
# if base_name in urdf_adjustment:
# pos[2] -= urdf_adjustment[base_name] - self.config.urdf_z_adjustment_offset
# # Build articulation
# builder = urdf_loader.parse(urdf_path)[0][0]
# pose = sapien.Pose(pos, quaternion)
# builder.initial_pose = pose
# #import pdb; pdb.set_trace()
# articulation = builder.build()
# # Remove unnecessary bodies
# for entity in scene.entities[::-1]:
# if 'body' in entity.get_name():
# break
# glog.info(entity.get_name())
# for component in entity.get_components():
# if isinstance(component, sapien.pysapien.render.RenderBodyComponent):
# component.visibility = 1e-2
# #entity.remove_from_scene()
# #import pdb; pdb.set_trace()
def load_objects_from_json(
self,
scene: sapien.Scene,
json_file_path: str,
background_visibility: float = 1.0,
full_articulations: Optional[Set[str]] = None,
freeze_articulation_joints: bool = True,
):
"""Load objects from JSON file into the scene"""
with open(json_file_path, "r") as f:
data = json.load(f)
# Load background
q = transforms3d.quaternions.axangle2quat(
np.array([1, 0, 0]), theta=np.deg2rad(self.config.rotation_offset_x)
)
bg_pose = sapien.Pose(q=q)
bg_path = data["background_file_path"]
builder = scene.create_actor_builder()
builder.add_visual_from_file(bg_path)
builder.add_nonconvex_collision_from_file(bg_path)
bg = builder.build_static(name="scene_background")
bg.set_pose(bg_pose)
# Background opacity: 1.0 = fully opaque (default).
# The original code set visibility to 0.15 for every entity here,
# which made the walls/room look ghost-like and transparent.
for component in bg.get_components():
if isinstance(component, sapien.pysapien.render.RenderBodyComponent):
component.visibility = background_visibility
# Load objects
for obj in data["object_instances"]:
if "name" in obj and obj["name"] == "GROUND":
continue
if "motion_type" in obj and obj["motion_type"] == "KEEP_FIXED":
self.fixed_objects.add(obj["name"])
self.add_object_to_scene(scene, obj)
# Load articulated objects
for articulated_meta in data.get("articulate_instances", []):
is_full = bool(full_articulations) and any(
articulated_meta["name"].startswith(name)
for name in full_articulations
)
self.add_articulation_to_scene(
scene,
articulated_meta,
body_only=not is_full,
freeze_joints=freeze_articulation_joints,
)
def apply_entity_shading(self, scene: sapien.Scene):
"""Apply special shading to entities"""
for entity in scene.entities:
if any(
excluded in entity.get_name()
for excluded in self.config.excluded_shading_objects
):
continue
for component in entity.get_components():
if isinstance(component, sapien.pysapien.render.RenderBodyComponent):
component.shading_mode = self.config.default_shading_mode
def remove_objects(self, scene: sapien.Scene, object_names: List[str]):
"""Remove objects from scene by names"""
for entity in scene.entities:
if entity.get_name() in object_names:
entity.remove_from_scene()
def add_single_object(self, scene: sapien.Scene, obj: Dict[str, Any]):
"""Add a single object with custom material (for debugging)"""
object_file_path = obj["visual_path"]
collision_path = obj.get("collision_path", None)
position = [
obj["centroid_translation"]["x"],
obj["centroid_translation"]["y"],
obj["centroid_translation"]["z"],
]
quaternion = [
obj["quaternion"]["w"],
obj["quaternion"]["x"],
obj["quaternion"]["y"],
obj["quaternion"]["z"],
]
if "cushion_03" in object_file_path:
position[2] += self.config.cushion_z_offset
quaternion = self._apply_rotation_correction(quaternion)
builder = scene.create_actor_builder()
builder.add_visual_from_file(filename=object_file_path)
if collision_path is not None:
builder.add_multiple_convex_collisions_from_file(filename=collision_path)
else:
builder.add_convex_collision_from_file(filename=object_file_path)
if obj["motion_type"] in ["STATIC", "KEEP_FIXED"]:
mesh = builder.build_static(name=obj["name"])
else:
mesh = builder.build(name=obj["name"])
mesh.set_pose(sapien.Pose(p=position, q=quaternion))
class EntityExporter:
"""Export scene entities to JSON format"""
def __init__(self):
self.urdf_processor = URDFProcessor()
self.config = get_sapien_config()
self.global_config = get_config()
@classmethod
def get_config(cls):
return get_sapien_config()
@staticmethod
def convert_to_float(obj):
"""Convert numpy types to Python float for JSON serialization"""
if isinstance(obj, np.float32):
return float(obj)
elif isinstance(obj, dict):
return {k: EntityExporter.convert_to_float(v) for k, v in obj.items()}
elif isinstance(obj, list):
return [EntityExporter.convert_to_float(i) for i in obj]
return obj
def reget_entities_from_sapien(
self,
scene,
json_file_path: str,
path: str = "entities.json",
fixed_objects: Set[str] = None,
):
"""Export entities from Sapien scene to JSON format"""
if fixed_objects is None:
fixed_objects = set()
# Load original data
with open(json_file_path, "r") as f:
data = json.load(f)
res = {
"background_file_path": data["background_file_path"],
"object_instances": [],
}
articulations = data.get("articulate_instances", [])
articulation_idx = -1
# Process entities
for entity in scene.entities:
entity_instance = {}
if len(entity.get_name()) == 0:
continue
if entity.get_name() == "root":
articulation_idx += 1
continue
if articulation_idx == -1:
# Regular object
entity_instance["name"] = entity.get_name()
filename = entity.get_name()
if filename in fixed_objects or "ground" in filename:
continue
filename = filename[: filename.rfind("_")]
entity_instance["visual_path"] = (
f"{self.global_config.visual_path_prefix}{filename}.glb"
)
elif articulation_idx < len(articulations):
if "body" not in entity.get_name():
glog.info(
f"Skipping entity {entity.get_name()} as it is not body part of an articulated object"
)
continue
# Articulated object
entity_instance["name"] = (
f'{articulations[articulation_idx]["name"]}_{entity.get_name()}'
)
urdf_path = articulations[articulation_idx]["urdf_path"]
urdf_dict = self.urdf_processor.urdf_to_dict(urdf_path)
if f"link_{entity.get_name()}" not in urdf_dict["robot"]:
glog.info(f"Warning: {entity.get_name()} not found in URDF")
continue
filename = urdf_dict["robot"][f"link_{entity.get_name()}"]["visual"][
"geometry"
]["mesh"]["filename"]
name = articulations[articulation_idx]["name"]
name = name[: name.rfind("_")]
entity_instance["visual_path"] = (
f"{self.global_config.urdf_path_prefix}/{name}/{filename}"
)
else:
glog.info("Error: articulation index out of range")
continue
# Extract pose information
quaternion = [self.convert_to_float(val) for val in entity.get_pose().q]
rpy = transforms3d.euler.quat2euler(quaternion, axes="sxyz")
quaternion = transforms3d.euler.euler2quat(
rpy[0] + np.deg2rad(self.config.correction_rotation_x),
rpy[1],
rpy[2],
axes="sxyz",
)
q = {
"w": self.convert_to_float(quaternion[0]),
"x": self.convert_to_float(quaternion[1]),
"y": self.convert_to_float(quaternion[2]),
"z": self.convert_to_float(quaternion[3]),
}
p = {
"x": self.convert_to_float(entity.get_pose().p[0]),
"y": self.convert_to_float(entity.get_pose().p[1]),
"z": self.convert_to_float(entity.get_pose().p[2]),
}
entity_instance["centroid_translation"] = p
entity_instance["quaternion"] = q
entity_instance["bbox"] = "deprecated"
res["object_instances"].append(entity_instance)
# Merge original object properties
for obj in data.get("object_instances", []):
for obj_idx in range(len(res["object_instances"])):
if res["object_instances"][obj_idx]["name"] == obj["name"]:
res["object_instances"][obj_idx]["motion_type"] = obj["motion_type"]
res["object_instances"][obj_idx]["collision_path"] = obj.get(
"collision_path", None
)
res["object_instances"][obj_idx]["visual_path"] = obj["visual_path"]
break
# Save result
with open(path, "w") as f:
json.dump(res, f, indent=4)
# Initialize res
def main():
parser = argparse.ArgumentParser(description="Export Sapien scene entities to JSON")
parser.add_argument(
"--json_file_path", type=str, required=True, help="Path to the JSON file"
)
parser.add_argument(
"--output_path",
type=str,
default="entities.json",
help="Output path for exported entities",
)
parser.add_argument(
"--full_articulation",
type=str,
nargs="*",
default=None,
help="Articulation name prefixes to load with ALL links (drawers, doors...), "
"e.g. kitchen_counter chestOfDrawers. Default: body link only.",
)
args = parser.parse_args()
exporter = EntityExporter()
scene = sapien.Scene()
sapien_scene_manager = SapienSceneManager()
sapien_scene_manager.load_objects_from_json(
scene, args.json_file_path, full_articulations=args.full_articulation
)
viewer = scene.create_viewer()
viewer.set_camera_xyz(x=-5, y=0, z=6)
viewer.set_camera_rpy(r=0, p=-np.arctan2(2, 4), y=0)
viewer.window.set_camera_parameters(near=0.05, far=100, fovy=1)
scene.set_ambient_light([0.5, 0.5, 0.5])
scene.add_directional_light([0, 1, -1], [0.5, 0.5, 0.5])
scene.add_point_light([1.989, -5.822, 1], [0.5, 0.5, 0.5])
"""
scene.add_point_light([1.2931, -5.7490, 1.0273],[1, 1, 1])
scene.add_point_light([2.2649, -6.4652, 1.0273],[1, 1, 1])
scene.add_point_light([2.6857, -5.8942, 1.0273],[1, 1, 1])
scene.add_point_light([1.7139, -5.1780, 1.0273],[1, 1, 1])
"""
scene.add_point_light([2 + 0.15, -5.75 - 0.15, 1.0], [0.4, 0.4, 0.4])
scene.add_point_light([1.2 + 0.15, -5.75 - 0.15, 1.0], [0.4, 0.4, 0.4])
scene.add_point_light([1.6 + 0.15, -6.5 - 0.15, 1.0], [0.4, 0.4, 0.4])
scene.add_point_light([1.6 + 0.15, -5 - 0.15, 1.0], [0.4, 0.4, 0.4])
scene.add_point_light([2 + 0.15, -6.5 - 0.15, 1.0], [0.4, 0.4, 0.4])
scene.add_point_light([2 + 0.15, -5.0 - 0.15, 1.0], [0.4, 0.4, 0.4])
scene.add_point_light([3 - 0.1, -7.35, 2.0], [0.4, 0.4, 0.4])
scene.add_point_light([3 + 0.1, -7.85, 2.0], [0.4, 0.4, 0.4])
# scene.add_point_light([1.2,-6.5,1.5],[2,2,2])
scene.add_point_light([1.2 + 0.15, -5 - 0.15, 1.0], [0.4, 0.4, 0.4])
for i in range(1000):
scene.step()
scene.update_render()
glog.info(scene.entities, dir(scene), dir(scene.entities[0]))
for entity in scene.entities:
glog.info(entity.get_name(), entity.get_pose(), entity.get_components())
# # start simulation
while not viewer.closed:
scene.step()
scene.update_render()
viewer.render()
exporter.reget_entities_from_sapien(scene, args.json_file_path, args.output_path)
if __name__ == "__main__":
main()
|